feat: add skill pack management features including creation, editing, and syncing

This commit is contained in:
Abhimanyu Saharan
2026-02-14 02:05:11 +05:30
committed by Abhimanyu Saharan
parent 88565f4d69
commit a7e1e5cbf4
28 changed files with 4403 additions and 430 deletions

View File

@@ -177,6 +177,9 @@ export * from "./organizationUserRead";
export * from "./readyzReadyzGet200";
export * from "./searchApiV1SoulsDirectorySearchGetParams";
export * from "./sendGatewaySessionMessageApiV1GatewaysSessionsSessionIdMessagePostParams";
export * from "./skillPackCreate";
export * from "./skillPackRead";
export * from "./skillPackSyncResponse";
export * from "./soulsDirectoryMarkdownResponse";
export * from "./soulsDirectorySearchResponse";
export * from "./soulsDirectorySoulRef";

View File

@@ -9,6 +9,7 @@
* Marketplace card payload with gateway-specific install state.
*/
export interface MarketplaceSkillCardRead {
category?: string | null;
created_at: string;
description?: string | null;
id: string;
@@ -16,6 +17,8 @@ export interface MarketplaceSkillCardRead {
installed_at?: string | null;
name: string;
organization_id: string;
risk?: string | null;
source?: string | null;
source_url: string;
updated_at: string;
}

View File

@@ -9,11 +9,14 @@
* Serialized marketplace skill catalog record.
*/
export interface MarketplaceSkillRead {
category?: string | null;
created_at: string;
description?: string | null;
id: string;
name: string;
organization_id: string;
risk?: string | null;
source?: string | null;
source_url: string;
updated_at: string;
}

View File

@@ -0,0 +1,16 @@
/**
* Generated by orval v8.3.0 🍺
* Do not edit manually.
* Mission Control API
* OpenAPI spec version: 0.1.0
*/
/**
* Payload used to register a pack URL in the organization.
*/
export interface SkillPackCreate {
description?: string | null;
name?: string | null;
/** @minLength 1 */
source_url: string;
}

View File

@@ -0,0 +1,20 @@
/**
* Generated by orval v8.3.0 🍺
* Do not edit manually.
* Mission Control API
* OpenAPI spec version: 0.1.0
*/
/**
* Serialized skill pack record.
*/
export interface SkillPackRead {
created_at: string;
description?: string | null;
id: string;
name: string;
organization_id: string;
skill_count?: number;
source_url: string;
updated_at: string;
}

View File

@@ -0,0 +1,17 @@
/**
* Generated by orval v8.3.0 🍺
* Do not edit manually.
* Mission Control API
* OpenAPI spec version: 0.1.0
*/
/**
* Pack sync summary payload.
*/
export interface SkillPackSyncResponse {
created: number;
ok?: boolean;
pack_id: string;
synced: number;
updated: number;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,12 @@
import { redirect } from "next/navigation";
type EditMarketplaceSkillPageProps = {
params: Promise<{ skillId: string }>;
};
export default async function EditMarketplaceSkillPage({
params,
}: EditMarketplaceSkillPageProps) {
const { skillId } = await params;
redirect(`/skills/packs/${skillId}/edit`);
}

View File

@@ -0,0 +1,5 @@
import { redirect } from "next/navigation";
export default function NewMarketplaceSkillPage() {
redirect("/skills/packs/new");
}

View File

@@ -0,0 +1,408 @@
"use client";
export const dynamic = "force-dynamic";
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import { useAuth } from "@/auth/clerk";
import { useQueryClient } from "@tanstack/react-query";
import { ApiError } from "@/api/mutator";
import {
type listGatewaysApiV1GatewaysGetResponse,
useListGatewaysApiV1GatewaysGet,
} from "@/api/generated/gateways/gateways";
import type { MarketplaceSkillCardRead } from "@/api/generated/model";
import {
listMarketplaceSkillsApiV1SkillsMarketplaceGet,
type listMarketplaceSkillsApiV1SkillsMarketplaceGetResponse,
useInstallMarketplaceSkillApiV1SkillsMarketplaceSkillIdInstallPost,
useListMarketplaceSkillsApiV1SkillsMarketplaceGet,
useUninstallMarketplaceSkillApiV1SkillsMarketplaceSkillIdUninstallPost,
} from "@/api/generated/skills-marketplace/skills-marketplace";
import {
type listSkillPacksApiV1SkillsPacksGetResponse,
useListSkillPacksApiV1SkillsPacksGet,
} from "@/api/generated/skills/skills";
import { MarketplaceSkillsTable } from "@/components/skills/MarketplaceSkillsTable";
import { DashboardPageLayout } from "@/components/templates/DashboardPageLayout";
import { Button, buttonVariants } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { useOrganizationMembership } from "@/lib/use-organization-membership";
import { useUrlSorting } from "@/lib/use-url-sorting";
const MARKETPLACE_SKILLS_SORTABLE_COLUMNS = [
"name",
"category",
"risk",
"source",
"updated_at",
];
const normalizeRepoSourceUrl = (sourceUrl: string): string => {
const trimmed = sourceUrl.trim().replace(/\/+$/, "");
return trimmed.endsWith(".git") ? trimmed.slice(0, -4) : trimmed;
};
const repoBaseFromSkillSourceUrl = (skillSourceUrl: string): string | null => {
try {
const parsed = new URL(skillSourceUrl);
const marker = "/tree/";
const markerIndex = parsed.pathname.indexOf(marker);
if (markerIndex <= 0) return null;
return normalizeRepoSourceUrl(
`${parsed.origin}${parsed.pathname.slice(0, markerIndex)}`,
);
} catch {
return null;
}
};
export default function SkillsMarketplacePage() {
const queryClient = useQueryClient();
const searchParams = useSearchParams();
const { isSignedIn } = useAuth();
const { isAdmin } = useOrganizationMembership(isSignedIn);
const [selectedSkill, setSelectedSkill] = useState<MarketplaceSkillCardRead | null>(null);
const [gatewayInstalledById, setGatewayInstalledById] = useState<
Record<string, boolean>
>({});
const [isGatewayStatusLoading, setIsGatewayStatusLoading] = useState(false);
const [gatewayStatusError, setGatewayStatusError] = useState<string | null>(null);
const [installingGatewayId, setInstallingGatewayId] = useState<string | null>(null);
const { sorting, onSortingChange } = useUrlSorting({
allowedColumnIds: MARKETPLACE_SKILLS_SORTABLE_COLUMNS,
defaultSorting: [{ id: "name", desc: false }],
paramPrefix: "skills_marketplace",
});
const gatewaysQuery = useListGatewaysApiV1GatewaysGet<
listGatewaysApiV1GatewaysGetResponse,
ApiError
>(undefined, {
query: {
enabled: Boolean(isSignedIn && isAdmin),
refetchOnMount: "always",
refetchInterval: 30_000,
},
});
const gateways = useMemo(
() =>
gatewaysQuery.data?.status === 200
? (gatewaysQuery.data.data.items ?? [])
: [],
[gatewaysQuery.data],
);
const resolvedGatewayId = gateways[0]?.id ?? "";
const skillsQuery = useListMarketplaceSkillsApiV1SkillsMarketplaceGet<
listMarketplaceSkillsApiV1SkillsMarketplaceGetResponse,
ApiError
>(
{ gateway_id: resolvedGatewayId },
{
query: {
enabled: Boolean(isSignedIn && isAdmin && resolvedGatewayId),
refetchOnMount: "always",
refetchInterval: 15_000,
},
},
);
const skills = useMemo<MarketplaceSkillCardRead[]>(
() => (skillsQuery.data?.status === 200 ? skillsQuery.data.data : []),
[skillsQuery.data],
);
const packsQuery = useListSkillPacksApiV1SkillsPacksGet<
listSkillPacksApiV1SkillsPacksGetResponse,
ApiError
>({
query: {
enabled: Boolean(isSignedIn && isAdmin),
refetchOnMount: "always",
},
});
const packs = useMemo(
() => (packsQuery.data?.status === 200 ? packsQuery.data.data : []),
[packsQuery.data],
);
const selectedPackId = searchParams.get("packId");
const selectedPack = useMemo(
() => packs.find((pack) => pack.id === selectedPackId) ?? null,
[packs, selectedPackId],
);
const visibleSkills = useMemo(() => {
if (!selectedPack) return skills;
const selectedRepo = normalizeRepoSourceUrl(selectedPack.source_url);
return skills.filter((skill) => {
const skillRepo = repoBaseFromSkillSourceUrl(skill.source_url);
return skillRepo === selectedRepo;
});
}, [selectedPack, skills]);
const installMutation =
useInstallMarketplaceSkillApiV1SkillsMarketplaceSkillIdInstallPost<ApiError>(
{
mutation: {
onSuccess: async (_, variables) => {
await queryClient.invalidateQueries({
queryKey: ["/api/v1/skills/marketplace"],
});
setGatewayInstalledById((previous) => ({
...previous,
[variables.params.gateway_id]: true,
}));
},
},
},
queryClient,
);
const uninstallMutation =
useUninstallMarketplaceSkillApiV1SkillsMarketplaceSkillIdUninstallPost<ApiError>(
{
mutation: {
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: ["/api/v1/skills/marketplace"],
});
},
},
},
queryClient,
);
useEffect(() => {
let cancelled = false;
const loadGatewayStatus = async () => {
if (!selectedSkill) {
setGatewayInstalledById({});
setGatewayStatusError(null);
setIsGatewayStatusLoading(false);
return;
}
if (gateways.length === 0) {
setGatewayInstalledById({});
setGatewayStatusError(null);
setIsGatewayStatusLoading(false);
return;
}
setIsGatewayStatusLoading(true);
setGatewayStatusError(null);
try {
const entries = await Promise.all(
gateways.map(async (gateway) => {
const response = await listMarketplaceSkillsApiV1SkillsMarketplaceGet({
gateway_id: gateway.id,
});
const row =
response.status === 200
? response.data.find((skill) => skill.id === selectedSkill.id)
: null;
return [gateway.id, Boolean(row?.installed)] as const;
}),
);
if (cancelled) return;
setGatewayInstalledById(Object.fromEntries(entries));
} catch (error) {
if (cancelled) return;
setGatewayStatusError(
error instanceof Error ? error.message : "Unable to load gateway status.",
);
} finally {
if (!cancelled) {
setIsGatewayStatusLoading(false);
}
}
};
void loadGatewayStatus();
return () => {
cancelled = true;
};
}, [gateways, selectedSkill]);
const mutationError =
installMutation.error?.message ?? uninstallMutation.error?.message;
const isMutating = installMutation.isPending || uninstallMutation.isPending;
const handleInstallToGateway = async (gatewayId: string) => {
if (!selectedSkill) return;
setInstallingGatewayId(gatewayId);
try {
await installMutation.mutateAsync({
skillId: selectedSkill.id,
params: { gateway_id: gatewayId },
});
} finally {
setInstallingGatewayId(null);
}
};
return (
<>
<DashboardPageLayout
signedOut={{
message: "Sign in to manage marketplace skills.",
forceRedirectUrl: "/skills/marketplace",
}}
title="Skills Marketplace"
description={
selectedPack
? `${visibleSkills.length} skill${
visibleSkills.length === 1 ? "" : "s"
} for ${selectedPack.name}.`
: `${visibleSkills.length} skill${
visibleSkills.length === 1 ? "" : "s"
} synced from packs.`
}
isAdmin={isAdmin}
adminOnlyMessage="Only organization owners and admins can manage skills."
stickyHeader
>
<div className="space-y-6">
{gateways.length === 0 ? (
<div className="rounded-xl border border-slate-200 bg-white p-6 text-sm text-slate-600 shadow-sm">
<p className="font-medium text-slate-900">No gateways available yet.</p>
<p className="mt-2">
Create a gateway first, then return here to manage installs.
</p>
<Link
href="/gateways/new"
className={`${buttonVariants({ variant: "primary", size: "md" })} mt-4`}
>
Create gateway
</Link>
</div>
) : (
<>
<div className="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm">
<MarketplaceSkillsTable
skills={visibleSkills}
isLoading={skillsQuery.isLoading}
sorting={sorting}
onSortingChange={onSortingChange}
stickyHeader
canInstallActions={Boolean(resolvedGatewayId)}
isMutating={isMutating}
onSkillClick={setSelectedSkill}
onUninstall={(skill) =>
uninstallMutation.mutate({
skillId: skill.id,
params: { gateway_id: resolvedGatewayId },
})
}
emptyState={{
title: "No marketplace skills yet",
description: "Add packs first, then synced skills will appear here.",
actionHref: "/skills/packs/new",
actionLabel: "Add your first pack",
}}
/>
</div>
</>
)}
{skillsQuery.error ? (
<p className="text-sm text-rose-600">{skillsQuery.error.message}</p>
) : null}
{packsQuery.error ? (
<p className="text-sm text-rose-600">{packsQuery.error.message}</p>
) : null}
{mutationError ? <p className="text-sm text-rose-600">{mutationError}</p> : null}
</div>
</DashboardPageLayout>
<Dialog
open={Boolean(selectedSkill)}
onOpenChange={(open) => {
if (!open) {
setSelectedSkill(null);
}
}}
>
<DialogContent
aria-label="Install skill on gateways"
className="max-w-xl p-6 sm:p-7"
>
<DialogHeader className="pb-1">
<DialogTitle>{selectedSkill ? selectedSkill.name : "Install skill"}</DialogTitle>
<DialogDescription>
Choose one or more gateways where this skill should be installed.
</DialogDescription>
</DialogHeader>
<div className="mt-2 space-y-3.5">
{isGatewayStatusLoading ? (
<p className="text-sm text-slate-500">Loading gateways...</p>
) : (
gateways.map((gateway) => {
const isInstalled = gatewayInstalledById[gateway.id] === true;
const isInstalling =
installMutation.isPending && installingGatewayId === gateway.id;
return (
<div
key={gateway.id}
className="flex items-center justify-between rounded-xl border border-slate-200 bg-white p-4"
>
<div>
<p className="text-sm font-medium text-slate-900">{gateway.name}</p>
<p className="text-xs text-slate-500">
{isInstalled ? "Installed" : "Not installed"}
</p>
</div>
<Button
type="button"
size="sm"
onClick={() => void handleInstallToGateway(gateway.id)}
disabled={isInstalled || installMutation.isPending}
>
{isInstalled ? "Installed" : isInstalling ? "Installing..." : "Install"}
</Button>
</div>
);
})
)}
{gatewayStatusError ? (
<p className="text-sm text-rose-600">{gatewayStatusError}</p>
) : null}
{installMutation.error ? (
<p className="text-sm text-rose-600">{installMutation.error.message}</p>
) : null}
</div>
<DialogFooter className="mt-6 border-t border-slate-200 pt-4">
<Button
variant="outline"
onClick={() => setSelectedSkill(null)}
disabled={installMutation.isPending}
>
Close
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}

