Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(skills): page the registry catalog server-side and show its freshness (#7082)

oxoxDevde1d4dbdda82
diff --git a/app/src/components/skills/RegistryStatusNotice.tsx b/app/src/components/skills/RegistryStatusNotice.tsx
new file mode 100644
index 0000000000..d64888ee0f
--- /dev/null
+++ b/app/src/components/skills/RegistryStatusNotice.tsx
@@ -0,0 +1,106 @@
+import { useT } from '../../lib/i18n/I18nContext';
+import type { CatalogPage, ParsedRegistryError } from '../../services/api/skillRegistryApi';
+import { Alert, AlertDescription } from '../ui';
+import Button from '../ui/Button';
+
+const UNREACHABLE_KINDS = new Set(['timeout', 'unavailable', 'transport']);
+
+function formatFetchedAt(fetchedAt: number | null): string | null {
+ if (fetchedAt == null) return null;
+ try {
+ return new Date(fetchedAt * 1000).toLocaleString();
+ } catch {
+ return null;
+ }
+}
+
+function RetryButton({ onRetry, tone }: { onRetry: () => void; tone?: 'danger' }) {
+ const { t } = useT();
+ return (
+ <Button
+ variant="secondary"
+ tone={tone}
+ size="xs"
+ data-testid="registry-retry"
+ onClick={onRetry}>
+ {t('common.retry')}
+ </Button>
+ );
+}
+
+/** The message a failed catalog read shows when nothing is held to display. */
+export function RegistryErrorNotice({
+ error,
+ onRetry,
+}: {
+ error: ParsedRegistryError;
+ onRetry: () => void;
+}) {
+ const { t } = useT();
+ let text = error.message;
+ if (error.kind === 'rate_limited') {
+ text =
+ error.retryAfterSecs != null
+ ? t('skills.registry.rateLimited').replace('{seconds}', String(error.retryAfterSecs))
+ : t('skills.registry.rateLimitedShortly');
+ } else if (error.kind && UNREACHABLE_KINDS.has(error.kind)) {
+ text = t('skills.registry.unreachable');
+ }
+ return (
+ <Alert variant="destructive" density="compact" data-testid="registry-error">
+ <AlertDescription className="flex flex-wrap items-center justify-between gap-2">
+ <span>{text}</span>
+ <RetryButton onRetry={onRetry} tone="danger" />
+ </AlertDescription>
+ </Alert>
+ );
+}
+
+/**
+ * The state of the catalog behind the page on screen: still loading for the
+ * first time, a saved copy shown while a refresh runs, or a saved copy shown
+ * because the registry could not be reached.
+ */
+export function RegistryStatusNotice({
+ page,
+ firstLoad,
+ onRetry,
+}: {
+ page: CatalogPage | null;
+ firstLoad: boolean;
+ onRetry: () => void;
+}) {
+ const { t } = useT();
+ if (firstLoad) {
+ return (
+ <Alert variant="info" density="compact" data-testid="registry-first-load">
+ <AlertDescription>{t('skills.registry.firstFetchHint')}</AlertDescription>
+ </Alert>
+ );
+ }
+ if (!page) return null;
+
+ const offline = page.lastError != null || page.freshness === 'local_fallback';
+ if (offline) {
+ const time = formatFetchedAt(page.fetchedAt);
+ const text = time
+ ? t('skills.registry.offline').replace('{time}', time)
+ : t('skills.registry.offlineNoTime');
+ return (
+ <Alert variant="warning" density="compact" data-testid="registry-offline">
+ <AlertDescription className="flex flex-wrap items-center justify-between gap-2">
+ <span>{text}</span>
+ <RetryButton onRetry={onRetry} />
+ </AlertDescription>
+ </Alert>
+ );
+ }
+ if (page.refreshing && page.freshness === 'cached') {
+ return (
+ <Alert variant="info" density="compact" data-testid="registry-refreshing">
+ <AlertDescription>{t('skills.registry.refreshing')}</AlertDescription>
+ </Alert>
+ );
+ }
+ return null;
+}
diff --git a/app/src/components/skills/SkillsExplorerTab.tsx b/app/src/components/skills/SkillsExplorerTab.tsx
index 3fdbd4a151..99a8558455 100644
--- a/app/src/components/skills/SkillsExplorerTab.tsx
+++ b/app/src/components/skills/SkillsExplorerTab.tsx
@@ -21,7 +21,15 @@ import { LuLibrary, LuSparkles } from 'react-icons/lu';
import { useNavigate } from 'react-router-dom';
import { useT } from '../../lib/i18n/I18nContext';
-import { type CatalogEntry, skillRegistryApi } from '../../services/api/skillRegistryApi';
+import {
+ type CatalogDetail,
+ type CatalogEntry,
+ type CatalogPage,
+ isInstallable,
+ type ParsedRegistryError,
+ parseRegistryError,
+ skillRegistryApi,
+} from '../../services/api/skillRegistryApi';
import {
type InstallWorkflowFromUrlResult,
skillsApi,
@@ -36,6 +44,7 @@ import DataTable, { type DataTableColumn } from '../ui/DataTable';
import { TableCell, TableRow } from '../ui/Table';
import CreateSkillModal from './CreateSkillModal';
import InstallSkillDialog from './InstallSkillDialog';
+import { RegistryErrorNotice, RegistryStatusNotice } from './RegistryStatusNotice';
import UninstallSkillConfirmDialog from './UninstallSkillConfirmDialog';
const log = debug('skills:explorer-tab');
@@ -294,6 +303,7 @@ interface CatalogTileProps {
interface SkillDetailDialogProps {
entry: CatalogEntry | null;
+ detail?: CatalogDetail | null;
skill: WorkflowSummary | null;
installed: boolean;
onClose: () => void;
@@ -301,6 +311,21 @@ interface SkillDetailDialogProps {
installing?: boolean;
}
+function SourceLink({ url, testId }: { url: string; testId: string }) {
+ const { t } = useT();
+ return (
+ <a
+ href={url}
+ target="_blank"
+ rel="noopener noreferrer"
+ data-testid={testId}
+ onClick={event => event.stopPropagation()}
+ className="text-xs font-medium text-primary-600 hover:underline dark:text-primary-300">
+ {t('skills.registry.viewSource')}
+ </a>
+ );
+}
+
function CatalogRow({ entry, installed, installing, onInstall, onClick }: CatalogTileProps) {
const { t } = useT();
return (
@@ -331,13 +356,18 @@ function CatalogRow({ entry, installed, installing, onInstall, onClick }: Catalo
<TableCell className="w-px whitespace-nowrap text-right">
{installed ? (
<Badge variant="success">{t('skills.explorer.installed')}</Badge>
- ) : !entry.download_url ? (
- <Badge
- variant="neutral"
- title={t('skills.explorer.notInstallableHint')}
- data-testid={`registry-not-installable-${entry.id}`}>
- {t('skills.explorer.notInstallable')}
- </Badge>
+ ) : !isInstallable(entry) ? (
+ <span className="inline-flex items-center gap-2">
+ <Badge
+ variant="neutral"
+ title={t('skills.explorer.notInstallableHint')}
+ data-testid={`registry-not-installable-${entry.id}`}>
+ {t('skills.explorer.notInstallable')}
+ </Badge>
+ {entry.source_url && (
+ <SourceLink url={entry.source_url} testId={`registry-source-link-${entry.id}`} />
+ )}
+ </span>
) : (
<Button
variant="secondary"
@@ -359,6 +389,7 @@ function CatalogRow({ entry, installed, installing, onInstall, onClick }: Catalo
function SkillDetailDialog({
entry,
+ detail,
skill,
installed,
onClose,
@@ -373,8 +404,11 @@ function SkillDetailDialog({
const author = entry?.author ?? '';
const source = entry?.source ?? '';
const category = entry?.category ?? '';
- const downloadUrl = entry?.download_url ?? '';
- const license = entry?.license ?? '';
+ const downloadUrl = detail?.download_url || entry?.download_url || '';
+ const license = detail?.license ?? entry?.license ?? '';
+ const overview = detail?.overview?.trim() ?? '';
+ const sourceUrl = detail?.source_url ?? entry?.source_url ?? '';
+ const installable = entry ? isInstallable(entry) : false;
return (
<ModalShell
@@ -401,13 +435,14 @@ function SkillDetailDialog({
footer={
!installed && onInstall ? (
<div className="flex justify-end">
- {downloadUrl ? (
+ {installable ? (
<Button variant="secondary" size="sm" disabled={installing} onClick={onInstall}>
{installing ? t('skills.explorer.installing') : t('skills.explorer.install')}
</Button>
) : (
- <p className="text-xs text-content-muted">
- {t('skills.explorer.notInstallableHint')}
+ <p className="flex flex-wrap items-center gap-2 text-xs text-content-muted">
+ <span>{t('skills.explorer.notInstallableHint')}</span>
+ {sourceUrl && <SourceLink url={sourceUrl} testId="skill-detail-source-link" />}
</p>
)}
</div>
@@ -425,6 +460,17 @@ function SkillDetailDialog({
</div>
)}
+ {overview && overview !== description && (
+ <div data-testid="skill-detail-overview">
+ <h3 className="text-[11px] font-semibold uppercase tracking-wider text-content-faint mb-1">
+ {t('skills.detail.overview')}
+ </h3>
+ <p className="text-sm text-content-secondary leading-relaxed whitespace-pre-wrap">
+ {overview}
+ </p>
+ </div>
+ )}
+
<div className="flex flex-wrap gap-x-6 gap-y-2">
{version && (
<div>
@@ -496,11 +542,13 @@ export default function SkillsExplorerTab({ onToast, view }: SkillsExplorerTabPr
const [skillsLoading, setSkillsLoading] = useState(true);
const [skillsError, setSkillsError] = useState<string | null>(null);
- // The whole fetched list; the table pages through it client-side.
- const [catalogEntries, setCatalogEntries] = useState<CatalogEntry[]>([]);
+ const [catalogPage, setCatalogPage] = useState<CatalogPage | null>(null);
+ const [catalogPageNum, setCatalogPageNum] = useState(1);
+ const [catalogPageSize, setCatalogPageSize] = useState(PAGE_SIZE);
const [catalogLoading, setCatalogLoading] = useState(false);
- const [catalogError, setCatalogError] = useState<string | null>(null);
+ const [catalogError, setCatalogError] = useState<ParsedRegistryError | null>(null);
const [catalogInitialized, setCatalogInitialized] = useState(false);
+ const catalogRequestRef = useRef(0);
const [installingId, setInstallingId] = useState<string | null>(null);
// Catalog entry ids we just installed this session. The "installed" badge is
// otherwise derived purely from `isCatalogEntryInstalled`, a heuristic that
@@ -522,6 +570,7 @@ export default function SkillsExplorerTab({ onToast, view }: SkillsExplorerTabPr
const [createOpen, setCreateOpen] = useState<WorkflowSummary | null | undefined>(null);
const [uninstallTarget, setUninstallTarget] = useState<WorkflowSummary | null>(null);
const [detailEntry, setDetailEntry] = useState<CatalogEntry | null>(null);
+ const [entryDetail, setEntryDetail] = useState<CatalogDetail | null>(null);
const [detailSkill, setDetailSkill] = useState<WorkflowSummary | null>(null);
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -556,41 +605,55 @@ export default function SkillsExplorerTab({ onToast, view }: SkillsExplorerTabPr
}
}, []);
- // Compute the active source filter for RPC calls.
- // Only apply when the user has deselected at least one source.
const activeSourceFilter = useMemo(() => {
if (activeSources.size === 0 || activeSources.size >= sources.length) return undefined;
- // If exactly one source is active, pass it as the filter
- if (activeSources.size === 1) return [...activeSources][0];
- return undefined;
+ return [...activeSources].sort();
}, [activeSources, sources.length]);
+ const activeSourceKey = activeSourceFilter?.join('\u0000') ?? '';
- // Fetch catalog via RPC search (handles both browse and search).
- // When query is empty and no source filter, uses browse; otherwise uses search.
const fetchCatalog = useCallback(
- async (query: string, sourceFilter: string | undefined, forceRefresh: boolean) => {
- log('fetchCatalog: query=%s source=%s forceRefresh=%s', query, sourceFilter, forceRefresh);
+ async (
+ query: string,
+ sourceFilter: string[] | undefined,
+ page: number,
+ pageSize: number,
+ forceRefresh: boolean
+ ) => {
+ const request = ++catalogRequestRef.current;
+ log(
+ 'fetchCatalog: query=%s sources=%d page=%d size=%d forceRefresh=%s',
+ query,
+ sourceFilter?.length ?? 0,
+ page,
+ pageSize,
+ forceRefresh
+ );
setCatalogLoading(true);
setCatalogError(null);
try {
- let entries: CatalogEntry[];
- if (!query && !sourceFilter && !forceRefresh) {
- entries = await skillRegistryApi.browse(false);
- } else if (!query && !sourceFilter && forceRefresh) {
- entries = await skillRegistryApi.browse(true);
- } else {
- entries = await skillRegistryApi.search(query || '', sourceFilter);
- }
- log('fetchCatalog: total=%d', entries.length);
- // Keep the full list; the table pages through it without another RPC.
- setCatalogEntries(entries);
+ const result = await skillRegistryApi.browsePage({
+ query,
+ sources: sourceFilter,
+ page,
+ pageSize,
+ forceRefresh,
+ });
+ if (request !== catalogRequestRef.current) return;
+ log(
+ 'fetchCatalog: total=%d page=%d freshness=%s',
+ result.total,
+ result.page,
+ result.freshness
+ );
+ setCatalogPage(result);
setCatalogInitialized(true);
} catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- log('fetchCatalog: error=%s', msg);
- setCatalogError(msg);
+ if (request !== catalogRequestRef.current) return;
+ const parsed = parseRegistryError(err);
+ log('fetchCatalog: error kind=%s msg=%s', parsed.kind, parsed.message);
+ setCatalogError(parsed);
} finally {
- setCatalogLoading(false);
+ if (request === catalogRequestRef.current) setCatalogLoading(false);
}
},
[]
@@ -607,12 +670,41 @@ export default function SkillsExplorerTab({ onToast, view }: SkillsExplorerTabPr
.catch(() => {});
}, [fetchSkills]);
- // Trigger catalog search when debounced query or source filter changes
+ useEffect(() => {
+ setCatalogPageNum(1);
+ }, [debouncedQuery, activeSourceKey]);
+
useEffect(() => {
if (view === 'registry') {
- void fetchCatalog(debouncedQuery, activeSourceFilter, false);
+ void fetchCatalog(debouncedQuery, activeSourceFilter, catalogPageNum, catalogPageSize, false);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [view, debouncedQuery, activeSourceKey, catalogPageNum, catalogPageSize, fetchCatalog]);
+
+ const refreshCatalog = useCallback(
+ () =>
+ void fetchCatalog(debouncedQuery, activeSourceFilter, catalogPageNum, catalogPageSize, true),
+ [fetchCatalog, debouncedQuery, activeSourceFilter, catalogPageNum, catalogPageSize]
+ );
+
+ useEffect(() => {
+ if (!detailEntry) {
+ setEntryDetail(null);
+ return;
}
- }, [view, debouncedQuery, activeSourceFilter, fetchCatalog]);
+ let cancelled = false;
+ skillRegistryApi
+ .detail(detailEntry.id)
+ .then(detail => {
+ if (!cancelled) setEntryDetail(detail);
+ })
+ .catch(err => {
+ log('detail: error=%s', parseRegistryError(err).message);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [detailEntry]);
const installedKeys = useMemo(
() => new Set(skills.flatMap(skill => workflowInstallKeys(skill))),
@@ -650,18 +742,7 @@ export default function SkillsExplorerTab({ onToast, view }: SkillsExplorerTabPr
});
}, [filteredSkills]);
- // When multiple sources are active (but not all), do client-side filtering
- // on the already-fetched results since the RPC only supports single source filter.
- const filteredCatalog = useMemo(() => {
- if (
- activeSources.size === 0 ||
- activeSources.size >= sources.length ||
- activeSources.size === 1
- ) {
- return catalogEntries;
- }
- return catalogEntries.filter(e => activeSources.has(e.source));
- }, [catalogEntries, activeSources, sources.length]);
+ const catalogEntries = catalogPage?.entries ?? [];
const handleInstalled = useCallback(
(result: InstallWorkflowFromUrlResult) => {
@@ -712,9 +793,22 @@ export default function SkillsExplorerTab({ onToast, view }: SkillsExplorerTabPr
message: `Installed ${entry.name}${result.newSkills.length > 0 ? ` (${result.newSkills.join(', ')})` : ''}`,
});
} catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- log('handleRegistryInstall: error=%s', msg);
- onToast?.({ type: 'error', title: t('skills.install.errors.genericTitle'), message: msg });
+ const parsed = parseRegistryError(err);
+ log('handleRegistryInstall: error kind=%s msg=%s', parsed.kind, parsed.message);
+ let message = parsed.message;
+ if (parsed.kind === 'no_direct_download') {
+ message = entry.source_url
+ ? `${t('skills.registry.noDirectDownload')} ${entry.source_url}`
+ : t('skills.registry.noDirectDownload');
+ } else if (parsed.kind === 'upstream_ambiguous') {
+ message = t('skills.registry.upstreamAmbiguous');
+ } else if (parsed.kind === 'rate_limited') {
+ message =
+ parsed.retryAfterSecs != null
+ ? t('skills.registry.rateLimited').replace('{seconds}', String(parsed.retryAfterSecs))
+ : t('skills.registry.rateLimitedShortly');
+ }
+ onToast?.({ type: 'error', title: t('skills.install.errors.genericTitle'), message });
} finally {
setInstallingId(null);
}
@@ -723,31 +817,33 @@ export default function SkillsExplorerTab({ onToast, view }: SkillsExplorerTabPr
);
const loading = view === 'installed' ? skillsLoading : catalogLoading;
- const error = view === 'installed' ? skillsError : catalogError;
const runSkill = (skill: WorkflowSummary) =>
navigate(`/workflows/run?workflow=${encodeURIComponent(skill.id)}&lock=1`);
- const errorNode =
- !loading && error ? (
+ const installedErrorNode =
+ !skillsLoading && skillsError ? (
<Alert variant="destructive" density="compact">
<AlertDescription className="flex flex-wrap items-center justify-between gap-2">
- <span>{error}</span>
- <Button
- variant="secondary"
- tone="danger"
- size="xs"
- onClick={() =>
- void (view === 'installed'
- ? fetchSkills()
- : fetchCatalog(debouncedQuery, activeSourceFilter, true))
- }>
+ <span>{skillsError}</span>
+ <Button variant="secondary" tone="danger" size="xs" onClick={() => void fetchSkills()}>
{t('common.retry')}
</Button>
</AlertDescription>
</Alert>
) : undefined;
+ const registryErrorNode =
+ !catalogLoading && catalogError ? (
+ <RegistryErrorNotice error={catalogError} onRetry={refreshCatalog} />
+ ) : (
+ <RegistryStatusNotice
+ page={catalogPage}
+ firstLoad={catalogLoading && !catalogInitialized}
+ onRetry={refreshCatalog}
+ />
+ );
+
const search = {
value: searchQuery,
onChange: setSearchQuery,
@@ -779,7 +875,7 @@ export default function SkillsExplorerTab({ onToast, view }: SkillsExplorerTabPr
title={debouncedQuery ? t('skills.noResults') : t('skills.explorer.registryEmptyTitle')}
description={debouncedQuery ? '' : t('skills.explorer.registryEmptyDescription')}
actionLabel={debouncedQuery ? undefined : t('skills.explorer.refreshRegistry')}
- onAction={debouncedQuery ? undefined : () => void fetchCatalog('', undefined, true)}
+ onAction={debouncedQuery ? undefined : refreshCatalog}
/>
) : null;
@@ -814,6 +910,7 @@ export default function SkillsExplorerTab({ onToast, view }: SkillsExplorerTabPr
{(detailEntry || detailSkill) && (
<SkillDetailDialog
entry={detailEntry}
+ detail={entryDetail}
skill={detailSkill}
installed={detailEntry ? entryInstalled(detailEntry) : true}
onClose={() => {
@@ -916,7 +1013,7 @@ export default function SkillsExplorerTab({ onToast, view }: SkillsExplorerTabPr
]}
pagination={{ pageSize: PAGE_SIZE }}
loading={loading}
- error={errorNode}
+ error={installedErrorNode}
empty={installedEmpty}
ariaLabel={t('skills.rows.installedTitle')}
/>
@@ -936,7 +1033,7 @@ export default function SkillsExplorerTab({ onToast, view }: SkillsExplorerTabPr
<Button
variant="secondary"
size="sm"
- onClick={() => void fetchCatalog(debouncedQuery, activeSourceFilter, true)}
+ onClick={refreshCatalog}
disabled={catalogLoading}
aria-label={t('skills.explorer.refreshRegistry')}
leadingIcon={
@@ -949,7 +1046,7 @@ export default function SkillsExplorerTab({ onToast, view }: SkillsExplorerTabPr
</Button>
}
columns={catalogColumns}
- rows={filteredCatalog}
+ rows={catalogEntries}
rowKey={entry => `${entry.source}-${entry.id}`}
renderRow={entry => (
<CatalogRow
@@ -977,9 +1074,16 @@ export default function SkillsExplorerTab({ onToast, view }: SkillsExplorerTabPr
]
: undefined
}
- pagination={{ pageSize: PAGE_SIZE, testId: 'registry-pagination' }}
- loading={loading && filteredCatalog.length === 0}
- error={errorNode}
+ pagination={{
+ page: catalogPage?.page ?? catalogPageNum,
+ pageSize: catalogPageSize,
+ total: catalogPage?.total,
+ onPageChange: setCatalogPageNum,
+ onPageSizeChange: setCatalogPageSize,
+ testId: 'registry-pagination',
+ }}
+ loading={loading && catalogEntries.length === 0}
+ error={registryErrorNode}
empty={registryEmpty ?? undefined}
ariaLabel={t('skills.rows.registryTitle')}
/>
diff --git a/app/src/components/skills/__tests__/SkillsExplorerTab.test.tsx b/app/src/components/skills/__tests__/SkillsExplorerTab.test.tsx
index 6a9cf7d132..e222f94723 100644
--- a/app/src/components/skills/__tests__/SkillsExplorerTab.test.tsx
+++ b/app/src/components/skills/__tests__/SkillsExplorerTab.test.tsx
@@ -2,7 +2,7 @@ import { act, fireEvent, render, screen, waitFor, within } from '@testing-librar
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import type { CatalogEntry } from '../../../services/api/skillRegistryApi';
+import type { CatalogEntry, CatalogPage, CatalogPageQuery } from '../../../services/api/skillRegistryApi';
import type { WorkflowSummary } from '../../../services/api/skillsApi';
import SkillsPage from '../SkillsPage';
@@ -14,15 +14,58 @@ vi.mock('../../../services/api/skillsApi', () => ({
},
}));
-vi.mock('../../../services/api/skillRegistryApi', () => ({
- skillRegistryApi: {
- browse: vi.fn(),
- search: vi.fn(),
- sources: vi.fn(),
- categories: vi.fn(),
- install: vi.fn(),
- },
-}));
+vi.mock('../../../services/api/skillRegistryApi', async importOriginal => {
+ const actual = await importOriginal<typeof import('../../../services/api/skillRegistryApi')>();
+ return {
+ ...actual,
+ skillRegistryApi: {
+ browsePage: vi.fn(),
+ detail: vi.fn(),
+ sources: vi.fn(),
+ categories: vi.fn(),
+ install: vi.fn(),
+ },
+ };
+});
+
+function pageOf(
+ entries: CatalogEntry[],
+ query: CatalogPageQuery,
+ overrides: Partial<CatalogPage> = {}
+): CatalogPage {
+ const text = query.query?.trim().toLowerCase() ?? '';
+ let hits = entries;
+ if (text) {
+ hits = hits.filter(
+ e =>
+ e.name.toLowerCase().includes(text) ||
+ e.description.toLowerCase().includes(text) ||
+ e.tags.some(tag => tag.toLowerCase().includes(text))
+ );
+ }
+ if (query.sources?.length) hits = hits.filter(e => query.sources?.includes(e.source));
+ const start = (query.page - 1) * query.pageSize;
+ return {
+ entries: hits.slice(start, start + query.pageSize),
+ total: hits.length,
+ page: query.page,
+ pageSize: query.pageSize,
+ totalPages: Math.ceil(hits.length / query.pageSize),
+ freshness: 'live',
+ fetchedAt: null,
+ refreshing: false,
+ lastError: null,
+ ...overrides,
+ };
+}
+
+/** Serve `entries` from the mocked core, paged and filtered like the real one. */
+async function serveCatalog(entries: CatalogEntry[], overrides: Partial<CatalogPage> = {}) {
+ const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
+ vi.mocked(skillRegistryApi.browsePage).mockImplementation(async query =>
+ pageOf(entries, query, overrides)
+ );
+}
const MOCK_SKILL: WorkflowSummary = {
id: 'test-skill',
@@ -113,20 +156,19 @@ describe('SkillsExplorerTab', () => {
const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
vi.mocked(skillsApi.listWorkflows).mockReset();
vi.mocked(skillsApi.uninstallWorkflow).mockReset();
- vi.mocked(skillRegistryApi.browse).mockReset();
- vi.mocked(skillRegistryApi.search).mockReset();
+ vi.mocked(skillRegistryApi.browsePage).mockReset();
+ vi.mocked(skillRegistryApi.detail).mockReset();
vi.mocked(skillRegistryApi.install).mockReset();
vi.mocked(skillRegistryApi.sources).mockReset();
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([]);
- vi.mocked(skillRegistryApi.search).mockResolvedValue([]);
+ await serveCatalog([]);
+ vi.mocked(skillRegistryApi.detail).mockRejectedValue(new Error('no detail'));
vi.mocked(skillRegistryApi.sources).mockResolvedValue([]);
});
it('defaults to registry view and shows catalog entries', async () => {
const { skillsApi } = await import('../../../services/api/skillsApi');
- const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([MOCK_CATALOG_ENTRY]);
+ await serveCatalog([MOCK_CATALOG_ENTRY]);
render(
<MemoryRouter>
@@ -149,7 +191,7 @@ describe('SkillsExplorerTab', () => {
id: `paged-skill-${i}`,
name: `Paged Skill ${i}`,
}));
- vi.mocked(skillRegistryApi.browse).mockResolvedValue(entries);
+ await serveCatalog(entries);
const { container } = render(
<MemoryRouter>
@@ -164,31 +206,40 @@ describe('SkillsExplorerTab', () => {
const tileCount = () =>
container.querySelectorAll('[data-testid^="registry-tile-"]').length;
- // Registry rows page through the shared DataTable pager (25/page) rather
- // than an incremental "Show more" reveal.
expect(tileCount()).toBe(25);
+ expect(skillRegistryApi.browsePage).toHaveBeenLastCalledWith(
+ expect.objectContaining({ page: 1, pageSize: 25 })
+ );
const pager = screen.getByTestId('registry-pagination');
await act(async () => {
fireEvent.click(within(pager).getByRole('button', { name: 'Next page' }));
});
+ await waitFor(() => {
+ expect(screen.getByText('Paged Skill 25')).toBeInTheDocument();
+ });
+ expect(skillRegistryApi.browsePage).toHaveBeenLastCalledWith(
+ expect.objectContaining({ page: 2, pageSize: 25 })
+ );
expect(tileCount()).toBe(25);
- expect(screen.getByText('Paged Skill 25')).toBeInTheDocument();
await act(async () => {
fireEvent.click(within(pager).getByRole('button', { name: 'Last page' }));
});
- // 130 entries / 25 per page → last page holds the remainder (5).
+ await waitFor(() => {
+ expect(screen.getByText('Paged Skill 129')).toBeInTheDocument();
+ });
+ expect(skillRegistryApi.browsePage).toHaveBeenLastCalledWith(
+ expect.objectContaining({ page: 6 })
+ );
expect(tileCount()).toBe(5);
- expect(screen.getByText('Paged Skill 129')).toBeInTheDocument();
});
it('searches catalog via RPC when typing in search box', async () => {
const { skillsApi } = await import('../../../services/api/skillsApi');
const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([MOCK_CATALOG_ENTRY]);
- vi.mocked(skillRegistryApi.search).mockResolvedValue([MOCK_DOCKER_ENTRY]);
+ await serveCatalog([MOCK_CATALOG_ENTRY, MOCK_DOCKER_ENTRY]);
render(
<MemoryRouter>
@@ -208,7 +259,9 @@ describe('SkillsExplorerTab', () => {
// Wait for the debounce to fire and the RPC search to be called
await waitFor(
() => {
- expect(skillRegistryApi.search).toHaveBeenCalledWith('docker', undefined);
+ expect(skillRegistryApi.browsePage).toHaveBeenCalledWith(
+ expect.objectContaining({ query: 'docker', page: 1 })
+ );
},
{ timeout: 2000 }
);
@@ -216,6 +269,7 @@ describe('SkillsExplorerTab', () => {
await waitFor(() => {
expect(screen.getByText('Docker Manager')).toBeInTheDocument();
});
+ expect(screen.queryByText('Registry Skill')).toBeNull();
});
it('shows installed skills when switching to installed tab', async () => {
@@ -260,7 +314,7 @@ describe('SkillsExplorerTab', () => {
const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
const { skillsApi } = await import('../../../services/api/skillsApi');
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
- vi.mocked(skillRegistryApi.browse).mockRejectedValue(new Error('Network error'));
+ vi.mocked(skillRegistryApi.browsePage).mockRejectedValue(new Error('Network error'));
render(
<MemoryRouter>
@@ -385,7 +439,6 @@ describe('SkillsExplorerTab', () => {
it('shows "Installed" badge for already-installed catalog entries', async () => {
const { skillsApi } = await import('../../../services/api/skillsApi');
- const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
const catalogEntry = {
...MOCK_CATALOG_ENTRY,
id: 'built-in/apple-notes',
@@ -399,7 +452,7 @@ describe('SkillsExplorerTab', () => {
location: '/Users/test/.openhuman/skills/apple-notes/SKILL.md',
};
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([installedSkill]);
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([catalogEntry]);
+ await serveCatalog([catalogEntry]);
render(
<MemoryRouter>
@@ -428,7 +481,6 @@ describe('SkillsExplorerTab', () => {
it('does not mark catalog entries installed by display name alone', async () => {
const { skillsApi } = await import('../../../services/api/skillsApi');
- const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
const catalogEntry = {
...MOCK_CATALOG_ENTRY,
id: 'built-in/apple-notes',
@@ -442,7 +494,7 @@ describe('SkillsExplorerTab', () => {
location: '/Users/test/.openhuman/skills/apple-notes-copy/SKILL.md',
};
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([unrelatedInstalledSkill]);
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([catalogEntry]);
+ await serveCatalog([catalogEntry]);
render(
<MemoryRouter>
@@ -471,7 +523,7 @@ describe('SkillsExplorerTab', () => {
// The installed list never resolves to anything that maps back to the entry
// (simulates a post-install id/location the heuristic can't match).
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([catalogEntry]);
+ await serveCatalog([catalogEntry]);
vi.mocked(skillRegistryApi.install).mockResolvedValue({
url: '',
stdout: '',
@@ -588,9 +640,8 @@ describe('SkillsExplorerTab', () => {
it('opens catalog entry detail dialog when a registry tile is clicked', async () => {
const { skillsApi } = await import('../../../services/api/skillsApi');
- const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([MOCK_CATALOG_ENTRY_WITH_META]);
+ await serveCatalog([MOCK_CATALOG_ENTRY_WITH_META]);
render(
<MemoryRouter>
@@ -655,9 +706,8 @@ describe('SkillsExplorerTab', () => {
it('shows install button in detail dialog footer for non-installed registry entry', async () => {
const { skillsApi } = await import('../../../services/api/skillsApi');
- const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([MOCK_CATALOG_ENTRY]);
+ await serveCatalog([MOCK_CATALOG_ENTRY]);
render(
<MemoryRouter>
@@ -690,7 +740,7 @@ describe('SkillsExplorerTab', () => {
const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
const onToast = vi.fn();
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([MOCK_CATALOG_ENTRY]);
+ await serveCatalog([MOCK_CATALOG_ENTRY]);
vi.mocked(skillRegistryApi.install).mockResolvedValue({
url: 'https://example.com/SKILL.md',
stdout: 'ok',
@@ -722,9 +772,8 @@ describe('SkillsExplorerTab', () => {
it('marks an entry with no SKILL.md download as not installable instead of offering Install', async () => {
const { skillsApi } = await import('../../../services/api/skillsApi');
- const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([
+ await serveCatalog([
{
...MOCK_CATALOG_ENTRY,
id: 'lobehub/prompt-agent',
@@ -747,9 +796,8 @@ describe('SkillsExplorerTab', () => {
it('explains in the detail dialog why an entry with no SKILL.md download cannot be installed', async () => {
const { skillsApi } = await import('../../../services/api/skillsApi');
- const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([
+ await serveCatalog([
{
...MOCK_CATALOG_ENTRY,
id: 'lobehub/prompt-agent',
@@ -782,7 +830,7 @@ describe('SkillsExplorerTab', () => {
const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
const onToast = vi.fn();
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([MOCK_CATALOG_ENTRY]);
+ await serveCatalog([MOCK_CATALOG_ENTRY]);
vi.mocked(skillRegistryApi.install).mockRejectedValue(new Error('Install failed'));
render(
@@ -810,7 +858,7 @@ describe('SkillsExplorerTab', () => {
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
vi.mocked(skillRegistryApi.sources).mockResolvedValue(['built-in', 'ClawHub']);
// No catalog entries so "built-in" only appears in the toggle buttons
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([]);
+ await serveCatalog([]);
render(
<MemoryRouter>
@@ -833,8 +881,6 @@ describe('SkillsExplorerTab', () => {
const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
vi.mocked(skillRegistryApi.sources).mockResolvedValue(['built-in', 'ClawHub']);
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([]);
- vi.mocked(skillRegistryApi.search).mockResolvedValue([]);
render(
<MemoryRouter>
@@ -854,7 +900,9 @@ describe('SkillsExplorerTab', () => {
});
await waitFor(() => {
- expect(skillRegistryApi.search).toHaveBeenCalledWith('', 'built-in');
+ expect(skillRegistryApi.browsePage).toHaveBeenCalledWith(
+ expect.objectContaining({ sources: ['built-in'], page: 1 })
+ );
});
});
@@ -902,9 +950,8 @@ describe('SkillsExplorerTab', () => {
it('shows empty registry state when catalog returns no results', async () => {
const { skillsApi } = await import('../../../services/api/skillsApi');
- const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([]);
+ await serveCatalog([]);
render(
<MemoryRouter>
@@ -922,9 +969,8 @@ describe('SkillsExplorerTab', () => {
const { skillsApi } = await import('../../../services/api/skillsApi');
const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
- vi.mocked(skillRegistryApi.browse)
- .mockRejectedValueOnce(new Error('timeout'))
- .mockResolvedValue([MOCK_CATALOG_ENTRY]);
+ await serveCatalog([MOCK_CATALOG_ENTRY]);
+ vi.mocked(skillRegistryApi.browsePage).mockRejectedValueOnce(new Error('timeout'));
render(
<MemoryRouter>
@@ -975,7 +1021,7 @@ describe('SkillsExplorerTab', () => {
const { skillsApi } = await import('../../../services/api/skillsApi');
const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([MOCK_CATALOG_ENTRY]);
+ await serveCatalog([MOCK_CATALOG_ENTRY]);
render(
<MemoryRouter>
@@ -987,7 +1033,7 @@ describe('SkillsExplorerTab', () => {
expect(screen.getByText('Registry Skill')).toBeInTheDocument();
});
- const callsBefore = vi.mocked(skillRegistryApi.browse).mock.calls.length;
+ const callsBefore = vi.mocked(skillRegistryApi.browsePage).mock.calls.length;
const refreshBtn = screen.getByRole('button', { name: 'Refresh registry' });
await act(async () => {
@@ -995,12 +1041,12 @@ describe('SkillsExplorerTab', () => {
});
await waitFor(() => {
- expect(vi.mocked(skillRegistryApi.browse).mock.calls.length).toBeGreaterThan(callsBefore);
+ expect(vi.mocked(skillRegistryApi.browsePage).mock.calls.length).toBeGreaterThan(
+ callsBefore
+ );
});
- // The last browse call should use forceRefresh=true
- const calls = vi.mocked(skillRegistryApi.browse).mock.calls;
- const lastCall = calls[calls.length - 1];
- expect(lastCall[0]).toBe(true);
+ const calls = vi.mocked(skillRegistryApi.browsePage).mock.calls;
+ expect(calls[calls.length - 1][0]).toMatchObject({ forceRefresh: true });
});
it('sorts hermes skills before non-hermes in installed view', async () => {
@@ -1040,9 +1086,8 @@ describe('SkillsExplorerTab', () => {
it('activates catalog tile on Enter key', async () => {
const { skillsApi } = await import('../../../services/api/skillsApi');
- const { skillRegistryApi } = await import('../../../services/api/skillRegistryApi');
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([MOCK_CATALOG_ENTRY]);
+ await serveCatalog([MOCK_CATALOG_ENTRY]);
render(
<MemoryRouter>
@@ -1068,7 +1113,7 @@ describe('SkillsExplorerTab', () => {
const onToast = vi.fn();
vi.mocked(skillsApi.listWorkflows).mockResolvedValue([]);
// Override the beforeEach mock so browse returns an entry
- vi.mocked(skillRegistryApi.browse).mockResolvedValue([MOCK_CATALOG_ENTRY]);
+ await serveCatalog([MOCK_CATALOG_ENTRY]);
vi.mocked(skillRegistryApi.install).mockResolvedValue({
url: 'https://example.com/SKILL.md',
stdout: 'ok',
diff --git a/app/src/services/api/skillRegistryApi.test.ts b/app/src/services/api/skillRegistryApi.test.ts
index f32354e1c9..aaa2718f65 100644
--- a/app/src/services/api/skillRegistryApi.test.ts
+++ b/app/src/services/api/skillRegistryApi.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { invalidateSkillBrowseCache, skillRegistryApi } from './skillRegistryApi';
+import { isInstallable, parseRegistryError, skillRegistryApi } from './skillRegistryApi';
const mockCallCoreRpc = vi.fn();
vi.mock('../coreRpcClient', () => ({ callCoreRpc: (...a: unknown[]) => mockCallCoreRpc(...a) }));
@@ -8,8 +8,6 @@ vi.mock('../coreRpcClient', () => ({ callCoreRpc: (...a: unknown[]) => mockCallC
describe('skillRegistryApi', () => {
beforeEach(() => {
mockCallCoreRpc.mockReset();
- // The browse cache is module-level; clear it so each test starts cold.
- invalidateSkillBrowseCache();
});
it('normalizes install new_skills to newSkills', async () => {
@@ -58,39 +56,6 @@ describe('skillRegistryApi', () => {
expect(result[0].function).toBe('install');
});
- it('search calls skill_registry_search with query only when source/category absent', async () => {
- mockCallCoreRpc.mockResolvedValue({ entries: [{ id: 'demo', name: 'Demo' }] });
-
- const result = await skillRegistryApi.search('demo');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.skill_registry_search',
- params: { query: 'demo' },
- timeoutMs: 120_000,
- });
- expect(result[0].id).toBe('demo');
- });
-
- it('search forwards source and category when both are provided', async () => {
- mockCallCoreRpc.mockResolvedValue({ entries: [] });
-
- await skillRegistryApi.search('q', 'ClawHub', 'devops');
-
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.skill_registry_search',
- params: { query: 'q', source: 'ClawHub', category: 'devops' },
- timeoutMs: 120_000,
- });
- });
-
- it('search unwraps data-envelope shape', async () => {
- mockCallCoreRpc.mockResolvedValue({ data: { entries: [{ id: 'env-skill' }] } });
-
- const result = await skillRegistryApi.search('env');
-
- expect(result[0].id).toBe('env-skill');
- });
-
it('sources calls skill_registry_sources and returns array', async () => {
mockCallCoreRpc.mockResolvedValue({ sources: ['built-in', 'ClawHub'] });
@@ -144,81 +109,136 @@ describe('skillRegistryApi', () => {
expect(result.newSkills).toEqual([]);
});
- it('browse with forceRefresh=true forwards force_refresh=true', async () => {
- mockCallCoreRpc.mockResolvedValue({ entries: [] });
+ it('browsePage asks browse for an empty query and normalizes the page', async () => {
+ mockCallCoreRpc.mockResolvedValue({
+ entries: [{ id: 'a', name: 'A' }],
+ total: 30,
+ page: 2,
+ page_size: 25,
+ total_pages: 2,
+ freshness: 'cached',
+ fetched_at: 1_700_000_000,
+ refreshing: true,
+ last_error: { kind: 'unavailable', message: 'upstream returned status 503' },
+ });
- await skillRegistryApi.browse(true);
+ const page = await skillRegistryApi.browsePage({ page: 2, pageSize: 25 });
expect(mockCallCoreRpc).toHaveBeenCalledWith({
method: 'openhuman.skill_registry_browse',
- params: { force_refresh: true },
+ params: { page: 2, page_size: 25 },
timeoutMs: 120_000,
});
+ expect(page).toMatchObject({
+ total: 30,
+ page: 2,
+ pageSize: 25,
+ totalPages: 2,
+ freshness: 'cached',
+ fetchedAt: 1_700_000_000,
+ refreshing: true,
+ lastError: { kind: 'unavailable' },
+ });
});
- it('browse default arg passes force_refresh=false', async () => {
- mockCallCoreRpc.mockResolvedValue({ entries: [] });
+ it('browsePage searches with a query and forwards sources, category and refresh', async () => {
+ mockCallCoreRpc.mockResolvedValue({
+ data: { entries: [], total: 0, page: 1, page_size: 10, total_pages: 0, freshness: 'live' },
+ });
- await skillRegistryApi.browse();
+ const page = await skillRegistryApi.browsePage({
+ query: ' git ',
+ sources: ['ClawHub', 'skills.sh'],
+ category: 'devops',
+ page: 1,
+ pageSize: 10,
+ forceRefresh: true,
+ });
expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.skill_registry_browse',
- params: { force_refresh: false },
+ method: 'openhuman.skill_registry_search',
+ params: {
+ query: 'git',
+ sources: ['ClawHub', 'skills.sh'],
+ category: 'devops',
+ page: 1,
+ page_size: 10,
+ force_refresh: true,
+ },
timeoutMs: 120_000,
});
+ expect(page.lastError).toBeNull();
+ expect(page.fetchedAt).toBeNull();
});
- it('browse serves the second call from the in-memory cache (one RPC)', async () => {
- mockCallCoreRpc.mockResolvedValue({ entries: [{ id: 'a', name: 'A' }] });
+ it('every page read goes to the core; nothing is cached in the app', async () => {
+ mockCallCoreRpc.mockResolvedValue({
+ entries: [],
+ total: 0,
+ page: 1,
+ page_size: 25,
+ total_pages: 0,
+ freshness: 'live',
+ });
- const first = await skillRegistryApi.browse();
- const second = await skillRegistryApi.browse();
+ await skillRegistryApi.browsePage({ page: 1, pageSize: 25 });
+ await skillRegistryApi.browsePage({ page: 1, pageSize: 25 });
- expect(mockCallCoreRpc).toHaveBeenCalledTimes(1);
- expect(second).toBe(first); // same cached array reference
- expect(second[0].id).toBe('a');
+ expect(mockCallCoreRpc).toHaveBeenCalledTimes(2);
});
- it('browse de-dupes concurrent callers into a single in-flight RPC', async () => {
- let resolveRpc: (v: { entries: { id: string }[] }) => void = () => {};
- mockCallCoreRpc.mockReturnValue(
- new Promise(res => {
- resolveRpc = res;
- })
- );
+ it('detail calls skill_registry_detail', async () => {
+ mockCallCoreRpc.mockResolvedValue({ id: 'git-helper', overview: 'Longer text.' });
- const a = skillRegistryApi.browse();
- const b = skillRegistryApi.browse();
- resolveRpc({ entries: [{ id: 'x' }] });
- const [ra, rb] = await Promise.all([a, b]);
+ const detail = await skillRegistryApi.detail('git-helper');
- expect(mockCallCoreRpc).toHaveBeenCalledTimes(1);
- expect(ra).toBe(rb);
+ expect(mockCallCoreRpc).toHaveBeenCalledWith({
+ method: 'openhuman.skill_registry_detail',
+ params: { entry_id: 'git-helper' },
+ timeoutMs: 120_000,
+ });
+ expect(detail.overview).toBe('Longer text.');
});
- it('browse(forceRefresh=true) bypasses the cache and re-fetches', async () => {
- mockCallCoreRpc.mockResolvedValueOnce({ entries: [{ id: 'old' }] });
- await skillRegistryApi.browse(); // populates cache
- mockCallCoreRpc.mockResolvedValueOnce({ entries: [{ id: 'new' }] });
-
- const refreshed = await skillRegistryApi.browse(true);
-
- expect(mockCallCoreRpc).toHaveBeenCalledTimes(2);
- expect(refreshed[0].id).toBe('new');
-
- // Subsequent default call now serves the refreshed value from cache.
- const cached = await skillRegistryApi.browse();
- expect(mockCallCoreRpc).toHaveBeenCalledTimes(2);
- expect(cached[0].id).toBe('new');
+ it('parseRegistryError reads the kind, message and retry delay', () => {
+ expect(
+ parseRegistryError(new Error('SKILL_REGISTRY_RATE_LIMITED: rate limited: retry after 42s'))
+ ).toEqual({
+ kind: 'rate_limited',
+ message: 'rate limited: retry after 42s',
+ retryAfterSecs: 42,
+ });
+ expect(parseRegistryError(new Error('rpc failed: SKILL_REGISTRY_NOT_FOUND: no entry'))).toEqual(
+ { kind: 'not_found', message: 'no entry', retryAfterSecs: null }
+ );
+ expect(parseRegistryError('boom')).toEqual({
+ kind: null,
+ message: 'boom',
+ retryAfterSecs: null,
+ });
});
- it('invalidateSkillBrowseCache forces the next browse to re-fetch', async () => {
- mockCallCoreRpc.mockResolvedValue({ entries: [{ id: 'a' }] });
- await skillRegistryApi.browse();
- expect(mockCallCoreRpc).toHaveBeenCalledTimes(1);
-
- invalidateSkillBrowseCache();
- await skillRegistryApi.browse();
- expect(mockCallCoreRpc).toHaveBeenCalledTimes(2);
+ it('isInstallable prefers the core flag over the download url', () => {
+ const base = {
+ id: 'x',
+ name: 'x',
+ description: '',
+ source: 's',
+ category: '',
+ author: null,
+ version: null,
+ tags: [],
+ platforms: [],
+ docs_path: null,
+ commands: [],
+ env_vars: [],
+ license: null,
+ };
+ expect(isInstallable({ ...base, download_url: '', installable: true })).toBe(true);
+ expect(isInstallable({ ...base, download_url: 'https://e/SKILL.md', installable: false })).toBe(
+ false
+ );
+ expect(isInstallable({ ...base, download_url: 'https://e/SKILL.md' })).toBe(true);
+ expect(isInstallable({ ...base, download_url: '' })).toBe(false);
});
});
diff --git a/app/src/services/api/skillRegistryApi.ts b/app/src/services/api/skillRegistryApi.ts
index f8287ad293..92d8302588 100644
--- a/app/src/services/api/skillRegistryApi.ts
+++ b/app/src/services/api/skillRegistryApi.ts
@@ -4,49 +4,35 @@ import { callCoreRpc } from '../coreRpcClient';
const log = debug('skillRegistryApi');
-/**
- * Catalog reads (`browse`/`search`/`sources`/`categories`) all funnel through
- * the backend's single-flight `browse_catalog`, whose COLD fetch downloads the
- * full ~90k-entry registry and can take ~80s. That comfortably exceeds the
- * default 30s `CORE_RPC_TIMEOUT_MS`, so a first load (or post-TTL revalidate)
- * would spuriously time out. Give these the longer per-call timeout the RPC
- * client supports for exactly such "slow-but-alive" calls; warm-cache reads
- * still return in milliseconds, so this only raises the ceiling for the rare
- * cold path. 120s = ~80s cold download + margin (well under the 10min clamp).
- */
const CATALOG_RPC_TIMEOUT_MS = 120_000;
-/**
- * An install first locates the skill's SKILL.md (for skills.sh entries that
- * means probing the GitHub repo and possibly listing it), then fetches it with
- * the core's 60s download budget. That regularly outlasts the default 30s RPC
- * timeout, which would report a failure for an install still in progress.
- */
const INSTALL_RPC_TIMEOUT_MS = 120_000;
-/**
- * In-memory, session-scoped cache for the unfiltered `browse()` catalog.
- *
- * The backend already single-flights the upstream ~90k-entry fetch, so warm
- * backend reads are fast — but the FRONTEND still re-pulls and re-parses that
- * whole payload (tens of MB) over RPC on every Skills-page mount, which is the
- * recurring slowness users feel when clicking around. Holding the parsed result
- * here makes repeat visits within a session instant and de-dupes concurrent
- * mounts via a shared in-flight promise.
- *
- * Deliberately NOT persisted to localStorage: the payload far exceeds the ~5MB
- * quota, so a cold restart re-fetches (and the backend serves it warm). A TTL
- * bounds staleness for very long-lived sessions; `force_refresh` and
- * `invalidateSkillBrowseCache()` both drop it on demand.
- */
-const BROWSE_CACHE_TTL_MS = 30 * 60 * 1000;
-let browseCache: { fetchedAt: number; entries: CatalogEntry[] } | null = null;
-let browseInflight: Promise<CatalogEntry[]> | null = null;
-
-/** Drop the in-memory browse cache (e.g. after an install changes the list). */
-export function invalidateSkillBrowseCache(): void {
- browseCache = null;
- browseInflight = null;
+/** How fresh the catalog behind a page is. */
+export type RegistryFreshness = 'live' | 'cached' | 'local_fallback';
+
+/** Stable registry error kinds (`RegistryErrorKind` in tinyskills). */
+export type RegistryErrorKind =
+ | 'timeout'
+ | 'unavailable'
+ | 'rate_limited'
+ | 'too_large'
+ | 'malformed'
+ | 'not_found'
+ | 'ambiguous'
+ | 'upstream_ambiguous'
+ | 'no_direct_download'
+ | 'unsafe_url'
+ | 'invalid_document'
+ | 'unknown_registry'
+ | 'store'
+ | 'transport_contract'
+ | 'transport';
+
+export interface RegistryErrorSummary {
+ kind: RegistryErrorKind;
+ message: string;
+ retry_after_secs?: number | null;
}
export interface CatalogEntry {
@@ -59,11 +45,88 @@ export interface CatalogEntry {
version: string | null;
tags: string[];
platforms: string[];
+ /** Empty when the entry has no direct SKILL.md download. */
download_url: string;
+ /** Human-facing page for the entry. */
+ source_url?: string | null;
docs_path: string | null;
commands: string[];
env_vars: string[];
license: string | null;
+ /** The registry the entry came from. */
+ registry?: string;
+ /** Whether the entry installs directly; authoritative over `download_url`. */
+ installable?: boolean;
+ category_label?: string | null;
+}
+
+export interface CatalogDetail extends CatalogEntry {
+ overview: string;
+ install_identifier: string | null;
+}
+
+export interface CatalogPageQuery {
+ query?: string;
+ /** Upstream sources to keep; empty or absent keeps every source. */
+ sources?: string[];
+ category?: string;
+ /** 1-based page. */
+ page: number;
+ pageSize: number;
+ forceRefresh?: boolean;
+}
+
+export interface CatalogPage {
+ entries: CatalogEntry[];
+ total: number;
+ page: number;
+ pageSize: number;
+ totalPages: number;
+ freshness: RegistryFreshness;
+ /** Unix seconds of the oldest catalog fetch that answered. */
+ fetchedAt: number | null;
+ refreshing: boolean;
+ lastError: RegistryErrorSummary | null;
+}
+
+interface RawCatalogPage {
+ entries: CatalogEntry[];
+ total: number;
+ page: number;
+ page_size: number;
+ total_pages: number;
+ freshness: RegistryFreshness;
+ fetched_at?: number | null;
+ refreshing?: boolean;
+ last_error?: RegistryErrorSummary | null;
+}
+
+/** A registry error as the core reports it: `SKILL_REGISTRY_<KIND>: message`. */
+export interface ParsedRegistryError {
+ kind: RegistryErrorKind | null;
+ message: string;
+ retryAfterSecs: number | null;
+}
+
+const REGISTRY_ERROR_PATTERN = /SKILL_REGISTRY_([A-Z_]+):\s*([\s\S]*)$/;
+const RETRY_AFTER_PATTERN = /retry after (\d+)s/;
+
+/** Read the typed kind, message and retry delay out of a failed registry call. */
+export function parseRegistryError(error: unknown): ParsedRegistryError {
+ const raw = error instanceof Error ? error.message : String(error ?? '');
+ const match = REGISTRY_ERROR_PATTERN.exec(raw);
+ const message = match ? match[2].trim() : raw;
+ const retry = RETRY_AFTER_PATTERN.exec(message);
+ return {
+ kind: match ? (match[1].toLowerCase() as RegistryErrorKind) : null,
+ message,
+ retryAfterSecs: retry ? Number(retry[1]) : null,
+ };
+}
+
+/** Whether an entry can be installed directly from the registry. */
+export function isInstallable(entry: CatalogEntry): boolean {
+ return entry.installable ?? Boolean(entry.download_url);
}
interface RegistryInstallResult {
@@ -113,59 +176,57 @@ function unwrap<T>(response: Envelope<T> | T): T {
}
export const skillRegistryApi = {
- browse: async (forceRefresh = false): Promise<CatalogEntry[]> => {
- log('browse: forceRefresh=%s', forceRefresh);
- if (forceRefresh) {
- // Explicit refresh: drop any cache / in-flight join so we hit the backend.
- invalidateSkillBrowseCache();
- } else {
- if (browseCache && Date.now() - browseCache.fetchedAt < BROWSE_CACHE_TTL_MS) {
- log('browse: served from in-memory cache count=%d', browseCache.entries.length);
- return browseCache.entries;
- }
- // Concurrent mounts share a single fetch instead of each firing the RPC.
- if (browseInflight) {
- log('browse: joining in-flight request');
- return browseInflight;
- }
- }
-
- const fetchPromise = (async () => {
- const response = await callCoreRpc<
- Envelope<{ entries: CatalogEntry[] }> | { entries: CatalogEntry[] }
- >({
- method: 'openhuman.skill_registry_browse',
- params: { force_refresh: forceRefresh },
- timeoutMs: CATALOG_RPC_TIMEOUT_MS,
- });
- const result = unwrap(response);
- log('browse: count=%d', result.entries.length);
- browseCache = { fetchedAt: Date.now(), entries: result.entries };
- return result.entries;
- })();
-
- browseInflight = fetchPromise;
- try {
- return await fetchPromise;
- } finally {
- // Only clear the slot if it's still ours (a concurrent invalidate may have
- // already reset it).
- if (browseInflight === fetchPromise) browseInflight = null;
- }
+ browsePage: async (query: CatalogPageQuery): Promise<CatalogPage> => {
+ const text = query.query?.trim() ?? '';
+ const sources = query.sources?.filter(Boolean) ?? [];
+ log(
+ 'browsePage: query=%s sources=%d page=%d size=%d force=%s',
+ text,
+ sources.length,
+ query.page,
+ query.pageSize,
+ Boolean(query.forceRefresh)
+ );
+ const params: Record<string, unknown> = { page: query.page, page_size: query.pageSize };
+ if (text) params.query = text;
+ if (sources.length > 0) params.sources = sources;
+ if (query.category) params.category = query.category;
+ if (query.forceRefresh) params.force_refresh = true;
+ const response = await callCoreRpc<Envelope<RawCatalogPage> | RawCatalogPage>({
+ method: text ? 'openhuman.skill_registry_search' : 'openhuman.skill_registry_browse',
+ params,
+ timeoutMs: CATALOG_RPC_TIMEOUT_MS,
+ });
+ const raw = unwrap(response);
+ const page: CatalogPage = {
+ entries: raw.entries ?? [],
+ total: raw.total ?? 0,
+ page: raw.page ?? query.page,
+ pageSize: raw.page_size ?? query.pageSize,
+ totalPages: raw.total_pages ?? 0,
+ freshness: raw.freshness ?? 'live',
+ fetchedAt: raw.fetched_at ?? null,
+ refreshing: raw.refreshing ?? false,
+ lastError: raw.last_error ?? null,
+ };
+ log(
+ 'browsePage: total=%d returned=%d freshness=%s error=%s',
+ page.total,
+ page.entries.length,
+ page.freshness,
+ page.lastError?.kind ?? 'none'
+ );
+ return page;
},
- search: async (query: string, source?: string, category?: string): Promise<CatalogEntry[]> => {
- log('search: query=%s source=%s category=%s', query, source, category);
- const response = await callCoreRpc<
- Envelope<{ entries: CatalogEntry[] }> | { entries: CatalogEntry[] }
- >({
- method: 'openhuman.skill_registry_search',
- params: { query, ...(source ? { source } : {}), ...(category ? { category } : {}) },
+ detail: async (entryId: string): Promise<CatalogDetail> => {
+ log('detail: entryId=%s', entryId);
+ const response = await callCoreRpc<Envelope<CatalogDetail> | CatalogDetail>({
+ method: 'openhuman.skill_registry_detail',
+ params: { entry_id: entryId },
timeoutMs: CATALOG_RPC_TIMEOUT_MS,
});
- const result = unwrap(response);
- log('search: count=%d', result.entries.length);
- return result.entries;
+ return unwrap(response);
},
sources: async (): Promise<string[]> => {