Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Templates: community templates as cards with every bot's face, and folders that add
milind-soni29d65b499f99
diff --git a/server/routes/share.ts b/server/routes/share.tsindex 71acf20860..f2bfbb6217 100644--- a/server/routes/share.ts+++ b/server/routes/share.ts@@ -103,7 +103,7 @@ async function readLink(url: string, readers: ImportReaders): Promise<ShareFoldeexport async function readImport(source: ImportSource, readers: ImportReaders): Promise<ShareFolder> {if ("library" in source) {if (!readers.library) throw new ShareError(NO_LIBRARY, 404);- return readShareFolder(readers.library.files(source.library));+ return readShareFolder(readers.library.files(source.library), source.library);}if ("url" in source) return readLink(source.url, readers);if ("path" in source) {diff --git a/server/routes/teams.ts b/server/routes/teams.tsindex 6edae3ceeb..59e45e5542 100644--- a/server/routes/teams.ts+++ b/server/routes/teams.ts@@ -18,6 +18,7 @@ import type { Routine, RoutineManager } from "../routines.ts";import type { BotRecord, GroupRecord, Store } from "../store.ts";import { createTeamBackup, importTeamBackup } from "../team-backup.ts";import { fetchGithubTeam, fetchLibraryTeam, fetchTeamCatalog } from "../team-library.ts";+import { withCatalogPictures } from "../team-library-pictures.ts";import { parseTeamManifest } from "../team-manifest.ts";import type { RequestAuth } from "../request-auth.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -68,7 +69,7 @@ export function createTeamRoutes(deps: TeamRouteDeps): RouteHandler {}if (method === "GET" && path === "/api/team-library/catalog") {try {- return json(res, 200, await fetchTeamCatalog());+ return json(res, 200, await withCatalogPictures(await fetchTeamCatalog()));} catch (error) {return json(res, 502, { error: error instanceof Error ? error.message : "The team library is unavailable" });}diff --git a/server/share-github.ts b/server/share-github.tsindex e797afc175..fcc6e0029a 100644--- a/server/share-github.ts+++ b/server/share-github.ts@@ -101,11 +101,14 @@ async function fetchFolder(base: string, names: readonly string[], fetcher: Fetcreturn null;}+/** The folder's own name, which stands in for an id its manifest leaves out. */+const folderName = (base: string) => base.slice(base.lastIndexOf("/") + 1);+/** A template folder at a raw.githubusercontent.com address, through the folder reader. */export async function fetchGithubFolder(base: string, fetcher: Fetcher = fetch): Promise<ShareFolder> {const files = await fetchFolder(base, FOLDER_MANIFESTS, fetcher);if (!files) throw new GithubTemplateError("No bot.md or team.md was found in that folder.", 404);- return readShareFolder(files);+ return readShareFolder(files, folderName(base));}/** The template a GitHub link points at, through the folder reader. Throws GithubTemplateError or PackageFormatError. */@@ -119,7 +122,7 @@ export async function fetchGithubTemplate(input: string, fetcher: Fetcher = fetc}for (const folder of source.folders) {const files = await fetchFolder(folder.base, folder.names, fetcher);- if (files) return readShareFolder(files);+ if (files) return readShareFolder(files, folderName(folder.base));}throw new GithubTemplateError("No bot.md or team.md was found at that GitHub link.", 404);}diff --git a/server/team-library-pictures.test.ts b/server/team-library-pictures.test.tsnew file mode 100644index 0000000000..2e522e0eca--- /dev/null+++ b/server/team-library-pictures.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it, vi } from "vitest";++import { TEAM_LIBRARY_RAW_ROOT, type TeamCatalog } from "./team-library.ts";+import { withCatalogPictures } from "./team-library-pictures.ts";++const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]);++const catalogWith = (pictures: string[]): TeamCatalog => ({+ format: "openmaus.catalog", version: 1, repositoryUrl: "https://github.com/milind-soni/openmausbot-teams",+ teams: [{+ slug: "studio", name: "Studio", summary: "Pictures.", category: "Creative", manifest: "teams/studio/team.mausteam.json",+ readme: "teams/studio/README.md", members: pictures.length, skills: [], requires: { apps: [] },+ avatars: pictures.map((picture, index) => ({ key: `bot-${index}`, name: `Bot ${index}`, color: "cyan", picture })),+ }],+});++describe("the gallery's pictures", () => {+ it("hands each picture on as a data: URL, and leaves out one that isn't the picture its name says", async () => {+ const fetcher = vi.fn(async (url: string | URL | Request) => {+ const target = String(url);+ if (target === `${TEAM_LIBRARY_RAW_ROOT}/teams/studio/avatars/real.png`) return new Response(PNG);+ if (target === `${TEAM_LIBRARY_RAW_ROOT}/teams/studio/avatars/fake.png`) return new Response("<html>");+ return new Response("", { status: 404 });+ }) as unknown as typeof fetch;+ const read = await withCatalogPictures(catalogWith(["teams/studio/avatars/real.png", "teams/studio/avatars/fake.png", "teams/studio/avatars/gone.png"]), fetcher);+ const [real, fake, gone] = read.teams[0]!.avatars!;+ expect(real!.picture).toBe(`data:image/png;base64,${Buffer.from(PNG).toString("base64")}`);+ expect(fake!.picture).toBeUndefined();+ expect(gone!.picture).toBeUndefined();+ expect(fetcher).toHaveBeenCalledTimes(3);+ // Read once: a second catalog load reuses what was read.+ await withCatalogPictures(catalogWith(["teams/studio/avatars/real.png"]), fetcher);+ expect(fetcher).toHaveBeenCalledTimes(3);+ });+});diff --git a/server/team-library-pictures.ts b/server/team-library-pictures.tsnew file mode 100644index 0000000000..8e25aa6553--- /dev/null+++ b/server/team-library-pictures.ts@@ -0,0 +1,59 @@+// The community gallery's pictures. The catalog names each bot's picture by its path in the templates repository; the+// renderer never fetches from GitHub itself, so the catalog route reads each picture here (https to+// raw.githubusercontent.com only, no redirects, 64 KB at most, checked to be the picture its name says) and hands it on+// as a data: URL. A picture that can't be read is left out, and the card draws that bot's mascot instead.+import { TEAM_LIBRARY_RAW_ROOT, type TeamCatalog } from "./team-library.ts";++type Fetcher = typeof fetch;++const PICTURE_MAX_BYTES = 64 * 1024;+const MAX_PICTURES = 120;+const MAX_CACHED = 500;+const TYPES = { webp: "image/webp", png: "image/png", jpg: "image/jpeg" } as const;++const looksLike = (kind: keyof typeof TYPES, bytes: Uint8Array) => {+ const ascii = (from: number, to: number) => String.fromCharCode(...bytes.subarray(from, to));+ if (kind === "webp") return bytes.length > 12 && ascii(0, 4) === "RIFF" && ascii(8, 12) === "WEBP";+ if (kind === "png") return bytes.length > 8 && bytes[0] === 0x89 && ascii(1, 4) === "PNG";+ return bytes.length > 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;+};++/** Pictures already read, by path: a data: URL, or null when it couldn't be. */+const cache = new Map<string, string | null>();++async function readPicture(path: string, fetcher: Fetcher): Promise<string | null> {+ const kind = path.slice(path.lastIndexOf(".") + 1) as keyof typeof TYPES;+ if (!(kind in TYPES)) return null;+ try {+ const response = await fetcher(`${TEAM_LIBRARY_RAW_ROOT}/${path.split("/").map(encodeURIComponent).join("/")}`, {+ headers: { accept: "image/*" }, redirect: "error", signal: AbortSignal.timeout(10_000),+ });+ if (!response.ok || Number(response.headers.get("content-length") ?? 0) > PICTURE_MAX_BYTES) return null;+ const bytes = new Uint8Array(await response.arrayBuffer());+ if (bytes.byteLength > PICTURE_MAX_BYTES || !looksLike(kind, bytes)) return null;+ return `data:${TYPES[kind]};base64,${Buffer.from(bytes).toString("base64")}`;+ } catch {+ return null;+ }+}++/** The catalog with each named picture read into a data: URL, or left out. */+export async function withCatalogPictures(catalog: TeamCatalog, fetcher: Fetcher = fetch): Promise<TeamCatalog> {+ const paths = [...new Set(catalog.teams.flatMap((team) => (team.avatars ?? []).flatMap((face) => (face.picture ? [face.picture] : []))))]+ .slice(0, MAX_PICTURES);+ await Promise.all(paths.filter((path) => !cache.has(path)).map(async (path) => {+ const picture = await readPicture(path, fetcher);+ if (cache.size >= MAX_CACHED) cache.delete(cache.keys().next().value!);+ cache.set(path, picture);+ }));+ return {+ ...catalog,+ teams: catalog.teams.map((team) => team.avatars ? {+ ...team,+ avatars: team.avatars.map(({ picture, ...face }) => {+ const read = picture ? cache.get(picture) : undefined;+ return read ? { ...face, picture: read } : face;+ }),+ } : team),+ };+}diff --git a/server/team-library.test.ts b/server/team-library.test.tsindex dfea85e42b..ab7b81bdd0 100644--- a/server/team-library.test.ts+++ b/server/team-library.test.ts@@ -65,6 +65,25 @@ describe("team library", () => {expect(() => parseTeamCatalog(unsafe)).toThrow("safe catalog path");});+ it("keeps a template's kind and each bot's face, leaving out faces it can't trust", () => {+ const entry = {+ ...catalog.teams[0]!, kind: "bot",+ avatars: [+ { key: "lead", name: "Ada", color: "chrome", mascotBody: "cursor", mascotExpression: "happy", picture: "teams/engineering/avatars/lead.webp" },+ { key: "other", name: "Bo", color: "blue", picture: "teams/elsewhere/avatars/x.webp" },+ { key: "Bad Key", name: "Cy", color: "red" },+ { key: "nocolor", name: "Di" },+ ],+ };+ const [parsed] = parseTeamCatalog({ ...catalog, teams: [entry] }).teams;+ expect(parsed!.kind).toBe("bot");+ expect(parsed!.avatars).toEqual([+ { key: "lead", name: "Ada", color: "chrome", mascotBody: "cursor", mascotExpression: "happy", picture: "teams/engineering/avatars/lead.webp" },+ { key: "other", name: "Bo", color: "blue" },+ ]);+ expect(parseTeamCatalog(catalog).teams[0]!.avatars).toBeUndefined();+ });+it("accepts a catalog of hundreds of published templates", () => {const entry = catalog.teams[0]!;const teams = Array.from({ length: 500 }, (_, index) => {diff --git a/server/team-library.ts b/server/team-library.tsindex 703af9fdb0..b68e8e5733 100644--- a/server/team-library.ts+++ b/server/team-library.ts@@ -25,11 +25,24 @@ export interface TeamCatalogEntry {readme: string;/** A template folder (`teams/<slug>`): read whole, with its skills and pictures, instead of the files made from it. */folder?: string;+ /** A folder holding one bot (added without a department) or a department. */+ kind?: "bot" | "department";+ /** Each bot's face on the gallery card; `picture` is a path in the repository until the catalog route reads it. */+ avatars?: TeamCatalogAvatar[];members: number;skills: string[];requires: { apps: string[] };}+export interface TeamCatalogAvatar {+ key: string;+ name: string;+ color: string;+ mascotBody?: string;+ mascotExpression?: string;+ picture?: string;+}+export interface TeamCatalog {format: "openmaus.catalog";version: 1;@@ -68,6 +81,26 @@ function stringList(value: unknown, field: string, maxItems: number): string[] {return value.map((item, index) => text(item, `${field}[${index}]`, 100));}+const LOOK = /^[a-z0-9][a-z0-9-]{0,39}$/;+const MAX_FACES = 50;++/** The faces a catalog entry lists. A face that isn't well formed is left out; it never fails the catalog. */+function catalogAvatars(value: unknown, slug: string): TeamCatalogAvatar[] | undefined {+ if (!Array.isArray(value)) return undefined;+ const picture = new RegExp(`^teams/${slug}/avatars/[a-z0-9][a-z0-9_-]{0,63}\\.(?:webp|png|jpg)$`);+ return value.slice(0, MAX_FACES).flatMap((raw): TeamCatalogAvatar[] => {+ if (!isRecord(raw) || typeof raw.key !== "string" || !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(raw.key)) return [];+ if (typeof raw.name !== "string" || !raw.name.trim() || raw.name.trim().length > 100) return [];+ if (typeof raw.color !== "string" || !LOOK.test(raw.color)) return [];+ return [{+ key: raw.key, name: raw.name.trim(), color: raw.color,+ ...(typeof raw.mascotBody === "string" && LOOK.test(raw.mascotBody) ? { mascotBody: raw.mascotBody } : {}),+ ...(typeof raw.mascotExpression === "string" && LOOK.test(raw.mascotExpression) ? { mascotExpression: raw.mascotExpression } : {}),+ ...(typeof raw.picture === "string" && picture.test(raw.picture) ? { picture: raw.picture } : {}),+ }];+ });+}+/** Validate the remotely maintained index before any of it reaches the renderer. */export function parseTeamCatalog(value: unknown): TeamCatalog {if (!isRecord(value) || value.format !== "openmaus.catalog" || value.version !== 1) {@@ -87,6 +120,7 @@ export function parseTeamCatalog(value: unknown): TeamCatalog {slugs.add(slug);const prefix = `teams/${slug}/`;const requires = isRecord(raw.requires) ? raw.requires : {};+ const avatars = catalogAvatars(raw.avatars, slug);return {slug,name: text(raw.name, `${field}.name`, 100),@@ -102,6 +136,8 @@ export function parseTeamCatalog(value: unknown): TeamCatalog {: {}),manifest: relativeFile(raw.manifest, `${field}.manifest`, ".mausteam.json", prefix),...(raw.folder === `teams/${slug}` ? { folder: `teams/${slug}` } : {}),+ ...(raw.kind === "bot" || raw.kind === "department" ? { kind: raw.kind } : {}),+ ...(avatars ? { avatars } : {}),readme: relativeFile(raw.readme, `${field}.readme`, "README.md", prefix),members:typeof raw.members === "number" && Number.isSafeInteger(raw.members) && raw.members > 0 && raw.members <= 200diff --git a/shared/package-format.ts b/shared/package-format.tsindex aded50c2f5..24f20c9ecf 100644--- a/shared/package-format.ts+++ b/shared/package-format.ts@@ -12,6 +12,7 @@ import { redactSecretsInText } from "./redact.ts";import { normalizeCronSchedule } from "./routine-schedule.ts";import { isToolGroup } from "./tool-groups.ts";import { MAUS_COLOR_NAMES } from "./wire.ts";+import { readWeekdays } from "./package-weekdays.ts";import { isSkillName, parseSkillMd, scanSkillText, SKILL_FILE_MAX_BYTES } from "./skill-md.ts";import { skillFilesSchema } from "./skill-files.ts";@@ -120,7 +121,7 @@ export const packageRoutineScheduleSchema = z.discriminatedUnion("type", [z.object({type: z.literal("daily"),time: requiredText(5).regex(CLOCK_TIME, { message: "must use HH:MM" }),- weekdays: z.array(z.number().int().min(0).max(6)).min(1).max(7),+ weekdays: z.preprocess(readWeekdays, z.array(z.number().int().min(0).max(6)).min(1).max(7)),}),z.object({type: z.literal("interval"),diff --git a/shared/package-weekdays.ts b/shared/package-weekdays.tsnew file mode 100644index 0000000000..429ab7d11f--- /dev/null+++ b/shared/package-weekdays.ts@@ -0,0 +1,13 @@+const DAY_NAMES = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];++/** A routine's weekdays as a package carries them, 0-6 from Sunday. Hand-written templates count Sunday as 7, as cron+ * does, or name the days ("mon", "Monday"); both read as 0-6, once each. Anything else is left for the schema to refuse. */+export function readWeekdays(value: unknown): unknown {+ if (!Array.isArray(value)) return value;+ return [...new Set(value.map((day) => {+ if (day === 7) return 0;+ const name = typeof day === "string" ? day.trim().toLowerCase() : "";+ const index = DAY_NAMES.findIndex((full) => name === full || name === full.slice(0, 3));+ return index === -1 ? day : index;+ }))];+}diff --git a/shared/share-folder.test.ts b/shared/share-folder.test.tsindex 7fc5c8d762..702446a9c9 100644--- a/shared/share-folder.test.ts+++ b/shared/share-folder.test.ts@@ -90,6 +90,19 @@ describe("template folders", () => {expect(() => readShareFolder({ ...team, "avatars/lead.png": new Uint8Array(70 * 1024) })).toThrow(/larger than 64 KB/);});+ it("reads a folder that leaves out its id, release or department name, as its format allows", () => {+ const manifest = ["---", "botmrr: 2", "name: Clip Crew", "tagline: Turn recordings into clips.", "summary: Clips.", "category: Creative",+ "author:", " name: Someone", "license: MIT", "outcomes:", " - Clips", "setupMinutes: 5", "requirements:", " apps: []", " capabilities: []",+ "team:", " leader: lead", "agents:", " - key: lead", " name: Lead", " appearance:", " color: red",+ "routines:", " - key: daily", " name: Daily", " agent: lead", " prompt: Go", " runOn: maus", " durationMinutes: 15",+ " enabledAfterInstall: false", " schedule:", " type: daily", " time: \"09:00\"", " weekdays: [mon, 7]", "---", "", "Body."].join("\n");+ const folder = readShareFolder({ "team.md": manifest }, "clip-crew");+ if (folder.kind !== "package") throw new Error("expected a package");+ expect(folder.document.package).toMatchObject({ id: "clip-crew", release: "1.0.0", team: { name: "Clip Crew", leader: "lead" } });+ expect(folder.document.package.routines?.[0]?.schedule).toMatchObject({ type: "daily", weekdays: [1, 0] });+ expect(() => readShareFolder({ "team.md": manifest })).toThrow("package.id");+ });+it("refuses two manifests, no manifest and a newer version", () => {const files = writeShareFolder(oneBot(), "bot");expect(() => readShareFolder({ ...files, "team.md": files["bot.md"]! })).toThrow(/not both/);diff --git a/shared/share-folder.ts b/shared/share-folder.tsindex e6c38e99e5..c6b3e89402 100644--- a/shared/share-folder.ts+++ b/shared/share-folder.ts@@ -174,8 +174,24 @@ function folderPicture(files: ShareFolderFiles, value: unknown, crop: unknown) {return { mime: PICTURE_TYPES[match[2] as keyof typeof PICTURE_TYPES], data: btoa(binary), crop: crop === "rounded" || crop === "square" ? crop : "circle" };}-function packageFromFolder(metadata: Record<string, unknown>, files: ShareFolderFiles): unknown {- const { botmrr: _version, skills: skillNames, skillFiles, ...definition } = metadata;+const FOLDER_SLUG = /^[a-z0-9][a-z0-9-]{0,62}$/;++/** What a folder may leave out: the folder's name is its id, a first release is 1.0.0, and a department is named+ * after the template. */+function withFolderDefaults(definition: Record<string, unknown>, slug: string | undefined): Record<string, unknown> {+ const name = typeof definition.name === "string" ? definition.name.trim() : "";+ const team = definition.team && typeof definition.team === "object" && !Array.isArray(definition.team) ? definition.team as Record<string, unknown> : null;+ return {+ ...definition,+ ...(definition.id === undefined && slug && FOLDER_SLUG.test(slug) ? { id: slug } : {}),+ ...(definition.release === undefined ? { release: "1.0.0" } : {}),+ ...(team && team.name === undefined && name ? { team: { ...team, name: name.slice(0, 60).trim() } } : {}),+ };+}++function packageFromFolder(metadata: Record<string, unknown>, files: ShareFolderFiles, slug: string | undefined): unknown {+ const { botmrr: _version, skills: skillNames, skillFiles, ...given } = metadata;+ const definition = withFolderDefaults(given, slug);const listedFiles = (skillFiles && typeof skillFiles === "object" && !Array.isArray(skillFiles) ? skillFiles : {}) as Record<string, unknown>;const agents = Array.isArray(definition.agents) ? definition.agents : [];const named = new Set<unknown>(Array.isArray(skillNames) ? skillNames : []);@@ -196,8 +212,9 @@ function packageFromFolder(metadata: Record<string, unknown>, files: ShareFolderreturn { format: PACKAGE_FORMAT, version: packageVersionFor(pkg), package: pkg };}-/** Reads a template folder through the package gate (trust "file"). Throws PackageFormatError with a sentence. */-export function readShareFolder(input: ShareFolderFiles): ShareFolder {+/** Reads a template folder through the package gate (trust "file"). `slug` is the folder's name, when it has one.+ * Throws PackageFormatError with a sentence. */+export function readShareFolder(input: ShareFolderFiles, slug?: string): ShareFolder {const files = normalizeShareFolder(input);const bot = textOf(files[MANIFEST_NAMES.bot]), team = textOf(files[MANIFEST_NAMES.department]);if (bot !== undefined && team !== undefined) throw refuse("A template folder holds bot.md or team.md, not both.");@@ -207,7 +224,7 @@ export function readShareFolder(input: ShareFolderFiles): ShareFolder {const { metadata } = frontmatterOf(manifest);if (metadata.botmrr === 1) return { kind: "package", scope, document: parsePackageDocument(manifest, { trust: "file" }) };if (metadata.botmrr !== BOTMRR_FOLDER_VERSION) throw new PackageFormatError("unsupported_version", "This template was made by a newer MausBot. Update the app, then import it again.");- return { kind: "package", scope, document: parsePackageDocument(packageFromFolder(metadata, files), { trust: "file" }) };+ return { kind: "package", scope, document: parsePackageDocument(packageFromFolder(metadata, files, slug), { trust: "file" }) };}const legacy = textOf(files[LEGACY_MARKDOWN]);if (legacy !== undefined) return { kind: "package", scope: "department", document: parsePackageDocument(legacy, { trust: "file" }) };diff --git a/src/components/TeamCatalogCard.tsx b/src/components/TeamCatalogCard.tsxnew file mode 100644index 0000000000..1a300fe4ce--- /dev/null+++ b/src/components/TeamCatalogCard.tsx@@ -0,0 +1,42 @@+import { Loader2, Plus } from "lucide-react";++import { t } from "@/lib/i18n";+import { catalogCopy, catalogFaces, type TeamCatalogEntry } from "@/lib/team-catalog";+import { TemplateFaces } from "./TemplateCard";++/** A community template in the Templates gallery: the same card the ready-made bots have, with every bot's face. */+export function TeamCatalogCard({ entry, busy, disabled, onAdd }: {+ entry: TeamCatalogEntry;+ busy: boolean;+ disabled: boolean;+ onAdd: () => void;+}) {+ const copy = catalogCopy(entry);+ const bots = entry.members === 1 ? t("template.botsOne") : t("template.botsMany", { count: entry.members });+ const details = [+ entry.skills.length > 0 && (entry.skills.length === 1 ? t("template.skillsOne") : t("template.skillsMany", { count: entry.skills.length })),+ entry.requires.apps.length > 0 && entry.requires.apps.join(", "),+ entry.setupMinutes && t("templates.minutes", { count: entry.setupMinutes }),+ ].filter(Boolean).join(" · ");+ return (+ <article data-catalog-template={entry.slug} className="flex flex-col rounded-2xl border border-hairline/40 bg-card p-4">+ <div className="flex items-center justify-between gap-3">+ <TemplateFaces avatars={catalogFaces(entry)} size={36} />+ <button+ type="button"+ onClick={onAdd}+ disabled={disabled}+ aria-label={busy ? undefined : t("orgLibrary.addAria", { name: copy.name })}+ className="flex h-8 shrink-0 items-center gap-1 rounded-full bg-raised px-3 text-[13px] font-medium text-ink hover:bg-raised-hover focus-visible:outline-2 focus-visible:outline-accent disabled:opacity-40"+ >+ {busy ? <Loader2 size={14} aria-hidden="true" className="animate-spin motion-reduce:animate-none" /> : <Plus size={14} aria-hidden="true" />}+ {busy ? t("templates.loadingShort") : t("common.add")}+ </button>+ </div>+ <h4 dir="auto" className="mt-3 truncate text-[14px] font-medium text-ink" title={copy.name}>{copy.name}</h4>+ <p dir="auto" className="truncate text-[12px] text-ink-secondary">{bots} · {entry.category}</p>+ <p dir="auto" className="mt-2 line-clamp-3 text-[13px] leading-[1.45] text-ink-secondary">{copy.outcome ?? copy.summary}</p>+ {details && <p className="mt-auto truncate pt-2 text-[12px] text-ink-tertiary" title={details}>{details}</p>}+ </article>+ );+}diff --git a/src/components/TeamLibraryPanel.test.ts b/src/components/TeamLibraryPanel.test.tsindex 7d57fc7dfe..65e702035e 100644--- a/src/components/TeamLibraryPanel.test.ts+++ b/src/components/TeamLibraryPanel.test.ts@@ -15,4 +15,12 @@ describe("TeamLibraryPanel", () => {expect(source).not.toMatch(/role="tab(list)?"/);expect(source).not.toMatch(/teams\/scout|team-library\/github|ShareTeamDialog|openmaus\.backup|type="file"/);});++ it("shows community templates as cards with every bot's face, and adds a template folder through Import", () => {+ expect(source).toContain("<TeamCatalogCard");+ expect(source).not.toContain("TeamGlyph");+ // Import keeps a one-bot template out of a department; an older team's file still goes through the team import.+ expect(source).toMatch(/previewImport\(\{ url: link \}\)/);+ expect(source).toMatch(/addImport\(\{ url: from\.link \}, dispatch\)/);+ });});diff --git a/src/components/TeamLibraryPanel.tsx b/src/components/TeamLibraryPanel.tsxindex 7b53877560..80266ca642 100644--- a/src/components/TeamLibraryPanel.tsx+++ b/src/components/TeamLibraryPanel.tsx@@ -1,6 +1,7 @@import { track } from "@/lib/analytics";import { t } from "@/lib/i18n";import { addTemplate } from "@/lib/template-add";+import { addImport, previewImport } from "@/lib/template-share";import { templateDetailsOf } from "@/lib/template-details";import { orgCardAction, orgPackagePreview, type OrgLibraryListing, type OrgLibraryPackage } from "@/lib/org-library";import type { PackageDocument } from "../../shared/package-format";@@ -8,12 +9,13 @@ import { COMMUNITY_REPOSITORY_URL, type TemplateDetails } from "../../shared/shaimport type { Routine } from "@/lib/routines";import { openExternalLink } from "@/lib/app-links";import { api, useStore, type Bot, type Group } from "@/state/store";-import { ArrowLeft, Check, ExternalLink, Github, Loader2, Plus, Search, Users, X } from "lucide-react";+import { ArrowLeft, Check, ExternalLink, Github, Loader2, Search, X } from "lucide-react";import { useCallback, useEffect, useRef, useState } from "react";import { createPortal } from "react-dom";-import { catalogCopy, catalogMatches, type TeamCatalog, type TeamCatalogEntry } from "@/lib/team-catalog";+import { catalogFolderLink, catalogMatches, type TeamCatalog, type TeamCatalogEntry } from "@/lib/team-catalog";import { ReadyBotGallery } from "./ReadyBotGallery";+import { TeamCatalogCard } from "./TeamCatalogCard";import { OrgLibraryTab } from "./TeamLibraryPanelOrg";import { TemplateDetailsBody } from "./TemplateCard";@@ -24,16 +26,12 @@ export interface TeamImportResult {connections?: number;}-/** What the preview is of: a community team (its file, added as a file) or a package from the organization's library. */-type Pending = { details: TemplateDetails; manifest: unknown; org?: undefined } | { details: TemplateDetails; manifest?: undefined; org: OrgLibraryPackage };--function TeamGlyph() {- return (- <div className="flex size-11 shrink-0 items-center justify-center rounded-xl bg-ink/[0.06] text-ink-secondary">- <Users size={20} />- </div>- );-}+/** What the preview is of: a community template folder (added through Import, as its link), an older community team+ * (its file, added as a file) or a package from the organization's library. */+type Pending =+ | { details: TemplateDetails; link: string; manifest?: undefined; org?: undefined }+ | { details: TemplateDetails; manifest: unknown; link?: undefined; org?: undefined }+ | { details: TemplateDetails; manifest?: undefined; link?: undefined; org: OrgLibraryPackage };/** Templates: one gallery of ready-made bots, the organization's library and the community teams. Import and Share* live elsewhere ("+" → Import…, a department's Share). */@@ -133,6 +131,12 @@ export function TeamLibraryPanel({setBusySlug(entry.slug);setError("");try {+ // A folder goes through Import, which adds a one-bot template without making it a department.+ const link = catalog ? catalogFolderLink(catalog.repositoryUrl, entry) : null;+ if (link) {+ setPending({ details: await previewImport({ url: link }), link });+ return;+ }const manifest: unknown = await api(`/api/team-library/teams/${entry.slug}`);setPending({ details: templateDetailsOf(manifest), manifest });} catch (cause) {@@ -142,17 +146,27 @@ export function TeamLibraryPanel({}};- const importTeam = async (manifest: unknown, name: string) => {+ const importTeam = async (from: { manifest: unknown } | { link: string }, name: string) => {setImporting(true);setError("");try {- const response = await addTemplate(manifest, dispatch);- track("team_imported", { members: response.bots.length, source: "library", mode: "add", format: "package" });+ let added: { bots: unknown[] }, connections = 0, presets = 0;+ if ("link" in from) {+ const response = await addImport({ url: from.link }, dispatch);+ added = response;+ connections = response.appsToConnect ?? 0;+ } else {+ const response = await addTemplate(from.manifest, dispatch);+ added = response;+ connections = response.connections?.length ?? 0;+ presets = response.presets?.length ?? 0;+ }+ track("team_imported", { members: added.bots.length, source: "library", mode: "add", format: "package" });onImported({name,- members: response.bots.length,- ...(response.connections?.length ? { connections: response.connections.length } : {}),- ...(response.presets?.length ? { presets: response.presets.length } : {}),+ members: added.bots.length,+ ...(connections ? { connections } : {}),+ ...(presets ? { presets } : {}),});} catch (cause) {setError(cause instanceof Error ? cause.message : String(cause));@@ -295,7 +309,7 @@ export function TeamLibraryPanel({</span>)) : (- <button onClick={() => void importTeam(pending.manifest, pending.details.name)} disabled={importing} className={primary}>+ <button onClick={() => void importTeam(pending.link ? { link: pending.link } : { manifest: pending.manifest }, pending.details.name)} disabled={importing} className={primary}>{importing && <Loader2 size={15} className="animate-spin" />}{importing ? t("templates.importing") : t("templates.addTeam")}</button>@@ -334,7 +348,7 @@ export function TeamLibraryPanel({<div className="mb-3 text-[12px] font-medium text-ink-tertiary">{search ? t("templates.searchResults") : t("templates.communityTemplates")}</div>- {error && <div role="alert" className="mb-3 rounded-lg bg-danger/10 px-3 py-2 text-[13px] text-danger">{error}</div>}+ {error && <div ref={(node) => node?.scrollIntoView({ block: "nearest" })} role="alert" className="mb-3 rounded-lg bg-danger/10 px-3 py-2 text-[13px] text-danger">{error}</div>}{catalogLoading && (<div className="flex items-center justify-center gap-2 py-24 text-[13px] text-ink-secondary"><Loader2 size={16} className="animate-spin" /> {t("templates.loading")}@@ -347,35 +361,10 @@ export function TeamLibraryPanel({</div>)}{!catalogLoading && catalog && (- <div className="grid grid-cols-1 gap-x-10 md:grid-cols-2">- {visibleTeams.map((entry) => {- const copy = catalogCopy(entry);- return (- <article key={entry.slug} className="flex min-h-[104px] items-center gap-3 border-b border-hairline/35 px-1 py-4">- <TeamGlyph />- <div className="min-w-0 flex-1">- <h3 className="truncate text-[13px] font-medium text-ink">{copy.name}</h3>- <p className="mt-0.5 truncate text-[13px] text-ink-secondary">{copy.outcome ?? copy.summary}</p>- <p className="mt-1 truncate text-[12px] text-ink-tertiary">- {entry.members === 1 ? t("template.botsOne") : t("template.botsMany", { count: entry.members })}- {entry.skills.length > 0 && ` · ${entry.skills.length === 1 ? t("template.skillsOne") : t("template.skillsMany", { count: entry.skills.length })}`}- {entry.requires.apps.length > 0 && ` · ${entry.requires.apps.join(", ")}`}- {entry.setupMinutes && ` · ${t("templates.minutes", { count: entry.setupMinutes })}`}- </p>- </div>- <button- type="button"- onClick={() => void loadLibraryTeam(entry)}- disabled={busySlug !== null}- aria-label={busySlug === entry.slug ? undefined : t("orgLibrary.addAria", { name: copy.name })}- className="flex h-8 shrink-0 items-center gap-1 rounded-full bg-raised px-3 text-[13px] font-medium text-ink hover:bg-raised-hover disabled:opacity-40"- >- {busySlug === entry.slug ? <Loader2 size={14} aria-hidden="true" className="animate-spin motion-reduce:animate-none" /> : <Plus size={14} aria-hidden="true" />}- {busySlug === entry.slug ? t("templates.loadingShort") : t("common.add")}- </button>- </article>- );- })}+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2 lg:grid-cols-3">+ {visibleTeams.map((entry) => (+ <TeamCatalogCard key={entry.slug} entry={entry} busy={busySlug === entry.slug} disabled={busySlug !== null} onAdd={() => void loadLibraryTeam(entry)} />+ ))}</div>)}{!catalogLoading && catalog && visibleTeams.length === 0 && (diff --git a/src/lib/team-catalog.ts b/src/lib/team-catalog.tsindex 1897b634a8..213fcfd133 100644--- a/src/lib/team-catalog.ts+++ b/src/lib/team-catalog.ts@@ -2,6 +2,7 @@// summaries come in English; the built-in teams show in the app's language.import { t } from "./i18n";import type { LocaleKey } from "@/locales";+import type { TemplateAvatar } from "../../shared/share-card";export interface TeamCatalogEntry {slug: string;@@ -14,6 +15,11 @@ export interface TeamCatalogEntry {package?: string;manifest: string;readme: string;+ /** A template folder (`teams/<slug>`), added through Import so a one-bot template joins no department. */+ folder?: string;+ kind?: "bot" | "department";+ /** Each bot's face; a picture arrives as a data: URL. */+ avatars?: TemplateAvatar[];members: number;skills: string[];requires: { apps: string[] };@@ -45,3 +51,17 @@ export function catalogMatches(entry: TeamCatalogEntry, search: string): boolean.toLowerCase().includes(search);}++const FACE_COLORS = ["green", "blue", "red", "orange", "purple", "cyan", "pink", "yellow", "teal", "coral"];++/** The card's faces: the catalog's, or one mascot in a colour from the slug for a catalog that lists none. */+export function catalogFaces(entry: TeamCatalogEntry): TemplateAvatar[] {+ if (entry.avatars?.length) return entry.avatars;+ let hash = 0;+ for (const char of entry.slug) hash = (hash * 31 + char.codePointAt(0)!) >>> 0;+ return [{ key: entry.slug, name: entry.name, color: FACE_COLORS[hash % FACE_COLORS.length]! }];+}++/** The GitHub folder link Import reads a template folder from. */+export const catalogFolderLink = (repositoryUrl: string, entry: TeamCatalogEntry): string | null =>+ entry.folder ? `${repositoryUrl}/tree/main/${entry.folder}` : null;