View File

@@ -0,0 +1,104 @@
"use client";
export const dynamic = "force-dynamic";
import { useParams, useRouter } from "next/navigation";
import { useAuth } from "@/auth/clerk";
import { ApiError } from "@/api/mutator";
import {
type getSkillPackApiV1SkillsPacksPackIdGetResponse,
useGetSkillPackApiV1SkillsPacksPackIdGet,
useUpdateSkillPackApiV1SkillsPacksPackIdPatch,
} from "@/api/generated/skills/skills";
import { MarketplaceSkillForm } from "@/components/skills/MarketplaceSkillForm";
import { DashboardPageLayout } from "@/components/templates/DashboardPageLayout";
import { useOrganizationMembership } from "@/lib/use-organization-membership";
export default function EditSkillPackPage() {
const router = useRouter();
const params = useParams();
const { isSignedIn } = useAuth();
const { isAdmin } = useOrganizationMembership(isSignedIn);
const packIdParam = params?.packId;
const packId = Array.isArray(packIdParam) ? packIdParam[0] : packIdParam;
const packQuery = useGetSkillPackApiV1SkillsPacksPackIdGet<
getSkillPackApiV1SkillsPacksPackIdGetResponse,
ApiError
>(packId ?? "", {
query: {
enabled: Boolean(isSignedIn && isAdmin && packId),
refetchOnMount: "always",
retry: false,
},
});
const pack = (
packQuery.data?.status === 200 ? packQuery.data.data : null
);
const saveMutation = useUpdateSkillPackApiV1SkillsPacksPackIdPatch<ApiError>();
return (
<DashboardPageLayout
signedOut={{
message: "Sign in to edit skill packs.",
forceRedirectUrl: `/skills/packs/${packId ?? ""}/edit`,
}}
title={pack ? `Edit ${pack.name}` : "Edit skill pack"}
description="Update skill URL pack details."
isAdmin={isAdmin}
adminOnlyMessage="Only organization owners and admins can manage skill packs."
stickyHeader
>
{packQuery.isLoading ? (
<div className="rounded-xl border border-slate-200 bg-white p-6 text-sm text-slate-500 shadow-sm">
Loading pack...
</div>
) : packQuery.error ? (
<div className="rounded-xl border border-rose-200 bg-rose-50 p-6 text-sm text-rose-700 shadow-sm">
{packQuery.error.message}
</div>
) : !pack ? (
<div className="rounded-xl border border-slate-200 bg-white p-6 text-sm text-slate-500 shadow-sm">
Pack not found.
</div>
) : (
<MarketplaceSkillForm
key={pack.id}
initialValues={{
sourceUrl: pack.source_url,
name: pack.name,
description: pack.description ?? "",
}}
sourceLabel="Pack URL"
nameLabel="Pack name (optional)"
descriptionLabel="Pack description (optional)"
descriptionPlaceholder="Short summary shown in the packs list."
requiredUrlMessage="Pack URL is required."
submitLabel="Save changes"
submittingLabel="Saving..."
isSubmitting={saveMutation.isPending}
onCancel={() => router.push("/skills/packs")}
onSubmit={async (values) => {
const result = await saveMutation.mutateAsync({
packId: pack.id,
data: {
source_url: values.sourceUrl,
name: values.name || undefined,
description: values.description || undefined,
},
});
if (result.status !== 200) {
throw new Error("Unable to update pack.");
}
router.push("/skills/packs");
}}
/>
)}
</DashboardPageLayout>
);
}

