feat(webui): add catalog loading skeletons (#6092)

* feat(webui): add catalog loading skeletons

* feat(webui): add MCP tool loading skeleton

* fix(webui): make skill discovery skeletons visible

* refactor(webui): share skeleton status markup
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-07 21:28:53 +08:00
1 parent 7cb396788c
commit f24969d282
25 files changed
+538 -99

No files matched your search

+3 -1
View File
@@ -1232,7 +1232,7 @@ function Shell({
const [runningChatIds, setRunningChatIds] = useState<Set<string>>(() => new Set()); const [runningChatIds, setRunningChatIds] = useState<Set<string>>(() => new Set());
const [updatedChatIds, setUpdatedChatIds] = useState<Set<string>>(readSessionUpdateChatIds); const [updatedChatIds, setUpdatedChatIds] = useState<Set<string>>(readSessionUpdateChatIds);
const [workspaces, setWorkspaces] = useState<WorkspacesPayload | null>(null); const [workspaces, setWorkspaces] = useState<WorkspacesPayload | null>(null);
const skills = useSkills(getToken); const { skills, loading: skillsLoading, error: skillsError } = useSkills(getToken);
const pageVisible = usePageVisibility(); const pageVisible = usePageVisibility();
const [settingsSnapshot, setSettingsSnapshot] = useState<SettingsPayload | null>(null); const [settingsSnapshot, setSettingsSnapshot] = useState<SettingsPayload | null>(null);
const [settingsLoading, setSettingsLoading] = useState(true); const [settingsLoading, setSettingsLoading] = useState(true);
@@ -3092,6 +3092,8 @@ function Shell({
onModelNameChange={onModelNameChange} onModelNameChange={onModelNameChange}
onSettingsChange={setSettingsSnapshot} onSettingsChange={setSettingsSnapshot}
skills={skills} skills={skills}
skillsLoading={skillsLoading}
skillsError={skillsError}
onStartAutomationChat={onStartAutomationChat} onStartAutomationChat={onStartAutomationChat}
titleOverrides={sidebarState.title_overrides} titleOverrides={sidebarState.title_overrides}
sessions={topicSessions} sessions={topicSessions}
@@ -53,6 +53,8 @@ interface SettingsPageProps {
onToggleTheme: () => void; onToggleTheme: () => void;
onBackToChat: () => void; onBackToChat: () => void;
skills: SkillSummary[]; skills: SkillSummary[];
skillsLoading: boolean;
skillsError: boolean;
onStartAutomationChat?: ( onStartAutomationChat?: (
content: string, content: string,
images?: SendAttachment[], images?: SendAttachment[],
@@ -75,6 +77,8 @@ export function SettingsPage({
onToggleTheme, onToggleTheme,
onBackToChat, onBackToChat,
skills, skills,
skillsLoading,
skillsError,
onStartAutomationChat, onStartAutomationChat,
titleOverrides, titleOverrides,
sessions, sessions,
@@ -608,7 +612,7 @@ export function SettingsPage({
</div> </div>
); );
case "skills": case "skills":
return <SkillsCatalogSettings skills={skills} />; return <SkillsCatalogSettings skills={skills} loading={skillsLoading} error={skillsError} />;
case "runtime": case "runtime":
return ( return (
<div className="settings-stack"> <div className="settings-stack">
@@ -18,6 +18,8 @@ interface SettingsViewProps {
onModelNameChange: (modelName: string | null) => void; onModelNameChange: (modelName: string | null) => void;
onSettingsChange?: (payload: SettingsPayload) => void; onSettingsChange?: (payload: SettingsPayload) => void;
skills?: SkillSummary[]; skills?: SkillSummary[];
skillsLoading?: boolean;
skillsError?: boolean;
onStartAutomationChat?: ( onStartAutomationChat?: (
content: string, content: string,
images?: SendAttachment[], images?: SendAttachment[],
@@ -46,6 +48,8 @@ export function SettingsView({
onModelNameChange, onModelNameChange,
onSettingsChange, onSettingsChange,
skills = [], skills = [],
skillsLoading = false,
skillsError = false,
onStartAutomationChat, onStartAutomationChat,
titleOverrides, titleOverrides,
sessions, sessions,
@@ -76,6 +80,8 @@ export function SettingsView({
onToggleTheme={onToggleTheme} onToggleTheme={onToggleTheme}
onBackToChat={onBackToChat} onBackToChat={onBackToChat}
skills={skills} skills={skills}
skillsLoading={skillsLoading}
skillsError={skillsError}
onStartAutomationChat={onStartAutomationChat} onStartAutomationChat={onStartAutomationChat}
titleOverrides={titleOverrides} titleOverrides={titleOverrides}
sessions={sessions} sessions={sessions}
@@ -31,14 +31,19 @@ import { Input } from "@/components/ui/input";
import { SegmentedControl } from "@/components/ui/segmented-control"; import { SegmentedControl } from "@/components/ui/segmented-control";
import { Sheet, SheetContent, SheetDescription, SheetTitle } from "@/components/ui/sheet"; import { Sheet, SheetContent, SheetDescription, SheetTitle } from "@/components/ui/sheet";
import { SkillsMarketplace } from "@/components/settings/SkillsMarketplace"; import { SkillsMarketplace } from "@/components/settings/SkillsMarketplace";
import { CatalogSkeleton } from "@/components/settings/shared/CatalogSkeleton";
import { ToggleButton } from "@/components/settings/ToggleButton"; import { ToggleButton } from "@/components/settings/ToggleButton";
import { deleteSkill, fetchSkillDetail, updateSkillEnabled } from "@/lib/api"; import { deleteSkill, fetchSkillDetail, updateSkillEnabled } from "@/lib/api";
import { notifySkillsChanged } from "@/lib/skill-events"; import { notifySkillsChanged, requestSkillsRefresh } from "@/lib/skill-events";
import type { SkillDetail, SkillSummary } from "@/lib/types"; import type { SkillDetail, SkillSummary } from "@/lib/types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { useClient } from "@/providers/ClientProvider"; import { useClient } from "@/providers/ClientProvider";
export function SkillsCatalogSettings({ skills }: { skills: SkillSummary[] }) { export function SkillsCatalogSettings({ skills, loading = false, error = false }: {
skills: SkillSummary[];
loading?: boolean;
error?: boolean;
}) {
const { t } = useTranslation(); const { t } = useTranslation();
const [selectedSkill, setSelectedSkill] = useState<SkillSummary | null>(null); const [selectedSkill, setSelectedSkill] = useState<SkillSummary | null>(null);
const [view, setView] = useState<"installed" | "discover">("installed"); const [view, setView] = useState<"installed" | "discover">("installed");
@@ -140,14 +145,23 @@ export function SkillsCatalogSettings({ skills }: { skills: SkillSummary[] }) {
value, value,
label: ( label: (
<> <>
{label} <span className="ml-0.5 tabular-nums opacity-65">{count}</span> {label} <span className="ml-0.5 tabular-nums opacity-65">{loading || error ? "—" : count}</span>
</> </>
), ),
}))} }))}
onChange={setInstalledFilter} onChange={setInstalledFilter}
/> />
</div> </div>
{groupedSkills.length ? ( {loading ? (
<CatalogSkeleton label={t("settings.skills.loading")} layout="skills" />
) : error ? (
<div className="space-y-3 px-4 py-8 text-center text-sm">
<p role="alert" className="text-destructive">{t("settings.skills.catalogLoadFailed")}</p>
<Button type="button" variant="outline" size="sm" onClick={requestSkillsRefresh}>
{t("settings.skills.retry")}
</Button>
</div>
) : groupedSkills.length ? (
<div className="space-y-5 px-3 pb-3 pt-2 sm:px-4"> <div className="space-y-5 px-3 pb-3 pt-2 sm:px-4">
{groupedSkills.map((group) => ( {groupedSkills.map((group) => (
<section key={group.key} className="space-y-1"> <section key={group.key} className="space-y-1">
@@ -173,9 +187,7 @@ export function SkillsCatalogSettings({ skills }: { skills: SkillSummary[] }) {
</div> </div>
) : ( ) : (
<div className="px-3 py-12 text-center text-sm text-muted-foreground"> <div className="px-3 py-12 text-center text-sm text-muted-foreground">
{t("settings.skills.noMatching", { {t(skills.length ? "settings.skills.noMatching" : "settings.skills.empty")}
defaultValue: "No matching skills.",
})}
</div> </div>
)} )}
</section> </section>
@@ -9,6 +9,7 @@ import {
} from "lucide-react"; } from "lucide-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { SkeletonStatus } from "@/components/settings/shared/SkeletonStatus";
import { import {
AlertDialog, AlertDialog,
AlertDialogAction, AlertDialogAction,
@@ -125,9 +126,9 @@ export function SkillsMarketplace({
} }
let cancelled = false; let cancelled = false;
setLoading(true);
setError("");
const timer = window.setTimeout(() => { const timer = window.setTimeout(() => {
setLoading(true);
setError("");
searchMarketplaceSkills(getToken(), normalized) searchMarketplaceSkills(getToken(), normalized)
.then((payload) => { .then((payload) => {
if (cancelled) return; if (cancelled) return;
@@ -218,7 +219,7 @@ export function SkillsMarketplace({
defaultValue: "Searching", defaultValue: "Searching",
})} })}
> >
<Loader2 className="h-4 w-4 animate-spin" aria-hidden /> <Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden />
</span> </span>
) : null} ) : null}
</div> </div>
@@ -252,7 +253,7 @@ export function SkillsMarketplace({
) : null} ) : null}
</div> </div>
{trendingLoading ? ( {trendingLoading ? (
<TrendingSkeleton /> <MarketplaceSkeleton ranked />
) : visibleTrending.length ? ( ) : visibleTrending.length ? (
<MarketplaceSkillGroups <MarketplaceSkillGroups
skills={visibleTrending} skills={visibleTrending}
@@ -279,14 +280,18 @@ export function SkillsMarketplace({
</div> </div>
) : ( ) : (
<div className="overflow-hidden rounded-panel bg-settings-surface"> <div className="overflow-hidden rounded-panel bg-settings-surface">
<MarketplaceSkillGroups {loading && !visibleResults.length ? (
skills={visibleResults} <MarketplaceSkeleton />
installedNames={installedNames} ) : (
installing={installing} <MarketplaceSkillGroups
trends={trends} skills={visibleResults}
grouped={provider === "all"} installedNames={installedNames}
onSelect={setSelected} installing={installing}
/> trends={trends}
grouped={provider === "all"}
onSelect={setSelected}
/>
)}
</div> </div>
)} )}
@@ -566,7 +571,7 @@ function MarketplaceSkillRow({
} }
> >
{isInstalling ? ( {isInstalling ? (
<Loader2 className="h-4 w-4 animate-spin" aria-hidden /> <Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden />
) : installed ? ( ) : installed ? (
<Check className="h-4 w-4" aria-hidden /> <Check className="h-4 w-4" aria-hidden />
) : ( ) : (
@@ -669,19 +674,27 @@ function TrendSparkline({ values }: { values?: number[] }) {
); );
} }
function TrendingSkeleton() { function MarketplaceSkeleton({ ranked = false }: { ranked?: boolean }) {
const { t } = useTranslation();
return ( return (
<div className="space-y-1 px-5 pb-3" aria-hidden> <SkeletonStatus
label={t("settings.skills.loading")}
className="space-y-1 px-3 pb-3 sm:px-4"
>
{Array.from({ length: 5 }, (_, index) => ( {Array.from({ length: 5 }, (_, index) => (
<div key={index} className="flex items-center gap-3 py-4"> <div key={index} className="flex min-w-0 items-center gap-2 px-1 py-3.5 sm:gap-3 sm:px-2">
<div className="h-3 w-5 animate-pulse rounded bg-muted" /> {ranked ? <div className="h-3 w-6 shrink-0 rounded bg-muted-foreground/20 sm:w-7" /> : null}
<div className="flex-1 space-y-2"> <div className="min-w-0 flex-1">
<div className="h-3.5 w-48 max-w-[55%] animate-pulse rounded bg-muted" /> <div className="flex h-7 items-center">
<div className="h-3 w-32 max-w-[40%] animate-pulse rounded bg-muted/70" /> <div className="h-3.5 w-48 max-w-[70%] rounded bg-muted-foreground/20" />
</div>
<div className="mt-1 flex h-5 items-center">
<div className="h-3 w-32 max-w-[55%] rounded bg-muted-foreground/20 opacity-60" />
</div>
</div> </div>
<div className="h-8 w-[82px] animate-pulse rounded-full bg-muted sm:w-[92px]" /> <div className="h-9 w-9 shrink-0 rounded-full bg-muted-foreground/20" />
</div> </div>
))} ))}
</div> </SkeletonStatus>
); );
} }
@@ -0,0 +1,40 @@
import { SkeletonStatus } from "@/components/settings/shared/SkeletonStatus";
import { cn } from "@/lib/utils";
export function CatalogSkeleton({ label, layout }: {
label: string;
layout: "apps" | "channels" | "skills";
}) {
const channels = layout === "channels";
const skills = layout === "skills";
const block = "rounded bg-muted-foreground/20";
return (
<SkeletonStatus
label={label}
className={cn(
skills ? "space-y-1 px-3 pb-3 pt-2 sm:px-4" : "grid grid-cols-1 gap-y-1",
layout === "apps" && "gap-x-10 py-3 xl:grid-cols-2",
channels && "gap-x-4 min-[640px]:grid-cols-2",
)}
>
{Array.from({ length: 6 }, (_, index) => (
<div key={index} className={cn(
"flex min-w-0 items-center gap-3",
channels ? "settings-list-row py-2.5" : skills ? "px-2 py-3" : "px-3 py-3",
)}>
<div className={cn(block, "shrink-0", skills
? "h-1.5 w-1.5 rounded-full" : "h-9 w-9 rounded-[10px]")} />
<div className="min-w-0 flex-1 py-1">
<div className={cn(block, "h-3.5", index % 2 ? "w-1/2" : "w-2/3")} />
{!channels ? <div className={cn(block, "mt-2 h-3 w-4/5 opacity-60")} /> : null}
</div>
<div className={cn("flex shrink-0 items-center justify-center", channels && "w-16")}>
<div className={cn(block, channels ? "h-[22px] w-[38px] rounded-full"
: skills ? "hidden h-3 w-20 sm:block" : "h-7 w-7 rounded-full")} />
</div>
</div>
))}
</SkeletonStatus>
);
}
@@ -0,0 +1,18 @@
import type { ReactNode } from "react";
import { cn } from "@/lib/utils";
export function SkeletonStatus({ label, className, children }: {
label: string;
className: string;
children: ReactNode;
}) {
return (
<div role="status" aria-label={label} aria-busy="true">
<span className="sr-only">{label}</span>
<div aria-hidden className={cn("animate-pulse motion-reduce:animate-none", className)}>
{children}
</div>
</div>
);
}
@@ -31,6 +31,8 @@ import {
} from "lucide-react"; } from "lucide-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { CatalogSkeleton } from "@/components/settings/shared/CatalogSkeleton";
import { import {
DismissibleStatusMessage, DismissibleStatusMessage,
RestartRequiredNotice, RestartRequiredNotice,
@@ -218,10 +220,8 @@ export function AppsCatalogSettings({
const focusedApp = cliFocusName const focusedApp = cliFocusName
? (cliApps?.apps ?? []).find((app) => app.name === cliFocusName && app.installed) ? (cliApps?.apps ?? []).find((app) => app.name === cliFocusName && app.installed)
: null; : null;
const loading = const loading = (mcpPresetsLoading && !mcpPresets)
(cliAppsLoading || mcpPresetsLoading) && || ((filter !== "mcp" || Boolean(normalizedQuery)) && cliAppsLoading && !cliApps);
!cliApps &&
!mcpPresets;
const cliAppCount = cliApps?.apps.length ?? 0; const cliAppCount = cliApps?.apps.length ?? 0;
const emptyTitle = normalizedQuery const emptyTitle = normalizedQuery
? tx("settings.apps.empty", "No tools match your search.") ? tx("settings.apps.empty", "No tools match your search.")
@@ -305,15 +305,10 @@ export function AppsCatalogSettings({
: tx("settings.apps.featured", "Tools")} : tx("settings.apps.featured", "Tools")}
</SettingsSectionTitle> </SettingsSectionTitle>
<span className="text-[12px] tabular-nums text-muted-foreground"> <span className="text-[12px] tabular-nums text-muted-foreground">
{items.length} {loading ? "—" : items.length}
</span> </span>
</div> </div>
{loading ? ( {items.length ? (
<div className="flex h-36 items-center justify-center text-sm text-muted-foreground">
<Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden />
{tx("settings.apps.loading", "Loading apps…")}
</div>
) : items.length ? (
<div className="grid grid-cols-1 gap-x-10 gap-y-1 py-3 xl:grid-cols-2"> <div className="grid grid-cols-1 gap-x-10 gap-y-1 py-3 xl:grid-cols-2">
{items.map((item) => {items.map((item) =>
item.kind === "cli" ? ( item.kind === "cli" ? (
@@ -351,7 +346,10 @@ export function AppsCatalogSettings({
), ),
)} )}
</div> </div>
) : ( ) : null}
{loading ? (
<CatalogSkeleton label={tx("settings.apps.loading", "Loading apps…")} layout="apps" />
) : !items.length && !statusIsError ? (
<div className="px-3 py-12 text-center text-sm text-muted-foreground"> <div className="px-3 py-12 text-center text-sm text-muted-foreground">
<p>{emptyTitle}</p> <p>{emptyTitle}</p>
{normalizedQuery ? ( {normalizedQuery ? (
@@ -383,7 +381,7 @@ export function AppsCatalogSettings({
</p> </p>
)} )}
</div> </div>
)} ) : null}
</section> </section>
{filter === "mcp" ? ( {filter === "mcp" ? (
@@ -1,10 +1,11 @@
import { useCallback, useLayoutEffect, useRef, useState } from "react"; import { useCallback, useLayoutEffect, useRef, useState } from "react";
import { Loader2, Search, X } from "lucide-react"; import { Search, X } from "lucide-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { SegmentedControl } from "@/components/ui/segmented-control"; import { SegmentedControl } from "@/components/ui/segmented-control";
import { SETTINGS_SEARCH_INPUT_CLASS } from "@/components/settings/shared/SettingsControls"; import { SETTINGS_SEARCH_INPUT_CLASS } from "@/components/settings/shared/SettingsControls";
import { CatalogSkeleton } from "@/components/settings/shared/CatalogSkeleton";
import type { ChannelFeatureAction } from "@/channel-plugins/types"; import type { ChannelFeatureAction } from "@/channel-plugins/types";
import { ChannelCatalogRow } from "@/components/settings/channels/ChannelCatalogRow"; import { ChannelCatalogRow } from "@/components/settings/channels/ChannelCatalogRow";
import { localizedChannelDisplayName } from "@/components/settings/channels/ChannelIdentity"; import { localizedChannelDisplayName } from "@/components/settings/channels/ChannelIdentity";
@@ -120,10 +121,9 @@ export function ChannelsSettings({
onRestart={onRestart} isRestarting={isRestarting} /> onRestart={onRestart} isRestarting={isRestarting} />
) : null} ) : null}
{loading && !nanobotFeatures ? ( {loading && !nanobotFeatures ? (
<div className="flex h-36 items-center justify-center text-sm text-muted-foreground"> <SettingsGroup>
<Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden /> <CatalogSkeleton label={t("settings.channels.loading")} layout="channels" />
{t("settings.channels.loading")} </SettingsGroup>
</div>
) : visibleChannels.length ? ( ) : visibleChannels.length ? (
channelGroups.map((group) => ( channelGroups.map((group) => (
<section <section
@@ -151,11 +151,11 @@ export function ChannelsSettings({
</SettingsGroup> </SettingsGroup>
</section> </section>
)) ))
) : ( ) : !error ? (
<div className="px-3 py-12 text-center text-sm text-muted-foreground"> <div className="px-3 py-12 text-center text-sm text-muted-foreground">
{t(channels.length ? "settings.channels.noResults" : "settings.channels.empty")} {t(channels.length ? "settings.channels.noResults" : "settings.channels.empty")}
</div> </div>
)} ) : null}
<Dialog open={Boolean(selectedChannel)} onOpenChange={(open) => { if (!open) requestChannelClose(); }}> <Dialog open={Boolean(selectedChannel)} onOpenChange={(open) => { if (!open) requestChannelClose(); }}>
<DialogContent ref={dialogRef} showCloseButton={false} aria-describedby={undefined} className="max-h-[85dvh] w-[min(calc(100vw-2rem),40rem)] max-w-none overflow-hidden p-0 outline-none" <DialogContent ref={dialogRef} showCloseButton={false} aria-describedby={undefined} className="max-h-[85dvh] w-[min(calc(100vw-2rem),40rem)] max-w-none overflow-hidden p-0 outline-none"
onOpenAutoFocus={(event) => { onOpenAutoFocus={(event) => {
@@ -5,6 +5,7 @@ import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { Check, ExternalLink, Loader2, RotateCcw, Search, Server, Trash2, X } from "lucide-react"; import { Check, ExternalLink, Loader2, RotateCcw, Search, Server, Trash2, X } from "lucide-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { SkeletonStatus } from "@/components/settings/shared/SkeletonStatus";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
Dialog, Dialog,
@@ -363,6 +364,29 @@ function ToolsPanel({
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback }); const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
if (!toolNames.length && testBusy) {
return (
<SkeletonStatus label={tx("settings.mcp.loadingTools", "Loading tools…")} className="space-y-4">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
<div className="h-10 min-w-0 rounded-full bg-muted-foreground/20 sm:flex-1" />
<div className="flex h-8 items-center justify-between gap-4 sm:justify-end">
<div className="mr-auto h-3 w-20 rounded bg-muted-foreground/20 sm:mr-1" />
<div className="h-3 w-6 rounded bg-muted-foreground/20" />
<div className="h-3 w-9 rounded bg-muted-foreground/20" />
</div>
</div>
<div className="overflow-hidden rounded-floating border border-border/55">
{Array.from({ length: 6 }, (_, index) => (
<div key={index} className="flex min-h-11 items-center gap-3 border-b border-border/45 px-3.5 py-2.5 last:border-b-0">
<div className="h-5 w-5 shrink-0 rounded-compact bg-muted-foreground/20" />
<div className={cn("h-3.5 max-w-[70%] rounded bg-muted-foreground/20", index % 2 ? "w-40" : "w-52")} />
</div>
))}
</div>
</SkeletonStatus>
);
}
if (!toolNames.length) { if (!toolNames.length) {
return ( return (
<div <div
@@ -373,39 +397,31 @@ function ToolsPanel({
> >
<div className="flex min-w-0 items-center gap-3"> <div className="flex min-w-0 items-center gap-3">
<div className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-background text-muted-foreground"> <div className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-background text-muted-foreground">
{testBusy ? ( <AppActionsIcon className="h-4 w-4" aria-hidden />
<Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden />
) : (
<AppActionsIcon className="h-4 w-4" aria-hidden />
)}
</div> </div>
<p <p
role={preset.error ? "alert" : undefined} role={preset.error ? "alert" : undefined}
className={cn("min-w-0 text-[14px] font-medium", preset.error ? "text-destructive" : "text-foreground")} className={cn("min-w-0 text-[14px] font-medium", preset.error ? "text-destructive" : "text-foreground")}
> >
{testBusy {preset.error || tx("settings.mcp.noToolsAvailable", "No tools available")}
? tx("common.loading", "Loading…")
: preset.error || tx("settings.mcp.noToolsAvailable", "No tools available")}
</p> </p>
</div> </div>
{!testBusy ? ( <Button
<Button type="button"
type="button" size="sm"
size="sm" variant="outline"
variant="outline" onClick={configuredInstalled ? onTest : onOpenConnection}
onClick={configuredInstalled ? onTest : onOpenConnection} className="h-9 shrink-0 rounded-full px-4 text-[13px] font-semibold"
className="h-9 shrink-0 rounded-full px-4 text-[13px] font-semibold" >
> {configuredInstalled ? (
{configuredInstalled ? ( <RotateCcw className="mr-1.5 h-3.5 w-3.5" aria-hidden />
<RotateCcw className="mr-1.5 h-3.5 w-3.5" aria-hidden /> ) : (
) : ( <Server className="mr-1.5 h-3.5 w-3.5" aria-hidden />
<Server className="mr-1.5 h-3.5 w-3.5" aria-hidden /> )}
)} {configuredInstalled
{configuredInstalled ? tx("settings.mcp.reloadTools", "Reload tools")
? tx("settings.mcp.reloadTools", "Reload tools") : tx("settings.mcp.setup", "Connect")}
: tx("settings.mcp.setup", "Connect")} </Button>
</Button>
) : null}
</div> </div>
); );
} }
+19 -6
View File
@@ -4,8 +4,14 @@ import { fetchSkills } from "@/lib/api";
import { isSkillsPayload, SKILLS_CHANGED_EVENT, SKILLS_REFRESH_EVENT } from "@/lib/skill-events"; import { isSkillsPayload, SKILLS_CHANGED_EVENT, SKILLS_REFRESH_EVENT } from "@/lib/skill-events";
import type { SkillSummary } from "@/lib/types"; import type { SkillSummary } from "@/lib/types";
export function useSkills(getToken: () => string): SkillSummary[] { type SkillsState =
const [skills, setSkills] = useState<SkillSummary[]>([]); | { status: "loading" | "error"; skills: null }
| { status: "ready"; skills: SkillSummary[] };
const EMPTY_SKILLS: SkillSummary[] = [];
export function useSkills(getToken: () => string) {
const [state, setState] = useState<SkillsState>({ status: "loading", skills: null });
useEffect(() => { useEffect(() => {
let cancelled = false; let cancelled = false;
@@ -21,13 +27,16 @@ export function useSkills(getToken: () => string): SkillSummary[] {
} }
refreshing = true; refreshing = true;
refreshQueued = false; refreshQueued = false;
setState((current) => current.skills === null ? { status: "loading", skills: null } : current);
const version = payloadVersion; const version = payloadVersion;
fetchSkills(getToken()) fetchSkills(getToken())
.then(({ skills: nextSkills }) => { .then(({ skills: nextSkills }) => {
if (!cancelled && version === payloadVersion) setSkills(nextSkills); if (!cancelled && version === payloadVersion) setState({ status: "ready", skills: nextSkills });
}) })
.catch(() => { .catch(() => {
// Keep the last known list usable during transient refresh failures. if (!cancelled && version === payloadVersion) {
setState((current) => current.skills === null ? { status: "error", skills: null } : current);
}
}) })
.finally(() => { .finally(() => {
refreshing = false; refreshing = false;
@@ -38,7 +47,7 @@ export function useSkills(getToken: () => string): SkillSummary[] {
const payload = (event as CustomEvent<unknown>).detail; const payload = (event as CustomEvent<unknown>).detail;
if (!cancelled && isSkillsPayload(payload)) { if (!cancelled && isSkillsPayload(payload)) {
payloadVersion += 1; payloadVersion += 1;
setSkills(payload.skills); setState({ status: "ready", skills: payload.skills });
} }
}; };
@@ -52,5 +61,9 @@ export function useSkills(getToken: () => string): SkillSummary[] {
}; };
}, [getToken]); }, [getToken]);
return skills; return {
skills: state.skills ?? EMPTY_SKILLS,
loading: state.status === "loading",
error: state.status === "error",
};
} }
+4
View File
@@ -980,6 +980,7 @@
"endpointLabel": "Endpoint", "endpointLabel": "Endpoint",
"toolPreview": "Tools", "toolPreview": "Tools",
"noToolsAvailable": "No tools available", "noToolsAvailable": "No tools available",
"loadingTools": "Loading tools…",
"searchTools": "Search tools", "searchTools": "Search tools",
"searchToolsPlaceholder": "Search tools", "searchToolsPlaceholder": "Search tools",
"selectedCount": "{{count}} enabled", "selectedCount": "{{count}} enabled",
@@ -1627,6 +1628,9 @@
"filterEnabled": "Enabled", "filterEnabled": "Enabled",
"filterDisabled": "Disabled", "filterDisabled": "Disabled",
"noMatching": "No matching skills.", "noMatching": "No matching skills.",
"loading": "Loading skills…",
"catalogLoadFailed": "Could not load skills.",
"retry": "Retry",
"statusDisabled": "Disabled", "statusDisabled": "Disabled",
"statusEnabled": "Enabled", "statusEnabled": "Enabled",
"statusNeedsSetup": "Needs setup", "statusNeedsSetup": "Needs setup",
+4
View File
@@ -1005,6 +1005,7 @@
"endpointLabel": "URL", "endpointLabel": "URL",
"toolPreview": "Herramientas", "toolPreview": "Herramientas",
"noToolsAvailable": "No hay herramientas disponibles", "noToolsAvailable": "No hay herramientas disponibles",
"loadingTools": "Cargando herramientas…",
"searchTools": "Buscar herramientas", "searchTools": "Buscar herramientas",
"searchToolsPlaceholder": "Buscar herramientas", "searchToolsPlaceholder": "Buscar herramientas",
"selectedCount": "{{count}} activadas", "selectedCount": "{{count}} activadas",
@@ -1428,6 +1429,9 @@
"filterEnabled": "Activadas", "filterEnabled": "Activadas",
"filterDisabled": "Desactivadas", "filterDisabled": "Desactivadas",
"noMatching": "No hay habilidades coincidentes.", "noMatching": "No hay habilidades coincidentes.",
"loading": "Cargando habilidades…",
"catalogLoadFailed": "No se pudieron cargar las habilidades.",
"retry": "Reintentar",
"statusDisabled": "Desactivada", "statusDisabled": "Desactivada",
"statusEnabled": "Activada", "statusEnabled": "Activada",
"statusNeedsSetup": "Requiere configuración", "statusNeedsSetup": "Requiere configuración",
+4
View File
@@ -1005,6 +1005,7 @@
"endpointLabel": "URL", "endpointLabel": "URL",
"toolPreview": "Outils", "toolPreview": "Outils",
"noToolsAvailable": "Aucun outil disponible", "noToolsAvailable": "Aucun outil disponible",
"loadingTools": "Chargement des outils…",
"searchTools": "Rechercher des outils", "searchTools": "Rechercher des outils",
"searchToolsPlaceholder": "Rechercher des outils", "searchToolsPlaceholder": "Rechercher des outils",
"selectedCount": "{{count}} activés", "selectedCount": "{{count}} activés",
@@ -1427,6 +1428,9 @@
"filterEnabled": "Activées", "filterEnabled": "Activées",
"filterDisabled": "Désactivées", "filterDisabled": "Désactivées",
"noMatching": "Aucune compétence correspondante.", "noMatching": "Aucune compétence correspondante.",
"loading": "Chargement des compétences…",
"catalogLoadFailed": "Impossible de charger les compétences.",
"retry": "Réessayer",
"statusDisabled": "Désactivée", "statusDisabled": "Désactivée",
"statusEnabled": "Activée", "statusEnabled": "Activée",
"statusNeedsSetup": "Configuration requise", "statusNeedsSetup": "Configuration requise",
+4
View File
@@ -1005,6 +1005,7 @@
"endpointLabel": "Endpoint", "endpointLabel": "Endpoint",
"toolPreview": "Alat", "toolPreview": "Alat",
"noToolsAvailable": "Tidak ada alat yang tersedia", "noToolsAvailable": "Tidak ada alat yang tersedia",
"loadingTools": "Memuat alat…",
"searchTools": "Cari alat", "searchTools": "Cari alat",
"searchToolsPlaceholder": "Cari alat", "searchToolsPlaceholder": "Cari alat",
"selectedCount": "{{count}} aktif", "selectedCount": "{{count}} aktif",
@@ -1427,6 +1428,9 @@
"filterEnabled": "Aktif", "filterEnabled": "Aktif",
"filterDisabled": "Nonaktif", "filterDisabled": "Nonaktif",
"noMatching": "Tidak ada keterampilan yang cocok.", "noMatching": "Tidak ada keterampilan yang cocok.",
"loading": "Memuat keterampilan…",
"catalogLoadFailed": "Tidak dapat memuat keterampilan.",
"retry": "Coba lagi",
"statusDisabled": "Nonaktif", "statusDisabled": "Nonaktif",
"statusEnabled": "Aktif", "statusEnabled": "Aktif",
"statusNeedsSetup": "Perlu penyiapan", "statusNeedsSetup": "Perlu penyiapan",
+4
View File
@@ -1005,6 +1005,7 @@
"endpointLabel": "エンドポイント", "endpointLabel": "エンドポイント",
"toolPreview": "ツール", "toolPreview": "ツール",
"noToolsAvailable": "利用可能なツールはありません", "noToolsAvailable": "利用可能なツールはありません",
"loadingTools": "ツールを読み込み中…",
"searchTools": "ツールを検索", "searchTools": "ツールを検索",
"searchToolsPlaceholder": "ツールを検索", "searchToolsPlaceholder": "ツールを検索",
"selectedCount": "{{count}} 件有効", "selectedCount": "{{count}} 件有効",
@@ -1427,6 +1428,9 @@
"filterEnabled": "有効", "filterEnabled": "有効",
"filterDisabled": "無効", "filterDisabled": "無効",
"noMatching": "一致するスキルがありません。", "noMatching": "一致するスキルがありません。",
"loading": "スキルを読み込み中…",
"catalogLoadFailed": "スキルを読み込めませんでした。",
"retry": "再試行",
"statusDisabled": "無効", "statusDisabled": "無効",
"statusEnabled": "有効", "statusEnabled": "有効",
"statusNeedsSetup": "セットアップが必要", "statusNeedsSetup": "セットアップが必要",
+4
View File
@@ -1005,6 +1005,7 @@
"endpointLabel": "엔드포인트", "endpointLabel": "엔드포인트",
"toolPreview": "도구", "toolPreview": "도구",
"noToolsAvailable": "사용 가능한 도구가 없습니다", "noToolsAvailable": "사용 가능한 도구가 없습니다",
"loadingTools": "도구 로딩 중…",
"searchTools": "도구 검색", "searchTools": "도구 검색",
"searchToolsPlaceholder": "도구 검색", "searchToolsPlaceholder": "도구 검색",
"selectedCount": "{{count}}개 활성화", "selectedCount": "{{count}}개 활성화",
@@ -1427,6 +1428,9 @@
"filterEnabled": "활성화됨", "filterEnabled": "활성화됨",
"filterDisabled": "비활성화됨", "filterDisabled": "비활성화됨",
"noMatching": "일치하는 스킬이 없습니다.", "noMatching": "일치하는 스킬이 없습니다.",
"loading": "스킬 불러오는 중…",
"catalogLoadFailed": "스킬을 불러올 수 없습니다.",
"retry": "다시 시도",
"statusDisabled": "비활성화됨", "statusDisabled": "비활성화됨",
"statusEnabled": "활성화됨", "statusEnabled": "활성화됨",
"statusNeedsSetup": "설정 필요", "statusNeedsSetup": "설정 필요",
+4
View File
@@ -796,6 +796,7 @@
"endpointLabel": "Endpoint", "endpointLabel": "Endpoint",
"toolPreview": "Ferramentas", "toolPreview": "Ferramentas",
"noToolsAvailable": "Nenhuma ferramenta disponível", "noToolsAvailable": "Nenhuma ferramenta disponível",
"loadingTools": "Carregando ferramentas…",
"searchTools": "Buscar ferramentas", "searchTools": "Buscar ferramentas",
"searchToolsPlaceholder": "Buscar ferramentas", "searchToolsPlaceholder": "Buscar ferramentas",
"selectedCount": "{{count}} ativadas", "selectedCount": "{{count}} ativadas",
@@ -1441,6 +1442,9 @@
"filterEnabled": "Ativadas", "filterEnabled": "Ativadas",
"filterDisabled": "Desativadas", "filterDisabled": "Desativadas",
"noMatching": "Nenhuma habilidade correspondente.", "noMatching": "Nenhuma habilidade correspondente.",
"loading": "Carregando habilidades…",
"catalogLoadFailed": "Não foi possível carregar as habilidades.",
"retry": "Tentar novamente",
"statusDisabled": "Desativada", "statusDisabled": "Desativada",
"statusEnabled": "Ativada", "statusEnabled": "Ativada",
"statusNeedsSetup": "Requer configuração", "statusNeedsSetup": "Requer configuração",
+4
View File
@@ -1005,6 +1005,7 @@
"endpointLabel": "URL kết nối", "endpointLabel": "URL kết nối",
"toolPreview": "Công cụ", "toolPreview": "Công cụ",
"noToolsAvailable": "Không có công cụ khả dụng", "noToolsAvailable": "Không có công cụ khả dụng",
"loadingTools": "Đang tải công cụ…",
"searchTools": "Tìm công cụ", "searchTools": "Tìm công cụ",
"searchToolsPlaceholder": "Tìm công cụ", "searchToolsPlaceholder": "Tìm công cụ",
"selectedCount": "Đã bật {{count}}", "selectedCount": "Đã bật {{count}}",
@@ -1427,6 +1428,9 @@
"filterEnabled": "Đã bật", "filterEnabled": "Đã bật",
"filterDisabled": "Đã tắt", "filterDisabled": "Đã tắt",
"noMatching": "Không có kỹ năng phù hợp.", "noMatching": "Không có kỹ năng phù hợp.",
"loading": "Đang tải kỹ năng…",
"catalogLoadFailed": "Không thể tải kỹ năng.",
"retry": "Thử lại",
"statusDisabled": "Đã tắt", "statusDisabled": "Đã tắt",
"statusEnabled": "Đã bật", "statusEnabled": "Đã bật",
"statusNeedsSetup": "Cần thiết lập", "statusNeedsSetup": "Cần thiết lập",
+4
View File
@@ -982,6 +982,7 @@
"endpointLabel": "连接地址", "endpointLabel": "连接地址",
"toolPreview": "工具", "toolPreview": "工具",
"noToolsAvailable": "没有可用工具", "noToolsAvailable": "没有可用工具",
"loadingTools": "正在加载工具…",
"searchTools": "搜索工具", "searchTools": "搜索工具",
"searchToolsPlaceholder": "搜索工具", "searchToolsPlaceholder": "搜索工具",
"selectedCount": "已启用 {{count}} 个", "selectedCount": "已启用 {{count}} 个",
@@ -1627,6 +1628,9 @@
"filterEnabled": "已启用", "filterEnabled": "已启用",
"filterDisabled": "已停用", "filterDisabled": "已停用",
"noMatching": "没有匹配的技能。", "noMatching": "没有匹配的技能。",
"loading": "技能加载中…",
"catalogLoadFailed": "无法加载技能。",
"retry": "重试",
"statusDisabled": "已停用", "statusDisabled": "已停用",
"statusEnabled": "已启用", "statusEnabled": "已启用",
"statusNeedsSetup": "需要设置", "statusNeedsSetup": "需要设置",
+4
View File
@@ -1005,6 +1005,7 @@
"endpointLabel": "端點", "endpointLabel": "端點",
"toolPreview": "工具", "toolPreview": "工具",
"noToolsAvailable": "沒有可用工具", "noToolsAvailable": "沒有可用工具",
"loadingTools": "正在載入工具…",
"searchTools": "搜尋工具", "searchTools": "搜尋工具",
"searchToolsPlaceholder": "搜尋工具", "searchToolsPlaceholder": "搜尋工具",
"selectedCount": "已啟用 {{count}} 個", "selectedCount": "已啟用 {{count}} 個",
@@ -1427,6 +1428,9 @@
"filterEnabled": "已啟用", "filterEnabled": "已啟用",
"filterDisabled": "已停用", "filterDisabled": "已停用",
"noMatching": "沒有相符的技能。", "noMatching": "沒有相符的技能。",
"loading": "正在載入技能…",
"catalogLoadFailed": "無法載入技能。",
"retry": "重試",
"statusDisabled": "已停用", "statusDisabled": "已停用",
"statusEnabled": "已啟用", "statusEnabled": "已啟用",
"statusNeedsSetup": "需要設定", "statusNeedsSetup": "需要設定",
+1 -1
View File
@@ -1490,7 +1490,7 @@ describe("App layout", () => {
screen.queryByRole("button", { name: "Open details for custom-skill" }), screen.queryByRole("button", { name: "Open details for custom-skill" }),
).not.toBeInTheDocument(); ).not.toBeInTheDocument();
}); });
expect(screen.getByText("No matching skills.")).toBeInTheDocument(); expect(screen.getByText("No skills are available.")).toBeInTheDocument();
}); });
it("discovers and installs a skill from skills.sh", async () => { it("discovers and installs a skill from skills.sh", async () => {
+124
View File
@@ -0,0 +1,124 @@
import { act, fireEvent, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import type { CliAppInfo, McpPresetInfo, NanobotFeatureInfo } from "@/lib/types";
import {
installSettingsViewTestHooks,
jsonResponse,
renderSettingsView,
settingsPayload,
} from "@/tests/settings-test-utils";
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((res) => { resolve = res; });
return { promise, resolve };
}
const app: CliAppInfo = {
name: "anygen", display_name: "AnyGen", category: "generation",
description: "Generate documents.", requires: "ANYGEN_API_KEY", source: "harness",
entry_point: "cli-anything-anygen", install_supported: true, installed: true,
available: true, status: "installed", skill_installed: true,
};
const plugin: McpPresetInfo = {
name: "plugin-computer-use", display_name: "Computer Use", category: "Plugin",
description: "Control the desktop.", requires: "accessibility", transport: "stdio",
install_supported: false, installed: true, configured: true, enabled: false,
available: false, status: "disabled", required_fields: [], source: "agent-plugin",
docs_url: "", note: "", connection_summary: "",
};
const channel: NanobotFeatureInfo = {
name: "discord", display_name: "Discord", type: "channel", installed: true,
configured: false, enabled: false, ready: false, status: "not_enabled",
install_supported: true, requires_restart: false,
};
describe("catalog loading", () => {
installSettingsViewTestHooks();
it("keeps loaded Apps rows visible while waiting for Agent Plugins", async () => {
const cli = deferred<Response>();
const mcp = deferred<Response>();
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
const url = String(input);
if (url === "/api/settings/cli-apps") return cli.promise;
if (url === "/api/settings/mcp-presets") return mcp.promise;
return Promise.resolve(jsonResponse(settingsPayload()));
}));
renderSettingsView({ initialSettings: settingsPayload() });
expect(screen.getByRole("status", { name: "Loading apps…" })).toHaveAttribute("aria-busy", "true");
await act(async () => { cli.resolve(jsonResponse({ apps: [app], installed_count: 1 })); });
expect(screen.getByRole("heading", { name: "AnyGen" })).toBeInTheDocument();
expect(screen.getByRole("status", { name: "Loading apps…" })).toBeInTheDocument();
await act(async () => { mcp.resolve(jsonResponse({ presets: [plugin], installed_count: 1 })); });
expect(screen.getByRole("heading", { name: "Computer Use" })).toBeInTheDocument();
expect(screen.queryByRole("status", { name: "Loading apps…" })).not.toBeInTheDocument();
});
it("finishes an empty MCP category independently but waits for Apps when searching", async () => {
const cli = deferred<Response>();
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
const url = String(input);
if (url === "/api/settings/cli-apps") return cli.promise;
if (url === "/api/settings/mcp-presets") {
return Promise.resolve(jsonResponse({ presets: [], installed_count: 0 }));
}
return Promise.resolve(jsonResponse(settingsPayload()));
}));
renderSettingsView({ initialSettings: settingsPayload() });
await act(async () => {});
expect(screen.getByRole("status", { name: "Loading apps…" })).toBeInTheDocument();
expect(screen.queryByText("No apps available.")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "MCP" }));
expect(screen.getByText("No MCP tools available.")).toBeInTheDocument();
expect(screen.queryByRole("status", { name: "Loading apps…" })).not.toBeInTheDocument();
fireEvent.change(screen.getByPlaceholderText("Search tools"), { target: { value: "AnyGen" } });
expect(screen.getByRole("status", { name: "Loading apps…" })).toBeInTheDocument();
expect(screen.queryByText("No tools match your search.")).not.toBeInTheDocument();
await act(async () => { cli.resolve(jsonResponse({ apps: [app], installed_count: 1 })); });
expect(screen.getByRole("heading", { name: "AnyGen" })).toBeInTheDocument();
expect(screen.queryByRole("status", { name: "Loading apps…" })).not.toBeInTheDocument();
});
it.each(["apps", "channels"] as const)("reports a failed %s read without claiming an empty catalog", async (section) => {
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url === "/api/settings") return jsonResponse(settingsPayload());
if (url === "/api/settings/mcp-presets") return jsonResponse({ presets: [], installed_count: 0 });
throw new Error("Catalog offline");
}));
renderSettingsView({ initialSection: section, initialSettings: settingsPayload() });
expect(await screen.findByText("Catalog offline")).toBeInTheDocument();
expect(screen.queryByRole("status", { name: /Loading (apps|channels)/ })).not.toBeInTheDocument();
expect(screen.queryByText("No apps available.")).not.toBeInTheDocument();
expect(screen.queryByText("No channels match this filter.")).not.toBeInTheDocument();
});
it("shows Channels placeholders until the first response and preserves rows on a focus refresh", async () => {
const initial = deferred<Response>();
const refresh = deferred<Response>();
const fetchFeatures = vi.fn().mockReturnValueOnce(initial.promise).mockReturnValue(refresh.promise);
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => (
String(input) === "/api/settings/nanobot-features"
? fetchFeatures() : Promise.resolve(jsonResponse(settingsPayload()))
)));
renderSettingsView({ initialSection: "channels", initialSettings: settingsPayload() });
expect(screen.getByRole("status", { name: "Loading channels…" })).toHaveAttribute("aria-busy", "true");
fireEvent.change(screen.getByRole("searchbox", { name: "Search channels" }), {
target: { value: "discord" },
});
await act(async () => { initial.resolve(jsonResponse({ features: [channel], enabled_count: 0 })); });
expect(screen.getByRole("button", { name: "View Discord settings" })).toBeInTheDocument();
expect(screen.queryByRole("status", { name: "Loading channels…" })).not.toBeInTheDocument();
act(() => { window.dispatchEvent(new Event("focus")); });
expect(fetchFeatures).toHaveBeenCalledTimes(2);
expect(screen.getByRole("button", { name: "View Discord settings" })).toBeInTheDocument();
expect(screen.queryByRole("status", { name: "Loading channels…" })).not.toBeInTheDocument();
await act(async () => { refresh.resolve(jsonResponse({ features: [], enabled_count: 0 })); });
expect(screen.getByText("No channels match this filter.")).toBeInTheDocument();
});
});
+61 -3
View File
@@ -98,6 +98,56 @@ describe("McpManagementDialog", () => {
fireEvent.click(within(dialog).getByRole("button", { name: "Reload tools" })); fireEvent.click(within(dialog).getByRole("button", { name: "Reload tools" }));
expect(onAction).toHaveBeenCalledTimes(2); expect(onAction).toHaveBeenCalledTimes(2);
}); });
it("shows a skeleton for the first inspection and keeps tools and draft selections during reinspection", () => {
const emptyPreset = { ...connectedPreset, tool_count: 0, tool_names: [] };
const { updateDialog } = renderDialog({
initialTab: "tools",
preset: emptyPreset,
actionKey: "test:docs",
});
const dialog = screen.getByRole("dialog", { name: "Docs MCP" });
expect(within(dialog).getByRole("status", { name: "Loading tools…" })).toHaveAttribute("aria-busy", "true");
expect(within(dialog).queryByRole("textbox", { name: "Search tools" })).not.toBeInTheDocument();
expect(within(dialog).queryByText("No tools available")).not.toBeInTheDocument();
updateDialog(connectedPreset);
expect(within(dialog).queryByRole("status", { name: "Loading tools…" })).not.toBeInTheDocument();
const searchDocs = within(dialog).getByRole("checkbox", { name: /search_docs/ });
fireEvent.click(searchDocs);
expect(searchDocs).not.toBeChecked();
updateDialog({ ...connectedPreset, tool_names: [] }, "test:docs");
expect(within(dialog).queryByRole("status", { name: "Loading tools…" })).not.toBeInTheDocument();
expect(within(dialog).getByRole("checkbox", { name: /search_docs/ })).not.toBeChecked();
expect(within(dialog).getByRole("checkbox", { name: /write_note/ })).toBeChecked();
expect(within(dialog).getByText("2 enabled")).toBeInTheDocument();
expect(within(dialog).getByRole("button", { name: "Save changes" })).toBeEnabled();
});
it.each([
{ error: undefined, message: "No tools available" },
{ error: "Inspection failed", message: "Inspection failed" },
])("offers recovery when inspection finishes with $message", ({ error, message }) => {
const onAction = vi.fn();
const emptyPreset = { ...connectedPreset, tool_count: 0, tool_names: [], error };
const { updateDialog } = renderDialog({
initialTab: "tools",
preset: emptyPreset,
actionKey: "test:docs",
onAction,
});
const dialog = screen.getByRole("dialog", { name: "Docs MCP" });
expect(within(dialog).getByRole("status", { name: "Loading tools…" })).toBeInTheDocument();
updateDialog(emptyPreset);
expect(within(dialog).queryByRole("status", { name: "Loading tools…" })).not.toBeInTheDocument();
expect(within(dialog).getByText(message)).toBeInTheDocument();
if (error) expect(within(dialog).getByRole("alert")).toHaveTextContent(error);
fireEvent.click(within(dialog).getByRole("button", { name: "Reload tools" }));
expect(onAction).toHaveBeenLastCalledWith("test", "docs");
});
}); });
function renderDialog({ function renderDialog({
@@ -105,19 +155,21 @@ function renderDialog({
onAction = vi.fn(), onAction = vi.fn(),
onToolsChange = vi.fn(), onToolsChange = vi.fn(),
preset = connectedPreset, preset = connectedPreset,
actionKey = null,
}: { }: {
initialTab: McpManagementTab; initialTab: McpManagementTab;
onAction?: ReturnType<typeof vi.fn>; onAction?: ReturnType<typeof vi.fn>;
onToolsChange?: ReturnType<typeof vi.fn>; onToolsChange?: ReturnType<typeof vi.fn>;
preset?: McpPresetInfo; preset?: McpPresetInfo;
actionKey?: string | null;
}) { }) {
function Harness() { function Harness({ preset, actionKey }: { preset: McpPresetInfo; actionKey: string | null }) {
const [tab, setTab] = useState(initialTab); const [tab, setTab] = useState(initialTab);
return ( return (
<McpManagementDialog <McpManagementDialog
preset={preset} preset={preset}
values={{}} values={{}}
actionKey={null} actionKey={actionKey}
statusLabel="Connected" statusLabel="Connected"
statusTone="success" statusTone="success"
tab={tab} tab={tab}
@@ -131,5 +183,11 @@ function renderDialog({
/> />
); );
} }
return render(<Harness />); const view = render(<Harness preset={preset} actionKey={actionKey} />);
return {
...view,
updateDialog: (nextPreset: McpPresetInfo, nextActionKey: string | null = null) => {
view.rerender(<Harness preset={nextPreset} actionKey={nextActionKey} />);
},
};
} }
+107 -12
View File
@@ -2,6 +2,7 @@ import { act, fireEvent, render, renderHook, screen } from "@testing-library/rea
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SkillsMarketplace } from "@/components/settings/SkillsMarketplace"; import { SkillsMarketplace } from "@/components/settings/SkillsMarketplace";
import { SkillsCatalogSettings } from "@/components/settings/SkillsCatalogSettings";
import { ThreadComposer } from "@/components/thread/ThreadComposer"; import { ThreadComposer } from "@/components/thread/ThreadComposer";
import { import {
fetchSkills, fetchSkills,
@@ -38,6 +39,52 @@ function marketplace(token: string) {
} }
describe("useSkills", () => { describe("useSkills", () => {
it("shows loading, retries a failed first read, and preserves an empty catalog during refresh", async () => {
let rejectInitial!: (error: Error) => void;
let resolveRetry!: (value: Awaited<ReturnType<typeof fetchSkills>>) => void;
let resolveRefresh!: (value: Awaited<ReturnType<typeof fetchSkills>>) => void;
vi.mocked(fetchSkills).mockReset()
.mockImplementationOnce(() => new Promise((_resolve, reject) => { rejectInitial = reject; }))
.mockImplementationOnce(() => new Promise((resolve) => { resolveRetry = resolve; }))
.mockImplementationOnce(() => new Promise((resolve) => { resolveRefresh = resolve; }));
const getToken = () => "tok";
function Catalog() {
const state = useSkills(getToken);
return <SkillsCatalogSettings {...state} />;
}
render(<ClientProvider client={client} token="tok"><Catalog /></ClientProvider>);
expect(screen.getByRole("status", { name: "Loading skills…" })).toHaveAttribute("aria-busy", "true");
fireEvent.change(screen.getByRole("textbox", { name: "Search installed skills" }), {
target: { value: "cron" },
});
await act(async () => { rejectInitial(new Error("Offline")); });
expect(screen.getByRole("alert")).toHaveTextContent("Could not load skills.");
expect(screen.queryByText("No skills are available.")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
expect(screen.getByRole("status", { name: "Loading skills…" })).toBeInTheDocument();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
await act(async () => { resolveRetry({ skills: [] }); });
expect(screen.getByText("No skills are available.")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "All 0" })).toBeInTheDocument();
act(() => { requestSkillsRefresh(); });
expect(screen.getByText("No skills are available.")).toBeInTheDocument();
expect(screen.queryByRole("status", { name: "Loading skills…" })).not.toBeInTheDocument();
await act(async () => {
resolveRefresh({ skills: [{
name: "weather", description: "Get the weather.", source: "builtin", available: true,
}] });
});
expect(screen.getByText("No matching skills.")).toBeInTheDocument();
fireEvent.change(screen.getByRole("textbox", { name: "Search installed skills" }), {
target: { value: "" },
});
expect(screen.getByRole("button", { name: "Open details for weather" })).toBeInTheDocument();
expect(fetchSkills).toHaveBeenCalledTimes(3);
});
it("discovers skills added after page load when opening the $ menu, not on each keystroke", async () => { it("discovers skills added after page load when opening the $ menu, not on each keystroke", async () => {
const installed = { const installed = {
name: "simple-pr-review", name: "simple-pr-review",
@@ -50,7 +97,7 @@ describe("useSkills", () => {
.mockResolvedValue({ skills: [installed] }); .mockResolvedValue({ skills: [installed] });
const getToken = () => "tok"; const getToken = () => "tok";
function Composer() { function Composer() {
const skills = useSkills(getToken); const { skills } = useSkills(getToken);
return <ThreadComposer onSend={vi.fn()} skills={skills} />; return <ThreadComposer onSend={vi.fn()} skills={skills} />;
} }
render(<Composer />); render(<Composer />);
@@ -105,7 +152,7 @@ describe("useSkills", () => {
}); });
// The old response was captured before installation; it cannot satisfy the new opens. // The old response was captured before installation; it cannot satisfy the new opens.
expect(fetchSkills).toHaveBeenCalledTimes(2); expect(fetchSkills).toHaveBeenCalledTimes(2);
expect(result.current).toEqual([installed]); expect(result.current.skills).toEqual([installed]);
unmount(); unmount();
requestSkillsRefresh(); requestSkillsRefresh();
@@ -126,19 +173,19 @@ describe("useSkills", () => {
const getToken = () => "tok"; const getToken = () => "tok";
const { result } = renderHook(() => useSkills(getToken)); const { result } = renderHook(() => useSkills(getToken));
await act(async () => {}); await act(async () => {});
expect(result.current).toEqual([installed]); expect(result.current.skills).toEqual([installed]);
await act(async () => { await act(async () => {
requestSkillsRefresh(); requestSkillsRefresh();
}); });
expect(fetchSkills).toHaveBeenCalledTimes(2); expect(fetchSkills).toHaveBeenCalledTimes(2);
expect(result.current).toEqual([installed]); expect(result.current).toEqual({ skills: [installed], loading: false, error: false });
await act(async () => { await act(async () => {
requestSkillsRefresh(); requestSkillsRefresh();
}); });
expect(fetchSkills).toHaveBeenCalledTimes(3); expect(fetchSkills).toHaveBeenCalledTimes(3);
expect(result.current).toEqual([]); expect(result.current).toEqual({ skills: [], loading: false, error: false });
}); });
it.each([false, true])("does not start a queued refresh after unmount (failure: %s)", async (fails) => { it.each([false, true])("does not start a queued refresh after unmount (failure: %s)", async (fails) => {
@@ -162,11 +209,11 @@ describe("useSkills", () => {
expect(fetchSkills).toHaveBeenCalledTimes(1); expect(fetchSkills).toHaveBeenCalledTimes(1);
}); });
it("does not let an older request overwrite a newer skill event", async () => { it.each([false, true])("does not let an older request overwrite a newer skill event (failure: %s)", async (fails) => {
let resolveSkills!: (value: Awaited<ReturnType<typeof fetchSkills>>) => void; let settle!: () => void;
vi.mocked(fetchSkills).mockReset().mockImplementationOnce( vi.mocked(fetchSkills).mockReset().mockImplementationOnce(
() => new Promise((resolve) => { () => new Promise((resolve, reject) => {
resolveSkills = resolve; settle = () => fails ? reject(new Error("Offline")) : resolve({ skills: [] });
}), }),
); );
const installed = { const installed = {
@@ -184,13 +231,13 @@ describe("useSkills", () => {
detail: { skills: [installed] }, detail: { skills: [installed] },
})); }));
}); });
expect(result.current).toEqual([installed]); expect(result.current).toEqual({ skills: [installed], loading: false, error: false });
await act(async () => { await act(async () => {
resolveSkills({ skills: [] }); settle();
}); });
expect(result.current).toEqual([installed]); expect(result.current).toEqual({ skills: [installed], loading: false, error: false });
}); });
}); });
@@ -217,6 +264,54 @@ describe("SkillsMarketplace", () => {
vi.useRealTimers(); vi.useRealTimers();
}); });
it("shows discovery skeletons while trending or the first search is pending and keeps loaded search results", async () => {
const skill = {
id: "skillhub:react-testing", skill_id: "react-testing", name: "React Testing",
source: "react-testing", provider: "skillhub" as const, installs: 42,
url: "https://skillhub.cn/react-testing", installed: false, install_supported: true,
metric: "installs_total" as const, rank: 1,
};
let resolveTrending!: (value: Awaited<ReturnType<typeof fetchTrendingMarketplaceSkills>>) => void;
let resolveSearch!: (value: Awaited<ReturnType<typeof searchMarketplaceSkills>>) => void;
let resolveNextSearch!: (value: Awaited<ReturnType<typeof searchMarketplaceSkills>>) => void;
vi.mocked(fetchTrendingMarketplaceSkills).mockImplementationOnce(
() => new Promise((resolve) => { resolveTrending = resolve; }),
);
vi.mocked(searchMarketplaceSkills)
.mockImplementationOnce(() => new Promise((resolve) => { resolveSearch = resolve; }))
.mockImplementationOnce(() => new Promise((resolve) => { resolveNextSearch = resolve; }));
render(marketplace("tok"));
expect(screen.getByRole("status", { name: "Loading skills…" })).toHaveAttribute("aria-busy", "true");
await act(async () => {
resolveTrending({ period: "mixed", provider: "all", install_supported: true, skills: [skill] });
});
expect(screen.getByRole("button", { name: "Install React Testing" })).toBeInTheDocument();
fireEvent.change(screen.getByRole("textbox", { name: "Search skills" }), {
target: { value: "React" },
});
expect(screen.getByRole("status", { name: "Loading skills…" })).toHaveAttribute("aria-busy", "true");
expect(searchMarketplaceSkills).not.toHaveBeenCalled();
await act(async () => { await vi.advanceTimersByTimeAsync(300); });
expect(searchMarketplaceSkills).toHaveBeenCalledWith("tok", "React");
expect(screen.getByRole("status", { name: "Loading skills…" })).toBeInTheDocument();
await act(async () => {
resolveSearch({ query: "React", provider: "all", install_supported: true, skills: [skill] });
});
fireEvent.change(screen.getByRole("textbox", { name: "Search skills" }), {
target: { value: "Vue" },
});
await act(async () => { await vi.advanceTimersByTimeAsync(300); });
expect(screen.getByRole("button", { name: "Install React Testing" })).toBeInTheDocument();
expect(screen.queryByRole("status", { name: "Loading skills…" })).not.toBeInTheDocument();
await act(async () => {
resolveNextSearch({ query: "Vue", provider: "all", install_supported: true, skills: [] });
});
expect(screen.getByText("No skills found for “Vue”.")).toBeInTheDocument();
});
it("keeps loaded marketplace data stable when the auth token rotates", async () => { it("keeps loaded marketplace data stable when the auth token rotates", async () => {
const { rerender } = render(marketplace("tok-old")); const { rerender } = render(marketplace("tok-old"));