Skip to content

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

Go

feat(apps): redesign the Apps page with independent scroll areas and catalog-aware loading (MUL-10090) (#11450)

Jiayuan Zhang9d7a40d3f444
diff --git a/packages/views/apps/components/app-card.tsx b/packages/views/apps/components/app-card.tsx
index b81c4f377e..1f9727613f 100644
--- a/packages/views/apps/components/app-card.tsx
+++ b/packages/views/apps/components/app-card.tsx
@@ -2,9 +2,13 @@
import type { ReactNode } from "react";
import { ChevronRight } from "@multica/ui/icons";
+import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { ComposioToolkitLogo } from "../../common/composio-toolkit-logo";
import { AppLink } from "../../navigation";
+const CARD_CLASS =
+ "group/app-card relative flex h-16 min-w-0 items-center gap-3 rounded-lg border border-surface-border bg-surface px-3";
+
/**
* One app in the directory. Every card is the same height whatever it holds —
* the name, at most one `meta` line, and one trailing slot — so the grid's rows
@@ -15,6 +19,7 @@ import { AppLink } from "../../navigation";
export function AppCard({
slug,
name,
+ namePending = false,
logo,
href,
meta,
@@ -22,6 +27,8 @@ export function AppCard({
}: {
slug: string;
name: string;
+ /** The display name is still loading; `name` is only the slug, so it is read out but not shown. */
+ namePending?: boolean;
logo?: string;
href: string;
/** One line under the name; it must truncate itself. */
@@ -29,7 +36,7 @@ export function AppCard({
action?: ReactNode;
}) {
return (
- <li className="group/app-card relative flex h-16 min-w-0 items-center gap-3 rounded-lg border border-surface-border bg-surface px-3 transition-colors hover:bg-surface-hover">
+ <li className={`${CARD_CLASS} transition-colors hover:bg-surface-hover`}>
<ComposioToolkitLogo slug={slug} name={name} fallbackLogo={logo} className="h-9 w-9 rounded-sm" />
<div className="min-w-0 flex-1">
<AppLink
@@ -37,7 +44,14 @@ export function AppCard({
newTabTitle={name}
className="block truncate text-body font-medium outline-none after:absolute after:inset-0 after:rounded-lg focus-visible:after:ring-2 focus-visible:after:ring-ring"
>
- {name}
+ {namePending ? (
+ <>
+ <span className="sr-only">{name}</span>
+ <Skeleton aria-hidden="true" className="my-[3px] h-3.5 w-24" />
+ </>
+ ) : (
+ name
+ )}
</AppLink>
{meta ? <p className="flex min-w-0 text-caption text-muted-foreground">{meta}</p> : null}
</div>
@@ -52,3 +66,16 @@ export function AppCard({
</li>
);
}
+
+/** A card-shaped placeholder, so the grid keeps its rows while the catalog loads. */
+export function AppCardSkeleton() {
+ return (
+ <li aria-hidden="true" className={CARD_CLASS}>
+ <Skeleton className="size-9 shrink-0 rounded-sm" />
+ <div className="min-w-0 flex-1 space-y-2">
+ <Skeleton className="h-3.5 w-2/5" />
+ <Skeleton className="h-3 w-1/4" />
+ </div>
+ </li>
+ );
+}
diff --git a/packages/views/apps/components/apps-page.test.tsx b/packages/views/apps/components/apps-page.test.tsx
index 4512e09ed9..a8c3acda12 100644
--- a/packages/views/apps/components/apps-page.test.tsx
+++ b/packages/views/apps/components/apps-page.test.tsx
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useEffect, useState } from "react";
-import { cleanup, fireEvent, screen, waitFor, within } from "@testing-library/react";
+import { act, cleanup, fireEvent, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { api } from "@multica/core/api";
@@ -36,6 +36,13 @@ vi.mock("../../common/use-composio-available", () => ({ useComposioAvailable: ()
let overview: AppsOverview;
const nav = { search: "" };
const replace = vi.fn();
+const push = vi.fn();
+
+/** The scrolling content beside the directory's navigation. */
+const content = () => document.querySelector<HTMLElement>("[data-tab-scroll-root]")!;
+const firstGrid = () => within(content()).getAllByRole("list")[0]!;
+const directoryNav = () => screen.getByRole("navigation", { name: "Apps" });
+const navLink = (name: RegExp) => within(directoryNav()).getByRole("link", { name });
beforeEach(() => {
composio.available = true;
@@ -71,12 +78,16 @@ afterEach(() => {
vi.clearAllMocks();
});
-// Re-renders with the new search on replace, like the web and desktop routers.
+// Re-renders with the new search on navigation, like the web and desktop routers.
function RoutedAppsPage({ search }: { search: string }) {
const [current, setCurrent] = useState(search);
useEffect(() => setCurrent(search), [search]);
const adapter: NavigationAdapter = {
- push: vi.fn(), back: vi.fn(), pathname: "/acme/apps",
+ back: vi.fn(), pathname: "/acme/apps",
+ push: (url) => {
+ push(url);
+ setCurrent(url.split("?")[1] ?? "");
+ },
replace: (url) => {
replace(url);
setCurrent(url.split("?")[1] ?? "");
@@ -105,11 +116,12 @@ describe("AppsPage", () => {
it("groups apps in use, puts the ones needing attention first and counts them", async () => {
renderPage();
await waitFor(() =>
- expect(within(screen.getAllByRole("list")[0]!).getAllByRole("link").map((l) => l.textContent))
+ expect(within(firstGrid()).getAllByRole("link").map((l) => l.textContent))
.toEqual(["Gmail", "Slack", "Notion"]),
);
- const list = screen.getAllByRole("list")[0];
- expect(screen.getByRole("tab", { name: /Needs attention/ })).toHaveTextContent("2");
+ const list = firstGrid();
+ expect(navLink(/^Needs attention/)).toHaveTextContent("2");
+ expect(navLink(/^In use/)).toHaveAttribute("aria-current", "page");
expect(within(list!).getByRole("link", { name: "Notion" })).toHaveAttribute("href", "/acme/apps/notion");
// A card with nothing to do names its agents in place of an action.
expect(within(list!).getAllByRole("img", { name: /^Used by / }).map((el) => el.getAttribute("aria-label")))
@@ -136,10 +148,13 @@ describe("AppsPage", () => {
it("filters by search across every tab", async () => {
const user = userEvent.setup();
renderPage();
- await screen.findByRole("tab", { name: /In use/ });
- await user.click(screen.getByRole("tab", { name: /All apps/ }));
+ await screen.findByRole("link", { name: "Linear" });
+ await user.click(navLink(/^All apps/));
await user.type(screen.getByRole("searchbox", { name: "Search apps" }), "iss");
- expect(within(screen.getAllByRole("list")[0]!).getAllByRole("link").map((l) => l.textContent)).toEqual(["Linear"]);
+ expect(within(firstGrid()).getAllByRole("link").map((l) => l.textContent)).toEqual(["Linear"]);
+ // The navigation counts what the search leaves.
+ expect(navLink(/^All apps/)).toHaveTextContent(/1$/);
+ expect(navLink(/^In use/)).not.toHaveTextContent(/\d/);
});
it("narrows All apps to a category from the URL and names how each app connects", async () => {
@@ -154,22 +169,26 @@ describe("AppsPage", () => {
const user = userEvent.setup();
nav.search = "tab=all";
renderPage();
- const rail = await screen.findByRole("navigation", { name: "App categories" });
- expect(within(rail).getAllByRole("button").map((b) => b.textContent)).toEqual([
- "All5", "Featured1", "AI & Machine Learning3", "Collaboration & Communication1", "Data & Analytics1",
+ const tavily = await screen.findByRole("link", { name: "Tavily" });
+ const categories = within(directoryNav()).getByRole("region", { name: "Categories" });
+ expect(within(categories).getAllByRole("link").map((l) => l.textContent)).toEqual([
+ "AI & Machine Learning3", "Collaboration & Communication1", "Data & Analytics1",
]);
+ expect(navLink(/^All apps/)).toHaveTextContent(/5$/);
+ expect(navLink(/^Featured/)).toHaveTextContent(/1$/);
// Without a category, cards name theirs.
- expect(screen.getByRole("link", { name: "Tavily" }).closest("li")).toHaveTextContent("Data & Analytics");
+ expect(tavily.closest("li")).toHaveTextContent("Data & Analytics");
- await user.click(within(rail).getByRole("button", { name: /AI & Machine Learning/ }));
- expect(replace).toHaveBeenLastCalledWith("/acme/apps?tab=all&category=ai_ml");
- expect(screen.getByRole("heading", { name: /^AI & Machine Learning/ })).toHaveTextContent(/3$/);
- const list = screen.getAllByRole("list")[0]!;
+ await user.click(navLink(/^AI & Machine Learning/));
+ expect(push).toHaveBeenLastCalledWith("/acme/apps?tab=all&category=ai_ml");
+ expect(screen.getByRole("heading", { level: 2, name: /^AI & Machine Learning/ })).toHaveTextContent(/3$/);
+ expect(navLink(/^AI & Machine Learning/)).toHaveAttribute("aria-current", "page");
+ const list = firstGrid();
expect(within(list).getAllByRole("link").map((l) => l.textContent)).toEqual(["OpenAI", "Gemini", "Mistral"]);
expect(within(list).getAllByText("Uses an API key")).toHaveLength(3);
- await user.click(screen.getByRole("tab", { name: /In use/ }));
- expect(replace).toHaveBeenLastCalledWith("/acme/apps");
+ await user.click(navLink(/^In use/));
+ expect(push).toHaveBeenLastCalledWith("/acme/apps");
});
it("title-cases category names Multica has no label for", async () => {
@@ -179,22 +198,82 @@ describe("AppsPage", () => {
overview = { ...overview, team: [], agent_apps: [] };
nav.search = "tab=all";
renderPage();
- const rail = await screen.findByRole("navigation", { name: "App categories" });
- expect(within(rail).getByRole("button", { name: /^Space Exploration/ })).toBeInTheDocument();
- expect(screen.getByRole("link", { name: "A" }).closest("li")).toHaveTextContent("Space Exploration");
+ expect((await screen.findByRole("link", { name: "A" })).closest("li")).toHaveTextContent("Space Exploration");
+ expect(navLink(/^Space Exploration/)).toBeInTheDocument();
});
- it("shows a long catalog a page at a time", async () => {
- vi.mocked(api.listAppCatalog).mockResolvedValue({ catalog_mode: "all", apps: Array.from({ length: 75 }, (_, i) => ({
- slug: `app${i}`, name: `App ${String(i).padStart(2, "0")}`, curated: false,
- })) });
- overview = { ...overview, team: [], agent_apps: [] };
+ it("loads more of a long catalog as the list scrolls to its end", async () => {
+ let reachEnd!: () => void;
+ const observe = vi.fn();
+ vi.stubGlobal("IntersectionObserver", vi.fn(function Observer(callback: IntersectionObserverCallback) {
+ reachEnd = () => act(() => callback([{ isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver));
+ return { observe, disconnect: vi.fn(), unobserve: vi.fn(), takeRecords: vi.fn() };
+ }));
+ try {
+ vi.mocked(api.listAppCatalog).mockResolvedValue({ catalog_mode: "all", apps: Array.from({ length: 75 }, (_, i) => ({
+ slug: `app${i}`, name: `App ${String(i).padStart(2, "0")}`, curated: false,
+ })) });
+ overview = { ...overview, team: [], agent_apps: [] };
+ nav.search = "tab=all";
+ renderPage();
+ await screen.findByRole("link", { name: "App 00" });
+ expect(within(firstGrid()).getAllByRole("link")).toHaveLength(60);
+ expect(screen.getByRole("heading", { level: 2, name: /^All apps/ })).toHaveTextContent(/75$/);
+ reachEnd();
+ expect(within(firstGrid()).getAllByRole("link")).toHaveLength(75);
+ expect(observe).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it("does not count the catalog before it arrives, and names apps in use once it does", async () => {
+ let resolveCatalog!: (value: Awaited<ReturnType<typeof api.listAppCatalog>>) => void;
+ vi.mocked(api.listAppCatalog).mockImplementation(() => new Promise((resolve) => { resolveCatalog = resolve; }));
+ renderPage();
+ // Apps in use show without the catalog, but their names come from it.
+ const cards = await waitFor(() => {
+ const links = within(firstGrid()).getAllByRole("link");
+ expect(links).toHaveLength(3);
+ return links;
+ });
+ expect(cards.map((l) => l.textContent)).toEqual(["gmail", "slack", "notion"]);
+ expect(cards.every((l) => l.querySelector("[data-slot=skeleton]"))).toBe(true);
+ expect(navLink(/^In use/)).toHaveTextContent(/3$/);
+ expect(navLink(/^All apps/)).not.toHaveTextContent(/\d/);
+ expect(within(directoryNav()).queryByRole("region", { name: "Categories" })).toBeInTheDocument();
+ expect(screen.queryByRole("heading", { name: "Popular in Acme" })).toBeInTheDocument();
+
+ resolveCatalog({ catalog_mode: "all", apps: [
+ { slug: "gmail", name: "Gmail", curated: true },
+ { slug: "notion", name: "Notion", curated: true },
+ { slug: "slack", name: "Slack", curated: true },
+ { slug: "linear", name: "Linear", category: "Issues", curated: true },
+ ] });
+ await waitFor(() => expect(navLink(/^All apps/)).toHaveTextContent(/4$/));
+ expect(within(firstGrid()).getAllByRole("link").map((l) => l.textContent)).toEqual(["Gmail", "Slack", "Notion"]);
+ });
+
+ it("says when the catalog fails to load and retries it", async () => {
+ vi.mocked(api.listAppCatalog).mockRejectedValueOnce(new Error("upstream"));
const user = userEvent.setup();
nav.search = "tab=all";
renderPage();
- await user.click(await screen.findByRole("button", { name: /Show more/ }));
- expect(within(screen.getAllByRole("list")[0]!).getAllByRole("link")).toHaveLength(75);
- expect(screen.queryByRole("button", { name: /Show more/ })).not.toBeInTheDocument();
+ const alert = await screen.findByRole("alert");
+ expect(alert).toHaveTextContent("Couldn't load the app catalog.");
+ expect(navLink(/^All apps/)).not.toHaveTextContent(/\d/);
+ await user.click(within(alert).getByRole("button", { name: "Try again" }));
+ expect(await screen.findByRole("link", { name: "Linear" })).toBeInTheDocument();
+ expect(navLink(/^All apps/)).toHaveTextContent(/4$/);
+ });
+
+ it("names the view when a category link's catalog fails to load", async () => {
+ vi.mocked(api.listAppCatalog).mockRejectedValueOnce(new Error("upstream"));
+ nav.search = "tab=all&category=ai_ml";
+ renderPage();
+ expect(await screen.findByRole("alert")).toHaveTextContent("Couldn't load the app catalog.");
+ const title = screen.getByRole("heading", { level: 2, name: /^All apps/ });
+ expect(title.querySelector("[data-slot=skeleton]")).toBeNull();
});
it("recovers an empty saved catalog only after an admin confirms", async () => {
@@ -229,7 +308,7 @@ describe("AppsPage", () => {
(window as { desktopAPI?: unknown }).desktopAPI = { pickDirectory: vi.fn() };
try {
renderPage();
- await screen.findByRole("tab", { name: /In use/ });
+ await screen.findByRole("link", { name: "Gmail" });
expect(api.getAppsOverview).toHaveBeenCalledTimes(1);
fireEvent.focus(window);
await waitFor(() => expect(api.getAppsOverview).toHaveBeenCalledTimes(2));
@@ -240,7 +319,7 @@ describe("AppsPage", () => {
it("does not reload on focus on the web, where the flow returns to this tab", async () => {
renderPage();
- await screen.findByRole("tab", { name: /In use/ });
+ await screen.findByRole("link", { name: "Gmail" });
fireEvent.focus(window);
await new Promise((resolve) => setTimeout(resolve, 20));
expect(api.getAppsOverview).toHaveBeenCalledTimes(1);
@@ -293,7 +372,7 @@ describe("AppsPage › Accounts", () => {
const team = await screen.findByRole("region", { name: "Team accounts" });
await within(team).findByText("Slack");
expect(within(team).getAllByText(/^(Notion|Linear|Slack)$/).map((el) => el.textContent)).toEqual(["Notion", "Linear", "Slack"]);
- expect(screen.getByRole("tab", { name: /Accounts/ })).toHaveTextContent("5");
+ expect(navLink(/^Accounts/)).toHaveTextContent(/5$/);
expect(within(row("team", "notion")).getAllByText("Needs reconnecting").length).toBeGreaterThan(0);
expect(within(row("team", "linear")).getAllByText(/Requested · admin notified/).length).toBeGreaterThan(0);
expect(row("team", "linear")).toHaveTextContent("Name a2 needs it");
@@ -326,7 +405,7 @@ describe("AppsPage › Accounts", () => {
await waitFor(() => expect(row("personal", "gmail")).toHaveTextContent("used by Name a1, Name shared"));
expect(row("personal", "gmail")).not.toHaveTextContent("others-private");
expect(row("personal", "youtube")).toBeNull();
- expect(screen.getByRole("tab", { name: /Accounts/ })).toHaveTextContent("5");
+ expect(navLink(/^Accounts/)).toHaveTextContent(/5$/);
});
it("gives an admin Connect and Decline on a requested team account", async () => {
@@ -365,20 +444,35 @@ describe("AppsPage › Accounts", () => {
nav.search = "";
const user = userEvent.setup();
renderPage();
- await user.click(await screen.findByRole("tab", { name: /Accounts/ }));
- expect(replace).toHaveBeenLastCalledWith("/acme/apps?tab=accounts");
+ await screen.findByRole("link", { name: "Gmail" });
+ await user.click(navLink(/^Accounts/));
+ expect(push).toHaveBeenLastCalledWith("/acme/apps?tab=accounts");
await user.type(screen.getByRole("searchbox", { name: "Search apps" }), "not");
const team = screen.getByRole("region", { name: "Team accounts" });
expect(within(team).getByText("Notion")).toBeInTheDocument();
expect(within(team).queryByText("Slack")).not.toBeInTheDocument();
expect(within(screen.getByRole("region", { name: "Your accounts" })).getByText("You haven't connected any accounts in this workspace.")).toBeInTheDocument();
+ expect(navLink(/^Accounts/)).toHaveTextContent(/1$/);
+ });
+
+ it("counts accounts the search finds by slug, as the list does", async () => {
+ vi.mocked(api.listAppCatalog).mockResolvedValue({ catalog_mode: "all", apps: [
+ { slug: "googlecalendar", name: "Google Calendar", curated: true },
+ ] });
+ overview.personal = [{ id: "p-cal", toolkit_slug: "googlecalendar", status: "active", connected_at: "", last_used_at: null }];
+ const user = userEvent.setup();
+ renderPage();
+ await screen.findByRole("region", { name: "Your accounts" }).then((yours) => within(yours).findByText("Google Calendar"));
+ await user.type(screen.getByRole("searchbox", { name: "Search apps" }), "googlecalendar");
+ expect(within(screen.getByRole("region", { name: "Your accounts" })).getByText("Google Calendar")).toBeInTheDocument();
+ expect(navLink(/^Accounts/)).toHaveTextContent(/1$/);
});
- it("follows the URL when it changes outside the tabs, e.g. the sidebar link or Back", async () => {
+ it("follows the URL when it changes outside the page, e.g. the sidebar link or Back", async () => {
const { navigate } = renderPage();
expect(await screen.findByRole("region", { name: "Team accounts" })).toBeInTheDocument();
navigate("");
- await waitFor(() => expect(screen.getByRole("tab", { name: /In use/ })).toHaveAttribute("aria-selected", "true"));
+ await waitFor(() => expect(navLink(/^In use/)).toHaveAttribute("aria-current", "page"));
expect(screen.queryByRole("region", { name: "Team accounts" })).not.toBeInTheDocument();
navigate("tab=accounts");
expect(await screen.findByRole("region", { name: "Team accounts" })).toBeInTheDocument();
diff --git a/packages/views/apps/components/apps-page.tsx b/packages/views/apps/components/apps-page.tsx
index f632635e1d..9f18528d10 100644
--- a/packages/views/apps/components/apps-page.tsx
+++ b/packages/views/apps/components/apps-page.tsx
@@ -1,12 +1,11 @@
"use client";
-import { useMemo, useState, type ReactNode } from "react";
+import { useMemo, useState, type ComponentType, type ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
-import { AlertCircle, Plug, Search } from "@multica/ui/icons";
+import { AlertCircle, AlertTriangle, LayoutGrid, Plug, Search, Star, User, X } from "@multica/ui/icons";
import { Button } from "@multica/ui/components/ui/button";
-import { Input } from "@multica/ui/components/ui/input";
-import { Tabs, TabsList, TabsTrigger } from "@multica/ui/components/ui/tabs";
+import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceId } from "@multica/core/hooks";
import { useCurrentWorkspace } from "@multica/core/paths";
@@ -21,8 +20,11 @@ import type { AppAccountScope } from "@multica/core/types";
import { ConnectAppDialog } from "../../common/connect-app-dialog";
import { SavedAppRestriction } from "../../common/saved-app-restriction";
import { useComposioAvailable } from "../../common/use-composio-available";
+import { InfiniteScrollSentinel } from "../../issues/components/infinite-scroll-sentinel";
import { CollectionPageState } from "../../layout/collection-page";
-import { PageHeader } from "../../layout/page-header";
+import { CollapsedNavTrigger, PageHeader } from "../../layout/page-header";
+import { PanelBody, PanelCount, PanelHeader, PanelLink, PanelList, PanelSection } from "../../layout/panel-nav";
+import { useRestoredScrollRef } from "../../platform/scroll-restoration";
import { useTeamAppAccess } from "../../common/use-team-app-access";
import { useViewerAppsOverview } from "../../common/use-viewer-apps-overview";
import { useT } from "../../i18n";
@@ -32,14 +34,16 @@ import { useAppConnectReturn } from "../hooks/use-app-connect-return";
import { groupAppsByCategory } from "../lib/categories";
import { buildAppDirectory, matchesAppSearch, type DirectoryApp } from "../lib/directory";
import { AccountsList, useAccountRows } from "./accounts-list";
+import { AppCardSkeleton } from "./app-card";
import { DirectoryCard, SetUpCard, type DirectoryCardHandlers } from "./directory-card";
const TABS = ["in_use", "attention", "accounts", "all"] as const;
type DirectoryTab = (typeof TABS)[number];
-/** Cards rendered before "Show more"; the full catalog has well over a thousand apps. */
+/** Cards rendered per scroll step; the full catalog has well over a thousand apps. */
const PAGE_SIZE = 60;
const CURATED = "curated";
+const GRID_CLASS = "grid gap-3 @lg:grid-cols-2 @3xl:grid-cols-3";
function parseTab(value: string | null): DirectoryTab {
return (TABS as readonly string[]).includes(value ?? "") ? (value as DirectoryTab) : "in_use";
@@ -50,26 +54,29 @@ type ConnectTarget = { slug: string; name: string; logo?: string; scope: AppAcco
/** The workspace's apps: what agents use, what needs someone, and the catalog. */
export function AppsPage() {
const { t } = useT("settings");
- const { t: tl } = useT("layout");
const available = useComposioAvailable();
-
+ if (available) return <AppsDirectory />;
return (
<div className="flex min-h-0 flex-1 flex-col">
- <PageHeader>
- <h1 className="flex min-w-0 flex-1 items-center gap-2 px-2 text-body font-medium">
- <Plug aria-hidden="true" className="size-4 shrink-0 text-muted-foreground" />
- <span className="truncate">{tl(($) => $.nav.apps)}</span>
- </h1>
- </PageHeader>
- {available ? (
- <AppsDirectory />
- ) : (
- <CollectionPageState icon={Plug} title={t(($) => $.connected_apps.hub.unavailable)} />
- )}
+ <AppsPageHeader />
+ <CollectionPageState icon={Plug} title={t(($) => $.connected_apps.hub.unavailable)} />
</div>
);
}
+/** The page header for states that have no directory to navigate. */
+function AppsPageHeader() {
+ const { t: tl } = useT("layout");
+ return (
+ <PageHeader>
+ <h1 className="flex min-w-0 flex-1 items-center gap-2 px-2 text-body font-medium">
+ <Plug aria-hidden="true" className="size-4 shrink-0 text-muted-foreground" />
+ <span className="truncate">{tl(($) => $.nav.apps)}</span>
+ </h1>
+ </PageHeader>
+ );
+}
+
function AppsDirectory() {
const { t } = useT("settings");
const { t: tl } = useT("layout");
@@ -93,31 +100,30 @@ function AppsDirectory() {
const categoryLabel = useAppCategoryLabel();
useAppConnectReturn();
const accountRows = useAccountRows(viewerOverview, catalog.data?.apps ?? []);
+ // Until the catalog arrives the directory only knows the apps in use, so
+ // anything counted over the whole catalog would be wrong, not just early.
+ const catalogReady = catalog.isSuccess;
+ const catalogPending = catalog.isPending;
- // The tab and category live in the URL so a connect flow started here comes back to them.
- const replaceParams = (update: (params: URLSearchParams) => void) => {
+ // The view lives in the URL so a connect flow started here comes back to it.
+ const viewHref = (next: DirectoryTab, category: string | null = null) => {
const params = new URLSearchParams(navigation.searchParams);
- update(params);
+ if (next === "in_use") params.delete("tab");
+ else params.set("tab", next);
+ if (category) params.set("category", category);
+ else params.delete("category");
const search = params.toString();
- navigation.replace(`${navigation.pathname}${search ? `?${search}` : ""}`);
+ return `${navigation.pathname}${search ? `?${search}` : ""}`;
};
- const setTab = (next: DirectoryTab) =>
- replaceParams((params) => {
- if (next === "in_use") params.delete("tab");
- else params.set("tab", next);
- params.delete("category");
- });
- const setCategory = (next: string | null) =>
- replaceParams((params) => {
- if (next) params.set("category", next);
- else params.delete("category");
- });
const directory = useMemo(() => {
if (!viewerOverview) return null;
return buildAppDirectory({ overview: viewerOverview, catalog: catalog.data?.apps ?? [], viewerId });
}, [viewerOverview, catalog.data, viewerId]);
- const categories = useMemo(() => groupAppsByCategory(directory?.all ?? []), [directory]);
+ const categories = useMemo(
+ () => groupAppsByCategory(catalogReady ? (directory?.all ?? []) : []),
+ [catalogReady, directory],
+ );
const handlers: DirectoryCardHandlers = {
asking,
@@ -139,173 +145,292 @@ function AppsDirectory() {
},
};
- if (overview.isLoading) {
- return <p className="px-6 py-8 text-body text-muted-foreground">{t(($) => $.connected_apps.loading)}</p>;
- }
- if (overview.isError || !directory || !viewerOverview) {
+ const restoreScrollRef = useRestoredScrollRef(`apps:${tab}:${categoryParam ?? ""}`);
+
+ if (overview.isError) {
return (
- <CollectionPageState
- role="alert"
- tone="destructive"
- icon={AlertCircle}
- title={t(($) => $.connected_apps.load_failed)}
- actions={
- <Button variant="outline" size="sm" onClick={() => overview.refetch()}>
- {t(($) => $.connected_apps.hub.retry)}
- </Button>
- }
- />
+ <div className="flex min-h-0 flex-1 flex-col">
+ <AppsPageHeader />
+ <CollectionPageState
+ role="alert"
+ tone="destructive"
+ icon={AlertCircle}
+ title={t(($) => $.connected_apps.load_failed)}
+ actions={
+ <Button variant="outline" size="sm" onClick={() => overview.refetch()}>
+ {t(($) => $.connected_apps.hub.retry)}
+ </Button>
+ }
+ />
+ </div>
);
}
- const lists: Record<Exclude<DirectoryTab, "accounts">, DirectoryApp[]> = {
- in_use: directory.inUse,
- attention: directory.attention,
- all: directory.all,
- };
+ const loaded = directory && viewerOverview ? { directory, viewerOverview } : null;
const needle = query.trim().toLowerCase();
const matches = (app: DirectoryApp) =>
matchesAppSearch(app, query) || !!categoryLabel.entry(app.entry)?.toLowerCase().includes(needle);
- const found = tab === "accounts" ? [] : lists[tab].filter(matches);
- const category =
- categoryParam === CURATED || categories.groups.some((group) => group.key === categoryParam)
+ const matchesAccount = (name: string) => !needle || name.toLowerCase().includes(needle);
+ const inUse = loaded?.directory.inUse.filter(matches) ?? [];
+ const attention = loaded?.directory.attention.filter(matches) ?? [];
+ const all = catalogReady ? (loaded?.directory.all.filter(matches) ?? []) : [];
+ const accountCount =
+ accountRows.team.filter((row) => matchesAccount(row.name) || matchesAccount(row.slug)).length +
+ accountRows.personal.filter((row) => matchesAccount(row.name) || matchesAccount(row.slug)).length;
+
+ // An unknown category falls back to all apps once the catalog can tell;
+ // until then the URL's choice stands so the view doesn't flip on arrival.
+ const category = catalogReady
+ ? categoryParam === CURATED || categories.groups.some((group) => group.key === categoryParam)
? categoryParam
- : null;
+ : null
+ : categoryParam;
+ const categoryGroup = categories.groups.find((group) => group.key === category);
const inCategory = (app: DirectoryApp) =>
category === CURATED ? !!app.entry?.curated : categories.categoryOf.get(app.slug) === category;
- const shown = category ? found.filter(inCategory) : found;
+ const curatedCount = all.filter((app) => app.entry?.curated).length;
+ const list = tab === "in_use" ? inUse : tab === "attention" ? attention : category ? all.filter(inCategory) : all;
const pageKey = `${tab}|${category ?? ""}|${needle}`;
const limit = page.key === pageKey ? page.limit : PAGE_SIZE;
- const matchesAccount = (name: string) => !needle || name.toLowerCase().includes(needle);
- const emptyText = query.trim()
+
+ const catalogCount = (value: number) =>
+ catalogReady ? (
+ <PanelCount value={value} />
+ ) : catalogPending ? (
+ <Skeleton aria-hidden="true" className="h-3 w-5 shrink-0" />
+ ) : null;
+
+ const views: {
+ key: string;
+ tab: DirectoryTab;
+ category: string | null;
+ label: string;
+ icon?: ComponentType<{ className?: string }>;
+ count: ReactNode;
+ }[] = [
+ { key: "in_use", tab: "in_use", category: null, label: t(($) => $.connected_apps.hub.tabs.in_use), icon: Plug, count: <PanelCount value={inUse.length} /> },
+ {
+ key: "attention",
+ tab: "attention",
+ category: null,
+ label: t(($) => $.connected_apps.hub.tabs.attention),
+ icon: AlertTriangle,
+ count: <PanelCount value={attention.length} className="text-warning" />,
+ },
+ { key: "accounts", tab: "accounts", category: null, label: t(($) => $.connected_apps.hub.tabs.accounts), icon: User, count: <PanelCount value={accountCount} /> },
+ ];
+ const catalogViews: typeof views = [
+ { key: "all", tab: "all", category: null, label: t(($) => $.connected_apps.hub.tabs.all), icon: LayoutGrid, count: catalogCount(all.length) },
+ { key: CURATED, tab: "all", category: CURATED, label: t(($) => $.connected_apps.hub.category_curated), icon: Star, count: catalogCount(curatedCount) },
+ ];
+ const categoryViews: typeof views = categories.groups.flatMap((group) => {
+ const count = all.filter((app) => categories.categoryOf.get(app.slug) === group.key).length;
+ if (count === 0 && category !== group.key) return [];
+ return [{ key: group.key, tab: "all" as const, category: group.key, label: categoryLabel.group(group), count: <PanelCount value={count} /> }];
+ });
+ const isActive = (view: (typeof views)[number]) => view.tab === tab && (tab !== "all" || view.category === category);
+ const activeView = [...views, ...catalogViews, ...categoryViews].find(isActive);
+
+ const viewTitle =
+ activeView?.label ??
+ (category && catalogPending ? (
+ <Skeleton aria-hidden="true" className="h-3.5 w-24" />
+ ) : categoryGroup ? (
+ categoryLabel.group(categoryGroup)
+ ) : (
+ t(($) => $.connected_apps.hub.tabs.all)
+ ));
+ const ViewIcon = activeView?.icon ?? LayoutGrid;
+ const viewCount =
+ !loaded || tab === "accounts" ? null : tab === "all" && !catalogReady ? (
+ catalogPending ? <Skeleton aria-hidden="true" className="h-3 w-6" /> : null
+ ) : (
+ <span className="text-caption text-muted-foreground tabular-nums">{list.length}</span>
+ );
+
+ const navRow = (view: (typeof views)[number]) => {
+ const Icon = view.icon;
+ return (
+ <PanelLink
+ key={view.key}
+ href={viewHref(view.tab, view.category)}
+ label={view.label}
+ icon={Icon ? <Icon /> : undefined}
+ active={isActive(view)}
+ trailing={view.count}
+ />
+ );
+ };
+
+ const emptyText = needle
? t(($) => $.connected_apps.hub.no_matches)
: tab === "attention"
? t(($) => $.connected_apps.hub.empty_attention)
: tab === "in_use"
? t(($) => $.connected_apps.hub.empty_in_use)
- : catalog.isLoading
- ? t(($) => $.connected_apps.loading)
- : t(($) => $.connected_apps.add.empty);
- const popular = tab === "in_use" && !query.trim() ? directory.popular : [];
-
- return (
- <div className="min-h-0 flex-1 overflow-y-auto">
- <div className="mx-auto w-full max-w-5xl space-y-6 px-6 py-8">
- <div className="space-y-1">
- <h2 className="text-title font-semibold">{tl(($) => $.nav.apps)}</h2>
- <p className="text-body text-muted-foreground">
- {t(($) => $.connected_apps.hub.description, { workspace: workspaceName })}
- </p>
- </div>
+ : t(($) => $.connected_apps.add.empty);
- {viewerOverview.catalog_mode !== "all" && (
- <SavedAppRestriction
- kind="catalog"
- onRestore={viewerOverview.can_manage ? () => restore.mutateAsync({ catalog: true }) : undefined}
+ let content: ReactNode;
+ if (!loaded) {
+ content = <CardGridSkeleton count={6} />;
+ } else if (tab === "accounts") {
+ content = <AccountsList overview={loaded.viewerOverview} rows={accountRows} matches={matchesAccount} />;
+ } else if (tab === "all" && catalog.isError) {
+ content = <CatalogFailed onRetry={() => catalog.refetch()} />;
+ } else if (tab === "all" && !catalogReady) {
+ content = <CardGridSkeleton count={12} />;
+ } else {
+ const namePending = (app: DirectoryApp) => catalogPending && !app.entry;
+ content = (
+ <AppGrid
+ apps={list}
+ limit={limit}
+ onShowMore={() => setPage({ key: pageKey, limit: limit + PAGE_SIZE })}
+ emptyText={emptyText}
+ render={(app) => (
+ <DirectoryCard
+ key={app.slug}
+ app={app}
+ handlers={handlers}
+ detail={tab === "all" && category ? "connect" : "category"}
+ namePending={namePending(app)}
/>
)}
+ />
+ );
+ }
- <div className="flex flex-wrap items-center justify-between gap-3">
- <Tabs value={tab} onValueChange={(value) => setTab(value as DirectoryTab)}>
- <TabsList>
- <TabTrigger value="in_use" label={t(($) => $.connected_apps.hub.tabs.in_use)} count={directory.inUse.length} />
- <TabTrigger value="attention" label={t(($) => $.connected_apps.hub.tabs.attention)} count={directory.attention.length} />
- <TabTrigger value="accounts" label={t(($) => $.connected_apps.hub.tabs.accounts)} count={accountRows.team.length + accountRows.personal.length} />
- <TabTrigger value="all" label={t(($) => $.connected_apps.hub.tabs.all)} count={directory.all.length} />
- </TabsList>
- </Tabs>
- <div className="relative w-full sm:w-60">
- <Search aria-hidden="true" className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />
- <Input
- type="search"
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- placeholder={t(($) => $.connected_apps.hub.search)}
- aria-label={t(($) => $.connected_apps.hub.search)}
- className="pl-8"
- />
- </div>
- </div>
+ const showPopular = loaded && tab === "in_use" && !needle;
- {tab === "accounts" ? (
- <AccountsList overview={viewerOverview} rows={accountRows} matches={matchesAccount} />
- ) : tab === "all" ? (
- <div className="grid gap-6 md:grid-cols-[12rem_minmax(0,1fr)]">
- <nav
- aria-label={t(($) => $.connected_apps.hub.categories_nav)}
- className="-mx-1 flex gap-1 overflow-x-auto px-1 md:sticky md:top-0 md:mx-0 md:flex-col md:gap-px md:self-start md:overflow-visible md:px-0"
+ return (
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden md:flex-row">
+ <aside className="flex shrink-0 flex-col border-surface-border max-md:border-b md:w-60 md:border-r">
+ <PanelHeader as="h1" title={tl(($) => $.nav.apps)} leading={<CollapsedNavTrigger />} />
+ <div className="px-4 pb-3 md:hidden">
+ <label className="sr-only" htmlFor="apps-navigation">
+ {tl(($) => $.nav.apps)}
+ </label>
+ <select
+ id="apps-navigation"
+ className="h-10 w-full rounded-lg border border-input bg-background px-3 text-body text-foreground focus-visible:outline-2 focus-visible:outline-ring"
+ value={viewHref(tab, category)}
+ onChange={(event) => navigation.push(event.target.value)}
+ >
+ {views.map((view) => (
+ <option key={view.key} value={viewHref(view.tab, view.category)}>
+ {view.label}
+ </option>
+ ))}
+ <optgroup label={t(($) => $.connected_apps.hub.catalog)}>
+ {catalogViews.map((view) => (
+ <option key={view.key} value={viewHref(view.tab, view.category)}>
+ {view.label}
+ </option>
+ ))}
+ </optgroup>
+ {categoryViews.length > 0 && (
+ <optgroup label={t(($) => $.connected_apps.hub.categories_label)}>
+ {categoryViews.map((view) => (
+ <option key={view.key} value={viewHref(view.tab, view.category)}>
+ {view.label}
+ </option>
+ ))}
+ </optgroup>
+ )}
+ </select>
+ </div>
+ <div className="relative mx-4 mb-3 shrink-0 md:mx-2">
+ <Search
+ aria-hidden="true"
+ className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
+ />
+ <input
+ type="search"
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Escape" && query && !event.nativeEvent.isComposing) {
+ event.preventDefault();
+ setQuery("");
+ }
+ }}
+ placeholder={t(($) => $.connected_apps.hub.search)}
+ aria-label={t(($) => $.connected_apps.hub.search)}
+ className="h-8 w-full rounded-lg border border-input bg-transparent pl-[37px] pr-8 text-body outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30 [&::-webkit-search-cancel-button]:hidden"
+ />
+ {query ? (
+ <button
+ type="button"
+ onClick={() => setQuery("")}
+ aria-label={t(($) => $.page.search_clear)}
+ className="absolute right-1.5 top-1/2 flex size-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-surface-hover hover:text-foreground"
>
- <CategoryItem
- label={t(($) => $.connected_apps.hub.category_all)}
- count={found.length}
- active={category === null}
- onSelect={() => setCategory(null)}
- />
- <CategoryItem
- label={t(($) => $.connected_apps.hub.category_curated)}
- count={found.filter((app) => app.entry?.curated).length}
- active={category === CURATED}
- onSelect={() => setCategory(CURATED)}
+ <X className="size-3.5" aria-hidden="true" />
+ </button>
+ ) : null}
+ </div>
+ <nav aria-label={tl(($) => $.nav.apps)} className="hidden min-h-0 flex-1 flex-col md:flex">
+ <PanelBody>
+ <PanelList>{views.map(navRow)}</PanelList>
+ <PanelSection label={t(($) => $.connected_apps.hub.catalog)}>
+ <PanelList>{catalogViews.map(navRow)}</PanelList>
+ </PanelSection>
+ {catalogPending ? (
+ <PanelSection label={t(($) => $.connected_apps.hub.categories_label)}>
+ <NavSkeleton rows={8} />
+ </PanelSection>
+ ) : categoryViews.length > 0 ? (
+ <PanelSection label={t(($) => $.connected_apps.hub.categories_label)}>
+ <PanelList>{categoryViews.map(navRow)}</PanelList>
+ </PanelSection>
+ ) : null}
+ </PanelBody>
+ </nav>
+ </aside>
+
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">
+ <PageHeader leading={false}>
+ <h2 className="flex min-w-0 flex-1 items-center gap-2 px-2 text-body font-medium">
+ <ViewIcon aria-hidden="true" className="size-4 shrink-0 text-muted-foreground" />
+ <span className="truncate">{viewTitle}</span>
+ {viewCount}
+ </h2>
+ </PageHeader>
+ <div
+ ref={restoreScrollRef}
+ key={`${tab}:${categoryParam ?? ""}`}
+ data-tab-scroll-root={`apps:${tab}:${categoryParam ?? ""}`}
+ className="@container min-h-0 min-w-0 flex-1 overflow-y-auto overscroll-contain"
+ >
+ <div className="mx-auto w-full max-w-5xl space-y-6 px-4 py-6 sm:px-6">
+ {loaded && loaded.viewerOverview.catalog_mode !== "all" && (
+ <SavedAppRestriction
+ kind="catalog"
+ onRestore={loaded.viewerOverview.can_manage ? () => restore.mutateAsync({ catalog: true }) : undefined}
/>
- <p className="hidden px-2 pt-3 pb-1 text-caption font-medium text-muted-foreground md:block">
- {t(($) => $.connected_apps.hub.categories_label)}
+ )}
+ {tab === "in_use" && (
+ <p className="text-body text-muted-foreground">
+ {t(($) => $.connected_apps.hub.description, { workspace: workspaceName })}
</p>
- {categories.groups.map((group) => {
- const count = found.filter((app) => categories.categoryOf.get(app.slug) === group.key).length;
- if (count === 0 && category !== group.key) return null;
- return (
- <CategoryItem
- key={group.key}
- label={categoryLabel.group(group)}
- count={count}
- active={category === group.key}
- onSelect={() => setCategory(group.key)}
- />
- );
- })}
- </nav>
- <section className="min-w-0 space-y-3">
- {category && (
- <h3 className="flex items-baseline gap-2 text-body font-semibold">
- {category === CURATED
- ? t(($) => $.connected_apps.hub.category_curated)
- : categoryLabel.group(categories.groups.find((group) => group.key === category)!)}
- <span className="text-caption font-normal text-muted-foreground tabular-nums">{shown.length}</span>
+ )}
+ {content}
+ {showPopular && (catalogPending || loaded.directory.popular.length > 0) && (
+ <section className="space-y-3">
+ <h3 className="text-body font-semibold">
+ {t(($) => $.connected_apps.hub.popular, { workspace: workspaceName })}
</h3>
- )}
- <AppGrid
- apps={shown}
- limit={limit}
- onShowMore={() => setPage({ key: pageKey, limit: limit + PAGE_SIZE })}
- emptyText={emptyText}
- columns="sm:grid-cols-2 xl:grid-cols-3"
- render={(app) => (
- <DirectoryCard key={app.slug} app={app} handlers={handlers} detail={category ? "connect" : "category"} />
+ {catalogPending ? (
+ <CardGridSkeleton count={6} />
+ ) : (
+ <ul className={GRID_CLASS}>
+ {loaded.directory.popular.map((app) => <SetUpCard key={app.slug} app={app} />)}
+ </ul>
)}
- />
- </section>
+ </section>
+ )}
</div>
- ) : (
- <AppGrid
- apps={shown}
- limit={limit}
- onShowMore={() => setPage({ key: pageKey, limit: limit + PAGE_SIZE })}
- emptyText={emptyText}
- columns="sm:grid-cols-2 lg:grid-cols-3"
- render={(app) => <DirectoryCard key={app.slug} app={app} handlers={handlers} />}
- />
- )}
-
- {popular.length > 0 && (
- <section className="space-y-3">
- <h3 className="text-body font-semibold">
- {t(($) => $.connected_apps.hub.popular, { workspace: workspaceName })}
- </h3>
- <ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
- {popular.map((app) => <SetUpCard key={app.slug} app={app} />)}
- </ul>
- </section>
- )}
+ </div>
</div>
{connecting && (
@@ -327,17 +452,14 @@ function AppGrid({
limit,
onShowMore,
emptyText,
- columns,
render,
}: {
apps: DirectoryApp[];
limit: number;
onShowMore: () => void;
emptyText: string;
- columns: string;
render: (app: DirectoryApp) => ReactNode;
}) {
- const { t } = useT("settings");
if (apps.length === 0) {
return (
<p className="rounded-lg border border-dashed px-4 py-6 text-center text-caption text-muted-foreground">
@@ -345,51 +467,49 @@ function AppGrid({
</p>
);
}
- const hidden = apps.length - limit;
return (
<>
- <ul className={`grid gap-3 ${columns}`}>{apps.slice(0, limit).map(render)}</ul>
- {hidden > 0 && (
- <div className="flex justify-center">
- <Button variant="outline" size="sm" onClick={onShowMore}>
- {t(($) => $.connected_apps.hub.show_more)}
- <span className="text-muted-foreground tabular-nums">{hidden}</span>
- </Button>
- </div>
- )}
+ <ul className={GRID_CLASS}>{apps.slice(0, limit).map(render)}</ul>
+ {apps.length > limit && <InfiniteScrollSentinel onVisible={onShowMore} loading={false} rootMargin="400px" />}
</>
);
}
-function CategoryItem({
- label,
- count,
- active,
- onSelect,
-}: {
- label: string;
- count: number;
- active: boolean;
- onSelect: () => void;
-}) {
+function CatalogFailed({ onRetry }: { onRetry: () => void }) {
+ const { t } = useT("settings");
return (
- <button
- type="button"
- aria-current={active ? "true" : undefined}
- onClick={onSelect}
- className="flex h-7 shrink-0 items-center gap-2 rounded-md px-2 text-left text-body whitespace-nowrap outline-none hover:bg-accent/60 focus-visible:ring-2 focus-visible:ring-ring aria-[current=true]:bg-accent aria-[current=true]:font-medium md:w-full"
- >
- <span className="min-w-0 flex-1 truncate">{label}</span>
- <span className="text-caption text-muted-foreground tabular-nums">{count}</span>
- </button>
+ <CollectionPageState
+ role="alert"
+ tone="destructive"
+ size="compact"
+ icon={AlertCircle}
+ title={t(($) => $.connected_apps.hub.catalog_failed)}
+ actions={
+ <Button variant="outline" size="sm" onClick={onRetry}>
+ {t(($) => $.connected_apps.hub.retry)}
+ </Button>
+ }
+ />
);
}
-function TabTrigger({ value, label, count }: { value: DirectoryTab; label: string; count: number }) {
+function CardGridSkeleton({ count }: { count: number }) {
return (
- <TabsTrigger value={value} className="px-2.5">
- {label}
- <span className="text-caption text-muted-foreground tabular-nums">{count}</span>
- </TabsTrigger>
+ <ul aria-hidden="true" className={GRID_CLASS}>
+ {Array.from({ length: count }, (_, i) => <AppCardSkeleton key={i} />)}
+ </ul>
+ );
+}
+
+function NavSkeleton({ rows }: { rows: number }) {
+ return (
+ <div aria-hidden="true" className="space-y-px">
+ {Array.from({ length: rows }, (_, i) => (
+ <div key={i} className="flex h-(--nav-item-height,2rem) items-center gap-2.5 px-3">
+ <Skeleton className="h-3 flex-1" style={{ maxWidth: `${55 + ((i * 37) % 35)}%` }} />
+ <Skeleton className="h-3 w-5" />
+ </div>
+ ))}
+ </div>
);
}
diff --git a/packages/views/apps/components/directory-card.tsx b/packages/views/apps/components/directory-card.tsx
index 589b6ac11a..83c3bd63f6 100644
--- a/packages/views/apps/components/directory-card.tsx
+++ b/packages/views/apps/components/directory-card.tsx
@@ -32,16 +32,19 @@ export function DirectoryCard({
app,
handlers,
detail,
+ namePending,
}: {
app: DirectoryApp;
handlers: DirectoryCardHandlers;
detail?: SetUpDetail;
+ /** The catalog that names the app has not loaded yet. */
+ namePending?: boolean;
}) {
const { t } = useT("settings");
const paths = useWorkspacePaths();
const { getActorName } = useActorName();
- if (!app.inUse && !app.request) return <SetUpCard app={app} detail={detail} />;
+ if (!app.inUse && !app.request) return <SetUpCard app={app} detail={detail} namePending={namePending} />;
const scopeLine =
app.scopes.length === 2
@@ -65,6 +68,7 @@ export function DirectoryCard({
<AppCard
slug={app.slug}
name={app.name}
+ namePending={namePending}
logo={app.entry?.logo}
href={paths.appDetail(app.slug)}
meta={
@@ -97,7 +101,15 @@ export function DirectoryCard({
);
}
-export function SetUpCard({ app, detail = "category" }: { app: DirectoryApp; detail?: SetUpDetail }) {
+export function SetUpCard({
+ app,
+ detail = "category",
+ namePending,
+}: {
+ app: DirectoryApp;
+ detail?: SetUpDetail;
+ namePending?: boolean;
+}) {
const { t } = useT("settings");
const paths = useWorkspacePaths();
const categoryLabel = useAppCategoryLabel();
@@ -114,6 +126,7 @@ export function SetUpCard({ app, detail = "category" }: { app: DirectoryApp; det
<AppCard
slug={app.slug}
name={app.name}
+ namePending={namePending}
logo={app.entry?.logo}
href={paths.appDetail(app.slug)}
meta={text ? <span className="truncate">{text}</span> : undefined}
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 0dc436bd17..24461011d5 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -2066,10 +2066,10 @@
"no_matches": "No apps match your search.",
"unavailable": "Apps aren't available on this server.",
"retry": "Try again",
- "category_all": "All",
+ "catalog": "Catalog",
+ "catalog_failed": "Couldn't load the app catalog.",
"category_curated": "Featured",
"categories_label": "Categories",
- "categories_nav": "App categories",
"connect_oauth": "Signs in with OAuth",
"connect_key": "Uses an API key",
"show_more": "Show more",
diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.json
index a11d746eb7..a643116d1c 100644
--- a/packages/views/locales/es/settings.json
+++ b/packages/views/locales/es/settings.json
@@ -2066,10 +2066,10 @@
"no_matches": "Ninguna aplicación coincide con tu búsqueda.",
"unavailable": "Las aplicaciones no están disponibles en este servidor.",
"retry": "Reintentar",
- "category_all": "Todas",
+ "catalog": "Catálogo",
+ "catalog_failed": "No se pudo cargar el catálogo de aplicaciones.",
"category_curated": "Destacadas",
"categories_label": "Categorías",
- "categories_nav": "Categorías de apps",
"connect_oauth": "Inicio de sesión con OAuth",
"connect_key": "Usa una clave de API",
"show_more": "Mostrar más",
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index 55e68395ae..919d6de7b4 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -2066,10 +2066,10 @@
"no_matches": "Aucune app ne correspond à votre recherche.",
"unavailable": "Les apps ne sont pas disponibles sur ce serveur.",
"retry": "Réessayer",
- "category_all": "Toutes",
+ "catalog": "Catalogue",
+ "catalog_failed": "Impossible de charger le catalogue d'apps.",
"category_curated": "À la une",
"categories_label": "Catégories",
- "categories_nav": "Catégories d'apps",
"connect_oauth": "Connexion OAuth",
"connect_key": "Utilise une clé API",
"show_more": "Afficher plus",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 0149f790a4..90c5244168 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -2044,10 +2044,10 @@
"no_matches": "検索に一致するアプリはありません。",
"unavailable": "このサーバーではアプリを利用できません。",
"retry": "再試行",
- "category_all": "すべて",
+ "catalog": "カタログ",
+ "catalog_failed": "アプリカタログを読み込めませんでした。",
"category_curated": "おすすめ",
"categories_label": "カテゴリ",
- "categories_nav": "アプリのカテゴリ",
"connect_oauth": "OAuth でログイン",
"connect_key": "API キーを入力",
"show_more": "さらに表示",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index feaf2f41eb..46c7db5bc5 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -2044,10 +2044,10 @@
"no_matches": "검색과 일치하는 앱이 없습니다.",
"unavailable": "이 서버에서는 앱을 사용할 수 없습니다.",
"retry": "다시 시도",
- "category_all": "전체",
+ "catalog": "카탈로그",
+ "catalog_failed": "앱 카탈로그를 불러오지 못했습니다.",
"category_curated": "추천",
"categories_label": "카테고리",
- "categories_nav": "앱 카테고리",
"connect_oauth": "OAuth로 로그인",
"connect_key": "API 키 입력",
"show_more": "더 보기",
diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.json
index 3e77934026..d4d1ed1045 100644
--- a/packages/views/locales/ru/settings.json
+++ b/packages/views/locales/ru/settings.json
@@ -2110,10 +2110,10 @@
"no_matches": "Нет приложений по вашему запросу.",
"unavailable": "Приложения недоступны на этом сервере.",
"retry": "Повторить",
- "category_all": "Все",
+ "catalog": "Каталог",
+ "catalog_failed": "Не удалось загрузить каталог приложений.",
"category_curated": "Рекомендуемые",
"categories_label": "Категории",
- "categories_nav": "Категории приложений",
"connect_oauth": "Вход через OAuth",
"connect_key": "Нужен API-ключ",
"show_more": "Показать ещё",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index e42a4543a6..c24bdde916 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -2044,10 +2044,10 @@
"no_matches": "没有匹配的应用。",
"unavailable": "此服务器未提供应用功能。",
"retry": "重试",
- "category_all": "全部",
+ "catalog": "目录",
+ "catalog_failed": "无法加载应用目录。",
"category_curated": "精选",
"categories_label": "分类",
- "categories_nav": "应用分类",
"connect_oauth": "OAuth 登录",
"connect_key": "填写 API key",
"show_more": "显示更多",
diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.json
index eae5c6bcc6..0f77750496 100644
--- a/packages/views/locales/zh-Hant/settings.json
+++ b/packages/views/locales/zh-Hant/settings.json
@@ -2044,10 +2044,10 @@
"no_matches": "沒有符合的應用。",
"unavailable": "此伺服器未提供應用功能。",
"retry": "重試",
- "category_all": "全部",
+ "catalog": "目錄",
+ "catalog_failed": "無法載入應用目錄。",
"category_curated": "精選",
"categories_label": "分類",
- "categories_nav": "應用程式分類",
"connect_oauth": "OAuth 登入",
"connect_key": "填寫 API key",
"show_more": "顯示更多",
diff --git a/server/internal/integrations/composio/service.go b/server/internal/integrations/composio/service.go
index 3a8486f70b..d0702c1817 100644
--- a/server/internal/integrations/composio/service.go
+++ b/server/internal/integrations/composio/service.go
@@ -60,6 +60,11 @@ const defaultStateTTL = 5 * time.Minute
// connect/list requests does not hammer /auth_configs.
const defaultAuthCacheTTL = 5 * time.Minute
+// toolkitCacheTTL bounds how long Composio's toolkit list is reused. Fetching
+// it pages through well over a thousand toolkits, which makes the Apps page
+// wait seconds for its catalog; the list itself changes rarely.
+const toolkitCacheTTL = 5 * time.Minute
+
// maxAuthConfigPages / maxToolkitPages cap the paginated fetch-all loops so a
// pathological or buggy upstream cursor cannot spin forever. At limit=1000 per
// page these cover far more than any real project / catalog.
@@ -141,7 +146,13 @@ type Service struct {
// authCreateMu serializes creating auth configs so two concurrent
// connects for the same new app do not register two configs.
authCreateMu sync.Mutex
- tools toolCache
+ // toolkitCache holds Composio's unfiltered toolkit list. Filtering by
+ // the auth config map still runs on every read, so a newly created auth
+ // config shows without waiting for this cache.
+ toolkitCacheMu sync.Mutex
+ toolkitCache []sdk.Toolkit
+ toolkitCacheExp time.Time
+ tools toolCache
// teamConnectGate decides whether a completed team handshake may write
// its account; see SetTeamConnectGate.
teamConnectGate TeamConnectGate
@@ -635,9 +646,59 @@ func (s *Service) ListToolkits(ctx context.Context) ([]ToolkitView, error) {
return nil, fmt.Errorf("composio: resolve connectable toolkits: %w", err)
}
_, canCreateKeyConfigs := s.sdk.(customAuthCreator)
+ toolkits, err := s.allToolkits(ctx)
+ if err != nil {
+ return nil, err
+ }
out := []ToolkitView{}
seen := make(map[string]struct{})
+ for _, tk := range toolkits {
+ slug := strings.ToLower(strings.TrimSpace(tk.Slug))
+ if slug == "" {
+ continue
+ }
+ if _, dup := seen[slug]; dup {
+ continue
+ }
+ seen[slug] = struct{}{}
+ // Omit toolkits nobody can connect: no enabled auth config, no
+ // Composio-managed app, and no credential a member enters
+ // themselves.
+ existing, hasConfig := connectable[slug]
+ if !hasConfig && len(tk.ComposioManagedAuthSchemes) == 0 &&
+ (!canCreateKeyConfigs || userKeyScheme(tk) == "") {
+ continue
+ }
+ category := tk.PrimaryCategory()
+ out = append(out, ToolkitView{
+ Slug: tk.Slug,
+ Name: tk.Name,
+ LogoURL: toolkitLogoURL(slug, tk.Logo()),
+ Category: category.Name,
+ CategoryID: category.ID,
+ // Every surfaced toolkit is connectable by construction. The
+ // wire field is kept (see ComposioToolkitResponse) for backward
+ // compatibility with older desktop clients that branch on it.
+ Connectable: true,
+ ConnectMethod: connectMethodFor(tk, existing),
+ })
+ }
+
+ return out, nil
+}
+
+// allToolkits returns Composio's toolkit list in usage order, from the cache
+// while it is fresh. Like authConfigMap it fetches under the lock and serves
+// a stale list when a refresh fails. The cached slice is replaced, never
+// mutated, so callers may read it freely.
+func (s *Service) allToolkits(ctx context.Context) ([]sdk.Toolkit, error) {
+ s.toolkitCacheMu.Lock()
+ defer s.toolkitCacheMu.Unlock()
+ if s.toolkitCache != nil && s.now().Before(s.toolkitCacheExp) {
+ return s.toolkitCache, nil
+ }
+ toolkits := []sdk.Toolkit{}
cursor := ""
for page := 0; page < maxToolkitPages; page++ {
resp, err := s.sdk.ListToolkits(ctx, sdk.ListToolkitsRequest{
@@ -646,46 +707,20 @@ func (s *Service) ListToolkits(ctx context.Context) ([]ToolkitView, error) {
SortBy: "usage",
})
if err != nil {
- return nil, fmt.Errorf("composio: list toolkits: %w", err)
- }
- for _, tk := range resp.Items {
- slug := strings.ToLower(strings.TrimSpace(tk.Slug))
- if slug == "" {
- continue
+ if s.toolkitCache != nil {
+ return s.toolkitCache, nil
}
- if _, dup := seen[slug]; dup {
- continue
- }
- seen[slug] = struct{}{}
- // Omit toolkits nobody can connect: no enabled auth config, no
- // Composio-managed app, and no credential a member enters
- // themselves.
- existing, hasConfig := connectable[slug]
- if !hasConfig && len(tk.ComposioManagedAuthSchemes) == 0 &&
- (!canCreateKeyConfigs || userKeyScheme(tk) == "") {
- continue
- }
- category := tk.PrimaryCategory()
- out = append(out, ToolkitView{
- Slug: tk.Slug,
- Name: tk.Name,
- LogoURL: toolkitLogoURL(slug, tk.Logo()),
- Category: category.Name,
- CategoryID: category.ID,
- // Every surfaced toolkit is connectable by construction. The
- // wire field is kept (see ComposioToolkitResponse) for backward
- // compatibility with older desktop clients that branch on it.
- Connectable: true,
- ConnectMethod: connectMethodFor(tk, existing),
- })
+ return nil, fmt.Errorf("composio: list toolkits: %w", err)
}
+ toolkits = append(toolkits, resp.Items...)
if resp.NextCursor == "" {
break
}
cursor = resp.NextCursor
}
-
- return out, nil
+ s.toolkitCache = toolkits
+ s.toolkitCacheExp = s.now().Add(toolkitCacheTTL)
+ return toolkits, nil
}
// authConfigForToolkit returns the chosen auth_config_id for a toolkit slug, or
diff --git a/server/internal/integrations/composio/service_test.go b/server/internal/integrations/composio/service_test.go
index 5a379bb6bc..d36440a6f3 100644
--- a/server/internal/integrations/composio/service_test.go
+++ b/server/internal/integrations/composio/service_test.go
@@ -5,6 +5,7 @@ import (
"errors"
"net/http"
"net/url"
+ "slices"
"strings"
"testing"
"time"
@@ -49,8 +50,9 @@ type fakeSDK struct {
authConfigsSet bool
listAuthErr error
// toolkit catalog (ListToolkits).
- toolkits []sdk.Toolkit
- listToolkitsErr error
+ toolkits []sdk.Toolkit
+ listToolkitsErr error
+ listToolkitsCalls int
}
func (f *fakeSDK) bindTest(t testing.TB) { f.t = t }
@@ -115,6 +117,7 @@ func (f *fakeSDK) ListAuthConfigs(_ context.Context, _ sdk.ListAuthConfigsReques
}
func (f *fakeSDK) ListToolkits(_ context.Context, _ sdk.ListToolkitsRequest) (*sdk.ListToolkitsResponse, error) {
+ f.listToolkitsCalls++
if f.listToolkitsErr != nil {
return nil, f.listToolkitsErr
}
@@ -394,6 +397,60 @@ func TestListToolkits_FiltersToConnectable(t *testing.T) {
}
}
+// TestListToolkits_CachesTheUpstreamList: the toolkit list is fetched once
+// per TTL, a failed refresh serves the last list, and the auth config filter
+// still applies on every read.
+func TestListToolkits_CachesTheUpstreamList(t *testing.T) {
+ t.Parallel()
+ sdkFake := &fakeSDK{
+ authConfigsSet: true,
+ authConfigs: []sdk.AuthConfig{{ID: "ac_notion", Toolkit: sdk.Toolkit{Slug: "notion"}, Status: "ENABLED"}},
+ toolkits: []sdk.Toolkit{{Slug: "notion", Name: "Notion"}, {Slug: "slack", Name: "Slack"}},
+ }
+ svc := newTestService(t, sdkFake, newFakeStore())
+ now := time.Unix(1_700_000_000, 0)
+ svc.now = func() time.Time { return now }
+ slugs := func() []string {
+ t.Helper()
+ tks, err := svc.ListToolkits(context.Background())
+ if err != nil {
+ t.Fatalf("ListToolkits: %v", err)
+ }
+ out := make([]string, 0, len(tks))
+ for _, tk := range tks {
+ out = append(out, tk.Slug)
+ }
+ return out
+ }
+
+ if got := slugs(); !slices.Equal(got, []string{"notion"}) {
+ t.Fatalf("first read = %v, want [notion]", got)
+ }
+ // A new auth config shows at once, from the cached list.
+ sdkFake.authConfigs = append(sdkFake.authConfigs, sdk.AuthConfig{ID: "ac_slack", Toolkit: sdk.Toolkit{Slug: "slack"}, Status: "ENABLED"})
+ svc.invalidateAuthConfigs()
+ if got := slugs(); !slices.Equal(got, []string{"notion", "slack"}) {
+ t.Fatalf("after new auth config = %v, want [notion slack]", got)
+ }
+ if sdkFake.listToolkitsCalls != 1 {
+ t.Fatalf("toolkit fetches within TTL = %d, want 1", sdkFake.listToolkitsCalls)
+ }
+
+ now = now.Add(toolkitCacheTTL + time.Second)
+ sdkFake.listToolkitsErr = errors.New("upstream blip")
+ if got := slugs(); !slices.Equal(got, []string{"notion", "slack"}) {
+ t.Fatalf("stale read = %v, want [notion slack]", got)
+ }
+ sdkFake.listToolkitsErr = nil
+ sdkFake.toolkits = []sdk.Toolkit{{Slug: "notion", Name: "Notion"}}
+ if got := slugs(); !slices.Equal(got, []string{"notion"}) {
+ t.Fatalf("refreshed read = %v, want [notion]", got)
+ }
+ if sdkFake.listToolkitsCalls != 3 {
+ t.Fatalf("toolkit fetches = %d, want 3", sdkFake.listToolkitsCalls)
+ }
+}
+
// TestListToolkits_ResolverErrorReturnsError: an /auth_configs failure is
// surfaced as an error rather than silently degrading to an empty catalog
// (MUL-4009). With filtering in place, masking the error would render as a