View File

@@ -0,0 +1,60 @@
"use client";
export const dynamic = "force-dynamic";
import { useRouter } from "next/navigation";
import { useAuth } from "@/auth/clerk";
import { ApiError } from "@/api/mutator";
import { useCreateSkillPackApiV1SkillsPacksPost } from "@/api/generated/skills/skills";
import { MarketplaceSkillForm } from "@/components/skills/MarketplaceSkillForm";
import { DashboardPageLayout } from "@/components/templates/DashboardPageLayout";
import { useOrganizationMembership } from "@/lib/use-organization-membership";
export default function NewSkillPackPage() {
const router = useRouter();
const { isSignedIn } = useAuth();
const { isAdmin } = useOrganizationMembership(isSignedIn);
const createMutation = useCreateSkillPackApiV1SkillsPacksPost<ApiError>();
return (
<DashboardPageLayout
signedOut={{
message: "Sign in to add skill packs.",
forceRedirectUrl: "/skills/packs/new",
}}
title="Add skill pack"
description="Add a new skill URL pack for your organization."
isAdmin={isAdmin}
adminOnlyMessage="Only organization owners and admins can manage skill packs."
stickyHeader
>
<MarketplaceSkillForm
sourceLabel="Pack URL"
nameLabel="Pack name (optional)"
descriptionLabel="Pack description (optional)"
descriptionPlaceholder="Short summary shown in the packs list."
requiredUrlMessage="Pack URL is required."
submitLabel="Add pack"
submittingLabel="Adding..."
isSubmitting={createMutation.isPending}
onCancel={() => router.push("/skills/packs")}
onSubmit={async (values) => {
const result = await createMutation.mutateAsync({
data: {
source_url: values.sourceUrl,
name: values.name || undefined,
description: values.description || undefined,
},
});
if (result.status !== 200) {
throw new Error("Unable to add pack.");
}
router.push("/skills/packs");
}}
/>
</DashboardPageLayout>
);
}

View File

