diff --git a/src/components/SkillInstallSurface.tsx b/src/components/SkillInstallSurface.tsx index 73b45001a1..a3c12dad0c 100644 --- a/src/components/SkillInstallSurface.tsx +++ b/src/components/SkillInstallSurface.tsx @@ -23,7 +23,7 @@ type SkillCommandLineCardProps = { }; export function OpenClawCliInstallCommand({ command }: { command: string }) { - const match = command.match(/^(openclaw (?:skills|plugins) install)( .+)$/); + const match = command.match(/^(openclaw (?:(?:skills|plugins) install|templates add))( .+)$/); if (!match) { return {command}; } @@ -72,6 +72,7 @@ export function SkillCommandLineCard({ } type InstallCommandCardProps = { + copyEnabled?: boolean; cliCommand: string; prompt: string; cliCopyAriaLabel?: string; @@ -83,6 +84,7 @@ type InstallCommandCardProps = { }; export function InstallCommandCard({ + copyEnabled = true, cliCommand, prompt, cliCopyAriaLabel = "Copy OpenClaw CLI command", @@ -176,21 +178,23 @@ export function InstallCommandCard({ {activeInstallText} )} - + {copyEnabled ? ( + + ) : null} diff --git a/src/components/TemplateDetailPage.tsx b/src/components/TemplateDetailPage.tsx new file mode 100644 index 0000000000..2aa26e091d --- /dev/null +++ b/src/components/TemplateDetailPage.tsx @@ -0,0 +1,399 @@ +import type { TemplateManifest } from "clawhub-schema"; +import { TEMPLATE_CATEGORY_DEFINITIONS } from "clawhub-schema/catalogMetadata"; +import { useEffect, useId, useMemo, useRef, useState } from "react"; +import { fetchPackageFile, type PackageDetailResponse } from "../lib/packageApi"; +import { parseTemplateDocument } from "../lib/templateDetail"; +import { isTemplateReadyToAdd, templateSecurityStatusMessage } from "../lib/templateRoutes"; +import { DetailSecuritySummaryLabel } from "./DetailSecuritySummary"; +import { MarkdownPreview } from "./MarkdownPreview"; +import { SidebarMetadata } from "./SidebarMetadata"; +import { formatOpenClawPrompt } from "./skillDetailUtils"; +import { InstallCommandCard } from "./SkillInstallSurface"; +import { UserBadge } from "./UserBadge"; +import "./template-detail.css"; + +const tabs = ["CLAW.md", "Skills", "Automations", "Plugins", "Workspace files"] as const; +type TemplateTab = (typeof tabs)[number]; +type Package = NonNullable; + +export function TemplateDetailPage({ + detail, + contents, + fallbackOwner, +}: { + detail: PackageDetailResponse; + contents: string | null; + fallbackOwner: string; +}) { + const pkg = detail.package!; + const { markdown, manifest } = useMemo(() => parseTemplateDocument(contents), [contents]); + const [activeTab, setActiveTab] = useState("CLAW.md"); + const tabRefs = useRef>([]); + const id = useId(); + const summary = pkg.templateManifestSummary; + const categories = (pkg.categories ?? manifest?.categories ?? []).map( + (slug) => + TEMPLATE_CATEGORY_DEFINITIONS.find((category) => category.slug === slug)?.label ?? slug, + ); + const description = pkg.summary ?? summary?.agent.description ?? manifest?.agent.description; + const scanStatus = pkg.scanStatus ?? "pending"; + const ready = isTemplateReadyToAdd(scanStatus) && Boolean(pkg.latestVersion); + const installCommand = "openclaw templates add " + pkg.name; + const securityLabel = { + clean: "Clean", + suspicious: "Suspicious", + malicious: "Malicious", + pending: "Pending", + "not-run": "Not run", + }[scanStatus]; + + return ( +
+
+
+ {categories.length ? ( +

{categories.join(" · ")}

+ ) : null} +

{summary?.agent.name || manifest?.agent.name || pkg.displayName}

+ {description ?

{description}

: null} +
+ +
+
+
+
+
+ + {!ready ? ( +

+ {isTemplateReadyToAdd(scanStatus) + ? "This Template has no current release available to add." + : templateSecurityStatusMessage(scanStatus)} +

+ ) : null} +
+
+
+ {tabs.map((tab, index) => ( + + ))} +
+ {tabs.map((tab, index) => ( + + ))} +
+
+ +
+
+
+ ); +} + +function ContentMessage({ children }: { children: React.ReactNode }) { + return

{children}

; +} + +function TemplatePackages({ + manifest, + kind, +}: { + manifest: TemplateManifest; + kind: "skill" | "plugin"; +}) { + const packages = manifest.packages?.filter((entry) => entry.kind === kind) ?? []; + if (!packages.length) + return ( + + No {kind === "skill" ? "skills" : "plugins"} are included in this Template. + + ); + return ( +
    + {packages.map((entry) => ( +
  • + {entry.ref} + + Version {entry.version} · {entry.source} + +
  • + ))} +
+ ); +} + +function TemplateAutomations({ manifest }: { manifest: TemplateManifest }) { + if (!manifest.cronJobs?.length) + return No automations are included in this Template.; + return ( +
    + {manifest.cronJobs.map((job) => ( +
  • + {job.name || job.id} + + {job.schedule.cron} · {job.schedule.timezone} · {job.session} session + +

    {job.message}

    + {job.delivery ? ( + + Delivery: {job.delivery.mode} + {job.delivery.channel ? " · " + job.delivery.channel : ""} + + ) : null} +
  • + ))} +
+ ); +} + +function TemplateWorkspace({ + manifest, + pkg, + markdown, +}: { + manifest: TemplateManifest; + pkg: Package; + markdown: string | null; +}) { + const files: Array<{ path: string; source: string; contents?: string }> = [ + ...Object.entries(manifest.workspace?.bootstrapFiles ?? {}).map(([path, entry]) => ({ + path, + source: entry.source, + })), + ...(manifest.workspace?.files ?? []), + ]; + if (markdown?.trim() && !files.some((file) => file.path.toUpperCase() === "SOUL.MD")) { + files.unshift({ path: "SOUL.md", source: "CLAW.md body", contents: markdown }); + } + const [selectedPath, setSelectedPath] = useState(null); + const selectedFile = files.find((file) => file.path === selectedPath); + if (!files.length) + return No workspace files are included in this Template.; + return ( +
+
    + {files.map((file) => ( +
  • + + {file.source} +
  • + ))} +
+ {selectedFile?.contents !== undefined ? ( +
+

SOUL.md

+ + {selectedFile.contents} + +
+ ) : selectedFile && pkg.latestVersion ? ( + + ) : null} +
+ ); +} + +function WorkspaceFilePreview({ + name, + version, + path, +}: { + name: string; + version: string; + path: string; +}) { + const [state, setState] = useState<{ contents?: string | null; error?: boolean }>({}); + const [attempt, setAttempt] = useState(0); + useEffect(() => { + let cancelled = false; + setState({}); + void fetchPackageFile(name, path, version).then( + (contents) => { + if (!cancelled) setState({ contents }); + }, + () => { + if (!cancelled) setState({ error: true }); + }, + ); + return () => { + cancelled = true; + }; + }, [name, path, version, attempt]); + return ( +
+

{path}

+ {state.error ? ( +

+ Could not load this file.{" "} + +

+ ) : state.contents === undefined ? ( +

Loading file…

+ ) : state.contents === null ? ( +

File preview is unavailable for this release.

+ ) : /\.md$/i.test(path) ? ( + {state.contents} + ) : ( +
+          {state.contents}
+        
+ )} +
+ ); +} diff --git a/src/components/skillDetailUtils.ts b/src/components/skillDetailUtils.ts index 688a1c90aa..7980579483 100644 --- a/src/components/skillDetailUtils.ts +++ b/src/components/skillDetailUtils.ts @@ -170,8 +170,8 @@ export function formatSkillsCliInstallCommand(skillPageUrl: string) { } // Keep the copied prompt short: the agent resolves, inspects, and installs the -// named ClawHub skill or plugin through its own install flow. -export function formatOpenClawPrompt(name: string, kind: "skill" | "package") { +// named ClawHub skill, plugin or template through its own install flow. +export function formatOpenClawPrompt(name: string, kind: "skill" | "package" | "template") { return `Install the ${name.trim()} ${kind} from ClawHub`; } diff --git a/src/components/template-detail.css b/src/components/template-detail.css new file mode 100644 index 0000000000..46ef5d6255 --- /dev/null +++ b/src/components/template-detail.css @@ -0,0 +1,346 @@ +/* Visible plugin-style composition from the Paper template-detail reference. */ +.template-detail-page { + width: 100%; + padding: 55.672px 24px 48px; + color: var(--ink); + font-family: var(--font-body); + letter-spacing: -0.14px; +} + +.template-detail-container { + max-width: 1200px; + margin-inline: auto; +} + +.template-detail-hero { + max-width: 744px; + margin-bottom: 64px; +} + +.template-detail-category { + margin: 0 0 18px; + color: var(--oc-text-muted); + font-size: 12px; + font-weight: 520; + line-height: 12px; +} + +.template-detail-hero h1 { + margin: 0; + font-family: inherit; + font-size: 36px; + font-weight: 700; + line-height: 1.05; + overflow-wrap: anywhere; +} + +.template-detail-description { + margin: 14px 0 0; + color: var(--ink-soft); + font-size: 14px; + line-height: 1.4; + overflow-wrap: anywhere; +} + +.template-detail-publisher { + display: flex; + align-items: center; + min-height: 40.891px; + margin-top: 30px; +} + +.template-detail-publisher .user-name, +.template-detail-publisher .user-handle { + font-family: inherit; +} + +.template-detail-layout { + display: grid; + grid-template-columns: minmax(0, 744px) minmax(0, 360px); + column-gap: 96px; + align-items: start; +} + +.template-detail-main, +.template-detail-metadata { + min-width: 0; +} + +.template-detail-install .skill-install-command-header { + box-sizing: border-box; + min-height: 52px; + margin: 0; + padding-bottom: 16px; + border-bottom: 1px solid var(--line); + align-items: center; +} + +.template-detail-install .skill-install-panel-title { + margin: 0; + font-family: inherit; + font-size: 17.28px; + font-weight: 700; + line-height: 21.6px; +} + +.template-detail-install .skill-install-command-shell { + min-height: 54px; + background: var(--oc-bg-surface); +} + +.template-detail-install-warning { + margin: 12px 0 0; + color: var(--status-warning-fg); + font-size: 14px; + line-height: 1.5; +} + +.template-detail-contents { + margin-top: 48px; +} + +.template-detail-tabs { + display: flex; + gap: 22px; + min-width: 0; + overflow-x: auto; + border-bottom: 1px solid var(--line); + scrollbar-width: thin; +} + +.template-detail-tabs > button { + flex: none; + height: 43px; + padding: 0; + border: 0; + border-bottom: 2px solid transparent; + background: transparent; + color: var(--ink-soft); + font: inherit; + font-size: 14px; + font-weight: 600; + line-height: 21px; + white-space: nowrap; + cursor: pointer; +} + +.template-detail-tabs > button[aria-selected="true"] { + border-bottom-color: var(--ink); + color: var(--ink); +} + +.template-detail-tabs > button:focus-visible, +.template-detail-panel:focus-visible, +.template-detail-entry-list button:focus-visible, +.template-detail-file-preview button:focus-visible { + outline: 2px solid var(--oc-focus-ring); + outline-offset: -3px; +} + +.template-detail-panel { + margin-top: 18px; + padding: 22px; + border: 1px solid color-mix(in srgb, var(--line) 78%, transparent); + border-radius: 8px; + background: color-mix(in srgb, var(--bg) 60%, var(--oc-bg-surface)); + overflow-wrap: anywhere; +} + +.template-detail-panel[hidden] { + display: none; +} + +.template-detail-markdown { + font-size: 14px; + line-height: 1.68; +} + +.template-detail-markdown :is(h1, h2, h3, h4) { + padding: 0; + border: 0; + font-family: inherit; + line-height: 1.25; +} + +.template-detail-markdown h1 { + margin: 0 0 14px; + font-size: 28px; + font-weight: 700; +} + +.template-detail-markdown h2 { + margin: 24px 0 14px; + font-size: 22px; + font-weight: 700; +} + +.template-detail-markdown p { + margin: 14px 0; +} + +.template-detail-markdown ul, +.template-detail-markdown ol { + margin: 14px 0; + padding-left: 24px; + font-size: 16px; + line-height: 28px; +} + +.template-detail-markdown li { + padding-left: 1.5px; + margin-bottom: 6.4px; +} + +.template-detail-markdown > :first-child { + margin-top: 0; +} + +.template-detail-markdown > :last-child { + margin-bottom: 0; +} + +.template-detail-metadata .sidebar-metadata-compact > .sidebar-metadata-row:first-child { + min-height: 69.188px; + gap: 12px; + padding-bottom: 16px; +} + +.template-detail-metadata .sidebar-metadata-label { + font-family: inherit; + font-size: 13.76px; + font-weight: 700; + line-height: 16.512px; +} + +.template-detail-metadata .sidebar-metadata-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + column-gap: 32px; +} + +.template-detail-metadata .sidebar-metadata-grid .sidebar-metadata-row + .sidebar-metadata-row { + padding-left: 2px; +} + +.template-detail-metadata .sidebar-metadata-value { + font-family: inherit; + font-size: 16px; + font-weight: 700; + line-height: 21.6px; + overflow-wrap: anywhere; +} + +.template-detail-security-value { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 2px; + align-items: center; + line-height: 19.2px; +} + +.template-detail-security-value .security-audit-meter { + margin-right: 10px; +} + +.template-detail-content-message { + margin: 0; + color: var(--ink-soft); + font-size: 14px; + line-height: 1.6; +} + +.template-detail-entry-list { + margin: 0; + padding: 0; + list-style: none; +} + +.template-detail-entry-list > li { + display: grid; + gap: 6px; + padding: 16px 0; + border-bottom: 1px solid var(--line); + font-size: 14px; +} + +.template-detail-entry-list > li:first-child { + padding-top: 0; +} + +.template-detail-entry-list > li:last-child { + padding-bottom: 0; + border-bottom: 0; +} + +.template-detail-entry-meta { + color: var(--ink-soft); + font-size: 13px; + line-height: 1.5; +} + +.template-detail-job-message { + margin: 6px 0; + white-space: pre-wrap; +} + +.template-detail-entry-list button, +.template-detail-file-preview button { + justify-self: start; + padding: 0; + background: transparent; + color: var(--ink); + text-align: left; + text-decoration: underline; + text-underline-offset: 3px; + cursor: pointer; +} + +.template-detail-entry-list button[aria-pressed="true"] { + color: var(--accent); +} + +.template-detail-file-preview { + margin-top: 24px; + padding-top: 20px; + border-top: 1px solid var(--line); +} + +.template-detail-file-preview h3 { + margin: 0 0 18px; + font-size: 14px; +} + +.template-detail-file-preview pre { + max-width: 100%; + overflow: auto; + font-size: 13px; +} + +@media (max-width: 1100px) { + .template-detail-layout { + grid-template-columns: minmax(0, 1fr) minmax(0, 300px); + column-gap: 40px; + } +} + +@media (max-width: 800px) { + .template-detail-page { + padding: 36px 20px 48px; + } + + .template-detail-hero { + margin-bottom: 40px; + } + + .template-detail-layout { + grid-template-columns: minmax(0, 1fr); + row-gap: 36px; + } + + .template-detail-metadata { + grid-row: 1; + } + + .template-detail-panel { + padding: 20px; + } +} diff --git a/src/lib/templateDetail.ts b/src/lib/templateDetail.ts new file mode 100644 index 0000000000..d3e218a4c5 --- /dev/null +++ b/src/lib/templateDetail.ts @@ -0,0 +1,40 @@ +import { validateTemplateManifest, type TemplateManifest } from "clawhub-schema"; +import { parseDocument } from "yaml"; + +export function parseTemplateDocument(contents: string | null): { + markdown: string | null; + manifest: TemplateManifest | null; +} { + if (contents === null) return { markdown: null, manifest: null }; + const normalized = contents.replace(/^\uFEFF/, ""); + const frontmatter = normalized.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/); + if (!frontmatter) return { markdown: normalized, manifest: null }; + const markdown = normalized.slice(frontmatter[0].length).trim(); + try { + const document = parseDocument(frontmatter[1], { uniqueKeys: true }); + if (document.errors.length) return { markdown, manifest: null }; + const result = validateTemplateManifest(document.toJS({ maxAliasCount: 0 })); + return { markdown, manifest: result.ok ? result.manifest : null }; + } catch { + return { markdown, manifest: null }; + } +} + +/** The package entry point can live below the package root. */ +export function getTemplateManifestPath(packageJson: string | null): string { + try { + const value = JSON.parse(packageJson ?? "null"); + const path: unknown = value?.openclaw?.template; + if ( + typeof path === "string" && + !path.startsWith("/") && + !path.includes("\\") && + path.split("/").every((part) => part && part !== "." && part !== "..") && + path.split("/").at(-1) === "CLAW.md" + ) + return path; + } catch { + // Older registries may not expose package.json previews. + } + return "CLAW.md"; +} diff --git a/src/routes/$owner/templates/$slug.tsx b/src/routes/$owner/templates/$slug.tsx index 8c56a0c688..a8f3888946 100644 --- a/src/routes/$owner/templates/$slug.tsx +++ b/src/routes/$owner/templates/$slug.tsx @@ -1,24 +1,15 @@ -import { createFileRoute, notFound, redirect } from "@tanstack/react-router"; -import { Bot, Boxes, CalendarClock, Plug, ShieldAlert, ShieldCheck, Sparkles } from "lucide-react"; -import { DetailBody, DetailHero, DetailPageShell } from "../../../components/DetailPageShell"; -import { EmptyState } from "../../../components/EmptyState"; +import { createFileRoute, notFound, redirect, useRouter } from "@tanstack/react-router"; import { Container } from "../../../components/layout/Container"; -import { MarkdownPreview } from "../../../components/MarkdownPreview"; -import { Badge } from "../../../components/ui/badge"; -import { Button } from "../../../components/ui/button"; -import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card"; -import { UserBadge } from "../../../components/UserBadge"; -import { buildPublisherProfileHref } from "../../../lib/ownerRoute"; +import { TemplateDetailPage } from "../../../components/TemplateDetailPage"; import { fetchPackageDetail, fetchPackageFile, type PackageDetailResponse, } from "../../../lib/packageApi"; import { getClawHubSiteUrl } from "../../../lib/site"; +import { getTemplateManifestPath } from "../../../lib/templateDetail"; import { buildTemplateDetailHref, - templateSecurityStatusMessage, - isTemplateReadyToAdd, normalizePublisherHandle, packageNameFromPublisherTemplateRoute, } from "../../../lib/templateRoutes"; @@ -54,9 +45,18 @@ export async function loadPublisherTemplate(params: { ) { throw notFound(); } - const contents = detail.package.latestVersion - ? await fetchPackageFile(detail.package.name, "CLAW.md", detail.package.latestVersion) - : null; + let contents: string | null = null; + if (detail.package.latestVersion) { + const [rootContents, packageJson] = await Promise.all([ + fetchPackageFile(detail.package.name, "CLAW.md", detail.package.latestVersion), + fetchPackageFile(detail.package.name, "package.json", detail.package.latestVersion), + ]); + const manifestPath = getTemplateManifestPath(packageJson); + contents = + manifestPath === "CLAW.md" + ? rootContents + : await fetchPackageFile(detail.package.name, manifestPath, detail.package.latestVersion); + } return { detail, contents }; } @@ -103,6 +103,7 @@ export const Route = createFileRoute("/$owner/templates/$slug")({ }; }, pendingComponent: TemplateDetailPending, + errorComponent: TemplateDetailError, component: PublisherTemplatePage, }); @@ -118,129 +119,38 @@ function TemplateDetailPending() { ); } -function PublisherTemplatePage() { - const params = Route.useParams(); - const { detail, contents } = Route.useLoaderData() as TemplateDetailData; - const pkg = detail.package!; - const summary = pkg.templateManifestSummary; - const description = pkg.summary ?? summary?.agent.description ?? ""; - const owner = detail.owner; - const scanStatus = pkg.scanStatus ?? "pending"; - const readyToAdd = isTemplateReadyToAdd(scanStatus); - const stats = [ - { label: "Workspace files", value: summary?.workspace.fileCount ?? 0, icon: Boxes }, - { label: "Skills", value: summary?.packages.skillCount ?? 0, icon: Sparkles }, - { label: "Plugins", value: summary?.packages.pluginCount ?? 0, icon: Plug }, - { label: "Scheduled jobs", value: summary?.cronJobCount ?? 0, icon: CalendarClock }, - ]; - +function TemplateDetailError() { + const router = useRouter(); return ( -
- - - - -
-
-

- {summary?.agent.name || pkg.displayName || params.slug} -

- Template -
- {description ?

{description}

: null} -
- - - Version {pkg.latestVersion ?? "—"} - - - {scanStatus === "clean" ? ( - -
-
- - } - sidebar={ - - - - - - -

- {readyToAdd - ? "Find this Template in OpenClaw’s Templates catalog and add it as a new agent." - : templateSecurityStatusMessage(scanStatus)} -

- {readyToAdd ? ( - - ) : null} -
-
- } +
+ +
+

Could not load this Template

+

+ The registry could not return the Template details. Please try again. +

+ +
); } + +function PublisherTemplatePage() { + const params = Route.useParams(); + const { detail, contents } = Route.useLoaderData() as TemplateDetailData; + return ( + + ); +} diff --git a/src/routes/$owner/templates/-$slug.test.tsx b/src/routes/$owner/templates/-$slug.test.tsx index 29cd373660..47ad5674d6 100644 --- a/src/routes/$owner/templates/-$slug.test.tsx +++ b/src/routes/$owner/templates/-$slug.test.tsx @@ -1,5 +1,8 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { TemplateDetailPage } from "../../../components/TemplateDetailPage"; import type { PackageDetailResponse } from "../../../lib/packageApi"; +import { getTemplateManifestPath, parseTemplateDocument } from "../../../lib/templateDetail"; const mocks = vi.hoisted(() => ({ fetchPackageDetail: vi.fn(), @@ -7,8 +10,18 @@ const mocks = vi.hoisted(() => ({ })); vi.mock("../../../lib/packageApi", () => mocks); +// Exercise the real sanitized Markdown renderer without asynchronous syntax-engine setup. +vi.mock("../../../components/MarkdownPreview", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + MarkdownPreview: (props: { children: string; className?: string }) => ( + + ), + }; +}); -import { loadPublisherTemplate } from "./$slug"; +import { loadPublisherTemplate, Route } from "./$slug"; function packageDetail(family: "template" | "code-plugin" = "template"): PackageDetailResponse { return { @@ -83,3 +96,404 @@ describe("publisher Template detail route loader", () => { expect(mocks.fetchPackageFile).not.toHaveBeenCalled(); }); }); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +describe("publisher Template route invariants", () => { + beforeEach(() => { + vi.resetAllMocks(); + mocks.fetchPackageFile.mockResolvedValue("# Release Brief"); + }); + + it("falls back to an unscoped package only when its owner matches", async () => { + const detail = packageDetail(); + detail.package!.name = "release-brief"; + mocks.fetchPackageDetail + .mockResolvedValueOnce({ package: null, owner: null }) + .mockResolvedValueOnce(detail); + const loaded = await loadPublisherTemplate({ owner: "maker", slug: "release-brief" }); + expect(loaded.detail.package?.name).toBe("release-brief"); + expect(mocks.fetchPackageDetail.mock.calls).toEqual([ + ["@maker/release-brief"], + ["release-brief"], + ]); + expect(mocks.fetchPackageFile).toHaveBeenCalledWith("release-brief", "CLAW.md", "0.1.0"); + }); + + it("rejects an unscoped fallback owned by somebody else", async () => { + mocks.fetchPackageDetail + .mockResolvedValueOnce({ package: null, owner: null }) + .mockResolvedValueOnce({ ...packageDetail(), owner: { handle: "other" } }); + await expect( + loadPublisherTemplate({ owner: "maker", slug: "release-brief" }), + ).rejects.toMatchObject({ isNotFound: true }); + expect(mocks.fetchPackageFile).not.toHaveBeenCalled(); + }); + + it("does not request files without a release", async () => { + const detail = packageDetail(); + detail.package!.latestVersion = null; + mocks.fetchPackageDetail.mockResolvedValue(detail); + expect( + (await loadPublisherTemplate({ owner: "maker", slug: "release-brief" })).contents, + ).toBeNull(); + expect(mocks.fetchPackageFile).not.toHaveBeenCalled(); + }); + + it("reads the package's declared nested CLAW.md at the pinned release", async () => { + mocks.fetchPackageDetail.mockResolvedValue(packageDetail()); + mocks.fetchPackageFile.mockImplementation(async (_name, path) => + path === "package.json" + ? JSON.stringify({ openclaw: { template: "template/CLAW.md" } }) + : path === "template/CLAW.md" + ? "# Nested instructions" + : null, + ); + expect((await loadPublisherTemplate({ owner: "maker", slug: "release-brief" })).contents).toBe( + "# Nested instructions", + ); + expect(mocks.fetchPackageFile).toHaveBeenCalledWith( + "@maker/release-brief", + "template/CLAW.md", + "0.1.0", + ); + }); + + it("keeps registry errors as errors rather than reporting a missing Template", async () => { + mocks.fetchPackageDetail.mockRejectedValue(new Error("Registry unavailable")); + await expect(loadPublisherTemplate({ owner: "maker", slug: "release-brief" })).rejects.toThrow( + "Registry unavailable", + ); + }); + + it("redirects aliases to the actual package's canonical publisher URL", async () => { + const detail = packageDetail(); + detail.package!.name = "@maker/canonical-brief"; + mocks.fetchPackageDetail.mockResolvedValue(detail); + const loader = Route.options.loader; + if (typeof loader !== "function") throw new Error("Expected route loader"); + await expect( + loader({ params: { owner: "maker", slug: "release-brief" } } as Parameters[0]), + ).rejects.toMatchObject({ + options: { href: "/maker/templates/canonical-brief", replace: true }, + }); + }); + + it("rejects malformed publisher routes before querying the registry", async () => { + await expect( + loadPublisherTemplate({ owner: "../maker", slug: "release-brief" }), + ).rejects.toMatchObject({ isNotFound: true }); + expect(mocks.fetchPackageDetail).not.toHaveBeenCalled(); + }); +}); + +const manifest = { + schemaVersion: 1, + agent: { id: "release-brief", name: "Release Brief" }, + categories: ["engineering"], + workspace: { + bootstrapFiles: { "AGENTS.md": { source: "workspace/AGENTS.md" } }, + files: [{ path: "notes/checklist.txt", source: "workspace/checklist.txt" }], + }, + packages: [ + { kind: "skill", source: "clawhub", ref: "@maker/release-search", version: "1.2.3" }, + { kind: "plugin", source: "clawhub", ref: "@maker/release-alerts", version: "2.0.0" }, + ], + cronJobs: [ + { + id: "weekday-brief", + name: "Weekday release brief", + schedule: { cron: "0 9 * * 1-5", timezone: "America/Los_Angeles" }, + session: "isolated", + message: "Summarize the approved release sources.", + delivery: { mode: "none" }, + }, + ], +}; +const templateContents = + "---\n" + + JSON.stringify(manifest) + + "\n---\n# Release instructions\n\nRead the actual release notes."; + +function renderTemplate( + options: { + status?: NonNullable["scanStatus"]; + contents?: string | null; + version?: string | null; + } = {}, +) { + const detail = packageDetail(); + detail.package!.scanStatus = options.status ?? "clean"; + detail.package!.updatedAt = Date.UTC(2026, 10, 5); + if ("version" in options) detail.package!.latestVersion = options.version; + return render( + , + ); +} + +describe("Template detail composition and interactions", () => { + beforeEach(() => { + vi.resetAllMocks(); + mocks.fetchPackageFile.mockResolvedValue("# Workspace instructions\n\nActual file contents."); + }); + + it("defaults to rendered CLAW.md without exposing the manifest or old instructional UI", () => { + renderTemplate(); + expect(screen.getByRole("tab", { name: "CLAW.md" }).getAttribute("aria-selected")).toBe("true"); + expect(screen.getByRole("heading", { name: "Release instructions" })).toBeTruthy(); + expect(screen.getByText("Engineering")).toBeTruthy(); + expect(screen.getByText("Maker")).toBeTruthy(); + expect(screen.getByText("@maker")).toBeTruthy(); + expect(screen.queryByText(/schemaVersion/)).toBeNull(); + expect(screen.queryByText("Add this Template")).toBeNull(); + expect(screen.queryByText("About this Template")).toBeNull(); + expect(screen.getByText("Clean")).toBeTruthy(); + expect(screen.getByText("Nov 5, 2026")).toBeTruthy(); + expect(screen.getByText("v0.1.0")).toBeTruthy(); + }); + + it("renders actual pinned package dependencies and automation configuration", () => { + renderTemplate(); + fireEvent.click(screen.getByRole("tab", { name: "Skills" })); + expect(screen.getByText("@maker/release-search")).toBeTruthy(); + expect(screen.getByText("Version 1.2.3 · clawhub")).toBeTruthy(); + expect(screen.queryByText("@maker/release-alerts")).toBeNull(); + fireEvent.click(screen.getByRole("tab", { name: "Plugins" })); + expect(screen.getByText("@maker/release-alerts")).toBeTruthy(); + expect(screen.getByText("Version 2.0.0 · clawhub")).toBeTruthy(); + fireEvent.click(screen.getByRole("tab", { name: "Automations" })); + expect(screen.getByText("Weekday release brief")).toBeTruthy(); + expect(screen.getByText("0 9 * * 1-5")).toBeTruthy(); + expect(screen.getByText(/America\/Los_Angeles/)).toBeTruthy(); + expect(screen.getByText("Summarize the approved release sources.")).toBeTruthy(); + }); + + it("supports roving focus, wrapping arrow keys, Home and End with linked panels", () => { + renderTemplate(); + const claw = screen.getByRole("tab", { name: "CLAW.md" }); + fireEvent.keyDown(claw, { key: "ArrowRight" }); + const skills = screen.getByRole("tab", { name: "Skills" }); + expect(document.activeElement).toBe(skills); + expect(skills.tabIndex).toBe(0); + expect(claw.tabIndex).toBe(-1); + expect(screen.getByRole("tabpanel").id).toBe(skills.getAttribute("aria-controls")); + fireEvent.keyDown(skills, { key: "End" }); + const workspace = screen.getByRole("tab", { name: "Workspace files" }); + expect(document.activeElement).toBe(workspace); + fireEvent.keyDown(workspace, { key: "ArrowRight" }); + expect(document.activeElement).toBe(claw); + fireEvent.keyDown(claw, { key: "ArrowLeft" }); + expect(document.activeElement).toBe(workspace); + fireEvent.keyDown(workspace, { key: "Home" }); + expect(document.activeElement).toBe(claw); + }); + + it("copies the real package install command and reports success", async () => { + const writeText = vi.fn().mockResolvedValue(undefined); + Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } }); + renderTemplate(); + const button = screen.getByRole("button", { name: "Copy template install command" }); + fireEvent.click(button); + await waitFor(() => expect(button.getAttribute("data-copy-state")).toBe("copied")); + expect(writeText).toHaveBeenCalledWith("openclaw templates add @maker/release-brief"); + expect(document.querySelector(".skill-install-command-target")?.textContent).toBe( + " @maker/release-brief", + ); + expect(document.querySelector(".skill-install-command-verb")?.textContent).toBe( + "openclaw templates add", + ); + fireEvent.click(screen.getByRole("button", { name: "Prompt" })); + expect(screen.getByRole("button", { name: "Prompt" }).getAttribute("aria-pressed")).toBe( + "true", + ); + expect(screen.getByText("Install the @maker/release-brief template from ClawHub")).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Copy OpenClaw prompt" })); + await waitFor(() => + expect(writeText).toHaveBeenLastCalledWith( + "Install the @maker/release-brief template from ClawHub", + ), + ); + fireEvent.click(screen.getByRole("button", { name: "CLI" })); + expect(screen.getByRole("button", { name: "Copy template install command" })).toBeTruthy(); + }); + + it("truthfully reports clipboard failure", async () => { + Object.defineProperty(navigator, "clipboard", { + configurable: true, + value: { writeText: vi.fn().mockRejectedValue(new Error("Denied")) }, + }); + renderTemplate(); + const button = screen.getByRole("button", { name: "Copy template install command" }); + fireEvent.click(button); + await waitFor(() => expect(button.getAttribute("data-copy-state")).toBe("failed")); + }); + + it.each([ + ["pending", "Pending", /Security review pending/], + ["not-run", "Not run", /Security review has not started/], + ["suspicious", "Suspicious", /Security scan flagged/], + ["malicious", "Malicious", /marked this Template as malicious/], + ] as const)("preserves %s warnings and gates install copy", (status, label, warning) => { + renderTemplate({ status }); + expect(screen.getByText(label)).toBeTruthy(); + expect(screen.getAllByText(warning).length).toBeGreaterThan(0); + expect(screen.queryByRole("button", { name: "Copy template install command" })).toBeNull(); + expect(document.querySelector(".skill-install-command")?.textContent).toBe( + "openclaw templates add @maker/release-brief", + ); + fireEvent.click(screen.getByRole("button", { name: "Prompt" })); + expect(screen.queryByRole("button", { name: "Copy OpenClaw prompt" })).toBeNull(); + if (status === "suspicious" || status === "malicious") + expect(screen.getByRole("alert")).toBeTruthy(); + }); + + it("does not offer install copy for a clean package without a release", () => { + renderTemplate({ version: null }); + expect(screen.getByText("Not available")).toBeTruthy(); + expect(screen.getByText(/no current release/)).toBeTruthy(); + expect(screen.queryByRole("button", { name: "Copy template install command" })).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Prompt" })); + expect(screen.queryByRole("button", { name: "Copy OpenClaw prompt" })).toBeNull(); + }); + + it("previews the implicit SOUL.md from a body-only Template without fetching an archive file", () => { + renderTemplate({ + contents: + "---\n" + + JSON.stringify({ schemaVersion: 1, agent: { id: "release-brief" } }) + + "\n---\n# Managed instructions\n\nUse the published release notes.", + }); + fireEvent.click(screen.getByRole("tab", { name: "Workspace files" })); + expect(screen.queryByText("No workspace files are included in this Template.")).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "SOUL.md" })); + const preview = screen.getByRole("region", { name: "Preview of SOUL.md" }); + expect(within(preview).getByRole("heading", { name: "Managed instructions" })).toBeTruthy(); + expect(within(preview).getByText("Use the published release notes.")).toBeTruthy(); + expect(mocks.fetchPackageFile).not.toHaveBeenCalled(); + }); + + it("keeps explicit SOUL.md archive previews when the document body is empty", async () => { + renderTemplate({ + contents: + "---\n" + + JSON.stringify({ + schemaVersion: 1, + agent: { id: "release-brief" }, + workspace: { bootstrapFiles: { "SOUL.md": { source: "workspace/SOUL.md" } } }, + }) + + "\n---\n \n", + }); + fireEvent.click(screen.getByRole("tab", { name: "Workspace files" })); + expect(screen.getAllByRole("button", { name: "SOUL.md" })).toHaveLength(1); + fireEvent.click(screen.getByRole("button", { name: "SOUL.md" })); + expect(await screen.findByRole("heading", { name: "Workspace instructions" })).toBeTruthy(); + expect(mocks.fetchPackageFile).toHaveBeenCalledWith( + "@maker/release-brief", + "workspace/SOUL.md", + "0.1.0", + ); + }); + + it("reads real workspace source files only after selection and pins their version", async () => { + renderTemplate(); + expect(mocks.fetchPackageFile).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("tab", { name: "Workspace files" })); + fireEvent.click(screen.getByRole("button", { name: "AGENTS.md" })); + expect(await screen.findByRole("heading", { name: "Workspace instructions" })).toBeTruthy(); + expect(mocks.fetchPackageFile).toHaveBeenCalledWith( + "@maker/release-brief", + "workspace/AGENTS.md", + "0.1.0", + ); + mocks.fetchPackageFile.mockResolvedValueOnce("Checklist from the archive."); + fireEvent.click(screen.getByRole("button", { name: "notes/checklist.txt" })); + expect(await screen.findByText("Checklist from the archive.")).toBeTruthy(); + }); + + it("keeps file failures and unavailable previews distinct and supports retry", async () => { + mocks.fetchPackageFile + .mockRejectedValueOnce(new Error("Network unavailable")) + .mockResolvedValueOnce(null); + renderTemplate(); + fireEvent.click(screen.getByRole("tab", { name: "Workspace files" })); + fireEvent.click(screen.getByRole("button", { name: "AGENTS.md" })); + expect(await screen.findByRole("alert")).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Try again" })); + expect(await screen.findByText("File preview is unavailable for this release.")).toBeTruthy(); + }); + + it("does not let a stale file response overwrite the current selection", async () => { + let resolveFirst!: (contents: string) => void; + mocks.fetchPackageFile + .mockImplementationOnce( + () => + new Promise((resolve) => { + resolveFirst = resolve; + }), + ) + .mockResolvedValueOnce("Current checklist"); + renderTemplate(); + fireEvent.click(screen.getByRole("tab", { name: "Workspace files" })); + fireEvent.click(screen.getByRole("button", { name: "AGENTS.md" })); + expect(screen.getByRole("status").textContent).toBe("Loading file…"); + fireEvent.click(screen.getByRole("button", { name: "notes/checklist.txt" })); + expect(await screen.findByText("Current checklist")).toBeTruthy(); + await act(async () => resolveFirst("# Stale workspace instructions")); + expect(screen.queryByText("Stale workspace instructions")).toBeNull(); + }); + + it("distinguishes unavailable manifests from valid empty sections", () => { + const { unmount } = renderTemplate({ contents: null }); + expect(screen.getByText(/Template instructions are unavailable/)).toBeTruthy(); + fireEvent.click(screen.getByRole("tab", { name: "Skills" })); + expect(screen.getByText(/manifest is unavailable/)).toBeTruthy(); + unmount(); + renderTemplate({ + contents: + "---\n" + + JSON.stringify({ schemaVersion: 1, agent: { id: "empty" } }) + + "\n---\n# Empty template", + }); + fireEvent.click(screen.getByRole("tab", { name: "Skills" })); + expect( + within(screen.getByRole("tabpanel")).getByText("No skills are included in this Template."), + ).toBeTruthy(); + }); +}); + +describe("Template document handling", () => { + it("strips BOM and CRLF frontmatter while retaining the published Markdown", () => { + const parsed = parseTemplateDocument("\uFEFF" + templateContents.replace(/\n/g, "\r\n")); + expect(parsed.manifest?.packages).toHaveLength(2); + expect(parsed.markdown).toContain("# Release instructions"); + expect(parsed.markdown).not.toContain("schemaVersion"); + }); + + it("does not invent dependencies from malformed or aliased YAML", () => { + expect(parseTemplateDocument("---\nagent: [\n---\n# Readable body")).toEqual({ + manifest: null, + markdown: "# Readable body", + }); + expect( + parseTemplateDocument( + "---\nschemaVersion: 1\nagent: &agent {id: test}\nmetadata: *agent\n---\n# Body", + ).manifest, + ).toBeNull(); + }); + + it.each([ + null, + "not json", + '{"openclaw":{"template":"../CLAW.md"}}', + '{"openclaw":{"template":"/CLAW.md"}}', + ])("falls back safely from invalid package metadata: %s", (value) => { + expect(getTemplateManifestPath(value)).toBe("CLAW.md"); + }); +});