@@ -0,0 +1,188 @@
"use client";
export const dynamic = "force-dynamic";
import Link from "next/link";
import { useMemo, useState } from "react";
import { useAuth } from "@/auth/clerk";
import { useQueryClient } from "@tanstack/react-query";
import { ApiError } from "@/api/mutator";
import type { SkillPackRead } from "@/api/generated/model";
import {
getListSkillPacksApiV1SkillsPacksGetQueryKey,
type listSkillPacksApiV1SkillsPacksGetResponse,
useDeleteSkillPackApiV1SkillsPacksPackIdDelete,
useListSkillPacksApiV1SkillsPacksGet,
useSyncSkillPackApiV1SkillsPacksPackIdSyncPost,
} from "@/api/generated/skills/skills";
import { SkillPacksTable } from "@/components/skills/SkillPacksTable";
import { DashboardPageLayout } from "@/components/templates/DashboardPageLayout";
import { buttonVariants } from "@/components/ui/button";
import { ConfirmActionDialog } from "@/components/ui/confirm-action-dialog";
import { useOrganizationMembership } from "@/lib/use-organization-membership";
import { useUrlSorting } from "@/lib/use-url-sorting";
const PACKS_SORTABLE_COLUMNS = ["name", "source_url", "skill_count", "updated_at"];
export default function SkillsPacksPage() {
const queryClient = useQueryClient();
const { isSignedIn } = useAuth();
const { isAdmin } = useOrganizationMembership(isSignedIn);
const [deleteTarget, setDeleteTarget] = useState<SkillPackRead | null>(null);
const [syncingPackIds, setSyncingPackIds] = useState<Set<string>>(new Set());
const { sorting, onSortingChange } = useUrlSorting({
allowedColumnIds: PACKS_SORTABLE_COLUMNS,
defaultSorting: [{ id: "name", desc: false }],
paramPrefix: "skill_packs",
});
const packsQuery = useListSkillPacksApiV1SkillsPacksGet<
listSkillPacksApiV1SkillsPacksGetResponse,
ApiError
>({
query: {
enabled: Boolean(isSignedIn && isAdmin),
refetchOnMount: "always",
refetchInterval: 15_000,
},
});
const packsQueryKey = getListSkillPacksApiV1SkillsPacksGetQueryKey();
const packs = useMemo<SkillPackRead[]>(
() => (packsQuery.data?.status === 200 ? packsQuery.data.data : []),
[packsQuery.data],
);
const deleteMutation =
useDeleteSkillPackApiV1SkillsPacksPackIdDelete<ApiError>(
{
mutation: {
onSuccess: async () => {
setDeleteTarget(null);
await queryClient.invalidateQueries({
queryKey: packsQueryKey,
});
},
},
},
queryClient,
);
const syncMutation =
useSyncSkillPackApiV1SkillsPacksPackIdSyncPost<ApiError>(
{
mutation: {
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: packsQueryKey,
});
},
},
},
queryClient,
);
const handleDelete = () => {
if (!deleteTarget) return;
deleteMutation.mutate({ packId: deleteTarget.id });
};
return (
<>
<DashboardPageLayout
signedOut={{
message: "Sign in to manage skill packs.",
forceRedirectUrl: "/skills/packs",
}}
title="Skill Packs"
description={`${packs.length} pack${packs.length === 1 ? "" : "s"} configured.`}
headerActions={
isAdmin ? (
<Link
href="/skills/packs/new"
className={buttonVariants({ variant: "primary", size: "md" })}
>
Add pack
</Link>
) : null
}
isAdmin={isAdmin}
adminOnlyMessage="Only organization owners and admins can manage skill packs."
stickyHeader
>
<div className="space-y-6">
<div className="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm">
<SkillPacksTable
packs={packs}
isLoading={packsQuery.isLoading}
sorting={sorting}
onSortingChange={onSortingChange}
stickyHeader
getEditHref={(pack) => `/skills/packs/${pack.id}/edit`}
canSync
syncingPackIds={syncingPackIds}
onSync={(pack) => {
void (async () => {
setSyncingPackIds((previous) => {
const next = new Set(previous);
next.add(pack.id);
return next;
});
try {
await syncMutation.mutateAsync({
packId: pack.id,
});
} finally {
setSyncingPackIds((previous) => {
const next = new Set(previous);
next.delete(pack.id);
return next;
});
}
})();
}}
onDelete={setDeleteTarget}
emptyState={{
title: "No packs yet",
description: "Add your first skill URL pack to get started.",
actionHref: "/skills/packs/new",
actionLabel: "Add your first pack",
}}
/>
</div>
{packsQuery.error ? (
<p className="text-sm text-rose-600">{packsQuery.error.message}</p>
) : null}
{deleteMutation.error ? (
<p className="text-sm text-rose-600">{deleteMutation.error.message}</p>
) : null}
{syncMutation.error ? (
<p className="text-sm text-rose-600">{syncMutation.error.message}</p>
) : null}
</div>
</DashboardPageLayout>
<ConfirmActionDialog
open={Boolean(deleteTarget)}
onOpenChange={(open) => {
if (!open) setDeleteTarget(null);
}}
ariaLabel="Delete skill pack"
title="Delete skill pack"
description={
<>
This will remove <strong>{deleteTarget?.name}</strong> from your
pack list. This action cannot be undone.
</>
}
errorMessage={deleteMutation.error?.message}
onConfirm={handleDelete}
isConfirming={deleteMutation.isPending}
/>
</>
);
}

View File

@@ -1,412 +1,5 @@
"use client";
import { redirect } from "next/navigation";
export const dynamic = "force-dynamic";
import Link from "next/link";
import { FormEvent, useMemo, useState } from "react";
import { useAuth } from "@/auth/clerk";
import { useQueryClient } from "@tanstack/react-query";
import { ExternalLink, Package, PlusCircle, Trash2 } from "lucide-react";
import { ApiError } from "@/api/mutator";
import {
type listGatewaysApiV1GatewaysGetResponse,
useListGatewaysApiV1GatewaysGet,
} from "@/api/generated/gateways/gateways";
import type { MarketplaceSkillCardRead } from "@/api/generated/model";
import {
getListMarketplaceSkillsApiV1SkillsMarketplaceGetQueryKey,
type listMarketplaceSkillsApiV1SkillsMarketplaceGetResponse,
useCreateMarketplaceSkillApiV1SkillsMarketplacePost,
useDeleteMarketplaceSkillApiV1SkillsMarketplaceSkillIdDelete,
useInstallMarketplaceSkillApiV1SkillsMarketplaceSkillIdInstallPost,
useListMarketplaceSkillsApiV1SkillsMarketplaceGet,
useUninstallMarketplaceSkillApiV1SkillsMarketplaceSkillIdUninstallPost,
} from "@/api/generated/skills-marketplace/skills-marketplace";
import { DashboardPageLayout } from "@/components/templates/DashboardPageLayout";
import { Badge } from "@/components/ui/badge";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { formatRelativeTimestamp } from "@/lib/formatters";
import { useOrganizationMembership } from "@/lib/use-organization-membership";
export default function SkillsMarketplacePage() {
const queryClient = useQueryClient();
const { isSignedIn } = useAuth();
const { isAdmin } = useOrganizationMembership(isSignedIn);
const [selectedGatewayId, setSelectedGatewayId] = useState("");
const [sourceUrl, setSourceUrl] = useState("");
const [skillName, setSkillName] = useState("");
const [description, setDescription] = useState("");
const gatewaysQuery = useListGatewaysApiV1GatewaysGet<
listGatewaysApiV1GatewaysGetResponse,
ApiError
>(undefined, {
query: {
enabled: Boolean(isSignedIn && isAdmin),
refetchOnMount: "always",
refetchInterval: 30_000,
},
});
const gateways = useMemo(
() =>
gatewaysQuery.data?.status === 200
? (gatewaysQuery.data.data.items ?? [])
: [],
[gatewaysQuery.data],
);
const resolvedGatewayId = useMemo(() => {
if (selectedGatewayId && gateways.some((gateway) => gateway.id === selectedGatewayId)) {
return selectedGatewayId;
}
return gateways[0]?.id ?? "";
}, [gateways, selectedGatewayId]);
const skillsQueryKey = getListMarketplaceSkillsApiV1SkillsMarketplaceGetQueryKey(
resolvedGatewayId ? { gateway_id: resolvedGatewayId } : undefined,
);
const skillsQuery = useListMarketplaceSkillsApiV1SkillsMarketplaceGet<
listMarketplaceSkillsApiV1SkillsMarketplaceGetResponse,
ApiError
>(
{ gateway_id: resolvedGatewayId },
{
query: {
enabled: Boolean(isSignedIn && isAdmin && resolvedGatewayId),
refetchOnMount: "always",
refetchInterval: 15_000,
},
},
);
const skills = useMemo<MarketplaceSkillCardRead[]>(
() => (skillsQuery.data?.status === 200 ? skillsQuery.data.data : []),
[skillsQuery.data],
);
const createMutation =
useCreateMarketplaceSkillApiV1SkillsMarketplacePost<ApiError>(
{
mutation: {
onSuccess: async () => {
setSourceUrl("");
setSkillName("");
setDescription("");
await queryClient.invalidateQueries({
queryKey: skillsQueryKey,
});
},
},
},
queryClient,
);
const installMutation =
useInstallMarketplaceSkillApiV1SkillsMarketplaceSkillIdInstallPost<ApiError>(
{
mutation: {
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: skillsQueryKey,
});
},
},
},
queryClient,
);
const uninstallMutation =
useUninstallMarketplaceSkillApiV1SkillsMarketplaceSkillIdUninstallPost<ApiError>(
{
mutation: {
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: skillsQueryKey,
});
},
},
},
queryClient,
);
const deleteMutation =
useDeleteMarketplaceSkillApiV1SkillsMarketplaceSkillIdDelete<ApiError>(
{
mutation: {
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: skillsQueryKey,
});
},
},
},
queryClient,
);
const mutationError =
createMutation.error?.message ??
installMutation.error?.message ??
uninstallMutation.error?.message ??
deleteMutation.error?.message;
const handleAddSkill = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const normalizedUrl = sourceUrl.trim();
if (!normalizedUrl) return;
createMutation.mutate({
data: {
source_url: normalizedUrl,
name: skillName.trim() || undefined,
description: description.trim() || undefined,
},
});
};
const isMutating =
createMutation.isPending ||
installMutation.isPending ||
uninstallMutation.isPending ||
deleteMutation.isPending;
return (
<DashboardPageLayout
signedOut={{
message: "Sign in to manage marketplace skills.",
forceRedirectUrl: "/skills",
}}
title="Skills Marketplace"
description="Register skill links and install or uninstall them per gateway."
isAdmin={isAdmin}
adminOnlyMessage="Only organization owners and admins can manage skills."
stickyHeader
>
<div className="space-y-6">
{gateways.length === 0 ? (
<div className="rounded-xl border border-slate-200 bg-white p-6 text-sm text-slate-600 shadow-sm">
<p className="font-medium text-slate-900">No gateways available yet.</p>
<p className="mt-2">
Create a gateway first, then return here to install skills.
</p>
<Link
href="/gateways/new"
className={`${buttonVariants({ variant: "primary", size: "md" })} mt-4`}
>
Create gateway
</Link>
</div>
) : (
<Card>
<CardHeader className="border-b border-[color:var(--border)] pb-4">
<h2 className="font-heading text-lg font-semibold text-slate-900">
Add skill source
</h2>
<p className="text-sm text-slate-500">
Add a URL once, then install or uninstall the skill for the selected gateway.
</p>
</CardHeader>
<CardContent className="pt-5">
<form className="space-y-4" onSubmit={handleAddSkill}>
<div className="grid gap-4 md:grid-cols-[260px_1fr]">
<div className="space-y-2">
<label className="text-xs font-semibold uppercase tracking-wide text-slate-500">
Gateway
</label>
<Select value={resolvedGatewayId} onValueChange={setSelectedGatewayId}>
<SelectTrigger>
<SelectValue placeholder="Select gateway" />
</SelectTrigger>
<SelectContent>
{gateways.map((gateway) => (
<SelectItem key={gateway.id} value={gateway.id}>
{gateway.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<label
htmlFor="skill-url"
className="text-xs font-semibold uppercase tracking-wide text-slate-500"
>
Skill URL
</label>
<Input
id="skill-url"
type="url"
value={sourceUrl}
onChange={(event) => setSourceUrl(event.target.value)}
placeholder="https://github.com/org/skill-repo"
required
/>
</div>
</div>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<label
htmlFor="skill-name"
className="text-xs font-semibold uppercase tracking-wide text-slate-500"
>
Display name (optional)
</label>
<Input
id="skill-name"
value={skillName}
onChange={(event) => setSkillName(event.target.value)}
placeholder="Deploy Helper"
/>
</div>
<div className="space-y-2">
<label
htmlFor="skill-description"
className="text-xs font-semibold uppercase tracking-wide text-slate-500"
>
Description (optional)
</label>
<Textarea
id="skill-description"
value={description}
onChange={(event) => setDescription(event.target.value)}
placeholder="Short summary shown on the marketplace card."
className="min-h-[44px] py-3"
/>
</div>
</div>
<div className="flex items-center gap-3">
<Button
type="submit"
disabled={createMutation.isPending || !resolvedGatewayId}
>
<PlusCircle className="h-4 w-4" />
{createMutation.isPending ? "Adding…" : "Add skill"}
</Button>
{createMutation.error ? (
<p className="text-sm text-rose-600">
{createMutation.error.message}
</p>
) : null}
</div>
</form>
</CardContent>
</Card>
)}
{mutationError ? <p className="text-sm text-rose-600">{mutationError}</p> : null}
<div className="space-y-3">
<h2 className="font-heading text-lg font-semibold text-slate-900">
Marketplace skills
</h2>
{skillsQuery.isLoading ? (
<div className="rounded-xl border border-slate-200 bg-white p-6 text-sm text-slate-500 shadow-sm">
Loading skills
</div>
) : skillsQuery.error ? (
<div className="rounded-xl border border-rose-200 bg-rose-50 p-6 text-sm text-rose-700">
{skillsQuery.error.message}
</div>
) : skills.length === 0 ? (
<div className="rounded-xl border border-slate-200 bg-white p-6 text-sm text-slate-600 shadow-sm">
No skill links added yet.
</div>
) : (
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
{skills.map((skill) => (
<Card key={skill.id}>
<CardHeader className="border-b border-[color:var(--border)] pb-4">
<div className="flex items-start justify-between gap-3">
<div className="space-y-1">
<h3 className="text-base font-semibold text-slate-900">
{skill.name}
</h3>
<p className="text-sm text-slate-500">
{skill.description || "No description provided."}
</p>
</div>
<Badge variant={skill.installed ? "success" : "outline"}>
{skill.installed ? "Installed" : "Not installed"}
</Badge>
</div>
</CardHeader>
<CardContent className="space-y-4 pt-5">
<a
href={skill.source_url}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-2 text-sm font-medium text-[color:var(--accent)] hover:underline"
>
<ExternalLink className="h-4 w-4" />
Open source link
</a>
<p className="text-xs text-slate-500">
{skill.installed && skill.installed_at
? `Installed ${formatRelativeTimestamp(skill.installed_at)}`
: "Not installed on selected gateway"}
</p>
<div className="flex items-center gap-2">
{skill.installed ? (
<Button
type="button"
variant="outline"
onClick={() =>
uninstallMutation.mutate({
skillId: skill.id,
params: { gateway_id: resolvedGatewayId },
})
}
disabled={isMutating || !resolvedGatewayId}
>
<Package className="h-4 w-4" />
Uninstall
</Button>
) : (
<Button
type="button"
onClick={() =>
installMutation.mutate({
skillId: skill.id,
params: { gateway_id: resolvedGatewayId },
})
}
disabled={isMutating || !resolvedGatewayId}
>
<Package className="h-4 w-4" />
Install
</Button>
)}
<Button
type="button"
variant="ghost"
onClick={() => deleteMutation.mutate({ skillId: skill.id })}
disabled={isMutating}
aria-label={`Delete ${skill.name}`}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</CardContent>
</Card>
))}
</div>
)}
</div>
</div>
</DashboardPageLayout>
);
export default function SkillsIndexPage() {
redirect("/skills/marketplace");
}

View File

@@ -6,13 +6,14 @@ import {
Activity,
BarChart3,
Bot,
Boxes,
CheckCircle2,
Folder,
Building2,
LayoutGrid,
Network,
Package,
Settings,
Store,
Tags,
} from "lucide-react";
@@ -165,6 +166,42 @@ export function DashboardSidebar() {
</div>
</div>
<div>
{isAdmin ? (
<>
<p className="px-3 text-[11px] font-semibold uppercase tracking-wider text-slate-400">
Skills
</p>
<div className="mt-1 space-y-1">
<Link
href="/skills/marketplace"
className={cn(
"flex items-center gap-3 rounded-lg px-3 py-2.5 text-slate-700 transition",
pathname === "/skills" || pathname.startsWith("/skills/marketplace")
? "bg-blue-100 text-blue-800 font-medium"
: "hover:bg-slate-100",
)}
>
<Store className="h-4 w-4" />
Marketplace
</Link>
<Link
href="/skills/packs"
className={cn(
"flex items-center gap-3 rounded-lg px-3 py-2.5 text-slate-700 transition",
pathname.startsWith("/skills/packs")
? "bg-blue-100 text-blue-800 font-medium"
: "hover:bg-slate-100",
)}
>
<Boxes className="h-4 w-4" />
Packs
</Link>
</div>
</>
) : null}
</div>
<div>
<p className="px-3 text-[11px] font-semibold uppercase tracking-wider text-slate-400">
Administration
@@ -196,20 +233,6 @@ export function DashboardSidebar() {
Gateways
</Link>
) : null}
{isAdmin ? (
<Link
href="/skills"
className={cn(
"flex items-center gap-3 rounded-lg px-3 py-2.5 text-slate-700 transition",
pathname.startsWith("/skills")
? "bg-blue-100 text-blue-800 font-medium"
: "hover:bg-slate-100",
)}
>
<Package className="h-4 w-4" />
Skills
</Link>
) : null}
{isAdmin ? (
<Link
href="/agents"

View File

@@ -8,13 +8,14 @@ import { clearLocalAuthToken, isLocalAuthMode } from "@/auth/localAuth";
import {
Activity,
Bot,
Boxes,
ChevronDown,
LayoutDashboard,
LogOut,
Package,
Plus,
Server,
Settings,
Store,
Trello,
} from "lucide-react";
@@ -156,7 +157,12 @@ export function UserMenu({
{ href: "/activity", label: "Activity", icon: Activity },
{ href: "/agents", label: "Agents", icon: Bot },
{ href: "/gateways", label: "Gateways", icon: Server },
{ href: "/skills", label: "Skills", icon: Package },
{
href: "/skills/marketplace",
label: "Skills marketplace",
icon: Store,
},
{ href: "/skills/packs", label: "Skill packs", icon: Boxes },
{ href: "/settings", label: "Settings", icon: Settings },
] as const
).map((item) => (

View File

@@ -0,0 +1,170 @@
import { useState } from "react";
import { ApiError } from "@/api/mutator";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
type MarketplaceSkillFormValues = {
sourceUrl: string;
name: string;
description: string;
};
type MarketplaceSkillFormProps = {
initialValues?: MarketplaceSkillFormValues;
sourceUrlReadOnly?: boolean;
sourceUrlHelpText?: string;
sourceLabel?: string;
sourcePlaceholder?: string;
nameLabel?: string;
namePlaceholder?: string;
descriptionLabel?: string;
descriptionPlaceholder?: string;
requiredUrlMessage?: string;
submitLabel: string;
submittingLabel: string;
isSubmitting: boolean;
onCancel: () => void;
onSubmit: (values: MarketplaceSkillFormValues) => Promise<void>;
};
const DEFAULT_VALUES: MarketplaceSkillFormValues = {
sourceUrl: "",
name: "",
description: "",
};
const extractErrorMessage = (error: unknown, fallback: string) => {
if (error instanceof ApiError) return error.message || fallback;
if (error instanceof Error) return error.message || fallback;
return fallback;
};
export function MarketplaceSkillForm({
initialValues,
sourceUrlReadOnly = false,
sourceUrlHelpText,
sourceLabel = "Skill URL",
sourcePlaceholder = "https://github.com/org/skill-repo",
nameLabel = "Name (optional)",
namePlaceholder = "Deploy Helper",
descriptionLabel = "Description (optional)",
descriptionPlaceholder = "Short summary shown in the marketplace.",
requiredUrlMessage = "Skill URL is required.",
submitLabel,
submittingLabel,
isSubmitting,
onCancel,
onSubmit,
}: MarketplaceSkillFormProps) {
const resolvedInitial = initialValues ?? DEFAULT_VALUES;
const [sourceUrl, setSourceUrl] = useState(resolvedInitial.sourceUrl);
const [name, setName] = useState(resolvedInitial.name);
const [description, setDescription] = useState(resolvedInitial.description);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const normalizedUrl = sourceUrl.trim();
if (!normalizedUrl) {
setErrorMessage(requiredUrlMessage);
return;
}
setErrorMessage(null);
try {
await onSubmit({
sourceUrl: normalizedUrl,
name: name.trim(),
description: description.trim(),
});
} catch (error) {
setErrorMessage(extractErrorMessage(error, "Unable to save skill."));
}
};
return (
<form
onSubmit={handleSubmit}
className="space-y-6 rounded-xl border border-slate-200 bg-white p-6 shadow-sm"
>
<div className="space-y-5">
<div className="space-y-2">
<label
htmlFor="source-url"
className="text-xs font-semibold uppercase tracking-wider text-slate-500"
>
{sourceLabel}
</label>
<Input
id="source-url"
type="url"
value={sourceUrl}
onChange={(event) => setSourceUrl(event.target.value)}
placeholder={sourcePlaceholder}
readOnly={sourceUrlReadOnly}
disabled={isSubmitting || sourceUrlReadOnly}
/>
{sourceUrlHelpText ? (
<p className="text-xs text-slate-500">{sourceUrlHelpText}</p>
) : null}
</div>
<div className="space-y-2">
<label
htmlFor="skill-name"
className="text-xs font-semibold uppercase tracking-wider text-slate-500"
>
{nameLabel}
</label>
<Input
id="skill-name"
value={name}
onChange={(event) => setName(event.target.value)}
placeholder={namePlaceholder}
disabled={isSubmitting}
/>
</div>
<div className="space-y-2">
<label
htmlFor="skill-description"
className="text-xs font-semibold uppercase tracking-wider text-slate-500"
>
{descriptionLabel}
</label>
<Textarea
id="skill-description"
value={description}
onChange={(event) => setDescription(event.target.value)}
placeholder={descriptionPlaceholder}
className="min-h-[120px]"
disabled={isSubmitting}
/>
</div>
{errorMessage ? (
<div className="rounded-lg border border-rose-200 bg-rose-50 p-3 text-sm text-rose-700">
{errorMessage}
</div>
) : null}
</div>
<div className="flex justify-end gap-3">
<Button
type="button"
variant="outline"
onClick={onCancel}
disabled={isSubmitting}
>
Cancel
</Button>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? submittingLabel : submitLabel}
</Button>
</div>
</form>
);
}

View File

@@ -0,0 +1,269 @@
import { useMemo, useState } from "react";
import Link from "next/link";
import {
type ColumnDef,
type OnChangeFn,
type SortingState,
type Updater,
getCoreRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
import type { MarketplaceSkillCardRead } from "@/api/generated/model";
import { DataTable, type DataTableEmptyState } from "@/components/tables/DataTable";
import { dateCell } from "@/components/tables/cell-formatters";
import { Button, buttonVariants } from "@/components/ui/button";
import { truncateText as truncate } from "@/lib/formatters";
type MarketplaceSkillsTableProps = {
skills: MarketplaceSkillCardRead[];
isLoading?: boolean;
sorting?: SortingState;
onSortingChange?: OnChangeFn<SortingState>;
stickyHeader?: boolean;
disableSorting?: boolean;
canInstallActions: boolean;
isMutating?: boolean;
onSkillClick?: (skill: MarketplaceSkillCardRead) => void;
onUninstall: (skill: MarketplaceSkillCardRead) => void;
onDelete?: (skill: MarketplaceSkillCardRead) => void;
getEditHref?: (skill: MarketplaceSkillCardRead) => string;
emptyState?: Omit<DataTableEmptyState, "icon"> & {
icon?: DataTableEmptyState["icon"];
};
};
const DEFAULT_EMPTY_ICON = (
<svg
className="h-16 w-16 text-slate-300"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M4 7h16" />
<path d="M4 12h16" />
<path d="M4 17h16" />
<path d="M8 7v10" />
<path d="M16 7v10" />
</svg>
);
const toPackUrl = (sourceUrl: string): string => {
try {
const parsed = new URL(sourceUrl);
const treeMarker = "/tree/";
const markerIndex = parsed.pathname.indexOf(treeMarker);
if (markerIndex > 0) {
const repoPath = parsed.pathname.slice(0, markerIndex);
return `${parsed.origin}${repoPath}`;
}
return sourceUrl;
} catch {
return sourceUrl;
}
};
const toPackLabel = (packUrl: string): string => {
try {
const parsed = new URL(packUrl);
const segments = parsed.pathname.split("/").filter(Boolean);
if (segments.length >= 2) {
return `${segments[0]}/${segments[1]}`;
}
return parsed.host;
} catch {
return "Open pack";
}
};
const toPackDetailHref = (packUrl: string): string => {
const params = new URLSearchParams({ source_url: packUrl });
return `/skills/packs/detail?${params.toString()}`;
};
export function MarketplaceSkillsTable({
skills,
isLoading = false,
sorting,
onSortingChange,
stickyHeader = false,
disableSorting = false,
canInstallActions,
isMutating = false,
onSkillClick,
onUninstall,
onDelete,
getEditHref,
emptyState,
}: MarketplaceSkillsTableProps) {
const [internalSorting, setInternalSorting] = useState<SortingState>([
{ id: "name", desc: false },
]);
const resolvedSorting = sorting ?? internalSorting;
const handleSortingChange: OnChangeFn<SortingState> =
onSortingChange ??
((updater: Updater<SortingState>) => {
setInternalSorting(updater);
});
const columns = useMemo<ColumnDef<MarketplaceSkillCardRead>[]>(() => {
const baseColumns: ColumnDef<MarketplaceSkillCardRead>[] = [
{
accessorKey: "name",
header: "Skill",
cell: ({ row }) => (
<div>
{onSkillClick ? (
<button
type="button"
onClick={() => onSkillClick(row.original)}
className="text-sm font-medium text-blue-700 hover:text-blue-600 hover:underline"
>
{row.original.name}
</button>
) : (
<p className="text-sm font-medium text-slate-900">{row.original.name}</p>
)}
<p className="mt-1 line-clamp-2 text-xs text-slate-500">
{row.original.description || "No description provided."}
</p>
</div>
),
},
{
accessorKey: "source_url",
header: "Pack",
cell: ({ row }) => {
const packUrl = toPackUrl(row.original.source_url);
return (
<Link
href={toPackDetailHref(packUrl)}
className="inline-flex items-center gap-1 text-sm font-medium text-slate-700 hover:text-blue-600"
>
{truncate(toPackLabel(packUrl), 40)}
</Link>
);
},
},
{
accessorKey: "category",
header: "Category",
cell: ({ row }) => (
<span className="text-sm text-slate-700">
{row.original.category || "uncategorized"}
</span>
),
},
{
accessorKey: "risk",
header: "Risk",
cell: ({ row }) => (
<span className="text-sm text-slate-700">
{row.original.risk || "unknown"}
</span>
),
},
{
accessorKey: "source",
header: "Source",
cell: ({ row }) => (
<span className="text-sm text-slate-700" title={row.original.source || ""}>
{truncate(row.original.source || "unknown", 36)}
</span>
),
},
{
accessorKey: "updated_at",
header: "Updated",
cell: ({ row }) => dateCell(row.original.updated_at),
},
{
id: "actions",
header: "",
enableSorting: false,
cell: ({ row }) => (
<div className="flex justify-end gap-2">
{row.original.installed ? (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => onUninstall(row.original)}
disabled={isMutating || !canInstallActions}
>
Uninstall
</Button>
) : null}
{getEditHref ? (
<Link
href={getEditHref(row.original)}
className={buttonVariants({ variant: "ghost", size: "sm" })}
>
Edit
</Link>
) : null}
{onDelete ? (
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => onDelete(row.original)}
disabled={isMutating}
>
Delete
</Button>
) : null}
</div>
),
},
];
return baseColumns;
}, [
canInstallActions,
getEditHref,
isMutating,
onDelete,
onSkillClick,
onUninstall,
]);
// eslint-disable-next-line react-hooks/incompatible-library
const table = useReactTable({
data: skills,
columns,
enableSorting: !disableSorting,
state: {
...(!disableSorting ? { sorting: resolvedSorting } : {}),
},
...(disableSorting ? {} : { onSortingChange: handleSortingChange }),
getCoreRowModel: getCoreRowModel(),
...(disableSorting ? {} : { getSortedRowModel: getSortedRowModel() }),
});
return (
<DataTable
table={table}
isLoading={isLoading}
stickyHeader={stickyHeader}
rowClassName="transition hover:bg-slate-50"
cellClassName="px-6 py-4 align-top"
emptyState={
emptyState
? {
icon: emptyState.icon ?? DEFAULT_EMPTY_ICON,
title: emptyState.title,
description: emptyState.description,
actionHref: emptyState.actionHref,
actionLabel: emptyState.actionLabel,
}
: undefined
}
/>
);
}

View File

@@ -0,0 +1,188 @@
import { useMemo, useState } from "react";
import Link from "next/link";
import {
type ColumnDef,
type OnChangeFn,
type SortingState,
type Updater,
getCoreRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
import type { SkillPackRead } from "@/api/generated/model";
import { DataTable, type DataTableEmptyState } from "@/components/tables/DataTable";
import { dateCell } from "@/components/tables/cell-formatters";
import { Button } from "@/components/ui/button";
import { truncateText as truncate } from "@/lib/formatters";
type SkillPacksTableProps = {
packs: SkillPackRead[];
isLoading?: boolean;
sorting?: SortingState;
onSortingChange?: OnChangeFn<SortingState>;
stickyHeader?: boolean;
canSync?: boolean;
syncingPackIds?: Set<string>;
onSync?: (pack: SkillPackRead) => void;
onDelete?: (pack: SkillPackRead) => void;
getEditHref?: (pack: SkillPackRead) => string;
emptyState?: Omit<DataTableEmptyState, "icon"> & {
icon?: DataTableEmptyState["icon"];
};
};
const DEFAULT_EMPTY_ICON = (
<svg
className="h-16 w-16 text-slate-300"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M4 7h16" />
<path d="M4 12h16" />
<path d="M4 17h16" />
<path d="M8 7v10" />
<path d="M16 7v10" />
</svg>
);
export function SkillPacksTable({
packs,
isLoading = false,
sorting,
onSortingChange,
stickyHeader = false,
canSync = false,
syncingPackIds,
onSync,
onDelete,
getEditHref,
emptyState,
}: SkillPacksTableProps) {
const [internalSorting, setInternalSorting] = useState<SortingState>([
{ id: "name", desc: false },
]);
const resolvedSorting = sorting ?? internalSorting;
const handleSortingChange: OnChangeFn<SortingState> =
onSortingChange ??
((updater: Updater<SortingState>) => {
setInternalSorting(updater);
});
const columns = useMemo<ColumnDef<SkillPackRead>[]>(() => {
const baseColumns: ColumnDef<SkillPackRead>[] = [
{
accessorKey: "name",
header: "Pack",
cell: ({ row }) => (
<div>
<p className="text-sm font-medium text-slate-900">{row.original.name}</p>
<p className="mt-1 line-clamp-2 text-xs text-slate-500">
{row.original.description || "No description provided."}
</p>
</div>
),
},
{
accessorKey: "source_url",
header: "Pack URL",
cell: ({ row }) => (
<Link
href={row.original.source_url}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 text-sm font-medium text-slate-700 hover:text-blue-600"
>
{truncate(row.original.source_url, 48)}
</Link>
),
},
{
accessorKey: "skill_count",
header: "Skills",
cell: ({ row }) => (
<Link
href={`/skills/marketplace?packId=${encodeURIComponent(row.original.id)}`}
className="text-sm font-medium text-blue-700 hover:text-blue-600 hover:underline"
>
{row.original.skill_count ?? 0}
</Link>
),
},
{
accessorKey: "updated_at",
header: "Updated",
cell: ({ row }) => dateCell(row.original.updated_at),
},
{
id: "sync",
header: "",
enableSorting: false,
cell: ({ row }) => {
if (!onSync) return null;
const isThisPackSyncing = Boolean(syncingPackIds?.has(row.original.id));
return (
<div className="flex justify-end">
<Button
type="button"
size="sm"
variant="outline"
onClick={() => onSync(row.original)}
disabled={isThisPackSyncing || !canSync}
>
{isThisPackSyncing ? "Syncing..." : "Sync"}
</Button>
</div>
);
},
},
];
return baseColumns;
}, [canSync, onSync, syncingPackIds]);
// eslint-disable-next-line react-hooks/incompatible-library
const table = useReactTable({
data: packs,
columns,
state: {
sorting: resolvedSorting,
},
onSortingChange: handleSortingChange,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
});
return (
<DataTable
table={table}
isLoading={isLoading}
stickyHeader={stickyHeader}
rowClassName="transition hover:bg-slate-50"
cellClassName="px-6 py-4 align-top"
rowActions={
getEditHref || onDelete
? {
...(getEditHref ? { getEditHref } : {}),
...(onDelete ? { onDelete } : {}),
}
: undefined
}
emptyState={
emptyState
? {
icon: emptyState.icon ?? DEFAULT_EMPTY_ICON,
title: emptyState.title,
description: emptyState.description,
actionHref: emptyState.actionHref,
actionLabel: emptyState.actionLabel,
}
: undefined
}
/>
);
}