Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(marketplace): publish from the app — GitHub sign-in, a Publish Studio, and sharing wallpapers
rubenluetke10-beepe9c369501e4b
diff --git a/jarvis/ui/web/frontend/src/components/InstallStandard.tsx b/jarvis/ui/web/frontend/src/components/InstallStandard.tsxnew file mode 100644index 0000000000..4ae11e2c86--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/InstallStandard.tsx@@ -0,0 +1,123 @@+// The store's install standard — the CLI | runner | Prompt pattern every+// comparable store shows next to a listing.+//+// The strings arrive VERBATIM from the backend (jarvis/marketplace/+// install_standard.py). Nothing here builds a command out of a name: a store+// that derived its own strings client-side would drift from what the CLI+// actually accepts, and a shown-but-nonexistent command is the one bug a+// store is judged on.+//+// Shared by the Community browser (before installing) and the Publish tab+// (after publishing, where it is the line an author hands to everyone else),+// so both surfaces show the same three commands in the same order.+import { useEffect, useState } from "react";+import { Check, Copy } from "lucide-react";++import { robustCopy } from "@/lib/clipboard";+import { cn } from "@/lib/utils";++/** The three install surfaces, computed server-side. */+export interface InstallStandardWire {+ cli: string;+ runner: string;+ prompt: string;+}++// In the order a visitor tries them: the curated CLI command, the zero-install+// uvx runner, the assistant prompt.+const INSTALL_TABS = [+ { id: "cli", label: "CLI", hint: "Runs in any terminal while the app is running." },+ {+ id: "runner",+ label: "uvx",+ hint: "No install needed — uv fetches the CLI and runs the same command.",+ },+ {+ id: "prompt",+ label: "Prompt",+ hint: "Paste this to your assistant — it runs the install for you.",+ },+] as const;+type InstallTabId = (typeof INSTALL_TABS)[number]["id"];++export function InstallStandard({+ install,+ heading = "Install",+ note,+}: {+ install: InstallStandardWire;+ /** Overridden by the Publish tab, where the block is about sharing. */+ heading?: string;+ /** One extra line under the tabs' own hint, for surface-specific context. */+ note?: string;+}) {+ const [tab, setTab] = useState<InstallTabId>("cli");+ const [copied, setCopied] = useState(false);+ useEffect(() => {+ if (!copied) return;+ const t = setTimeout(() => setCopied(false), 2000);+ return () => clearTimeout(t);+ }, [copied]);++ const active = INSTALL_TABS.find((t) => t.id === tab) ?? INSTALL_TABS[0];+ const value = install[tab];+ return (+ <section>+ <div className="mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">+ <h3 className="text-xs font-semibold uppercase tracking-wider text-foreground">+ {heading}+ </h3>+ <div className="flex items-center">+ {INSTALL_TABS.map((t, i) => (+ <span key={t.id} className="flex items-center">+ {i > 0 && (+ <span aria-hidden className="mx-1.5 select-none text-muted-foreground/40">+ |+ </span>+ )}+ <button+ type="button"+ onClick={() => {+ setTab(t.id);+ setCopied(false);+ }}+ className={cn(+ "text-[11px] font-medium transition-colors",+ tab === t.id ? "text-primary" : "text-muted-foreground hover:text-foreground",+ )}+ >+ {t.label}+ </button>+ </span>+ ))}+ </div>+ </div>+ <div className="flex items-center gap-2 rounded-md border border-border bg-muted/40 py-1 pl-2.5 pr-1">+ <code className="min-w-0 flex-1 overflow-x-auto whitespace-nowrap py-1 text-xs text-foreground">+ {tab !== "prompt" && (+ <span aria-hidden className="select-none text-muted-foreground">+ ${" "}+ </span>+ )}+ {value}+ </code>+ <button+ type="button"+ onClick={async () => {+ if (await robustCopy(value)) setCopied(true);+ }}+ className="grid h-7 w-7 shrink-0 place-items-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ title={copied ? "Copied" : "Copy"}+ aria-label={`Copy the ${active.label} install command`}+ >+ {copied ? (+ <Check className="h-3.5 w-3.5 text-primary" />+ ) : (+ <Copy className="h-3.5 w-3.5" />+ )}+ </button>+ </div>+ <p className="mt-1.5 text-[11px] text-muted-foreground">{note ?? active.hint}</p>+ </section>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/marketplace/PublishIdentity.test.tsx b/jarvis/ui/web/frontend/src/components/marketplace/PublishIdentity.test.tsxnew file mode 100644index 0000000000..582903c3db--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/marketplace/PublishIdentity.test.tsx@@ -0,0 +1,173 @@+/**+ * The shared publishing identity: the header chip, the sign-in dialog and+ * the device-code ticket.+ *+ * What is pinned here is the contract every publishing surface relies on:+ * signed-out shows one button, signed-in shows the handle and a menu with+ * sign-out, and the dialog shows the device code GitHub handed out — split+ * for reading, copyable, with the GitHub button next to it.+ *+ * No jest-dom in this repo — assertions use toBeTruthy()/toBeNull().+ */+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++const openExternalUrl = vi.fn();+vi.mock("@/lib/openExternal", () => ({+ openExternalUrl: (url: string) => openExternalUrl(url),+}));+const robustCopy = vi.fn(async (_text: string) => true);+vi.mock("@/lib/clipboard", () => ({+ robustCopy: (text: string) => robustCopy(text),+}));++import {+ GithubSignInDialog,+ PublisherChip,+ type PublishIdentityWire,+} from "@/components/marketplace/PublishIdentity";+import { setUiLanguage } from "@/i18n";++const SIGNED_OUT: PublishIdentityWire = { enabled: true, wallpapers_enabled: true, signed_in: false };+const SIGNED_IN: PublishIdentityWire = {+ enabled: true,+ wallpapers_enabled: true,+ signed_in: true,+ login: "octocat",+ avatar_url: null,+};++function stubServer(initial: PublishIdentityWire) {+ const state = { identity: initial, pollsUntilConnected: 1, deleted: 0 };+ const json = (body: unknown, ok = true, status = 200) => ({ ok, status, json: async () => body });+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: unknown, init?: { method?: string }) => {+ const url = String(input);+ const method = (init?.method ?? "GET").toUpperCase();+ if (url === "/api/marketplace/publish/identity" && method === "GET") {+ return json(state.identity);+ }+ if (url === "/api/marketplace/publish/identity" && method === "DELETE") {+ state.deleted += 1;+ state.identity = SIGNED_OUT;+ return json({ ok: true });+ }+ if (url === "/api/marketplace/publish/signin/start") {+ return json({+ flow_id: "flow-1",+ user_code: "ABCD-1234",+ verification_uri: "https://github.com/login/device",+ interval: 1,+ });+ }+ if (url.startsWith("/api/marketplace/publish/signin/poll/")) {+ if (state.pollsUntilConnected > 0) {+ state.pollsUntilConnected -= 1;+ return json({ status: "pending" });+ }+ state.identity = SIGNED_IN;+ return json({ status: "connected", login: "octocat" });+ }+ if (url.startsWith("/api/marketplace/publish/signin/") && method === "DELETE") {+ return json({ ok: true });+ }+ throw new Error(`unexpected fetch: ${method} ${url}`);+ }),+ );+ return state;+}++function renderWith(ui: React.ReactElement) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);+}++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.useRealTimers();+ openExternalUrl.mockReset();+ robustCopy.mockClear();+ setUiLanguage("en");+});++describe("PublisherChip", () => {+ it("offers the sign-in while signed out", async () => {+ stubServer(SIGNED_OUT);+ const onSignIn = vi.fn();+ renderWith(<PublisherChip onSignIn={onSignIn} />);++ const button = await screen.findByTestId("publisher-chip-signed-out");+ expect(button.textContent).toContain("Sign in with GitHub");+ fireEvent.click(button);+ expect(onSignIn).toHaveBeenCalledTimes(1);+ });++ it("shows the handle and signs out from its menu", async () => {+ const server = stubServer(SIGNED_IN);+ const onMine = vi.fn();+ renderWith(<PublisherChip onSignIn={() => undefined} onMine={onMine} />);++ const chip = await screen.findByTestId("publisher-chip");+ expect(chip.textContent).toContain("@octocat");++ fireEvent.click(chip);+ fireEvent.click(screen.getByRole("menuitem", { name: /My publications/ }));+ expect(onMine).toHaveBeenCalledTimes(1);++ fireEvent.click(chip);+ fireEvent.click(screen.getByRole("menuitem", { name: /Sign out/ }));+ await waitFor(() => expect(server.deleted).toBe(1));+ // The chip re-reads the identity and falls back to the sign-in button.+ expect(await screen.findByTestId("publisher-chip-signed-out")).toBeTruthy();+ });++ it("renders nothing when publishing is disabled in this deployment", async () => {+ stubServer({ enabled: false, wallpapers_enabled: false, signed_in: false });+ renderWith(<PublisherChip onSignIn={() => undefined} />);+ await waitFor(() => expect((fetch as unknown as ReturnType<typeof vi.fn>).mock.calls.length).toBeGreaterThan(0));+ await waitFor(() => expect(screen.queryByTestId("publisher-chip-signed-out")).toBeNull());+ expect(screen.queryByTestId("publisher-chip")).toBeNull();+ });+});++describe("GithubSignInDialog", () => {+ it("starts the device flow on open and shows the code as a ticket", async () => {+ stubServer(SIGNED_OUT);+ renderWith(<GithubSignInDialog onClose={() => undefined} />);++ const ticket = await screen.findByTestId("device-code-ticket");+ expect(ticket).toBeTruthy();+ // The code is split at the dash for reading, but announced whole.+ expect(screen.getByTestId("device-code").getAttribute("aria-label")).toBe("ABCD-1234");+ expect(screen.getByText("ABCD")).toBeTruthy();+ expect(screen.getByText("1234")).toBeTruthy();++ fireEvent.click(screen.getByRole("button", { name: /Open GitHub/ }));+ expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/login/device");++ fireEvent.click(screen.getByRole("button", { name: /Copy the sign-in code|Copy the code/ }));+ await waitFor(() => expect(robustCopy).toHaveBeenCalledWith("ABCD-1234"));+ });++ it("turns into the signed-in card once GitHub approves", async () => {+ stubServer(SIGNED_OUT);+ renderWith(<GithubSignInDialog onClose={() => undefined} />);+ await screen.findByTestId("device-code-ticket");++ // The poller runs every `interval` seconds (1s here); two polls settle it.+ expect(await screen.findByText(/Signed in as @octocat/, undefined, { timeout: 5000 })).toBeTruthy();+ expect(screen.queryByTestId("device-code-ticket")).toBeNull();+ expect(screen.getByRole("button", { name: "Done" })).toBeTruthy();+ }, 10_000);++ it("speaks German when the UI does", async () => {+ stubServer(SIGNED_OUT);+ setUiLanguage("de");+ renderWith(<GithubSignInDialog onClose={() => undefined} />);+ expect(await screen.findByText("Mit GitHub anmelden")).toBeTruthy(); // i18n-allow+ expect(await screen.findByText("Dein Einmal-Code")).toBeTruthy(); // i18n-allow+ });+});diff --git a/jarvis/ui/web/frontend/src/components/marketplace/PublishIdentity.tsx b/jarvis/ui/web/frontend/src/components/marketplace/PublishIdentity.tsxnew file mode 100644index 0000000000..b634db8943--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/marketplace/PublishIdentity.tsx@@ -0,0 +1,646 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import {+ AlertTriangle,+ Check,+ ChevronDown,+ Copy,+ ExternalLink,+ Github,+ Loader2,+ LogOut,+ ShieldCheck,+ Store,+ X,+} from "lucide-react";++import { Button } from "@/components/ui/button";+import { fill, useLocaleChunk, useT } from "@/i18n";+import { robustCopy } from "@/lib/clipboard";+import { openExternalUrl } from "@/lib/openExternal";+import { cn } from "@/lib/utils";++// ---------------------------------------------------------------------------+// One identity for everything the app publishes.+//+// Packages and wallpapers are two lanes with two endpoints, but a person signs+// in once — so the sign-in lives here rather than inside either surface. Every+// surface reads the same query key, which means signing in from the wallpaper+// picker leaves the marketplace signed in and the other way round, with no+// state to keep in step.+//+// The flow is GitHub's DEVICE flow: the app shows a code, the user types it at+// github.com/login/device, and the app polls until GitHub reports approval.+// That is what lets a downloadable program authenticate at all — it holds no+// client secret, so the redirect flow the website uses is not available to it.+// The scope list is empty: the sign-in proves who someone is and grants+// nothing on their account.+// ---------------------------------------------------------------------------++export interface PublishIdentityWire {+ /** Package publishing (plugins and skills) is configured. */+ enabled: boolean;+ /** The wallpaper lane is configured — a fork may run one without the other. */+ wallpapers_enabled?: boolean;+ signed_in: boolean;+ login?: string;+ avatar_url?: string | null;+ /** Set when GitHub could not be reached — NOT the same as signed out. */+ unreachable?: string;+}++interface SigninStartWire {+ flow_id: string;+ user_code: string;+ verification_uri?: string | null;+ verification_uri_complete?: string | null;+ interval?: number;+}++export const PUBLISH_IDENTITY_KEY = ["marketplace-publish-identity"] as const;++const GITHUB_DEVICE_URL = "https://github.com/login/device";++async function fetchIdentity(): Promise<PublishIdentityWire> {+ const res = await fetch("/api/marketplace/publish/identity", { cache: "no-store" });+ if (!res.ok) throw new Error(`Identity request failed (${res.status})`);+ return res.json();+}++/** Who is signed in, shared by every surface that publishes. */+export function usePublishIdentity() {+ return useQuery({ queryKey: PUBLISH_IDENTITY_KEY, queryFn: fetchIdentity });+}++/**+ * The device-flow state machine: start → poll → connected | error, plus+ * cancel and sign-out. One hook so the header chip, the sign-in dialog and+ * the compact card inside a publish form all drive the same flow.+ */+export function useGithubSignIn() {+ const queryClient = useQueryClient();+ const [flow, setFlow] = useState<SigninStartWire | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [justConnected, setJustConnected] = useState(false);++ const start = useMutation({+ mutationFn: async (): Promise<SigninStartWire> => {+ const res = await fetch("/api/marketplace/publish/signin/start", { method: "POST" });+ if (!res.ok) {+ const detail = await res+ .json()+ .then((b: { detail?: string }) => b.detail)+ .catch(() => undefined);+ throw new Error(detail ?? `Sign-in start failed (${res.status})`);+ }+ return res.json();+ },+ onSuccess: (f) => {+ setFlow(f);+ setError(null);+ setJustConnected(false);+ },+ onError: (err: Error) => setError(err.message),+ });++ const signOut = useMutation({+ mutationFn: async () => {+ const res = await fetch("/api/marketplace/publish/identity", { method: "DELETE" });+ if (!res.ok) throw new Error(`Sign-out failed (${res.status})`);+ return res.json();+ },+ onSuccess: () => {+ setJustConnected(false);+ queryClient.invalidateQueries({ queryKey: PUBLISH_IDENTITY_KEY });+ },+ });++ // Poll the running flow until GitHub reports approval or an error.+ useEffect(() => {+ if (!flow) return;+ const intervalMs = Math.max(2, flow.interval ?? 5) * 1000;+ const timer = setInterval(async () => {+ try {+ const res = await fetch(`/api/marketplace/publish/signin/poll/${flow.flow_id}`, {+ cache: "no-store",+ });+ if (res.status === 404) {+ setFlow(null);+ return;+ }+ const data = (await res.json()) as { status: string; error?: string };+ if (data.status === "connected") {+ setFlow(null);+ setJustConnected(true);+ queryClient.invalidateQueries({ queryKey: PUBLISH_IDENTITY_KEY });+ } else if (data.status === "error") {+ setFlow(null);+ setError(data.error ?? "sign-in failed");+ }+ } catch {+ // Network blip — keep polling until the flow expires.+ }+ }, intervalMs);+ return () => clearInterval(timer);+ }, [flow, queryClient]);++ const cancel = useCallback(() => {+ if (!flow) return;+ // Tell the backend to drop the flow, then forget it locally either way —+ // an already-finished flow 404s harmlessly.+ void fetch(`/api/marketplace/publish/signin/${flow.flow_id}`, { method: "DELETE" }).catch(+ () => undefined,+ );+ setFlow(null);+ }, [flow]);++ return {+ flow,+ error,+ justConnected,+ starting: start.isPending,+ signingOut: signOut.isPending,+ start: () => start.mutate(),+ cancel,+ signOut: () => signOut.mutate(),+ clearError: () => setError(null),+ };+}++/** Split "ABCD-1234" into its two halves for the ticket layout. */+function codeHalves(code: string): [string, string] {+ const idx = code.indexOf("-");+ if (idx === -1) return [code, ""];+ return [code.slice(0, idx), code.slice(idx + 1)];+}++/**+ * The GitHub avatar, with a letter tile behind it for the moment before the+ * picture arrives — and forever, if GitHub's CDN is unreachable.+ */+export function PublisherAvatar({+ login,+ url,+ size = 28,+ className,+}: {+ login?: string;+ url?: string | null;+ size?: number;+ className?: string;+}) {+ const [failed, setFailed] = useState(false);+ const initial = (login ?? "?").slice(0, 1).toUpperCase();+ return (+ <span+ className={cn(+ "relative grid shrink-0 place-items-center overflow-hidden rounded-full",+ "bg-gradient-to-br from-primary/70 to-primary/30 text-primary-foreground",+ "ring-2 ring-background",+ className,+ )}+ style={{ width: size, height: size }}+ aria-hidden+ >+ <span className="text-[11px] font-bold">{initial}</span>+ {url && !failed && (+ <img+ src={url}+ alt=""+ onError={() => setFailed(true)}+ className="absolute inset-0 h-full w-full object-cover"+ />+ )}+ </span>+ );+}++/**+ * The device-code ticket. Big code, one button that opens GitHub, a copy+ * button, and a pulse while the app waits — the whole sign-in on one card.+ * Shared by the dialog and the inline card so the flow looks identical+ * wherever it is started.+ */+function DeviceCodeTicket({+ flow,+ onCancel,+}: {+ flow: SigninStartWire;+ onCancel: () => void;+}) {+ const t = useT();+ const [copied, setCopied] = useState(false);+ useEffect(() => {+ if (!copied) return;+ const timer = setTimeout(() => setCopied(false), 2000);+ return () => clearTimeout(timer);+ }, [copied]);+ const [left, right] = codeHalves(flow.user_code);+ const verifyUrl = flow.verification_uri ?? GITHUB_DEVICE_URL;+ return (+ <div+ className="relative overflow-hidden rounded-2xl border border-primary/30 bg-gradient-to-br from-primary/10 via-card to-card p-5"+ data-testid="device-code-ticket"+ >+ <div+ aria-hidden+ className="pointer-events-none absolute -right-16 -top-16 h-48 w-48 rounded-full bg-primary/15 blur-3xl"+ />+ <p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">+ {t("marketplace.identity_code_label")}+ </p>+ <div className="mt-2 flex flex-wrap items-center gap-3">+ <div+ className="flex items-center gap-2 font-mono text-3xl font-semibold tracking-[0.2em] text-foreground"+ data-testid="device-code"+ aria-label={flow.user_code}+ >+ <span>{left}</span>+ {right && (+ <>+ <span className="text-primary/60">–</span>+ <span>{right}</span>+ </>+ )}+ </div>+ <button+ type="button"+ onClick={async () => {+ if (await robustCopy(flow.user_code)) setCopied(true);+ }}+ className="grid h-9 w-9 place-items-center rounded-lg border border-border bg-background/60 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"+ title={copied ? t("marketplace.identity_copied") : t("marketplace.identity_copy_code")}+ aria-label={t("marketplace.identity_copy_code")}+ >+ {copied ? <Check className="h-4 w-4 text-primary" /> : <Copy className="h-4 w-4" />}+ </button>+ </div>+ <p className="mt-3 text-xs leading-relaxed text-muted-foreground">+ {t("marketplace.identity_code_hint")}+ </p>+ <div className="mt-4 flex flex-wrap items-center gap-2">+ <Button size="sm" onClick={() => openExternalUrl(verifyUrl)}>+ <Github className="mr-1.5 h-3.5 w-3.5" />+ {t("marketplace.identity_open_github")}+ <ExternalLink className="ml-1.5 h-3 w-3" />+ </Button>+ <Button size="sm" variant="ghost" onClick={onCancel}>+ {t("marketplace.identity_cancel")}+ </Button>+ <span className="ml-auto flex items-center gap-2 text-[11px] text-muted-foreground">+ <span className="relative flex h-2 w-2">+ <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-primary/60" />+ <span className="relative inline-flex h-2 w-2 rounded-full bg-primary" />+ </span>+ {t("marketplace.identity_waiting")}+ </span>+ </div>+ </div>+ );+}++/**+ * The full sign-in dialog: what the sign-in is (and is not), then the ticket.+ * Opened from the marketplace header and from any surface that needs an+ * identity before it can continue.+ */+export function GithubSignInDialog({ onClose }: { onClose: () => void }) {+ const t = useT();+ useLocaleChunk("marketplace");+ const identity = usePublishIdentity();+ const signIn = useGithubSignIn();+ const startedRef = useRef(false);++ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") onClose();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [onClose]);++ // Auto-start once: the person clicked "Sign in", so the code is what they+ // came for — not a second button that says "sign in" again.+ useEffect(() => {+ if (startedRef.current) return;+ if (identity.data?.signed_in) return;+ startedRef.current = true;+ signIn.start();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [identity.data?.signed_in]);++ const signedIn = identity.data?.signed_in === true;++ return (+ <div+ role="dialog"+ aria-modal="true"+ aria-label={t("marketplace.identity_dialog_title")}+ data-testid="github-signin-dialog"+ className="fixed inset-0 z-[70] flex items-center justify-center bg-background/80 p-6 backdrop-blur-sm"+ >+ <div className="relative w-full max-w-lg overflow-hidden rounded-2xl border border-border bg-card shadow-2xl">+ <header className="flex items-start gap-3 border-b border-border px-5 py-4">+ <span className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-foreground text-background">+ <Github className="h-5 w-5" />+ </span>+ <div className="min-w-0 flex-1">+ <h2 className="font-display text-base font-semibold tracking-tight text-foreground">+ {t("marketplace.identity_dialog_title")}+ </h2>+ <p className="text-xs text-muted-foreground">+ {t("marketplace.identity_dialog_subtitle")}+ </p>+ </div>+ <Button+ size="sm"+ variant="ghost"+ onClick={onClose}+ aria-label={t("marketplace.close")}+ >+ <X className="h-4 w-4" />+ </Button>+ </header>++ <div className="space-y-4 px-5 py-5">+ {signedIn ? (+ <div className="flex items-center gap-3 rounded-xl border border-primary/30 bg-primary/5 p-4">+ <PublisherAvatar+ login={identity.data?.login}+ url={identity.data?.avatar_url}+ size={40}+ />+ <div className="min-w-0 flex-1">+ <p className="text-sm font-semibold text-foreground">+ {fill(t("marketplace.identity_signed_in_as"), {+ login: identity.data?.login ?? "",+ })}+ </p>+ <p className="text-xs text-muted-foreground">+ {t("marketplace.identity_signed_in_hint")}+ </p>+ </div>+ <Check className="h-5 w-5 text-primary" />+ </div>+ ) : signIn.flow ? (+ <DeviceCodeTicket flow={signIn.flow} onCancel={signIn.cancel} />+ ) : (+ <div className="flex items-center gap-3 rounded-xl border border-border bg-secondary/30 p-4 text-sm text-muted-foreground">+ {signIn.starting || identity.isLoading ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Button size="sm" onClick={() => signIn.start()}>+ <Github className="mr-1.5 h-3.5 w-3.5" />+ {t("marketplace.identity_sign_in")}+ </Button>+ )}+ <span>{t("marketplace.identity_requesting")}</span>+ </div>+ )}++ {signIn.error && (+ <p className="flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive">+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ {signIn.error}+ </p>+ )}++ <ul className="grid gap-2 text-xs text-muted-foreground sm:grid-cols-3">+ <li className="flex items-start gap-2 rounded-lg border border-border/70 bg-background/50 p-2.5">+ <ShieldCheck className="mt-0.5 h-3.5 w-3.5 shrink-0 text-primary" />+ {t("marketplace.identity_fact_scope")}+ </li>+ <li className="flex items-start gap-2 rounded-lg border border-border/70 bg-background/50 p-2.5">+ <Store className="mt-0.5 h-3.5 w-3.5 shrink-0 text-primary" />+ {t("marketplace.identity_fact_name")}+ </li>+ <li className="flex items-start gap-2 rounded-lg border border-border/70 bg-background/50 p-2.5">+ <LogOut className="mt-0.5 h-3.5 w-3.5 shrink-0 text-primary" />+ {t("marketplace.identity_fact_keyring")}+ </li>+ </ul>+ </div>++ <footer className="flex items-center justify-end gap-2 border-t border-border px-5 py-3">+ {signedIn ? (+ <Button size="sm" onClick={onClose}>+ {t("marketplace.identity_done")}+ </Button>+ ) : (+ <Button size="sm" variant="ghost" onClick={onClose}>+ {t("marketplace.close")}+ </Button>+ )}+ </footer>+ </div>+ </div>+ );+}++/**+ * The header chip: "Sign in with GitHub" while signed out, the avatar and+ * handle with a small menu while signed in. Hidden entirely when publishing+ * is disabled in this deployment — a door that answers 503 is not a door.+ */+export function PublisherChip({+ onMine,+ onSignIn,+}: {+ /** Jump to "my publications" — the list filtered to this account. */+ onMine?: () => void;+ /** Open the sign-in dialog; the chip only asks, the view owns the dialog. */+ onSignIn: () => void;+}) {+ const t = useT();+ const ready = useLocaleChunk("marketplace");+ const identity = usePublishIdentity();+ const signIn = useGithubSignIn();+ const [open, setOpen] = useState(false);+ const menuRef = useRef<HTMLDivElement | null>(null);++ useEffect(() => {+ if (!open) return;+ const onDown = (event: MouseEvent) => {+ if (!menuRef.current?.contains(event.target as Node)) setOpen(false);+ };+ window.addEventListener("mousedown", onDown);+ return () => window.removeEventListener("mousedown", onDown);+ }, [open]);++ const data = identity.data;+ if (data && !data.enabled && !data.wallpapers_enabled) return null;++ if (identity.isLoading || !ready) {+ return <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" aria-hidden />;+ }++ if (!data?.signed_in) {+ return (+ <Button+ size="sm"+ variant="outline"+ onClick={onSignIn}+ data-testid="publisher-chip-signed-out"+ title={data?.unreachable ? t("marketplace.identity_unreachable") : undefined}+ >+ <Github className="mr-1.5 h-3.5 w-3.5" />+ {t("marketplace.identity_sign_in")}+ </Button>+ );+ }++ return (+ <div className="relative" ref={menuRef}>+ <button+ type="button"+ onClick={() => setOpen((o) => !o)}+ aria-haspopup="menu"+ aria-expanded={open}+ data-testid="publisher-chip"+ className={cn(+ "flex h-8 items-center gap-2 rounded-full border border-border bg-card/70 pl-1 pr-2.5",+ "text-xs font-medium text-foreground backdrop-blur transition-colors hover:border-primary/50",+ )}+ >+ <PublisherAvatar login={data.login} url={data.avatar_url} size={24} />+ <span className="max-w-[10rem] truncate">@{data.login}</span>+ <ChevronDown className="h-3 w-3 text-muted-foreground" />+ </button>+ {open && (+ <div+ role="menu"+ className="absolute right-0 top-full z-50 mt-1.5 w-56 overflow-hidden rounded-xl border border-border bg-card p-1 shadow-xl"+ >+ <div className="px-2.5 py-2">+ <p className="truncate text-xs font-semibold text-foreground">@{data.login}</p>+ <p className="text-[11px] text-muted-foreground">+ {t("marketplace.identity_menu_hint")}+ </p>+ </div>+ {onMine && (+ <button+ type="button"+ role="menuitem"+ onClick={() => {+ setOpen(false);+ onMine();+ }}+ className="flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-xs text-foreground transition-colors hover:bg-secondary"+ >+ <Store className="h-3.5 w-3.5 text-muted-foreground" />+ {t("marketplace.identity_menu_mine")}+ </button>+ )}+ <button+ type="button"+ role="menuitem"+ onClick={() => {+ setOpen(false);+ signIn.signOut();+ }}+ disabled={signIn.signingOut}+ className="flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-xs text-foreground transition-colors hover:bg-secondary"+ >+ <LogOut className="h-3.5 w-3.5 text-muted-foreground" />+ {t("marketplace.identity_sign_out")}+ </button>+ </div>+ )}+ </div>+ );+}++/**+ * The compact identity card inside a publish form or dialog: who you are, or+ * the ticket to become somebody. `blurb` lets each surface say what+ * publishing means where it stands — the consequence of publishing a plugin+ * and of publishing a picture are not the same sentence.+ */+export function PublishIdentityCard({+ identity,+ loading,+ blurb,+ compact = false,+}: {+ identity: PublishIdentityWire | undefined;+ loading: boolean;+ blurb?: string;+ compact?: boolean;+}) {+ const t = useT();+ useLocaleChunk("marketplace");+ const signIn = useGithubSignIn();+ const signedIn = identity?.signed_in === true;+ return (+ <section+ className={cn(!compact && "rounded-xl border border-border bg-card/40 p-4")}+ data-testid="publish-identity"+ data-signed-in={signedIn ? "yes" : "no"}+ >+ <div className="flex flex-wrap items-center gap-3">+ {signedIn ? (+ <PublisherAvatar login={identity?.login} url={identity?.avatar_url} size={32} />+ ) : (+ <span className="grid h-8 w-8 place-items-center rounded-full bg-foreground text-background">+ <Github className="h-4 w-4" />+ </span>+ )}+ <div className="min-w-0 flex-1">+ <p className="text-xs font-semibold uppercase tracking-wider text-foreground">+ {t("marketplace.identity_label")}+ </p>+ <p className="text-xs text-muted-foreground">+ {signedIn ? (+ <>+ {fill(t("marketplace.identity_signed_in_as"), { login: identity?.login ?? "" })}+ {" — "}+ {blurb ?? t("marketplace.identity_publishes_under")}+ </>+ ) : (+ t("marketplace.identity_sign_in_blurb")+ )}+ </p>+ {identity?.unreachable && (+ <p className="mt-1 text-[11px] text-muted-foreground">+ {t("marketplace.identity_unreachable")}+ </p>+ )}+ </div>+ {loading ? (+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />+ ) : signedIn ? (+ <Button+ size="sm"+ variant="ghost"+ onClick={() => signIn.signOut()}+ disabled={signIn.signingOut}+ >+ <LogOut className="mr-1.5 h-3.5 w-3.5" />+ {t("marketplace.identity_sign_out")}+ </Button>+ ) : signIn.flow ? null : (+ <Button size="sm" onClick={() => signIn.start()} disabled={signIn.starting}>+ {signIn.starting ? (+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />+ ) : (+ <Github className="mr-1.5 h-3.5 w-3.5" />+ )}+ {t("marketplace.identity_sign_in")}+ </Button>+ )}+ </div>++ {signIn.flow && (+ <div className="mt-3">+ <DeviceCodeTicket flow={signIn.flow} onCancel={signIn.cancel} />+ </div>+ )}+ {signIn.error && (+ <p className="mt-2 flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 px-2 py-1.5 text-xs text-destructive">+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ {signIn.error}+ </p>+ )}+ </section>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/marketplace/PublishStudio.test.tsx b/jarvis/ui/web/frontend/src/components/marketplace/PublishStudio.test.tsxnew file mode 100644index 0000000000..82cc957e7d--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/marketplace/PublishStudio.test.tsx@@ -0,0 +1,193 @@+/**+ * The Publish Studio: the doors, the form, the check, the submit.+ *+ * Pinned here: the entry screen offers every way a package can arrive, a+ * blank skill starts with a template rather than an empty box, the Check+ * button runs the backend's own validator and reports its field errors where+ * the field is, and Publish stays disabled until somebody is signed in.+ *+ * No jest-dom in this repo — assertions use toBeTruthy()/toBeNull().+ */+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++vi.mock("@/lib/openExternal", () => ({ openExternalUrl: vi.fn() }));+vi.mock("@/lib/clipboard", () => ({ robustCopy: vi.fn(async () => true) }));++import { PublishStudio } from "@/components/marketplace/PublishStudio";+import type { PublishIdentityWire } from "@/components/marketplace/PublishIdentity";+import { setUiLanguage } from "@/i18n";++const SIGNED_IN: PublishIdentityWire = {+ enabled: true,+ wallpapers_enabled: true,+ signed_in: true,+ login: "octocat",+ avatar_url: null,+};+const SIGNED_OUT: PublishIdentityWire = { enabled: true, wallpapers_enabled: true, signed_in: false };++function stubServer(identity: PublishIdentityWire, opts?: { validateErrors?: unknown[] }) {+ const calls: { url: string; body?: unknown }[] = [];+ const json = (body: unknown, ok = true, status = 200) => ({ ok, status, json: async () => body });+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: unknown, init?: { method?: string; body?: string }) => {+ const url = String(input);+ const method = (init?.method ?? "GET").toUpperCase();+ calls.push({ url, body: init?.body ? JSON.parse(init.body) : undefined });+ if (url === "/api/marketplace/publish/identity" && method === "GET") return json(identity);+ if (url === "/api/marketplace/publish/validate") {+ return json({ ok: !(opts?.validateErrors?.length), errors: opts?.validateErrors ?? [] });+ }+ if (url === "/api/marketplace/publish/submit") {+ const body = JSON.parse(init?.body ?? "{}") as { name: string; version: string };+ return json(+ {+ ok: true,+ name: body.name,+ version: body.version,+ pr_url: "https://github.com/PersonalJarvis/marketplace/pull/1",+ install: {+ cli: `jarvis marketplace install ${body.name}`,+ runner: `uvx --from personal-jarvis jarvis marketplace install ${body.name}`,+ prompt: `Install the "${body.name}" skill from the community marketplace.`,+ },+ },+ true,+ 201,+ );+ }+ if (url === "/api/wallpapers/uploads") {+ return json({+ items: [+ { id: "u0000000000000001", title: "Harbour At Dawn", theme: "light", createdAt: 1, source: "own" },+ {+ id: "u0000000000000002",+ title: "Borrowed",+ theme: "dark",+ createdAt: 2,+ source: "marketplace",+ publisher: "someone",+ },+ ],+ });+ }+ if (url.startsWith("/api/marketplace/publish/status")) return json({ live: true });+ return json({});+ }),+ );+ return calls;+}++function renderStudio(onClose = () => undefined, initialStage?: "source" | "wallpapers") {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(+ <QueryClientProvider client={client}>+ <PublishStudio onClose={onClose} initialStage={initialStage} />+ </QueryClientProvider>,+ );+}++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ setUiLanguage("en");+});++describe("PublishStudio", () => {+ it("opens on the doors, with the wallpaper lane among them", async () => {+ stubServer(SIGNED_IN);+ renderStudio();+ expect(await screen.findByTestId("studio-door-folder")).toBeTruthy();+ expect(screen.getByTestId("studio-door-github")).toBeTruthy();+ expect(screen.getByTestId("studio-door-wallpaper")).toBeTruthy();+ // The rail lights the "what" station once somebody is signed in.+ await screen.findByText(/Signed in as @octocat/);+ });++ it("closes on Escape", async () => {+ stubServer(SIGNED_IN);+ const onClose = vi.fn();+ renderStudio(onClose);+ await screen.findByTestId("studio-door-folder");+ fireEvent.keyDown(window, { key: "Escape" });+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it("starts a blank skill with a template, checks it, and publishes it", async () => {+ const calls = stubServer(SIGNED_IN);+ renderStudio();+ await screen.findByTestId("studio-door-folder");++ fireEvent.click(screen.getByRole("button", { name: /^Skill$/ }));+ const form = await screen.findByTestId("studio-form");+ expect(form).toBeTruthy();+ // The SKILL.md box is pre-filled — nobody starts at an empty document.+ expect((screen.getByDisplayValue(/name: my-skill/) as HTMLTextAreaElement).value).toContain(+ "---",+ );+ // The live card preview follows the name.+ fireEvent.change(screen.getByTestId("studio-name"), { target: { value: "three-point-check" } });+ expect(screen.getByTestId("studio-card-preview").textContent).toContain("three-point-check");++ fireEvent.click(screen.getByRole("button", { name: "Check" }));+ expect(await screen.findByTestId("studio-check-ok")).toBeTruthy();+ const validate = calls.find((c) => c.url === "/api/marketplace/publish/validate");+ expect(validate?.body).toMatchObject({ kind: "skill", name: "three-point-check", version: "1.0.0" });++ fireEvent.click(screen.getByTestId("studio-publish"));+ const done = await screen.findByTestId("studio-published");+ expect(done.textContent).toContain("three-point-check");+ expect(done.textContent).toContain("View the pull request");+ });++ it("puts a field error where the field is", async () => {+ stubServer(SIGNED_IN, {+ validateErrors: [{ field: "version", error: "version must be plain SemVer, e.g. 1.0.0" }],+ });+ renderStudio();+ await screen.findByTestId("studio-door-folder");+ fireEvent.click(screen.getByRole("button", { name: /^Skill$/ }));+ await screen.findByTestId("studio-form");+ fireEvent.click(screen.getByRole("button", { name: "Check" }));+ expect(await screen.findByText(/version must be plain SemVer/)).toBeTruthy();+ expect(screen.queryByTestId("studio-check-ok")).toBeNull();+ });++ it("keeps Publish disabled until somebody is signed in", async () => {+ stubServer(SIGNED_OUT);+ renderStudio();+ await screen.findByTestId("studio-door-folder");+ fireEvent.click(screen.getByRole("button", { name: /^Skill$/ }));+ await screen.findByTestId("studio-form");+ expect((screen.getByTestId("studio-publish") as HTMLButtonElement).disabled).toBe(true);+ });++ it("lists only the owner's own pictures in the wallpaper lane", async () => {+ stubServer(SIGNED_IN);+ renderStudio(() => undefined, "wallpapers");+ const grid = await screen.findByTestId("studio-own-wallpapers");+ expect(grid.textContent).toContain("Harbour At Dawn");+ // An installed community picture is somebody else's work — not offered.+ expect(grid.textContent).not.toContain("Borrowed");++ fireEvent.click(screen.getByRole("button", { name: /Harbour At Dawn/ }));+ expect(await screen.findByTestId("publish-wallpaper-dialog")).toBeTruthy();+ });++ it("says so when publishing is disabled in this deployment", async () => {+ stubServer({ enabled: false, wallpapers_enabled: false, signed_in: false });+ renderStudio();+ expect(await screen.findByText(/Publishing is disabled/)).toBeTruthy();+ });++ it("speaks German when the UI does", async () => {+ stubServer(SIGNED_IN);+ setUiLanguage("de");+ renderStudio();+ expect(await screen.findByText("Paketordner ablegen")).toBeTruthy(); // i18n-allow+ expect(screen.getByText("Im Marketplace veröffentlichen")).toBeTruthy(); // i18n-allow+ });+});diff --git a/jarvis/ui/web/frontend/src/components/marketplace/PublishStudio.tsx b/jarvis/ui/web/frontend/src/components/marketplace/PublishStudio.tsxnew file mode 100644index 0000000000..f5bf0727eb--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/marketplace/PublishStudio.tsx@@ -0,0 +1,1699 @@+import { useEffect, useMemo, useRef, useState } from "react";+import { useMutation, useQueryClient } from "@tanstack/react-query";+import {+ AlertTriangle,+ ArrowLeft,+ Check,+ ExternalLink,+ FileText,+ FolderUp,+ Github,+ Image as ImageIcon,+ Loader2,+ PencilLine,+ Plug,+ Search,+ Sparkles,+ UploadCloud,+ X,+} from "lucide-react";++import { Button } from "@/components/ui/button";+import { ScrollArea } from "@/components/ui/scroll-area";+import { InstallStandard, type InstallStandardWire } from "@/components/InstallStandard";+import {+ PublishIdentityCard,+ PublisherAvatar,+ usePublishIdentity,+} from "@/components/marketplace/PublishIdentity";+import { PublishWallpaperDialog } from "@/components/wallpaper/PublishWallpaperDialog";+import { thumbUrlFor, type WallpaperEntry } from "@/hooks/useWallpaperCatalog";+import { uploadAsEntry, useWallpaperUploads } from "@/hooks/useWallpaperUploads";+import { fill, useLocaleChunk, useT } from "@/i18n";+import { openExternalUrl } from "@/lib/openExternal";+import { cn } from "@/lib/utils";+import {+ collectDroppedFiles,+ collectPickedFiles,+ folderToDraft,+ MAX_SKILL_MD_BYTES,+ type FolderDraft,+ type PackageSkill,+} from "@/lib/packageFolder";+import {+ fetchRepoFile,+ getRepo,+ listRepos,+ parseRepoRef,+ scanRepo,+ type RepoCandidate,+ type RepoSummary,+} from "@/lib/githubImport";++// ---------------------------------------------------------------------------+// The Publish Studio — the in-app half of the marketplace's publish path.+//+// A full-height overlay over the storefront with a rail of four stations on+// the left (who · what · check · live) and the work on the right. The author+// never starts at an empty form: the entry screen offers the ways a package+// can arrive — drop the folder, import it from a public GitHub repo, write it+// by hand, or pick one of your own wallpapers — and "the folder is the+// classification" (publishing-plan.md §2): what is inside decides whether it+// becomes a skill or a plugin card.+//+// Anyone may publish: whatever passes the automated checks goes live with no+// human review, so the copy stays honest about the two things that matter —+// the upload appears PUBLICLY under the user's GitHub name, and the only gate+// is the rule check. Identity comes from the GitHub device flow; the+// submission travels through the same storefront endpoint the web form uses,+// so web and app cannot drift apart.+// ---------------------------------------------------------------------------++type Translate = (key: string) => string;++interface FieldErrorWire {+ field: string | null;+ error: string;+}++interface SubmitResultWire {+ ok: boolean;+ name: string;+ version: string;+ pr_url?: string | null;+ submission_path?: string | null;+ /** The three commands other people will run to install this — computed+ * server-side by install_standard.py, never derived here. */+ install?: InstallStandardWire | null;+}++type Kind = "skill" | "plugin";+type Stage = "source" | "github" | "wallpapers" | "form" | "done";++interface Draft {+ kind: Kind;+ name: string;+ version: string;+ title: string;+ description: string;+ categories: string;+ skill_md: string;+ plugin_json_text: string;+ mcp_json_text: string;+ usage_card: string;+ skills: PackageSkill[];+}++const EMPTY_DRAFT: Draft = {+ kind: "skill",+ name: "",+ version: "1.0.0",+ title: "",+ description: "",+ categories: "",+ skill_md: "",+ plugin_json_text: "",+ mcp_json_text: "",+ usage_card: "",+ skills: [],+};++const SKILL_TEMPLATE = `---+name: my-skill+description: One sentence on when the assistant should reach for this skill.+version: 1.0.0+---++# My Skill++Write the instructions the assistant follows, step by step.+`;++const PLUGIN_TEMPLATE = `{+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",+ "name": "my-plugin",+ "version": "1.0.0",+ "description": "One sentence on what the plugin connects.",+ "extensions": {+ "io.github.personaljarvis": {+ "display_name": "My Plugin",+ "category": "Productivity",+ "auth": { "mode": "pat_paste", "pat_help_url": "https://example.com/settings/tokens" }+ }+ }+}+`;++const MCP_TEMPLATE = `{+ "mcpServers": {+ "my-plugin": { "type": "streamable-http", "url": "https://mcp.example.com/mcp" }+ }+}+`;++/** The JSON body the backend's validate/submit routes expect, or a field+ * error when a pasted JSON block does not parse. */+function draftToBody(+ draft: Draft,+ t: Translate,+): { body: Record<string, unknown> } | { parseError: FieldErrorWire } {+ const base = {+ kind: draft.kind,+ name: draft.name.trim(),+ version: draft.version.trim(),+ };+ if (draft.kind === "skill") {+ return {+ body: {+ ...base,+ title: draft.title.trim(),+ description: draft.description.trim(),+ categories: draft.categories+ .split(",")+ .map((c) => c.trim())+ .filter(Boolean),+ skill_md: draft.skill_md,+ },+ };+ }+ let pluginJson: unknown;+ try {+ pluginJson = draft.plugin_json_text.trim() ? JSON.parse(draft.plugin_json_text) : null;+ } catch {+ return {+ parseError: { field: "plugin_json", error: t("marketplace.studio_err_plugin_json") },+ };+ }+ let mcpJson: unknown = null;+ try {+ mcpJson = draft.mcp_json_text.trim() ? JSON.parse(draft.mcp_json_text) : null;+ } catch {+ return { parseError: { field: "mcp_json", error: t("marketplace.studio_err_mcp_json") } };+ }+ const body: Record<string, unknown> = {+ ...base,+ plugin_json: pluginJson,+ mcp_json: mcpJson,+ usage_card: draft.usage_card.trim() ? draft.usage_card : null,+ };+ // Bundled skills ride inside the plugin submission (registry schema W2).+ if (draft.skills.length > 0) body.skills = draft.skills;+ return { body };+}++/**+ * The studio. `initialStage` lets a caller open it straight at a lane — the+ * wallpaper picker's "Share" lands in the wallpapers station, for example.+ */+export function PublishStudio({+ onClose,+ initialStage = "source",+}: {+ onClose: () => void;+ initialStage?: Stage;+}) {+ const t = useT();+ const localeReady = useLocaleChunk("marketplace");+ const queryClient = useQueryClient();+ const identity = usePublishIdentity();++ const [stage, setStage] = useState<Stage>(initialStage);+ const [draft, setDraft] = useState<Draft>(EMPTY_DRAFT);+ const [prefill, setPrefill] = useState<{+ origin: string;+ files: string[];+ warnings: string[];+ } | null>(null);+ const [errors, setErrors] = useState<FieldErrorWire[]>([]);+ const [checked, setChecked] = useState(false);+ const [result, setResult] = useState<SubmitResultWire | null>(null);++ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") onClose();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [onClose]);++ const set = (patch: Partial<Draft>) => {+ setDraft((d) => ({ ...d, ...patch }));+ setChecked(false);+ };++ const applyFolderDraft = (folder: FolderDraft, origin: string) => {+ setDraft({+ kind: folder.kind,+ name: folder.name,+ version: folder.version,+ title: folder.title,+ description: folder.description,+ categories: folder.categories,+ skill_md: folder.skill_md,+ plugin_json_text: folder.plugin_json_text,+ mcp_json_text: folder.mcp_json_text,+ usage_card: folder.usage_card,+ skills: folder.skills,+ });+ setPrefill({ origin, files: folder.files, warnings: folder.warnings });+ setErrors([]);+ setChecked(false);+ setStage("form");+ };++ const startBlank = (kind: Kind) => {+ setDraft({+ ...EMPTY_DRAFT,+ kind,+ skill_md: kind === "skill" ? SKILL_TEMPLATE : "",+ plugin_json_text: kind === "plugin" ? PLUGIN_TEMPLATE : "",+ mcp_json_text: kind === "plugin" ? MCP_TEMPLATE : "",+ });+ setPrefill(null);+ setErrors([]);+ setChecked(false);+ setStage("form");+ };++ const startOver = () => {+ setStage("source");+ setDraft(EMPTY_DRAFT);+ setPrefill(null);+ setErrors([]);+ setChecked(false);+ setResult(null);+ };++ const validateMutation = useMutation({+ mutationFn: async (): Promise<FieldErrorWire[]> => {+ const converted = draftToBody(draft, t);+ if ("parseError" in converted) return [converted.parseError];+ const res = await fetch("/api/marketplace/publish/validate", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(converted.body),+ });+ if (!res.ok) throw new Error(`Validation request failed (${res.status})`);+ const data = (await res.json()) as { errors: FieldErrorWire[] };+ return data.errors;+ },+ onSuccess: (errs) => {+ setErrors(errs);+ setChecked(true);+ },+ });++ const submitMutation = useMutation({+ mutationFn: async (): Promise<SubmitResultWire> => {+ const converted = draftToBody(draft, t);+ if ("parseError" in converted) {+ setErrors([converted.parseError]);+ throw new Error(converted.parseError.error);+ }+ const res = await fetch("/api/marketplace/publish/submit", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(converted.body),+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) {+ const detail = (data as { detail?: { error?: string; field?: string | null } }).detail;+ if (detail?.error) {+ setErrors([{ field: detail.field ?? null, error: detail.error }]);+ throw new Error(detail.error);+ }+ throw new Error(`Publish failed (${res.status})`);+ }+ return data as SubmitResultWire;+ },+ onSuccess: (r) => {+ setResult(r);+ setErrors([]);+ setStage("done");+ queryClient.invalidateQueries({ queryKey: ["marketplace-community"] });+ },+ });++ const signedIn = identity.data?.signed_in === true;+ const disabled = identity.data ? !identity.data.enabled : false;++ // The rail: which station is lit. "live" only after a publish went through.+ const station: 1 | 2 | 3 | 4 =+ stage === "done" ? 4 : stage === "form" ? 3 : signedIn ? 2 : 1;++ return (+ <div+ role="dialog"+ aria-modal="true"+ aria-label={t("marketplace.studio_title")}+ data-testid="publish-studio"+ className="fixed inset-0 z-[60] flex bg-background/80 backdrop-blur-md"+ >+ <button+ type="button"+ aria-label={t("marketplace.close")}+ onClick={onClose}+ className="absolute inset-0 cursor-default"+ />+ <div className="relative m-auto flex h-[min(92vh,56rem)] w-[min(96vw,72rem)] overflow-hidden rounded-2xl border border-border bg-card shadow-2xl">+ {/* Rail */}+ <aside className="relative hidden w-60 shrink-0 flex-col border-r border-border bg-secondary/30 p-5 md:flex">+ <div+ aria-hidden+ className="pointer-events-none absolute -left-20 top-0 h-64 w-64 rounded-full bg-primary/10 blur-3xl"+ />+ <p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">+ {t("marketplace.studio_eyebrow")}+ </p>+ <h2 className="mt-1 font-display text-lg font-semibold tracking-tight text-foreground">+ {t("marketplace.studio_title")}+ </h2>+ <ol className="mt-6 space-y-1">+ <Station n={1} active={station === 1} done={station > 1} label={t("marketplace.studio_station_who")} />+ <Station n={2} active={station === 2} done={station > 2} label={t("marketplace.studio_station_what")} />+ <Station n={3} active={station === 3} done={station > 3} label={t("marketplace.studio_station_check")} />+ <Station n={4} active={station === 4} done={false} label={t("marketplace.studio_station_live")} />+ </ol>+ <div className="mt-auto space-y-2 text-[11px] leading-relaxed text-muted-foreground">+ <p>{t("marketplace.studio_rail_note_public")}</p>+ <p>{t("marketplace.studio_rail_note_rules")}</p>+ </div>+ </aside>++ {/* Work area */}+ <div className="flex min-w-0 flex-1 flex-col">+ <header className="flex items-center gap-3 border-b border-border px-5 py-3">+ {stage !== "source" && stage !== "done" && (+ <Button size="sm" variant="ghost" onClick={() => setStage("source")}>+ <ArrowLeft className="mr-1.5 h-3.5 w-3.5" />+ {t("marketplace.studio_back")}+ </Button>+ )}+ <div className="min-w-0 flex-1">+ <p className="truncate text-sm font-semibold text-foreground">+ {stage === "source" && t("marketplace.studio_h_source")}+ {stage === "github" && t("marketplace.studio_h_github")}+ {stage === "wallpapers" && t("marketplace.studio_h_wallpapers")}+ {stage === "form" && t("marketplace.studio_h_form")}+ {stage === "done" && t("marketplace.studio_h_done")}+ </p>+ </div>+ {signedIn && identity.data && (+ <span className="hidden items-center gap-2 rounded-full border border-border bg-background/60 py-0.5 pl-0.5 pr-2.5 text-[11px] text-foreground sm:flex">+ <PublisherAvatar login={identity.data.login} url={identity.data.avatar_url} size={20} />+ @{identity.data.login}+ </span>+ )}+ <Button size="sm" variant="ghost" onClick={onClose} aria-label={t("marketplace.close")}>+ <X className="h-4 w-4" />+ </Button>+ </header>++ <ScrollArea className="min-h-0 flex-1">+ <div className="px-5 py-5">+ {!localeReady ? (+ <p className="flex items-center gap-2 py-10 text-sm text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin" />+ </p>+ ) : disabled ? (+ <p className="text-sm text-muted-foreground">{t("marketplace.studio_disabled")}</p>+ ) : stage === "done" && result ? (+ <PublishedCard result={result} onPublishAnother={startOver} t={t} />+ ) : (+ <div className="space-y-5">+ {stage !== "wallpapers" && (+ <PublishIdentityCard identity={identity.data} loading={identity.isLoading} />+ )}++ {stage === "source" && (+ <SourcePicker+ onFolder={applyFolderDraft}+ onGithub={() => setStage("github")}+ onBlank={startBlank}+ onWallpapers={() => setStage("wallpapers")}+ wallpapersEnabled={identity.data?.wallpapers_enabled !== false}+ t={t}+ />+ )}++ {stage === "github" && (+ <GithubImportPanel+ login={signedIn ? (identity.data?.login ?? "") : ""}+ onImported={applyFolderDraft}+ t={t}+ />+ )}++ {stage === "wallpapers" && (+ <WallpaperLane identityLoading={identity.isLoading} identity={identity.data} t={t} />+ )}++ {stage === "form" && (+ <DraftForm+ draft={draft}+ set={set}+ prefill={prefill}+ errors={errors}+ checked={checked}+ signedIn={signedIn}+ validating={validateMutation.isPending}+ submitting={submitMutation.isPending}+ onCheck={() => validateMutation.mutate()}+ onPublish={() => submitMutation.mutate()}+ onStartOver={startOver}+ t={t}+ />+ )}+ </div>+ )}+ </div>+ </ScrollArea>+ </div>+ </div>+ </div>+ );+}++function Station({+ n,+ active,+ done,+ label,+}: {+ n: number;+ active: boolean;+ done: boolean;+ label: string;+}) {+ return (+ <li+ className={cn(+ "flex items-center gap-3 rounded-lg px-2.5 py-2 text-sm transition-colors",+ active ? "bg-background/70 text-foreground shadow-sm" : "text-muted-foreground",+ )}+ data-active={active ? "yes" : "no"}+ >+ <span+ className={cn(+ "grid h-6 w-6 shrink-0 place-items-center rounded-full border text-[11px] font-bold",+ done+ ? "border-primary bg-primary text-primary-foreground"+ : active+ ? "border-primary text-primary"+ : "border-border text-muted-foreground",+ )}+ >+ {done ? <Check className="h-3 w-3" /> : n}+ </span>+ <span className="truncate">{label}</span>+ </li>+ );+}++// ---------------------------------------------------------------------------+// Station 2: where does the thing come from?+// ---------------------------------------------------------------------------++function SourcePicker({+ onFolder,+ onGithub,+ onBlank,+ onWallpapers,+ wallpapersEnabled,+ t,+}: {+ onFolder: (draft: FolderDraft, origin: string) => void;+ onGithub: () => void;+ onBlank: (kind: Kind) => void;+ onWallpapers: () => void;+ wallpapersEnabled: boolean;+ t: Translate;+}) {+ const [dragOver, setDragOver] = useState(false);+ const [busy, setBusy] = useState(false);+ const [dropError, setDropError] = useState<string | null>(null);+ const pickerRef = useRef<HTMLInputElement | null>(null);++ const handleFiles = async (+ load: () => Promise<Parameters<typeof folderToDraft>[0]>,+ origin: string,+ ) => {+ setBusy(true);+ setDropError(null);+ try {+ const files = await load();+ const folder = await folderToDraft(files);+ onFolder(folder, origin);+ } catch (err) {+ setDropError(err instanceof Error ? err.message : t("marketplace.studio_err_folder"));+ } finally {+ setBusy(false);+ }+ };++ return (+ <section className="space-y-4">+ <div className="flex flex-wrap items-baseline gap-2">+ <span className="text-xs font-semibold uppercase tracking-wider text-foreground">+ {t("marketplace.studio_source_label")}+ </span>+ <span className="text-[11px] text-muted-foreground">+ {t("marketplace.studio_source_hint")}+ </span>+ </div>++ <div className="grid gap-3 md:grid-cols-2">+ {/* Folder drop — the primary door, so it gets the big tile. */}+ <div+ role="button"+ tabIndex={0}+ aria-label={t("marketplace.studio_door_folder")}+ data-testid="studio-door-folder"+ onClick={() => pickerRef.current?.click()}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") pickerRef.current?.click();+ }}+ onDragOver={(e) => {+ e.preventDefault();+ setDragOver(true);+ }}+ onDragLeave={() => setDragOver(false)}+ onDrop={(e) => {+ e.preventDefault();+ setDragOver(false);+ const items = e.dataTransfer.items;+ void handleFiles(() => collectDroppedFiles(items), t("marketplace.studio_origin_folder"));+ }}+ className={cn(+ "group relative flex min-h-44 cursor-pointer flex-col justify-end overflow-hidden rounded-2xl border border-dashed p-5 text-left transition-colors md:row-span-2",+ "focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ dragOver+ ? "border-primary bg-primary/10"+ : "border-border bg-gradient-to-br from-primary/10 via-card to-card hover:border-primary/50",+ )}+ >+ <div+ aria-hidden+ className="pointer-events-none absolute -right-10 -top-10 h-40 w-40 rounded-full bg-primary/15 blur-3xl transition-transform duration-500 group-hover:scale-125"+ />+ <span className="grid h-11 w-11 place-items-center rounded-xl bg-primary text-primary-foreground shadow-lg">+ {busy ? <Loader2 className="h-5 w-5 animate-spin" /> : <FolderUp className="h-5 w-5" />}+ </span>+ <p className="mt-4 font-display text-base font-semibold tracking-tight text-foreground">+ {t("marketplace.studio_door_folder")}+ </p>+ <p className="mt-1 text-xs leading-relaxed text-muted-foreground">+ {t("marketplace.studio_door_folder_hint")}+ </p>+ <input+ ref={pickerRef}+ type="file"+ multiple+ className="hidden"+ // Non-standard but universally supported attribute for folder pickers.+ {...({ webkitdirectory: "" } as Record<string, string>)}+ onChange={(e) => {+ const list = e.currentTarget.files;+ if (list && list.length > 0) {+ void handleFiles(+ () => Promise.resolve(collectPickedFiles(list)),+ t("marketplace.studio_origin_folder"),+ );+ }+ e.currentTarget.value = "";+ }}+ />+ </div>++ <Door+ icon={<Github className="h-4 w-4" />}+ title={t("marketplace.studio_door_github")}+ hint={t("marketplace.studio_door_github_hint")}+ onClick={onGithub}+ testId="studio-door-github"+ />++ <div className="flex flex-col rounded-2xl border border-border bg-card/50 p-4">+ <span className="grid h-9 w-9 place-items-center rounded-lg bg-secondary text-foreground">+ <PencilLine className="h-4 w-4" />+ </span>+ <p className="mt-3 text-sm font-semibold text-foreground">+ {t("marketplace.studio_door_blank")}+ </p>+ <p className="mt-1 text-xs text-muted-foreground">+ {t("marketplace.studio_door_blank_hint")}+ </p>+ <div className="mt-3 flex items-center gap-2">+ <Button size="sm" variant="outline" onClick={() => onBlank("skill")}>+ <FileText className="mr-1.5 h-3.5 w-3.5" />+ {t("marketplace.kind_skill")}+ </Button>+ <Button size="sm" variant="outline" onClick={() => onBlank("plugin")}>+ <Plug className="mr-1.5 h-3.5 w-3.5" />+ {t("marketplace.kind_plugin")}+ </Button>+ </div>+ </div>++ {wallpapersEnabled && (+ <Door+ icon={<ImageIcon className="h-4 w-4" />}+ title={t("marketplace.studio_door_wallpaper")}+ hint={t("marketplace.studio_door_wallpaper_hint")}+ onClick={onWallpapers}+ testId="studio-door-wallpaper"+ className="md:col-span-2"+ />+ )}+ </div>++ {dropError && (+ <p className="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 px-2 py-1.5 text-xs text-destructive">+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ {dropError}+ </p>+ )}++ <HowPublishingWorks t={t} />+ </section>+ );+}++function Door({+ icon,+ title,+ hint,+ onClick,+ testId,+ className,+}: {+ icon: React.ReactNode;+ title: string;+ hint: string;+ onClick: () => void;+ testId?: string;+ className?: string;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ data-testid={testId}+ className={cn(+ "flex flex-col rounded-2xl border border-border bg-card/50 p-4 text-left transition-colors",+ "hover:border-primary/50 hover:bg-secondary/40 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ className,+ )}+ >+ <span className="grid h-9 w-9 place-items-center rounded-lg bg-secondary text-foreground">+ {icon}+ </span>+ <p className="mt-3 text-sm font-semibold text-foreground">{title}</p>+ <p className="mt-1 text-xs text-muted-foreground">{hint}</p>+ </button>+ );+}++/** The built-in author guide: the four steps and the expected folder shape,+ * inline, so nobody needs to find a doc first. */+function HowPublishingWorks({ t }: { t: Translate }) {+ const [open, setOpen] = useState(false);+ return (+ <section className="rounded-2xl border border-border bg-card/40 p-4">+ <p className="text-xs font-semibold uppercase tracking-wider text-foreground">+ {t("marketplace.studio_how_title")}+ </p>+ <ol className="mt-2 grid gap-2 text-xs text-muted-foreground sm:grid-cols-4">+ {[1, 2, 3, 4].map((n) => (+ <li key={n} className="flex gap-2">+ <span className="grid h-5 w-5 shrink-0 place-items-center rounded-full border border-primary/50 text-[10px] font-bold text-primary">+ {n}+ </span>+ {t(`marketplace.studio_how_step_${n}`)}+ </li>+ ))}+ </ol>+ <button+ type="button"+ onClick={() => setOpen((o) => !o)}+ className="mt-3 text-[11px] font-medium text-primary hover:underline"+ >+ {open ? t("marketplace.studio_how_hide_layout") : t("marketplace.studio_how_show_layout")}+ </button>+ {open && (+ <div className="mt-2 overflow-x-auto">+ <pre className="rounded-md border border-border bg-background p-3 font-mono text-[11px] leading-relaxed text-foreground">+ {`my-plugin/+├── plugin.json ← required: name, description, version+├── mcp.json ← the server your plugin talks to (optional)+├── skills/ ← instructions that ship with it (optional)+│ └── my-skill/SKILL.md+└── io.github.personaljarvis/+ └── usage-card.md ← when the assistant should use it (optional)++my-skill/+└── SKILL.md ← a standalone skill: one file, YAML frontmatter first`}+ </pre>+ <p className="mt-2 text-[11px] text-muted-foreground">+ {t("marketplace.studio_how_layout_note")}+ </p>+ </div>+ )}+ </section>+ );+}++// ---------------------------------------------------------------------------+// GitHub import: repos → candidates → prefilled draft+// ---------------------------------------------------------------------------++function GithubImportPanel({+ login,+ onImported,+ t,+}: {+ login: string;+ onImported: (draft: FolderDraft, origin: string) => void;+ t: Translate;+}) {+ const [account, setAccount] = useState(login);+ const [refText, setRefText] = useState("");+ const [repos, setRepos] = useState<RepoSummary[] | null>(null);+ const [selected, setSelected] = useState<{ owner: string; repo: string; branch: string } | null>(+ null,+ );+ const [candidates, setCandidates] = useState<RepoCandidate[] | null>(null);+ const [truncated, setTruncated] = useState(false);+ const [busy, setBusy] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);++ const loadRepos = async (user: string) => {+ if (!user.trim()) return;+ setBusy("repos");+ setError(null);+ setSelected(null);+ setCandidates(null);+ setTruncated(false);+ try {+ setRepos(await listRepos(user.trim()));+ } catch (err) {+ setRepos(null);+ setError(err instanceof Error ? err.message : t("marketplace.studio_err_repos"));+ } finally {+ setBusy(null);+ }+ };++ // Auto-load the signed-in account's repos once.+ const autoLoaded = useRef(false);+ useEffect(() => {+ if (login && !autoLoaded.current) {+ autoLoaded.current = true;+ void loadRepos(login);+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [login]);++ const openRepo = async (owner: string, repo: string, branch: string) => {+ setBusy(`scan:${owner}/${repo}`);+ setError(null);+ setSelected({ owner, repo, branch });+ setCandidates(null);+ setTruncated(false);+ try {+ const { candidates: found, truncated: cutOff } = await scanRepo(owner, repo, branch);+ setCandidates(found);+ setTruncated(cutOff);+ if (found.length === 0) {+ setError(+ cutOff ? t("marketplace.studio_err_scan_truncated") : t("marketplace.studio_err_scan_empty"),+ );+ }+ } catch (err) {+ setError(err instanceof Error ? err.message : t("marketplace.studio_err_scan"));+ } finally {+ setBusy(null);+ }+ };++ const importCandidate = async (candidate: RepoCandidate) => {+ if (!selected) return;+ setBusy(`import:${candidate.dir}`);+ setError(null);+ try {+ const prefix = candidate.dir ? `${candidate.dir}/` : "";+ const files = await Promise.all(+ candidate.paths.map(async (path) => {+ const text = await fetchRepoFile(selected.owner, selected.repo, selected.branch, path);+ return { path: path.slice(prefix.length), file: new File([text], path) };+ }),+ );+ const draft = await folderToDraft(files);+ onImported(draft, `${selected.owner}/${selected.repo}`);+ } catch (err) {+ setError(err instanceof Error ? err.message : t("marketplace.studio_err_import"));+ } finally {+ setBusy(null);+ }+ };++ const openRef = async () => {+ const parsed = parseRepoRef(refText);+ if (!parsed) {+ setError(t("marketplace.studio_err_ref"));+ return;+ }+ // The git trees API needs a real branch name, not the literal "HEAD" —+ // resolve the repo's default branch first.+ setBusy(`resolve:${parsed.owner}/${parsed.repo}`);+ setError(null);+ try {+ const info = await getRepo(parsed.owner, parsed.repo);+ await openRepo(parsed.owner, parsed.repo, info.default_branch);+ } catch (err) {+ setError(err instanceof Error ? err.message : t("marketplace.studio_err_resolve"));+ setBusy(null);+ }+ };++ return (+ <section className="space-y-4 rounded-2xl border border-border bg-card/40 p-4">+ <p className="text-[11px] text-muted-foreground">{t("marketplace.studio_github_note")}</p>++ <div className="flex flex-wrap items-end gap-2">+ <div className="min-w-48 flex-1">+ <label className="mb-1 block text-xs font-medium text-foreground" htmlFor="gh-account">+ {t("marketplace.studio_github_account")}+ </label>+ <input+ id="gh-account"+ value={account}+ onChange={(e) => setAccount(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") void loadRepos(account);+ }}+ placeholder="your-github-name"+ className={inputCls(false)}+ />+ </div>+ <Button+ size="sm"+ variant="outline"+ onClick={() => void loadRepos(account)}+ disabled={busy === "repos" || !account.trim()}+ >+ {busy === "repos" ? (+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />+ ) : (+ <Search className="mr-1.5 h-3.5 w-3.5" />+ )}+ {t("marketplace.studio_github_list")}+ </Button>+ <div className="min-w-48 flex-1">+ <label className="mb-1 block text-xs font-medium text-foreground" htmlFor="gh-ref">+ {t("marketplace.studio_github_one_repo")}+ </label>+ <input+ id="gh-ref"+ value={refText}+ onChange={(e) => setRefText(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") void openRef();+ }}+ placeholder="owner/repo"+ className={inputCls(false)}+ />+ </div>+ <Button size="sm" variant="outline" onClick={() => void openRef()} disabled={busy !== null}>+ {busy?.startsWith("resolve:") ? (+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />+ ) : null}+ {t("marketplace.studio_github_scan")}+ </Button>+ </div>++ {error && (+ <p className="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 px-2 py-1.5 text-xs text-destructive">+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ {error}+ </p>+ )}++ {repos && !selected && (+ <ul className="max-h-72 space-y-1 overflow-y-auto">+ {repos.map((r) => (+ <li key={r.full_name}>+ <button+ type="button"+ onClick={() => {+ const [owner, repo] = r.full_name.split("/");+ void openRepo(owner, repo, r.default_branch);+ }}+ className={cn(+ "flex w-full items-baseline gap-2 rounded-md border border-transparent px-2 py-1.5 text-left transition-colors",+ "hover:border-border hover:bg-muted/40 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ )}+ >+ <span className="font-mono text-xs text-foreground">{r.full_name}</span>+ {busy === `scan:${r.full_name}` && (+ <Loader2 className="h-3 w-3 animate-spin text-muted-foreground" />+ )}+ {r.description && (+ <span className="truncate text-[11px] text-muted-foreground">+ {r.description}+ </span>+ )}+ </button>+ </li>+ ))}+ {repos.length === 0 && (+ <li className="px-2 py-1.5 text-xs text-muted-foreground">+ {t("marketplace.studio_github_no_repos")}+ </li>+ )}+ </ul>+ )}++ {selected && (+ <div className="space-y-2">+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={() => {+ setSelected(null);+ setCandidates(null);+ setTruncated(false);+ setError(null);+ }}+ className="text-[11px] font-medium text-primary hover:underline"+ >+ ← {t("marketplace.studio_github_all_repos")}+ </button>+ <span className="font-mono text-xs text-foreground">+ {selected.owner}/{selected.repo}+ </span>+ {busy?.startsWith("scan:") && (+ <Loader2 className="h-3 w-3 animate-spin text-muted-foreground" />+ )}+ </div>+ {truncated && candidates && candidates.length > 0 && (+ <p className="flex items-start gap-1.5 text-[11px] text-muted-foreground">+ <AlertTriangle className="mt-0.5 h-3 w-3 shrink-0" />+ {t("marketplace.studio_github_truncated")}+ </p>+ )}+ {candidates && candidates.length > 0 && (+ <ul className="space-y-1">+ {candidates.map((c) => (+ <li+ key={`${c.kind}:${c.dir}`}+ className="flex flex-wrap items-center gap-2 rounded-md border border-border bg-background px-2.5 py-2"+ >+ {c.kind === "plugin" ? (+ <Plug className="h-3.5 w-3.5 text-primary" />+ ) : (+ <FileText className="h-3.5 w-3.5 text-primary" />+ )}+ <span className="text-xs font-medium text-foreground">+ {c.kind === "plugin" ? t("marketplace.kind_plugin") : t("marketplace.kind_skill")}+ </span>+ <span className="font-mono text-[11px] text-muted-foreground">/{c.dir || ""}</span>+ <span className="text-[11px] text-muted-foreground">+ {fill(t("marketplace.studio_github_files"), { count: c.paths.length })}+ </span>+ <Button+ size="sm"+ variant="outline"+ className="ml-auto"+ onClick={() => void importCandidate(c)}+ disabled={busy !== null}+ >+ {busy === `import:${c.dir}` ? (+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />+ ) : null}+ {t("marketplace.studio_github_review")}+ </Button>+ </li>+ ))}+ </ul>+ )}+ </div>+ )}+ </section>+ );+}++// ---------------------------------------------------------------------------+// The wallpaper lane: your own pictures, one click from published.+// ---------------------------------------------------------------------------++function WallpaperLane({+ identity,+ identityLoading,+ t,+}: {+ identity: ReturnType<typeof usePublishIdentity>["data"];+ identityLoading: boolean;+ t: Translate;+}) {+ const { data: uploads, isLoading } = useWallpaperUploads();+ const [shareItem, setShareItem] = useState<WallpaperEntry | null>(null);+ const own = useMemo(+ () => (uploads ?? []).filter((u) => u.source !== "marketplace").map(uploadAsEntry),+ [uploads],+ );+ return (+ <section className="space-y-4">+ <PublishIdentityCard+ identity={identity}+ loading={identityLoading}+ blurb={t("marketplace.share_identity_blurb")}+ />+ <div className="flex flex-wrap items-baseline gap-2">+ <span className="text-xs font-semibold uppercase tracking-wider text-foreground">+ {t("marketplace.studio_wallpapers_label")}+ </span>+ <span className="text-[11px] text-muted-foreground">+ {t("marketplace.studio_wallpapers_hint")}+ </span>+ </div>+ {isLoading ? (+ <p className="flex items-center gap-2 text-xs text-muted-foreground">+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ {t("marketplace.loading")}+ </p>+ ) : own.length === 0 ? (+ <div className="rounded-2xl border border-dashed border-border p-6 text-center">+ <ImageIcon className="mx-auto mb-2 h-5 w-5 text-muted-foreground" />+ <p className="text-xs text-muted-foreground">{t("marketplace.studio_wallpapers_empty")}</p>+ </div>+ ) : (+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3" data-testid="studio-own-wallpapers">+ {own.map((entry) => (+ <button+ key={entry.id}+ type="button"+ onClick={() => setShareItem(entry)}+ className="group relative aspect-[16/10] overflow-hidden rounded-xl border border-border bg-secondary/40 text-left transition-colors hover:border-primary/60 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <img+ src={thumbUrlFor(entry)}+ alt=""+ loading="lazy"+ className="h-full w-full object-cover transition-transform duration-500 group-hover:scale-[1.03]"+ />+ <span className="absolute inset-x-0 bottom-0 flex items-center gap-2 bg-gradient-to-t from-black/75 to-transparent p-3">+ <span className="min-w-0 flex-1 truncate text-xs font-medium text-white">+ {entry.title}+ </span>+ <span className="rounded-full bg-white/15 px-2 py-0.5 text-[10px] font-medium text-white backdrop-blur">+ {t("marketplace.share_cta")}+ </span>+ </span>+ </button>+ ))}+ </div>+ )}+ {shareItem && <PublishWallpaperDialog item={shareItem} onClose={() => setShareItem(null)} />}+ </section>+ );+}++// ---------------------------------------------------------------------------+// Station 3: the form (prefilled or blank) + live store-card preview+// ---------------------------------------------------------------------------++function DraftForm({+ draft,+ set,+ prefill,+ errors,+ checked,+ signedIn,+ validating,+ submitting,+ onCheck,+ onPublish,+ onStartOver,+ t,+}: {+ draft: Draft;+ set: (patch: Partial<Draft>) => void;+ prefill: { origin: string; files: string[]; warnings: string[] } | null;+ errors: FieldErrorWire[];+ checked: boolean;+ signedIn: boolean;+ validating: boolean;+ submitting: boolean;+ onCheck: () => void;+ onPublish: () => void;+ onStartOver: () => void;+ t: Translate;+}) {+ const errorFor = (field: string) => errors.filter((e) => e.field === field);+ const generalErrors = errors.filter((e) => e.field === null);+ const skillBytes = new TextEncoder().encode(draft.skill_md).length;++ return (+ <div className="grid gap-5 lg:grid-cols-[minmax(0,1fr)_18rem]">+ <section className="space-y-4" data-testid="studio-form">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-xs font-semibold uppercase tracking-wider text-foreground">+ {t("marketplace.studio_form_label")}+ </span>+ <div className="ml-auto flex items-center gap-1">+ <KindButton+ active={draft.kind === "skill"}+ icon={<FileText className="h-3.5 w-3.5" />}+ label={t("marketplace.kind_skill")}+ onClick={() => set({ kind: "skill" })}+ />+ <KindButton+ active={draft.kind === "plugin"}+ icon={<Plug className="h-3.5 w-3.5" />}+ label={t("marketplace.kind_plugin")}+ onClick={() => set({ kind: "plugin" })}+ />+ </div>+ </div>++ {prefill && (+ <div className="rounded-xl border border-primary/30 bg-primary/5 px-3 py-2">+ <p className="text-xs text-foreground">+ <Check className="mr-1 inline h-3.5 w-3.5 text-primary" />+ {fill(t("marketplace.studio_prefilled_from"), { origin: prefill.origin })}+ </p>+ {prefill.files.length > 0 && (+ <p className="mt-1 font-mono text-[11px] text-muted-foreground">+ {prefill.files.join(" · ")}+ </p>+ )}+ {prefill.warnings.map((w, i) => (+ <p key={i} className="mt-1 flex items-start gap-1.5 text-[11px] text-muted-foreground">+ <AlertTriangle className="mt-0.5 h-3 w-3 shrink-0" />+ {w}+ </p>+ ))}+ </div>+ )}++ <div className="grid gap-3 sm:grid-cols-2">+ <Field+ label={t("marketplace.studio_f_name")}+ hint={t("marketplace.studio_f_name_hint")}+ errors={errorFor("name")}+ >+ <input+ value={draft.name}+ onChange={(e) => set({ name: e.target.value })}+ placeholder="my-skill"+ className={inputCls(errorFor("name").length > 0)}+ data-testid="studio-name"+ />+ </Field>+ <Field+ label={t("marketplace.studio_f_version")}+ hint={t("marketplace.studio_f_version_hint")}+ errors={errorFor("version")}+ >+ <input+ value={draft.version}+ onChange={(e) => set({ version: e.target.value })}+ placeholder="1.0.0"+ className={inputCls(errorFor("version").length > 0)}+ />+ </Field>+ </div>++ {draft.kind === "skill" ? (+ <>+ <Field label={t("marketplace.studio_f_title")} errors={errorFor("title")}>+ <input+ value={draft.title}+ onChange={(e) => set({ title: e.target.value })}+ placeholder="My Skill"+ className={inputCls(errorFor("title").length > 0)}+ />+ </Field>+ <Field+ label={t("marketplace.studio_f_description")}+ hint={fill(t("marketplace.studio_f_description_hint"), {+ count: draft.description.length,+ })}+ errors={errorFor("description")}+ >+ <textarea+ value={draft.description}+ onChange={(e) => set({ description: e.target.value })}+ rows={2}+ className={inputCls(errorFor("description").length > 0)}+ />+ </Field>+ <Field+ label={t("marketplace.studio_f_categories")}+ hint={t("marketplace.studio_f_categories_hint")}+ errors={[]}+ >+ <input+ value={draft.categories}+ onChange={(e) => set({ categories: e.target.value })}+ placeholder="writing, research"+ className={inputCls(false)}+ />+ </Field>+ <Field+ label="SKILL.md"+ hint={fill(t("marketplace.studio_f_skill_md_hint"), {+ kb: (skillBytes / 1024).toFixed(1),+ max: MAX_SKILL_MD_BYTES / 1024,+ })}+ errors={errorFor("skill_md")}+ action={+ draft.skill_md.trim() === "" ? (+ <button+ type="button"+ onClick={() => set({ skill_md: SKILL_TEMPLATE })}+ className="text-[11px] font-medium text-primary hover:underline"+ >+ {t("marketplace.studio_insert_template")}+ </button>+ ) : null+ }+ >+ <textarea+ value={draft.skill_md}+ onChange={(e) => set({ skill_md: e.target.value })}+ rows={12}+ spellCheck={false}+ className={cn(inputCls(errorFor("skill_md").length > 0), "font-mono text-xs")}+ />+ </Field>+ </>+ ) : (+ <>+ <Field+ label="plugin.json"+ hint={t("marketplace.studio_f_plugin_json_hint")}+ errors={errorFor("plugin_json")}+ >+ <textarea+ value={draft.plugin_json_text}+ onChange={(e) => set({ plugin_json_text: e.target.value })}+ rows={10}+ spellCheck={false}+ placeholder='{ "name": "my-plugin", "version": "1.0.0", … }'+ className={cn(inputCls(errorFor("plugin_json").length > 0), "font-mono text-xs")}+ />+ </Field>+ <Field+ label="mcp.json"+ hint={t("marketplace.studio_f_mcp_json_hint")}+ errors={errorFor("mcp_json")}+ >+ <textarea+ value={draft.mcp_json_text}+ onChange={(e) => set({ mcp_json_text: e.target.value })}+ rows={6}+ spellCheck={false}+ placeholder='{ "mcpServers": { "my-plugin": { "type": "streamable-http", "url": "https://…" } } }'+ className={cn(inputCls(errorFor("mcp_json").length > 0), "font-mono text-xs")}+ />+ </Field>++ <Field+ label={t("marketplace.studio_f_skills")}+ hint={t("marketplace.studio_f_skills_hint")}+ errors={errorFor("skills")}+ >+ {draft.skills.length === 0 ? (+ <p className="rounded-md border border-dashed border-border px-2.5 py-2 text-[11px] text-muted-foreground">+ {t("marketplace.studio_f_skills_none")}+ </p>+ ) : (+ <ul className="flex flex-wrap gap-1.5">+ {draft.skills.map((s) => (+ <li+ key={s.name}+ className="flex items-center gap-1.5 rounded-full border border-border bg-background px-2.5 py-1"+ >+ <FileText className="h-3 w-3 text-primary" />+ <span className="font-mono text-[11px] text-foreground">{s.name}</span>+ <span className="text-[10px] text-muted-foreground">+ {Math.max(1, Math.round(s.skill_md.length / 1024))} KB+ </span>+ <button+ type="button"+ aria-label={`Remove ${s.name}`}+ onClick={() =>+ set({ skills: draft.skills.filter((x) => x.name !== s.name) })+ }+ className="grid h-4 w-4 place-items-center rounded text-muted-foreground hover:text-foreground"+ >+ <X className="h-3 w-3" />+ </button>+ </li>+ ))}+ </ul>+ )}+ </Field>++ <Field+ label={t("marketplace.studio_f_usage_card")}+ hint={t("marketplace.studio_f_usage_card_hint")}+ errors={[]}+ >+ <textarea+ value={draft.usage_card}+ onChange={(e) => set({ usage_card: e.target.value })}+ rows={4}+ spellCheck={false}+ className={cn(inputCls(false), "font-mono text-xs")}+ />+ </Field>+ </>+ )}++ {generalErrors.map((e, i) => (+ <p+ key={i}+ className="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 px-2 py-1.5 text-xs text-destructive"+ >+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ {e.error}+ </p>+ ))}+ {checked && errors.length === 0 && (+ <p+ className="flex items-center gap-2 rounded-md border border-primary/40 bg-primary/5 px-3 py-2 text-xs text-foreground"+ data-testid="studio-check-ok"+ >+ <Check className="h-3.5 w-3.5 text-primary" />+ {t("marketplace.studio_check_ok")}+ </p>+ )}++ <div className="flex flex-wrap items-center justify-end gap-2 border-t border-border/50 pt-3">+ <Button size="sm" variant="ghost" onClick={onStartOver}>+ <ArrowLeft className="mr-1.5 h-3.5 w-3.5" />+ {t("marketplace.studio_start_over")}+ </Button>+ <Button size="sm" variant="outline" onClick={onCheck} disabled={validating}>+ {validating ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" /> : null}+ {t("marketplace.studio_check")}+ </Button>+ <Button+ size="sm"+ onClick={onPublish}+ disabled={submitting || !signedIn}+ title={signedIn ? undefined : t("marketplace.studio_sign_in_first")}+ data-testid="studio-publish"+ >+ {submitting ? (+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />+ ) : (+ <UploadCloud className="mr-1.5 h-3.5 w-3.5" />+ )}+ {t("marketplace.studio_publish")}+ </Button>+ </div>+ </section>++ <aside className="lg:sticky lg:top-0 lg:self-start">+ <CardPreview draft={draft} t={t} />+ </aside>+ </div>+ );+}++/** What the store card will look like — the author sees the listing before+ * the world does. Derived from the draft on every keystroke. */+function CardPreview({ draft, t }: { draft: Draft; t: Translate }) {+ const preview = useMemo(() => {+ if (draft.kind === "skill") {+ return {+ title: draft.title.trim() || draft.name.trim() || t("marketplace.studio_preview_untitled"),+ description: draft.description.trim() || t("marketplace.studio_preview_no_description"),+ detail: draft.categories+ .split(",")+ .map((c) => c.trim())+ .filter(Boolean)+ .join(" · "),+ initial: (draft.title.trim() || draft.name.trim() || "S").slice(0, 1).toUpperCase(),+ };+ }+ let displayName = draft.name.trim();+ let description = "";+ let category = "Community";+ try {+ const manifest = JSON.parse(draft.plugin_json_text || "{}") as {+ description?: string;+ extensions?: Record<string, { display_name?: string; category?: string }>;+ };+ description = manifest.description ?? "";+ const ext = manifest.extensions?.["io.github.personaljarvis"];+ if (ext?.display_name) displayName = ext.display_name;+ if (ext?.category) category = ext.category;+ } catch {+ // Preview only — the real validation reports JSON errors properly.+ }+ let server = "";+ try {+ const mcp = JSON.parse(draft.mcp_json_text || "{}") as {+ mcpServers?: Record<string, { url?: string; command?: string; args?: string[] }>;+ };+ const first = Object.values(mcp.mcpServers ?? {})[0];+ if (first?.url) server = first.url;+ else if (first?.command) server = [first.command, ...(first.args ?? [])].join(" ");+ } catch {+ // Preview only.+ }+ const bits = [category];+ if (draft.skills.length > 0) {+ bits.push(fill(t("marketplace.studio_preview_bundled"), { count: draft.skills.length }));+ }+ if (server) bits.push(server);+ return {+ title: displayName || t("marketplace.studio_preview_untitled"),+ description: description || t("marketplace.studio_preview_no_description"),+ detail: bits.join(" · "),+ initial: (displayName || "P").slice(0, 1).toUpperCase(),+ };+ }, [draft, t]);++ return (+ <div data-testid="studio-card-preview">+ <p className="mb-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">+ {t("marketplace.studio_preview_label")}+ </p>+ <div className="overflow-hidden rounded-2xl border border-border bg-card/70 shadow-sm">+ <div className="flex items-center gap-3 px-3.5 py-3">+ <div className="grid h-10 w-10 shrink-0 place-items-center rounded-lg bg-gradient-to-br from-primary/70 to-primary/30 text-sm font-semibold text-primary-foreground">+ {draft.kind === "skill" ? <Sparkles className="h-4 w-4" /> : preview.initial}+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <span className="truncate text-sm font-semibold text-foreground">{preview.title}</span>+ <span className="shrink-0 rounded-full border border-border px-1.5 py-px text-[9px] font-semibold uppercase tracking-wider text-muted-foreground">+ {draft.kind === "skill" ? t("marketplace.kind_skill") : t("marketplace.kind_plugin")}+ </span>+ </div>+ <p className="truncate text-xs text-muted-foreground">{preview.description}</p>+ </div>+ </div>+ <div className="flex items-center justify-between border-t border-border/70 px-3.5 py-2 text-[10px] text-muted-foreground">+ <span className="truncate">{preview.detail || "—"}</span>+ <span className="ml-2 shrink-0 tabular-nums">v{draft.version.trim() || "?"}</span>+ </div>+ </div>+ <p className="mt-2 text-[11px] leading-relaxed text-muted-foreground">+ {t("marketplace.studio_preview_note")}+ </p>+ </div>+ );+}++function inputCls(hasError: boolean): string {+ return cn(+ "w-full rounded-lg border bg-background px-2.5 py-1.5 text-sm text-foreground",+ "placeholder:text-muted-foreground/60 focus:outline-none focus:ring-1 focus:ring-ring",+ hasError ? "border-destructive/60" : "border-border",+ );+}++function Field({+ label,+ hint,+ errors,+ action,+ children,+}: {+ label: string;+ hint?: string;+ errors: FieldErrorWire[];+ action?: React.ReactNode;+ children: React.ReactNode;+}) {+ return (+ <div>+ <div className="mb-1 flex items-baseline justify-between gap-2">+ <label className="text-xs font-medium text-foreground">{label}</label>+ {action}+ </div>+ {children}+ {hint && errors.length === 0 && (+ <p className="mt-1 text-[11px] text-muted-foreground">{hint}</p>+ )}+ {errors.map((e, i) => (+ <p key={i} className="mt-1 text-[11px] text-destructive">+ {e.error}+ </p>+ ))}+ </div>+ );+}++function KindButton({+ active,+ icon,+ label,+ onClick,+}: {+ active: boolean;+ icon: React.ReactNode;+ label: string;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ aria-pressed={active}+ className={cn(+ "inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs font-medium transition-colors",+ active+ ? "border-primary/50 bg-primary/10 text-foreground"+ : "border-border text-muted-foreground hover:border-primary/30 hover:text-foreground",+ )}+ >+ {icon}+ {label}+ </button>+ );+}++// ---------------------------------------------------------------------------+// Station 4: the PR is open — watch the live feed until the package appears.+// ---------------------------------------------------------------------------++function PublishedCard({+ result,+ onPublishAnother,+ t,+}: {+ result: SubmitResultWire;+ onPublishAnother: () => void;+ t: Translate;+}) {+ const [live, setLive] = useState(false);+ const [waitedOut, setWaitedOut] = useState(false);++ useEffect(() => {+ if (live) return;+ let ticks = 0;+ const timer = setInterval(async () => {+ ticks += 1;+ if (ticks > 20) {+ // ~7 minutes of watching is enough; the PR link remains the source+ // of truth for anything slower (checks queued, merge conflict).+ setWaitedOut(true);+ clearInterval(timer);+ return;+ }+ try {+ const params = new URLSearchParams({+ name: result.name,+ version: result.version,+ force: "true",+ });+ const res = await fetch(`/api/marketplace/publish/status?${params.toString()}`, {+ cache: "no-store",+ });+ if (!res.ok) return;+ const data = (await res.json()) as { live: boolean };+ if (data.live) {+ setLive(true);+ clearInterval(timer);+ }+ } catch {+ // Feed unreachable — keep trying until the tick budget runs out.+ }+ }, 20_000);+ return () => clearInterval(timer);+ }, [live, result]);++ return (+ <div className="space-y-4" data-testid="studio-published">+ <section className="relative overflow-hidden rounded-2xl border border-primary/30 bg-gradient-to-br from-primary/15 via-card to-card p-5">+ <div+ aria-hidden+ className="pointer-events-none absolute -right-16 -top-16 h-56 w-56 rounded-full bg-primary/20 blur-3xl"+ />+ <p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">+ {t("marketplace.studio_done_eyebrow")}+ </p>+ <p className="mt-1 flex items-center gap-2 font-display text-lg font-semibold tracking-tight text-foreground">+ <Check className="h-5 w-5 text-primary" />+ {result.name} <span className="text-muted-foreground">v{result.version}</span>+ </p>+ <p className="mt-2 max-w-xl text-xs leading-relaxed text-muted-foreground">+ {t("marketplace.studio_done_body")}+ </p>+ <div className="mt-4 flex flex-wrap items-center gap-2">+ {result.pr_url && (+ <Button+ size="sm"+ variant="outline"+ onClick={() => openExternalUrl(result.pr_url ?? "")}+ >+ <ExternalLink className="mr-1.5 h-3.5 w-3.5" />+ {t("marketplace.studio_done_view_pr")}+ </Button>+ )}+ <Button size="sm" variant="ghost" onClick={onPublishAnother}>+ {t("marketplace.studio_done_another")}+ </Button>+ </div>+ </section>++ <section className="space-y-4 rounded-2xl border border-border bg-card/40 p-4">+ {live ? (+ <p className="flex items-center gap-2 text-sm text-foreground">+ <Check className="h-4 w-4 text-primary" />+ {fill(t("marketplace.studio_done_live"), { name: result.name, version: result.version })}+ </p>+ ) : waitedOut ? (+ <p className="text-xs text-muted-foreground">{t("marketplace.studio_done_waited_out")}</p>+ ) : (+ <p className="flex items-center gap-2 text-xs text-muted-foreground">+ <span className="relative flex h-2 w-2">+ <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-primary/60" />+ <span className="relative inline-flex h-2 w-2 rounded-full bg-primary" />+ </span>+ {t("marketplace.studio_done_watching")}+ </p>+ )}++ {/* Gated on `live` on purpose: handed out a minute too early, the+ command resolves against an index that does not list the entry yet+ and fails for whoever the author sent it to. */}+ {live && result.install && (+ <InstallStandard+ install={result.install}+ heading={t("marketplace.studio_done_share_heading")}+ note={t("marketplace.studio_done_share_note")}+ />+ )}+ </section>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/wallpaper/PublishWallpaperDialog.tsx b/jarvis/ui/web/frontend/src/components/wallpaper/PublishWallpaperDialog.tsxnew file mode 100644index 0000000000..151515da7a--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/wallpaper/PublishWallpaperDialog.tsx@@ -0,0 +1,361 @@+import { useEffect, useState } from "react";+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { AlertTriangle, Check, Loader2, Send, X } from "lucide-react";++import { Button } from "@/components/ui/button";+import { InstallStandard, type InstallStandardWire } from "@/components/InstallStandard";+import {+ PublishIdentityCard,+ usePublishIdentity,+} from "@/components/marketplace/PublishIdentity";+import { fullUrlFor, type WallpaperEntry } from "@/hooks/useWallpaperCatalog";+import { fill, useLocaleChunk, useT } from "@/i18n";+import { cn } from "@/lib/utils";++// ---------------------------------------------------------------------------+// "Share to community" — publishing one of your own wallpapers.+//+// What this dialog owes the person using it is honesty about three things,+// because all three are irreversible in ways a picker normally is not:+//+// 1. It goes PUBLIC, under their GitHub name, and nobody reviews it first.+// 2. The license they pick is the permission strangers get — this lane+// only accepts licenses that allow redistribution, because the picture+// is copied onto other people's machines.+// 3. Taking it down later removes it from the store, not from the machines+// that already imported it.+//+// The rights checkbox is the record that carries the lane: no human inspects+// the image before it is live, so the uploader's own statement is the thing+// that makes publishing an accountable act rather than an anonymous one.+// ---------------------------------------------------------------------------++/** Exactly the licenses the endpoint accepts (publish.py WALLPAPER_LICENSES). */+const LICENSES = ["CC0-1.0", "CC-BY-4.0", "CC-BY-SA-4.0"] as const;+type LicenseId = (typeof LICENSES)[number];+const LICENSE_KEY: Record<LicenseId, string> = {+ "CC0-1.0": "cc0",+ "CC-BY-4.0": "ccby",+ "CC-BY-SA-4.0": "ccbysa",+};++const MAX_TITLE_CHARS = 80;+const MAX_DESCRIPTION_CHARS = 500;++interface PublishedWire {+ ok: boolean;+ name: string;+ version: string;+ install?: InstallStandardWire | null;+}++interface FieldErrorWire {+ field: string | null;+ error: string;+}++export function PublishWallpaperDialog({+ item,+ onClose,+}: {+ item: WallpaperEntry;+ onClose: () => void;+}) {+ const t = useT();+ useLocaleChunk("marketplace");+ const queryClient = useQueryClient();+ const identity = usePublishIdentity();+ const signedIn = identity.data?.signed_in === true;++ const [title, setTitle] = useState(item.title);+ const [description, setDescription] = useState("");+ const [license, setLicense] = useState<LicenseId>(LICENSES[0]);+ const [rights, setRights] = useState(false);+ const [error, setError] = useState<FieldErrorWire | null>(null);+ const [published, setPublished] = useState<PublishedWire | null>(null);++ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") onClose();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [onClose]);++ const publish = useMutation({+ mutationFn: async (): Promise<PublishedWire> => {+ const res = await fetch("/api/marketplace/publish/submit-wallpaper", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ upload_id: item.id,+ title: title.trim(),+ description: description.trim(),+ license,+ // The picker's own light/dark filing travels with the picture, so+ // it lands in the right half of somebody else's store too.+ theme: item.theme,+ rights,+ }),+ });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) {+ const detail = (body as { detail?: unknown }).detail;+ if (detail && typeof detail === "object") {+ const shaped = detail as FieldErrorWire;+ throw Object.assign(new Error(shaped.error), { field: shaped.field ?? null });+ }+ throw new Error(+ typeof detail === "string" ? detail : `Publishing failed (${res.status})`,+ );+ }+ return body as PublishedWire;+ },+ onSuccess: (result) => {+ setError(null);+ setPublished(result);+ queryClient.invalidateQueries({ queryKey: ["marketplace-community"] });+ },+ onError: (err: Error & { field?: string | null }) => {+ setError({ field: err.field ?? null, error: err.message });+ },+ });++ const titleTooLong = title.trim().length > MAX_TITLE_CHARS;+ const descriptionTooLong = description.trim().length > MAX_DESCRIPTION_CHARS;+ const ready =+ signedIn && rights && title.trim().length > 0 && !titleTooLong && !descriptionTooLong;++ return (+ <div+ role="dialog"+ aria-modal="true"+ aria-label={fill(t("marketplace.share_dialog_aria"), { title: item.title })}+ data-testid="publish-wallpaper-dialog"+ className="fixed inset-0 z-[65] flex items-center justify-center bg-background/80 p-6 backdrop-blur-sm"+ >+ <div className="flex max-h-full w-full max-w-2xl flex-col overflow-hidden rounded-2xl border border-border bg-card shadow-2xl">+ <header className="flex items-center gap-3 border-b border-border px-5 py-3">+ <div className="min-w-0 flex-1">+ <h2 className="truncate font-display text-sm font-semibold tracking-tight">+ {t("marketplace.share_title")}+ </h2>+ <p className="truncate text-xs text-muted-foreground">+ {published ? t("marketplace.share_subtitle_done") : t("marketplace.share_subtitle")}+ </p>+ </div>+ <Button size="sm" variant="ghost" onClick={onClose} aria-label={t("marketplace.close")}>+ <X className="h-4 w-4" />+ </Button>+ </header>++ <div className="min-h-0 flex-1 space-y-4 overflow-y-auto p-5">+ <div className="flex gap-4">+ <img+ src={fullUrlFor(item)}+ alt={item.title}+ className="h-24 w-40 shrink-0 rounded-xl border border-border object-cover shadow-sm"+ />+ <p className="text-xs leading-relaxed text-muted-foreground">+ {t("marketplace.share_consequences")}+ </p>+ </div>++ {published ? (+ <PublishedPanel result={published} t={t} />+ ) : (+ <>+ <PublishIdentityCard+ identity={identity.data}+ loading={identity.isLoading}+ blurb={t("marketplace.share_identity_blurb")}+ />++ <Field+ label={t("marketplace.share_f_title")}+ error={error?.field === "title" ? error.error : null}+ >+ <input+ value={title}+ onChange={(e) => setTitle(e.target.value)}+ maxLength={MAX_TITLE_CHARS * 2}+ className={inputCls(error?.field === "title" || titleTooLong)}+ placeholder="Rain Antenna City"+ data-testid="wallpaper-title"+ />+ <p className="mt-1 text-[11px] text-muted-foreground">+ {titleTooLong+ ? fill(t("marketplace.share_f_title_too_long"), {+ count: title.trim().length,+ max: MAX_TITLE_CHARS,+ })+ : t("marketplace.share_f_title_hint")}+ </p>+ </Field>++ <Field+ label={t("marketplace.share_f_description")}+ error={error?.field === "description" ? error.error : null}+ >+ <textarea+ value={description}+ onChange={(e) => setDescription(e.target.value)}+ rows={2}+ className={cn(+ inputCls(error?.field === "description" || descriptionTooLong),+ "resize-y",+ )}+ placeholder={t("marketplace.share_f_description_placeholder")}+ />+ </Field>++ <Field+ label={t("marketplace.share_f_license")}+ error={error?.field === "license" ? error.error : null}+ >+ <div className="grid gap-1.5 sm:grid-cols-3">+ {LICENSES.map((id) => (+ <label+ key={id}+ className={cn(+ "flex cursor-pointer items-start gap-2.5 rounded-xl border p-2.5 transition-colors",+ license === id+ ? "border-primary bg-primary/5"+ : "border-border hover:bg-muted/40",+ )}+ >+ <input+ type="radio"+ name="wallpaper-license"+ checked={license === id}+ onChange={() => setLicense(id)}+ className="mt-0.5 accent-primary"+ />+ <span className="min-w-0">+ <span className="block text-xs font-medium text-foreground">+ {t(`marketplace.share_license_${LICENSE_KEY[id]}`)}+ </span>+ <span className="block text-[11px] text-muted-foreground">+ {t(`marketplace.share_license_${LICENSE_KEY[id]}_hint`)}+ </span>+ </span>+ </label>+ ))}+ </div>+ <p className="mt-1.5 text-[11px] text-muted-foreground">+ {t("marketplace.share_f_license_note")}+ </p>+ </Field>++ <label+ className={cn(+ "flex cursor-pointer items-start gap-2.5 rounded-xl border p-3 transition-colors",+ error?.field === "rights"+ ? "border-destructive/50 bg-destructive/5"+ : "border-border hover:bg-muted/40",+ )}+ >+ <input+ type="checkbox"+ checked={rights}+ onChange={(e) => setRights(e.target.checked)}+ className="mt-0.5 accent-primary"+ data-testid="wallpaper-rights"+ />+ <span className="text-xs leading-relaxed text-foreground">+ {t("marketplace.share_rights")}+ </span>+ </label>++ {error && error.field === null && (+ <p className="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive">+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ {error.error}+ </p>+ )}+ </>+ )}+ </div>++ <footer className="flex items-center gap-2 border-t border-border px-5 py-3">+ <p className="min-w-0 flex-1 text-[11px] text-muted-foreground">+ {published+ ? t("marketplace.share_footer_done")+ : signedIn+ ? t("marketplace.share_footer_ready")+ : t("marketplace.share_footer_sign_in")}+ </p>+ {published ? (+ <Button size="sm" onClick={onClose}>+ {t("marketplace.identity_done")}+ </Button>+ ) : (+ <Button+ size="sm"+ onClick={() => publish.mutate()}+ disabled={!ready || publish.isPending}+ data-testid="wallpaper-publish-submit"+ >+ {publish.isPending ? (+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />+ ) : (+ <Send className="mr-1.5 h-3.5 w-3.5" />+ )}+ {t("marketplace.studio_publish")}+ </Button>+ )}+ </footer>+ </div>+ </div>+ );+}++/** After the upload: what it is called now, and how anyone else gets it. */+function PublishedPanel({+ result,+ t,+}: {+ result: PublishedWire;+ t: (key: string) => string;+}) {+ return (+ <div className="space-y-3">+ <p className="flex items-start gap-2 rounded-xl border border-primary/40 bg-primary/5 px-3 py-2 text-xs text-foreground">+ <Check className="mt-0.5 h-3.5 w-3.5 shrink-0 text-primary" />+ <span>{fill(t("marketplace.share_published_as"), { name: result.name })}</span>+ </p>+ {result.install && <InstallStandard install={result.install} />}+ </div>+ );+}++function Field({+ label,+ error,+ children,+}: {+ label: string;+ error: string | null;+ children: React.ReactNode;+}) {+ return (+ <div>+ <label className="mb-1 block text-xs font-medium text-foreground">{label}</label>+ {children}+ {error && (+ <p className="mt-1 flex items-start gap-1.5 text-[11px] text-destructive">+ <AlertTriangle className="mt-0.5 h-3 w-3 shrink-0" />+ {error}+ </p>+ )}+ </div>+ );+}++function inputCls(hasError: boolean): string {+ return cn(+ "w-full rounded-lg border bg-background px-2.5 py-1.5 text-xs text-foreground",+ "placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary",+ hasError ? "border-destructive/60" : "border-border",+ );+}diff --git a/jarvis/ui/web/frontend/src/i18n/index.ts b/jarvis/ui/web/frontend/src/i18n/index.tsindex 15419d7eee..820d68fef1 100644--- a/jarvis/ui/web/frontend/src/i18n/index.ts+++ b/jarvis/ui/web/frontend/src/i18n/index.ts@@ -18,6 +18,7 @@* its own setting, distinct from the UI and the reply language:* useSttLanguage(), setSttLanguage("auto" | "en" | "de" | "es")*/+import { useEffect } from "react";import { create } from "zustand";import enJson from "./locales/en.json";import deJson from "./locales/de.json";@@ -68,6 +69,72 @@ const RESOURCES: Record<UiLanguage, Record<string, unknown>> = {es: esJson as Record<string, unknown>,};+/**+ * Locale chunks that load on demand.+ *+ * The three main locale files ride in the startup bundle, which has a byte+ * budget (scripts/ci/check_frontend_bundle_budget.py). A section nobody opens+ * on start — the marketplace's publish studio, say — keeps its strings in+ * `locales/<chunk>/<lang>.json` and asks for them with `useLocaleChunk` when+ * it mounts. Until the chunk has arrived, `t()` returns the key, so a view+ * that cares waits for `ready` before it paints.+ */+export type LocaleChunk = "marketplace";++const CHUNK_LOADERS: Record<LocaleChunk, Record<UiLanguage, () => Promise<unknown>>> = {+ marketplace: {+ en: () => import("./locales/marketplace/en.json"),+ de: () => import("./locales/marketplace/de.json"),+ es: () => import("./locales/marketplace/es.json"),+ },+};++const EXTRA: Record<UiLanguage, Record<string, unknown>[]> = { en: [], de: [], es: [] };+const CHUNK_PROMISES: Partial<Record<LocaleChunk, Promise<void>>> = {};++function unwrapModule(mod: unknown): Record<string, unknown> {+ const m = mod as { default?: Record<string, unknown> };+ return (m.default ?? (mod as Record<string, unknown>)) as Record<string, unknown>;+}++/** Load one chunk for every language; idempotent, shared across callers. */+export function loadLocaleChunk(chunk: LocaleChunk): Promise<void> {+ const pending = CHUNK_PROMISES[chunk];+ if (pending) return pending;+ const loaders = CHUNK_LOADERS[chunk];+ const promise = Promise.all(+ (Object.keys(loaders) as UiLanguage[]).map(async (lang) => {+ EXTRA[lang].push(unwrapModule(await loaders[lang]()));+ }),+ ).then(() => {+ LOADED_CHUNKS.add(chunk);+ // Bump the revision so every `useT` consumer re-renders with the strings.+ useI18nStore.setState((state) => ({ chunkRevision: state.chunkRevision + 1 }));+ });+ CHUNK_PROMISES[chunk] = promise;+ return promise;+}++/** True once `chunk` is resident — for tests and imperative callers. */+export function isLocaleChunkLoaded(chunk: LocaleChunk): boolean {+ return LOADED_CHUNKS.has(chunk);+}+const LOADED_CHUNKS = new Set<LocaleChunk>();++/**+ * Mount-time loader for a view that needs a chunk. Returns `true` once the+ * strings are resident; the view decides whether to wait on it.+ */+export function useLocaleChunk(chunk: LocaleChunk): boolean {+ const revision = useI18nStore((s) => s.chunkRevision);+ useEffect(() => {+ void loadLocaleChunk(chunk);+ }, [chunk]);+ // `revision` is read so the hook re-evaluates when any chunk lands.+ void revision;+ return LOADED_CHUNKS.has(chunk);+}+const UI_KEY = "jarvis.ui.language";const REPLY_KEY = "jarvis.reply.language";const STT_KEY = "jarvis.stt.language";@@ -229,6 +296,8 @@ interface I18nState {stt: SttLanguage;/** Languages the recogniser accepts, as reported by the backend. */sttOptions: readonly string[];+ /** Bumped each time a lazy locale chunk lands, so `useT` consumers re-render. */+ chunkRevision: number;setUi: (lang: UiLanguage, opts?: { push?: boolean }) => void;setReply: (lang: ReplyLanguage, opts?: { push?: boolean }) => void;setStt: (lang: SttLanguage, opts?: { push?: boolean }) => void;@@ -240,6 +309,7 @@ export const useI18nStore = create<I18nState>((set) => ({reply: readReply(),stt: readStt(),sttOptions: STT_FALLBACK_OPTIONS,+ chunkRevision: 0,setSttOptions: (options) => set({ sttOptions: options }),setUi: (lang, opts) => {try {@@ -302,7 +372,20 @@ function resolve(lang: UiLanguage, key: string): string {}return typeof cur === "string" ? cur : null;};- return tryLookup(RESOURCES[lang]) ?? tryLookup(RESOURCES.en) ?? key;+ const tryChunks = (l: UiLanguage): string | null => {+ for (const extra of EXTRA[l]) {+ const hit = tryLookup(extra);+ if (hit !== null) return hit;+ }+ return null;+ };+ return (+ tryLookup(RESOURCES[lang]) ??+ tryChunks(lang) ??+ tryLookup(RESOURCES.en) ??+ tryChunks("en") ??+ key+ );}// The assistant-name token. Any locale value referring to the assistant by name@@ -333,8 +416,25 @@ export function translate(key: string): string {return interpolateName(resolve(lang, key), name);}+/**+ * Fill `{token}` placeholders in a translated string.+ *+ * The resolver interpolates exactly one token — the assistant's name — and+ * takes no variables, so counts, names and titles are substituted by the view+ * with this helper rather than by widening a resolver three locales and every+ * view depend on. Unknown tokens are left in place, visibly, so a typo in a+ * locale file reads as a bug rather than vanishing.+ */+export function fill(template: string, vars: Record<string, string | number>): string {+ return template.replace(/\{(\w+)\}/g, (match, key: string) =>+ key in vars ? String(vars[key]) : match,+ );+}+export function useT(): (key: string) => string {const lang = useI18nStore((s) => s.ui);+ // Re-render when a lazy locale chunk lands, so keys turn into strings.+ useI18nStore((s) => s.chunkRevision);// Reactive: every t() consumer re-renders when the assistant name changes,// so a Settings rename live-updates the whole UI. Selector-scoped, so other// store mutations (voiceState, transcript, …) do NOT trigger a re-render.diff --git a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/de.json b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/de.jsonnew file mode 100644index 0000000000..03f57196c1--- /dev/null+++ b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/de.json@@ -0,0 +1,156 @@+{+ "marketplace": {+ "filter_mine": "Meine",+ "empty_mine": "Unter deinem Namen ist noch nichts veröffentlicht. Dein erstes Paket oder Wallpaper ist einen Klick entfernt.",+ "hero_eyebrow": "Community-Marketplace",+ "hero_title": "Gebaut von Leuten, die diese App benutzen",+ "hero_body": "Plugins, Skills und Wallpaper — von der Community veröffentlicht, mit einem Klick installiert. Jeder kann veröffentlichen: mit GitHub anmelden, und alles, was die automatischen Prüfungen besteht, geht unter deinem Namen live.",+ "hero_publish_signed_in": "Etwas veröffentlichen",+ "publish_on_web": "Auf der Website",+ "identity_label": "Identität",+ "identity_sign_in": "Mit GitHub anmelden",+ "identity_sign_out": "Abmelden",+ "identity_done": "Fertig",+ "identity_cancel": "Abbrechen",+ "identity_signed_in_as": "Angemeldet als @{login}",+ "identity_signed_in_hint": "Alles, was du aus dieser App veröffentlichst, erscheint unter diesem Namen.",+ "identity_publishes_under": "deine Pakete erscheinen unter diesem Namen.",+ "identity_sign_in_blurb": "Melde dich mit GitHub an, um zu veröffentlichen. Die Anmeldung beweist nur, wer du bist — sie erhält keine Rechte an deinem Konto.",+ "identity_unreachable": "GitHub ist gerade nicht erreichbar — dein Anmeldestatus konnte nicht geprüft werden.",+ "identity_dialog_title": "Mit GitHub anmelden",+ "identity_dialog_subtitle": "Ein Code, bei GitHub eingetippt. Kein Passwort erreicht jemals diese App.",+ "identity_code_label": "Dein Einmal-Code",+ "identity_code_hint": "Öffne GitHub, füge den Code ein und bestätige. Diese App holt sich das Ergebnis selbst — hier ist nichts weiter zu tun.",+ "identity_copy_code": "Code kopieren",+ "identity_copied": "Kopiert",+ "identity_open_github": "GitHub öffnen",+ "identity_waiting": "Warte auf deine Bestätigung",+ "identity_requesting": "Anmeldecode wird bei GitHub angefordert …",+ "identity_fact_scope": "Die Anmeldung verlangt keine Rechte an deinem Konto — sie beweist nur, wer du bist.",+ "identity_fact_name": "Alles, was du veröffentlichst, erscheint öffentlich unter deinem GitHub-Namen.",+ "identity_fact_keyring": "Das Token bleibt im Schlüsselbund deines Systems. Abmelden entfernt es.",+ "identity_menu_hint": "Deine Veröffentlichungs-Identität",+ "identity_menu_mine": "Meine Veröffentlichungen",+ "studio_eyebrow": "Publish-Studio",+ "studio_title": "Im Marketplace veröffentlichen",+ "studio_station_who": "Wer du bist",+ "studio_station_what": "Was du veröffentlichst",+ "studio_station_check": "Prüfen & veröffentlichen",+ "studio_station_live": "Live im Store",+ "studio_rail_note_public": "Jeder kann veröffentlichen. Was die automatischen Prüfungen besteht, geht ohne menschliche Durchsicht live — öffentlich unter deinem GitHub-Namen.",+ "studio_rail_note_rules": "Wer installiert, sieht vorher genau, was dein Paket dürfen würde.",+ "studio_back": "Zurück",+ "studio_h_source": "Wo ist dein Paket?",+ "studio_h_github": "Aus GitHub importieren",+ "studio_h_wallpapers": "Ein Wallpaper teilen",+ "studio_h_form": "Prüfen, checken, veröffentlichen",+ "studio_h_done": "Eingereicht",+ "studio_disabled": "Veröffentlichen ist in dieser Installation abgeschaltet — es ist kein Publish-Endpunkt konfiguriert.",+ "studio_source_label": "Wähle eine Tür",+ "studio_source_hint": "was drin ist, entscheidet, ob daraus ein Skill oder eine Plugin-Karte wird",+ "studio_door_folder": "Paketordner ablegen",+ "studio_door_folder_hint": "Zieh den Ordner hierher oder klicke, um ihn zu wählen. plugin.json, mcp.json und gebündelte Skills werden automatisch gelesen — hochgeladen wird erst, wenn du auf Veröffentlichen drückst.",+ "studio_door_github": "Aus GitHub importieren",+ "studio_door_github_hint": "Durchsuche deine öffentlichen Repositories, wähle das Paket, prüfe es zuerst.",+ "studio_door_blank": "Von vorn beginnen",+ "studio_door_blank_hint": "Direkt im Formular schreiben — am besten für einen einzelnen Skill.",+ "studio_door_wallpaper": "Ein Wallpaper teilen",+ "studio_door_wallpaper_hint": "Veröffentliche eines deiner eigenen Bilder aus der Wallpaper-Auswahl — die Community kann es mit einem Klick übernehmen.",+ "studio_origin_folder": "deinem Ordner",+ "studio_err_folder": "Der Ordner konnte nicht gelesen werden.",+ "studio_err_plugin_json": "plugin.json ist kein gültiges JSON",+ "studio_err_mcp_json": "mcp.json ist kein gültiges JSON",+ "studio_how_title": "So funktioniert Veröffentlichen",+ "studio_how_step_1": "Mit GitHub anmelden — das beweist nur, wer du bist.",+ "studio_how_step_2": "Paket hinzufügen: Ordner ablegen, aus GitHub importieren oder hier schreiben.",+ "studio_how_step_3": "Prüfen — genau die Regeln des Stores laufen, bevor du einreichst.",+ "studio_how_step_4": "Veröffentlichen. Die Prüfungen laufen erneut, bei Grün wird gemergt, und nach wenigen Minuten ist es im Store.",+ "studio_how_show_layout": "Wie sieht ein Paketordner aus?",+ "studio_how_hide_layout": "Ordnerstruktur ausblenden",+ "studio_how_layout_note": "Namen bestehen aus Kleinbuchstaben a-z 0-9 - . — wer zuerst veröffentlicht, besitzt den Namen. Keine Zugangsdaten in Dateien — Tokens sind Platzhalter wie $plugin_…, die beim Verbinden auf dem Rechner des Nutzers gefüllt werden.",+ "studio_github_note": "Nur öffentliche Repositories — du prüfst alles, bevor es veröffentlicht wird. Hier wird kein Token benutzt; es werden nur öffentliche Dateien gelesen.",+ "studio_github_account": "GitHub-Konto",+ "studio_github_list": "Repositories auflisten",+ "studio_github_one_repo": "… oder ein bestimmtes Repository",+ "studio_github_scan": "Scannen",+ "studio_github_no_repos": "Dieses Konto hat keine öffentlichen Repositories.",+ "studio_github_all_repos": "alle Repositories",+ "studio_github_truncated": "GitHub hat die Liste gekürzt — dieses Repository ist so groß, dass der Scan ein Paket außerhalb des Gezeigten übersehen haben kann.",+ "studio_github_files": "{count} Datei(en)",+ "studio_github_review": "Prüfen & vorausfüllen",+ "studio_err_repos": "Repositories konnten nicht geladen werden.",+ "studio_err_scan": "Das Repository konnte nicht gescannt werden.",+ "studio_err_scan_truncated": "Dieses Repository ist zu groß für einen vollständigen Scan, und in dem, was GitHub geliefert hat, war keine plugin.json und keine SKILL.md — versuche einen bestimmten Unterordner.",+ "studio_err_scan_empty": "Keine plugin.json und keine SKILL.md in diesem Repository — hier ist nichts, das sich veröffentlichen ließe.",+ "studio_err_import": "Import fehlgeschlagen.",+ "studio_err_ref": "Gib ein Repository als „owner/name“ an oder füge seine GitHub-URL ein.",+ "studio_err_resolve": "Das Repository konnte nicht aufgelöst werden.",+ "studio_wallpapers_label": "Deine Bilder",+ "studio_wallpapers_hint": "nur Bilder, die du selbst mitgebracht hast — ein installiertes Community-Wallpaper ist die Arbeit von jemand anderem",+ "studio_wallpapers_empty": "Du hast noch kein eigenes Wallpaper hinzugefügt. Füge eines in der Wallpaper-Sektion hinzu und teile es dann von hier aus.",+ "studio_form_label": "Was du veröffentlichst",+ "studio_prefilled_from": "Geladen aus {origin} — prüfe die Felder, dann checken und veröffentlichen.",+ "studio_f_name": "Paketname",+ "studio_f_name_hint": "a-z 0-9 - . — wer zuerst veröffentlicht, besitzt den Namen",+ "studio_f_version": "Version",+ "studio_f_version_hint": "SemVer, z. B. 1.0.0",+ "studio_f_title": "Titel",+ "studio_f_description": "Beschreibung",+ "studio_f_description_hint": "{count}/500 — was der Skill tut, ein oder zwei Sätze",+ "studio_f_categories": "Kategorien",+ "studio_f_categories_hint": "kommagetrennt, optional",+ "studio_f_skill_md_hint": "{kb} KB / {max} KB — die Anweisungen, denen der Assistent folgt; beginnt mit YAML-Frontmatter",+ "studio_f_plugin_json_hint": "das Agent-Plugins-Manifest (name, description, version, extensions)",+ "studio_f_mcp_json_hint": "optional — genau ein Server mit seinem „type“ („streamable-http“ oder „stdio“): eine https-URL oder ein festgepinnter npx/uvx/docker-Befehl",+ "studio_f_skills": "Gebündelte Skills",+ "studio_f_skills_hint": "Anweisungen, die zusammen mit dem Plugin installiert werden — bis zu 10",+ "studio_f_skills_none": "Keine. Skills reisen im Paketordner als skills/<name>/SKILL.md — lege einen Ordner ab oder importiere aus GitHub, um sie zu bündeln.",+ "studio_f_usage_card": "Usage Card",+ "studio_f_usage_card_hint": "optional — Stichwörter, die dem Assistenten sagen, wann das Plugin relevant ist",+ "studio_insert_template": "Vorlage einfügen",+ "studio_check": "Prüfen",+ "studio_check_ok": "Besteht jede Regel, die der Store prüft — bereit zum Veröffentlichen.",+ "studio_publish": "Veröffentlichen",+ "studio_start_over": "Von vorn",+ "studio_sign_in_first": "Zuerst mit GitHub anmelden",+ "studio_preview_label": "Vorschau der Store-Karte",+ "studio_preview_untitled": "Ohne Titel",+ "studio_preview_no_description": "Noch keine Beschreibung.",+ "studio_preview_bundled": "{count} gebündelte(r) Skill(s)",+ "studio_preview_note": "So ungefähr wird dein Eintrag im Store aussehen — für alle, sobald die Prüfungen bestanden sind.",+ "studio_done_eyebrow": "An die Registry übermittelt",+ "studio_done_body": "Die Registry hat dein Paket erhalten und den Pull Request eröffnet. Jetzt laufen die automatischen Prüfungen; wenn sie bestehen, wird gemergt und der Eintrag erscheint von selbst im Store.",+ "studio_done_view_pr": "Pull Request ansehen",+ "studio_done_another": "Noch eins veröffentlichen",+ "studio_done_live": "Live — {name} v{version} ist jetzt im Marketplace.",+ "studio_done_waited_out": "Nach mehreren Minuten noch nicht im Feed — öffne den Pull Request oben und sieh nach, was die Prüfungen sagen.",+ "studio_done_watching": "Beobachte den Live-Feed, bis dein Paket erscheint — meist ein paar Minuten.",+ "studio_done_share_heading": "Weitergeben",+ "studio_done_share_note": "Das kann jetzt jeder ausführen — es löst deinen Eintrag aus der öffentlichen Registry auf.",+ "share_cta": "Teilen",+ "share_title": "Mit der Community teilen",+ "share_subtitle": "Jeder, der Personal Jarvis nutzt, kann dieses Wallpaper übernehmen.",+ "share_subtitle_done": "Veröffentlicht — es erscheint im Store, sobald der Feed neu gebaut ist.",+ "share_dialog_aria": "{title} mit der Community teilen",+ "share_consequences": "Das veröffentlicht das Bild öffentlich unter deinem GitHub-Namen, ohne Durchsicht vorab. Lade nur hoch, was du selbst gemacht hast oder woran du die Rechte hältst. Nimmst du es später zurück, verschwindet es aus dem Store — nicht von Rechnern, die es schon übernommen haben.",+ "share_identity_blurb": "dieses Wallpaper erscheint unter diesem Namen.",+ "share_f_title": "Titel",+ "share_f_title_hint": "Der Store macht daraus die Adresse des Wallpapers — wähle ihn unverwechselbar.",+ "share_f_title_too_long": "{count}/{max} — zu lang.",+ "share_f_description": "Beschreibung (optional)",+ "share_f_description_placeholder": "Neon-Dächer und Antennenwälder im Regen.",+ "share_f_license": "Lizenz",+ "share_f_license_note": "Nur Lizenzen, die Weitergabe erlauben — das Bild wird auf die Rechner anderer Leute kopiert.",+ "share_license_cc0": "CC0 — gemeinfrei",+ "share_license_cc0_hint": "Jeder darf es für alles nutzen, ohne Namensnennung.",+ "share_license_ccby": "CC BY — Namensnennung",+ "share_license_ccby_hint": "Jeder darf es nutzen, solange dein Name genannt wird.",+ "share_license_ccbysa": "CC BY-SA — Namensnennung, gleiche Bedingungen",+ "share_license_ccbysa_hint": "Wie CC BY, und alles, was darauf aufbaut, trägt dieselbe Lizenz.",+ "share_rights": "Ich habe dieses Bild gemacht oder halte die Rechte, es zu veröffentlichen, und es darf geteilt werden — kein geschütztes Werk eines anderen, nichts Hasserfülltes und keine echte Person ohne ihre Zustimmung.",+ "share_footer_done": "Du kannst das hier schließen — mehr ist nicht nötig.",+ "share_footer_ready": "Hochgeladen wird erst, wenn du auf Veröffentlichen klickst.",+ "share_footer_sign_in": "Melde dich oben mit GitHub an, um zu veröffentlichen.",+ "share_published_as": "Veröffentlicht als {name}. Der Store baut seine Liste alle paar Minuten neu — dort und im Marketplace dieser App erscheint es in Kürze."+ }+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/en.json b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/en.jsonnew file mode 100644index 0000000000..67eb284ea8--- /dev/null+++ b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/en.json@@ -0,0 +1,156 @@+{+ "marketplace": {+ "filter_mine": "Mine",+ "empty_mine": "Nothing published under your name yet. Your first package or wallpaper is one click away.",+ "hero_eyebrow": "Community marketplace",+ "hero_title": "Built by people who use this app",+ "hero_body": "Plugins, skills and wallpapers, published by the community and installed in one click. Anyone can publish — sign in with GitHub, and whatever passes the automated checks goes live under your name.",+ "hero_publish_signed_in": "Publish something",+ "publish_on_web": "On the website",+ "identity_label": "Identity",+ "identity_sign_in": "Sign in with GitHub",+ "identity_sign_out": "Sign out",+ "identity_done": "Done",+ "identity_cancel": "Cancel",+ "identity_signed_in_as": "Signed in as @{login}",+ "identity_signed_in_hint": "Everything you publish from this app appears under this name.",+ "identity_publishes_under": "your packages publish under this name.",+ "identity_sign_in_blurb": "Sign in with GitHub to publish. The sign-in only proves who you are — it grants nothing on your account.",+ "identity_unreachable": "GitHub is unreachable right now — your sign-in state could not be checked.",+ "identity_dialog_title": "Sign in with GitHub",+ "identity_dialog_subtitle": "One code, typed at GitHub. No password ever reaches this app.",+ "identity_code_label": "Your one-time code",+ "identity_code_hint": "Open GitHub, paste the code, and approve. This app picks up the result on its own — nothing else to do here.",+ "identity_copy_code": "Copy the code",+ "identity_copied": "Copied",+ "identity_open_github": "Open GitHub",+ "identity_waiting": "Waiting for your approval",+ "identity_requesting": "Requesting a sign-in code from GitHub…",+ "identity_fact_scope": "The sign-in asks for no permissions on your account — it only proves who you are.",+ "identity_fact_name": "Everything you publish appears publicly under your GitHub name.",+ "identity_fact_keyring": "The token stays in your system keyring. Sign out removes it.",+ "identity_menu_hint": "Your publishing identity",+ "identity_menu_mine": "My publications",+ "studio_eyebrow": "Publish Studio",+ "studio_title": "Publish to the marketplace",+ "studio_station_who": "Who you are",+ "studio_station_what": "What you publish",+ "studio_station_check": "Check & publish",+ "studio_station_live": "Live in the store",+ "studio_rail_note_public": "Anyone can publish. Whatever passes the automated checks goes live without human review, publicly under your GitHub name.",+ "studio_rail_note_rules": "Installing users see exactly what your package would be allowed to do before they accept it.",+ "studio_back": "Back",+ "studio_h_source": "Where is your package?",+ "studio_h_github": "Import from GitHub",+ "studio_h_wallpapers": "Share a wallpaper",+ "studio_h_form": "Review, check, publish",+ "studio_h_done": "Submitted",+ "studio_disabled": "Publishing is disabled in this deployment — no publish endpoint is configured.",+ "studio_source_label": "Pick a door",+ "studio_source_hint": "what is inside decides whether it becomes a skill or a plugin card",+ "studio_door_folder": "Drop a package folder",+ "studio_door_folder_hint": "Drag the folder here or click to choose it. plugin.json, mcp.json and bundled skills are read automatically — nothing is uploaded until you press Publish.",+ "studio_door_github": "Import from GitHub",+ "studio_door_github_hint": "Browse your public repositories, pick the package, review it first.",+ "studio_door_blank": "Start from scratch",+ "studio_door_blank_hint": "Write it in the form — best for a single skill.",+ "studio_door_wallpaper": "Share a wallpaper",+ "studio_door_wallpaper_hint": "Publish one of your own pictures from the wallpaper picker — the community can add it in one click.",+ "studio_origin_folder": "your folder",+ "studio_err_folder": "Could not read the folder.",+ "studio_err_plugin_json": "plugin.json is not valid JSON",+ "studio_err_mcp_json": "mcp.json is not valid JSON",+ "studio_how_title": "How publishing works",+ "studio_how_step_1": "Sign in with GitHub — it only proves who you are.",+ "studio_how_step_2": "Add your package: drop the folder, import it from GitHub, or write it here.",+ "studio_how_step_3": "Check it — the exact rules the store enforces run before you submit.",+ "studio_how_step_4": "Publish. The checks re-run, it merges on green, and appears in the store within minutes.",+ "studio_how_show_layout": "What does a package folder look like?",+ "studio_how_hide_layout": "Hide the folder layout",+ "studio_how_layout_note": "Names are lowercase a-z 0-9 - . and the first published claim owns the name. No credentials in any file — tokens are placeholders like $plugin_…, filled in on the user's machine at connect time.",+ "studio_github_note": "Public repositories only — you review everything before publishing. No token is used here; this only reads public files.",+ "studio_github_account": "GitHub account",+ "studio_github_list": "List repositories",+ "studio_github_one_repo": "…or one specific repository",+ "studio_github_scan": "Scan",+ "studio_github_no_repos": "This account has no public repositories.",+ "studio_github_all_repos": "all repositories",+ "studio_github_truncated": "GitHub cut this listing short — this repository is large enough that the scan may have missed a package outside what is shown here.",+ "studio_github_files": "{count} file(s)",+ "studio_github_review": "Review & prefill",+ "studio_err_repos": "Could not list repositories.",+ "studio_err_scan": "Could not scan the repository.",+ "studio_err_scan_truncated": "This repository is too large to scan fully, and no plugin.json or SKILL.md turned up in what GitHub returned — try a specific subfolder instead.",+ "studio_err_scan_empty": "No plugin.json and no SKILL.md in this repository — nothing here is a publishable package.",+ "studio_err_import": "Import failed.",+ "studio_err_ref": "Enter a repository as \"owner/name\" or paste its GitHub URL.",+ "studio_err_resolve": "Could not resolve the repository.",+ "studio_wallpapers_label": "Your pictures",+ "studio_wallpapers_hint": "only pictures you brought yourself — an installed community wallpaper is somebody else's work",+ "studio_wallpapers_empty": "You have not added a wallpaper of your own yet. Add one in the Wallpaper section, then share it from here.",+ "studio_form_label": "What you are publishing",+ "studio_prefilled_from": "Loaded from {origin} — review the fields, then check and publish.",+ "studio_f_name": "Package name",+ "studio_f_name_hint": "a-z 0-9 - . — the first published claim owns the name",+ "studio_f_version": "Version",+ "studio_f_version_hint": "SemVer, e.g. 1.0.0",+ "studio_f_title": "Title",+ "studio_f_description": "Description",+ "studio_f_description_hint": "{count}/500 — what the skill does, one or two sentences",+ "studio_f_categories": "Categories",+ "studio_f_categories_hint": "comma-separated, optional",+ "studio_f_skill_md_hint": "{kb} KB / {max} KB — the instructions the assistant follows, starting with YAML frontmatter",+ "studio_f_plugin_json_hint": "the Agent Plugins manifest (name, description, version, extensions)",+ "studio_f_mcp_json_hint": "optional — exactly one server with its \"type\" (\"streamable-http\" or \"stdio\"): an https URL, or a pinned npx/uvx/docker command",+ "studio_f_skills": "Bundled skills",+ "studio_f_skills_hint": "instructions that install together with the plugin — up to 10",+ "studio_f_skills_none": "None. Skills travel in the package folder as skills/<name>/SKILL.md — drop a folder or import from GitHub to bundle them.",+ "studio_f_usage_card": "Usage card",+ "studio_f_usage_card_hint": "optional — keywords that tell the assistant when the plugin is relevant",+ "studio_insert_template": "Insert template",+ "studio_check": "Check",+ "studio_check_ok": "Passes every rule the store checks — ready to publish.",+ "studio_publish": "Publish",+ "studio_start_over": "Start over",+ "studio_sign_in_first": "Sign in with GitHub first",+ "studio_preview_label": "Store card preview",+ "studio_preview_untitled": "Untitled",+ "studio_preview_no_description": "No description yet.",+ "studio_preview_bundled": "{count} bundled skill(s)",+ "studio_preview_note": "This is roughly how your entry will look in the store — for everyone, as soon as the checks pass.",+ "studio_done_eyebrow": "Submitted to the registry",+ "studio_done_body": "The registry received your package and opened its pull request. The automated checks now run; when they pass, it merges and appears in the store on its own.",+ "studio_done_view_pr": "View the pull request",+ "studio_done_another": "Publish another",+ "studio_done_live": "Live — {name} v{version} is in the marketplace now.",+ "studio_done_waited_out": "Still not in the feed after several minutes — open the pull request above to see what its checks say.",+ "studio_done_watching": "Watching the live feed until your package appears — usually a few minutes.",+ "studio_done_share_heading": "Share it",+ "studio_done_share_note": "Anyone can run this now — it resolves your listing from the public registry.",+ "share_cta": "Share",+ "share_title": "Share with the community",+ "share_subtitle": "Anyone using Personal Jarvis will be able to add this wallpaper.",+ "share_subtitle_done": "Published — it appears in the store once the feed rebuilds.",+ "share_dialog_aria": "Share {title} with the community",+ "share_consequences": "This publishes the picture publicly, under your GitHub name, with no review before it goes live. Only upload something you made or hold the rights to. If you take it down later it disappears from the store — not from machines that already added it.",+ "share_identity_blurb": "this wallpaper publishes under this name.",+ "share_f_title": "Title",+ "share_f_title_hint": "The store turns this into the wallpaper's address, so make it distinctive.",+ "share_f_title_too_long": "{count}/{max} — too long.",+ "share_f_description": "Description (optional)",+ "share_f_description_placeholder": "Neon rooftops and antenna forests in the rain.",+ "share_f_license": "License",+ "share_f_license_note": "Only licenses that allow redistribution — the picture is copied onto other people's machines.",+ "share_license_cc0": "CC0 — public domain",+ "share_license_cc0_hint": "Anyone may use it for anything, no credit required.",+ "share_license_ccby": "CC BY — credit required",+ "share_license_ccby_hint": "Anyone may use it, as long as they credit you.",+ "share_license_ccbysa": "CC BY-SA — credit, share alike",+ "share_license_ccbysa_hint": "As CC BY, and anything built on it carries the same license.",+ "share_rights": "I made this picture or hold the rights to publish it, and it is legal to share — no copyrighted work of someone else, nothing hateful, and nothing that depicts a real person without their consent.",+ "share_footer_done": "You can close this — nothing else is needed.",+ "share_footer_ready": "Nothing is uploaded until you click Publish.",+ "share_footer_sign_in": "Sign in with GitHub above to publish.",+ "share_published_as": "Published as {name}. The store rebuilds its list every few minutes — it appears there, and in this app's Marketplace, shortly."+ }+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/es.json b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/es.jsonnew file mode 100644index 0000000000..ceb3633a5e--- /dev/null+++ b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/es.json@@ -0,0 +1,156 @@+{+ "marketplace": {+ "filter_mine": "Míos",+ "empty_mine": "Todavía no hay nada publicado con tu nombre. Tu primer paquete o fondo de pantalla está a un clic.",+ "hero_eyebrow": "Marketplace de la comunidad",+ "hero_title": "Creado por gente que usa esta app",+ "hero_body": "Plugins, skills y fondos de pantalla, publicados por la comunidad e instalados con un clic. Cualquiera puede publicar: inicia sesión con GitHub y todo lo que supere las comprobaciones automáticas sale en vivo con tu nombre.",+ "hero_publish_signed_in": "Publicar algo",+ "publish_on_web": "En la web",+ "identity_label": "Identidad",+ "identity_sign_in": "Iniciar sesión con GitHub",+ "identity_sign_out": "Cerrar sesión",+ "identity_done": "Listo",+ "identity_cancel": "Cancelar",+ "identity_signed_in_as": "Sesión iniciada como @{login}",+ "identity_signed_in_hint": "Todo lo que publiques desde esta app aparece con este nombre.",+ "identity_publishes_under": "tus paquetes se publican con este nombre.",+ "identity_sign_in_blurb": "Inicia sesión con GitHub para publicar. El inicio de sesión solo demuestra quién eres: no concede nada sobre tu cuenta.",+ "identity_unreachable": "GitHub no está disponible ahora mismo: no se pudo comprobar tu estado de sesión.",+ "identity_dialog_title": "Iniciar sesión con GitHub",+ "identity_dialog_subtitle": "Un código, escrito en GitHub. Ninguna contraseña llega jamás a esta app.",+ "identity_code_label": "Tu código de un solo uso",+ "identity_code_hint": "Abre GitHub, pega el código y aprueba. Esta app recoge el resultado por sí sola: aquí no hay nada más que hacer.",+ "identity_copy_code": "Copiar el código",+ "identity_copied": "Copiado",+ "identity_open_github": "Abrir GitHub",+ "identity_waiting": "Esperando tu aprobación",+ "identity_requesting": "Solicitando un código de inicio de sesión a GitHub…",+ "identity_fact_scope": "El inicio de sesión no pide permisos sobre tu cuenta: solo demuestra quién eres.",+ "identity_fact_name": "Todo lo que publiques aparece públicamente con tu nombre de GitHub.",+ "identity_fact_keyring": "El token se queda en el llavero de tu sistema. Cerrar sesión lo elimina.",+ "identity_menu_hint": "Tu identidad para publicar",+ "identity_menu_mine": "Mis publicaciones",+ "studio_eyebrow": "Estudio de publicación",+ "studio_title": "Publicar en el marketplace",+ "studio_station_who": "Quién eres",+ "studio_station_what": "Qué publicas",+ "studio_station_check": "Comprobar y publicar",+ "studio_station_live": "En vivo en la tienda",+ "studio_rail_note_public": "Cualquiera puede publicar. Lo que supere las comprobaciones automáticas sale en vivo sin revisión humana, públicamente con tu nombre de GitHub.",+ "studio_rail_note_rules": "Quien instala ve exactamente lo que tu paquete podría hacer antes de aceptarlo.",+ "studio_back": "Atrás",+ "studio_h_source": "¿Dónde está tu paquete?",+ "studio_h_github": "Importar desde GitHub",+ "studio_h_wallpapers": "Compartir un fondo de pantalla",+ "studio_h_form": "Revisar, comprobar, publicar",+ "studio_h_done": "Enviado",+ "studio_disabled": "La publicación está desactivada en esta instalación: no hay ningún endpoint de publicación configurado.",+ "studio_source_label": "Elige una puerta",+ "studio_source_hint": "lo que hay dentro decide si se convierte en skill o en tarjeta de plugin",+ "studio_door_folder": "Suelta la carpeta del paquete",+ "studio_door_folder_hint": "Arrastra la carpeta aquí o haz clic para elegirla. plugin.json, mcp.json y las skills incluidas se leen automáticamente; no se sube nada hasta que pulses Publicar.",+ "studio_door_github": "Importar desde GitHub",+ "studio_door_github_hint": "Explora tus repositorios públicos, elige el paquete y revísalo primero.",+ "studio_door_blank": "Empezar desde cero",+ "studio_door_blank_hint": "Escríbelo en el formulario: ideal para una sola skill.",+ "studio_door_wallpaper": "Compartir un fondo de pantalla",+ "studio_door_wallpaper_hint": "Publica una de tus propias imágenes desde el selector de fondos; la comunidad puede añadirla con un clic.",+ "studio_origin_folder": "tu carpeta",+ "studio_err_folder": "No se pudo leer la carpeta.",+ "studio_err_plugin_json": "plugin.json no es JSON válido",+ "studio_err_mcp_json": "mcp.json no es JSON válido",+ "studio_how_title": "Cómo funciona publicar",+ "studio_how_step_1": "Inicia sesión con GitHub: solo demuestra quién eres.",+ "studio_how_step_2": "Añade tu paquete: suelta la carpeta, impórtala desde GitHub o escríbelo aquí.",+ "studio_how_step_3": "Compruébalo: las mismas reglas que aplica la tienda se ejecutan antes de enviar.",+ "studio_how_step_4": "Publica. Las comprobaciones se repiten, se fusiona en verde y aparece en la tienda en minutos.",+ "studio_how_show_layout": "¿Cómo es una carpeta de paquete?",+ "studio_how_hide_layout": "Ocultar la estructura de carpetas",+ "studio_how_layout_note": "Los nombres son minúsculas a-z 0-9 - . y la primera publicación se queda con el nombre. Sin credenciales en ningún archivo: los tokens son marcadores como $plugin_…, rellenados en la máquina del usuario al conectar.",+ "studio_github_note": "Solo repositorios públicos: revisas todo antes de publicar. Aquí no se usa ningún token; solo se leen archivos públicos.",+ "studio_github_account": "Cuenta de GitHub",+ "studio_github_list": "Listar repositorios",+ "studio_github_one_repo": "…o un repositorio concreto",+ "studio_github_scan": "Escanear",+ "studio_github_no_repos": "Esta cuenta no tiene repositorios públicos.",+ "studio_github_all_repos": "todos los repositorios",+ "studio_github_truncated": "GitHub recortó este listado: el repositorio es tan grande que el escaneo puede haber pasado por alto un paquete fuera de lo que se muestra.",+ "studio_github_files": "{count} archivo(s)",+ "studio_github_review": "Revisar y rellenar",+ "studio_err_repos": "No se pudieron listar los repositorios.",+ "studio_err_scan": "No se pudo escanear el repositorio.",+ "studio_err_scan_truncated": "Este repositorio es demasiado grande para escanearlo por completo y no apareció ningún plugin.json ni SKILL.md en lo que devolvió GitHub; prueba con una subcarpeta concreta.",+ "studio_err_scan_empty": "No hay plugin.json ni SKILL.md en este repositorio: nada aquí es un paquete publicable.",+ "studio_err_import": "La importación falló.",+ "studio_err_ref": "Indica un repositorio como \"owner/name\" o pega su URL de GitHub.",+ "studio_err_resolve": "No se pudo resolver el repositorio.",+ "studio_wallpapers_label": "Tus imágenes",+ "studio_wallpapers_hint": "solo imágenes que trajiste tú; un fondo instalado desde la comunidad es obra de otra persona",+ "studio_wallpapers_empty": "Todavía no has añadido ningún fondo propio. Añade uno en la sección Fondo de pantalla y compártelo desde aquí.",+ "studio_form_label": "Lo que estás publicando",+ "studio_prefilled_from": "Cargado desde {origin}: revisa los campos, luego comprueba y publica.",+ "studio_f_name": "Nombre del paquete",+ "studio_f_name_hint": "a-z 0-9 - . — la primera publicación se queda con el nombre",+ "studio_f_version": "Versión",+ "studio_f_version_hint": "SemVer, p. ej. 1.0.0",+ "studio_f_title": "Título",+ "studio_f_description": "Descripción",+ "studio_f_description_hint": "{count}/500 — qué hace la skill, una o dos frases",+ "studio_f_categories": "Categorías",+ "studio_f_categories_hint": "separadas por comas, opcional",+ "studio_f_skill_md_hint": "{kb} KB / {max} KB — las instrucciones que sigue el asistente; empieza con frontmatter YAML",+ "studio_f_plugin_json_hint": "el manifiesto de Agent Plugins (name, description, version, extensions)",+ "studio_f_mcp_json_hint": "opcional — exactamente un servidor con su \"type\" (\"streamable-http\" o \"stdio\"): una URL https o un comando npx/uvx/docker con versión fijada",+ "studio_f_skills": "Skills incluidas",+ "studio_f_skills_hint": "instrucciones que se instalan junto con el plugin — hasta 10",+ "studio_f_skills_none": "Ninguna. Las skills viajan en la carpeta del paquete como skills/<name>/SKILL.md: suelta una carpeta o importa desde GitHub para incluirlas.",+ "studio_f_usage_card": "Tarjeta de uso",+ "studio_f_usage_card_hint": "opcional — palabras clave que indican al asistente cuándo es relevante el plugin",+ "studio_insert_template": "Insertar plantilla",+ "studio_check": "Comprobar",+ "studio_check_ok": "Supera todas las reglas que comprueba la tienda: listo para publicar.",+ "studio_publish": "Publicar",+ "studio_start_over": "Empezar de nuevo",+ "studio_sign_in_first": "Inicia sesión con GitHub primero",+ "studio_preview_label": "Vista previa de la tarjeta",+ "studio_preview_untitled": "Sin título",+ "studio_preview_no_description": "Aún sin descripción.",+ "studio_preview_bundled": "{count} skill(s) incluida(s)",+ "studio_preview_note": "Así se verá más o menos tu entrada en la tienda, para todos, en cuanto pasen las comprobaciones.",+ "studio_done_eyebrow": "Enviado al registro",+ "studio_done_body": "El registro recibió tu paquete y abrió su pull request. Ahora se ejecutan las comprobaciones automáticas; cuando pasen, se fusiona y aparece en la tienda por sí solo.",+ "studio_done_view_pr": "Ver el pull request",+ "studio_done_another": "Publicar otro",+ "studio_done_live": "En vivo — {name} v{version} ya está en el marketplace.",+ "studio_done_waited_out": "Tras varios minutos sigue sin aparecer en el feed: abre el pull request de arriba para ver qué dicen sus comprobaciones.",+ "studio_done_watching": "Vigilando el feed en vivo hasta que aparezca tu paquete; suelen ser unos minutos.",+ "studio_done_share_heading": "Compártelo",+ "studio_done_share_note": "Cualquiera puede ejecutar esto ahora: resuelve tu entrada desde el registro público.",+ "share_cta": "Compartir",+ "share_title": "Compartir con la comunidad",+ "share_subtitle": "Cualquiera que use Personal Jarvis podrá añadir este fondo de pantalla.",+ "share_subtitle_done": "Publicado: aparecerá en la tienda cuando se reconstruya el feed.",+ "share_dialog_aria": "Compartir {title} con la comunidad",+ "share_consequences": "Esto publica la imagen públicamente, con tu nombre de GitHub, sin revisión previa. Sube solo algo que hayas hecho tú o cuyos derechos tengas. Si la retiras más tarde desaparece de la tienda, no de las máquinas que ya la añadieron.",+ "share_identity_blurb": "este fondo se publica con este nombre.",+ "share_f_title": "Título",+ "share_f_title_hint": "La tienda lo convierte en la dirección del fondo, así que hazlo distintivo.",+ "share_f_title_too_long": "{count}/{max} — demasiado largo.",+ "share_f_description": "Descripción (opcional)",+ "share_f_description_placeholder": "Azoteas de neón y bosques de antenas bajo la lluvia.",+ "share_f_license": "Licencia",+ "share_f_license_note": "Solo licencias que permiten la redistribución: la imagen se copia en las máquinas de otras personas.",+ "share_license_cc0": "CC0 — dominio público",+ "share_license_cc0_hint": "Cualquiera puede usarla para lo que sea, sin atribución.",+ "share_license_ccby": "CC BY — con atribución",+ "share_license_ccby_hint": "Cualquiera puede usarla, siempre que te dé crédito.",+ "share_license_ccbysa": "CC BY-SA — atribución, compartir igual",+ "share_license_ccbysa_hint": "Como CC BY, y todo lo que se construya sobre ella lleva la misma licencia.",+ "share_rights": "Hice esta imagen o tengo los derechos para publicarla, y es legal compartirla: ninguna obra protegida de otra persona, nada de odio y ninguna persona real sin su consentimiento.",+ "share_footer_done": "Puedes cerrar esto: no hace falta nada más.",+ "share_footer_ready": "No se sube nada hasta que hagas clic en Publicar.",+ "share_footer_sign_in": "Inicia sesión con GitHub arriba para publicar.",+ "share_published_as": "Publicado como {name}. La tienda reconstruye su lista cada pocos minutos: aparecerá allí y en el Marketplace de esta app en breve."+ }+}diff --git a/jarvis/ui/web/frontend/src/lib/githubImport.test.ts b/jarvis/ui/web/frontend/src/lib/githubImport.test.tsnew file mode 100644index 0000000000..94bc2db96f--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/githubImport.test.ts@@ -0,0 +1,108 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { getRepo, parseRepoRef, scanRepo } from "./githubImport";++function jsonResponse(body: unknown, status = 200) {+ return {+ status,+ ok: status >= 200 && status < 300,+ json: vi.fn().mockResolvedValue(body),+ };+}++describe("parseRepoRef", () => {+ it("accepts owner/repo", () => {+ expect(parseRepoRef("todofox/todo-fox")).toEqual({ owner: "todofox", repo: "todo-fox" });+ });++ it("accepts a full GitHub URL, stripping a trailing .git", () => {+ expect(parseRepoRef("https://github.com/todofox/todo-fox.git")).toEqual({+ owner: "todofox",+ repo: "todo-fox",+ });+ });++ it("rejects text that is neither", () => {+ expect(parseRepoRef("not a repo ref")).toBeNull();+ });+});++describe("getRepo", () => {+ afterEach(() => vi.unstubAllGlobals());++ it("resolves the repo's real default branch, not the literal HEAD", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ jsonResponse({+ full_name: "todofox/todo-fox",+ description: "Tasks and reminders",+ default_branch: "trunk",+ pushed_at: "2026-08-01T00:00:00Z",+ stargazers_count: 3,+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ const repo = await getRepo("todofox", "todo-fox");+ expect(repo.default_branch).toBe("trunk");+ expect(fetchMock).toHaveBeenCalledWith(+ "https://api.github.com/repos/todofox/todo-fox",+ expect.anything(),+ );+ });++ it("reports a readable message on a 404", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse({}, 404)));+ await expect(getRepo("nobody", "nothing")).rejects.toThrow(/not found/i);+ });++ it("reports a readable message on a rate limit", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse({}, 403)));+ await expect(getRepo("someone", "somewhere")).rejects.toThrow(/rate limit/i);+ });+});++describe("scanRepo", () => {+ afterEach(() => vi.unstubAllGlobals());++ it("finds a plugin package with its bundled skills, and a standalone skill outside it", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ jsonResponse({+ truncated: false,+ tree: [+ { path: "plugin.json", type: "blob" },+ { path: "mcp.json", type: "blob" },+ { path: "skills/todo-triage/SKILL.md", type: "blob" },+ { path: "standalone-skill/SKILL.md", type: "blob" },+ { path: "README.md", type: "blob" },+ ],+ }),+ ),+ );++ const { candidates, truncated } = await scanRepo("todofox", "todo-fox", "main");+ expect(truncated).toBe(false);+ const plugin = candidates.find((c) => c.kind === "plugin");+ expect(plugin?.paths).toEqual(+ expect.arrayContaining(["plugin.json", "mcp.json", "skills/todo-triage/SKILL.md"]),+ );+ const skill = candidates.find((c) => c.kind === "skill");+ expect(skill?.dir).toBe("standalone-skill");+ });++ it("surfaces a truncated tree instead of silently under-scanning", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ jsonResponse({+ truncated: true,+ tree: [{ path: "README.md", type: "blob" }],+ }),+ ),+ );++ const { candidates, truncated } = await scanRepo("owner", "huge-repo", "main");+ expect(truncated).toBe(true);+ expect(candidates).toEqual([]);+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/githubImport.ts b/jarvis/ui/web/frontend/src/lib/githubImport.tsnew file mode 100644index 0000000000..3809dae4e8--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/githubImport.ts@@ -0,0 +1,150 @@+/**+ * Browse a GitHub account's public repositories for publishable packages.+ *+ * Everything runs client-side against api.github.com (CORS-enabled,+ * unauthenticated — public data only, ~60 requests/hour per IP, plenty for a+ * hand-driven import). The flow mirrors what the folder drop does, one level+ * earlier: pick a repo, scan its tree for plugin.json / SKILL.md, fetch just+ * those files, and hand back the same shape `folderToDraft` consumes.+ *+ * No token is ever used here: the publisher token in the keyring is identity+ * for the submit endpoint, and this browser is only reading public files.+ */++const API = "https://api.github.com";+const UA_HEADERS = { Accept: "application/vnd.github+json" };++export interface RepoSummary {+ full_name: string;+ description: string | null;+ default_branch: string;+ pushed_at: string | null;+ stargazers_count: number;+}++export interface RepoCandidate {+ /** Directory the package lives in, "" for the repo root. */+ dir: string;+ kind: "plugin" | "skill";+ /** Paths (relative to repo root) that will be fetched on import. */+ paths: string[];+}++export interface RepoScan {+ candidates: RepoCandidate[];+ /** GitHub's tree API stopped before listing every file (huge repo) — the+ * scan may have missed a package that lives deep in the tree. */+ truncated: boolean;+}++async function gh<T>(path: string): Promise<T> {+ const res = await fetch(`${API}${path}`, { headers: UA_HEADERS });+ if (res.status === 403 || res.status === 429) {+ throw new Error("GitHub rate limit reached — wait a few minutes and try again.");+ }+ if (res.status === 404) throw new Error("Not found on GitHub — check the name.");+ if (!res.ok) throw new Error(`GitHub request failed (${res.status})`);+ return (await res.json()) as T;+}++function toRepoSummary(r: Record<string, unknown>): RepoSummary {+ return {+ full_name: String(r.full_name ?? ""),+ description: typeof r.description === "string" ? r.description : null,+ default_branch: String(r.default_branch ?? "main"),+ pushed_at: typeof r.pushed_at === "string" ? r.pushed_at : null,+ stargazers_count: Number(r.stargazers_count ?? 0),+ };+}++/** Public repos of a user, most recently pushed first. */+export async function listRepos(login: string): Promise<RepoSummary[]> {+ const raw = await gh<Array<Record<string, unknown>>>(+ `/users/${encodeURIComponent(login)}/repos?sort=pushed&per_page=50`,+ );+ return raw.map(toRepoSummary);+}++/**+ * One repo's summary — used to resolve the real default branch before+ * scanning. The git trees API takes a branch name or SHA, not the literal+ * string "HEAD", so a "owner/repo" or URL paste must look this up first+ * instead of guessing a branch name.+ */+export async function getRepo(owner: string, repo: string): Promise<RepoSummary> {+ const raw = await gh<Record<string, unknown>>(+ `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`,+ );+ return toRepoSummary(raw);+}++/** Accepts "owner/repo" or a full github.com URL; null when unparseable. */+export function parseRepoRef(text: string): { owner: string; repo: string } | null {+ const trimmed = text.trim().replace(/\.git$/, "");+ const url = /github\.com\/([^/\s]+)\/([^/\s#?]+)/.exec(trimmed);+ if (url) return { owner: url[1], repo: url[2] };+ const plain = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(trimmed);+ if (plain) return { owner: plain[1], repo: plain[2] };+ return null;+}++/**+ * Scan a repo's file tree for package roots.+ *+ * A directory containing plugin.json is a plugin candidate (its mcp.json,+ * skills/ and usage card ride along). A SKILL.md whose directory is not+ * inside a plugin's skills/ tree is a standalone skill candidate.+ */+export async function scanRepo(owner: string, repo: string, branch: string): Promise<RepoScan> {+ const tree = await gh<{ tree: Array<{ path: string; type: string; size?: number }>; truncated?: boolean }>(+ `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/git/trees/${encodeURIComponent(branch)}?recursive=1`,+ );+ const paths = tree.tree.filter((t) => t.type === "blob").map((t) => t.path);+ const pathSet = new Set(paths);++ const pluginDirs = paths+ .filter((p) => p === "plugin.json" || p.endsWith("/plugin.json"))+ .map((p) => (p === "plugin.json" ? "" : p.slice(0, -"/plugin.json".length)));++ const candidates: RepoCandidate[] = pluginDirs.map((dir) => {+ const prefix = dir ? `${dir}/` : "";+ const wanted = [+ `${prefix}plugin.json`,+ `${prefix}mcp.json`,+ `${prefix}io.github.personaljarvis/usage-card.md`,+ ].filter((p) => pathSet.has(p));+ const skillMds = paths.filter((p) => p.startsWith(`${prefix}skills/`) && p.endsWith("/SKILL.md"));+ return { dir, kind: "plugin", paths: [...wanted, ...skillMds.slice(0, 10)] };+ });++ const insidePlugin = (p: string) =>+ pluginDirs.some((dir) => p.startsWith(dir ? `${dir}/` : "") && p.includes("skills/"));+ for (const p of paths) {+ if (!(p === "SKILL.md" || p.endsWith("/SKILL.md"))) continue;+ if (insidePlugin(p)) continue;+ const dir = p === "SKILL.md" ? "" : p.slice(0, -"/SKILL.md".length);+ candidates.push({ dir, kind: "skill", paths: [p] });+ if (candidates.length >= 40) break;+ }+ return { candidates, truncated: tree.truncated === true };+}++/** Fetch one file's text via the contents API (base64, UTF-8 decoded). */+export async function fetchRepoFile(+ owner: string,+ repo: string,+ branch: string,+ path: string,+): Promise<string> {+ const data = await gh<{ content?: string; encoding?: string }>(+ `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/contents/${path+ .split("/")+ .map(encodeURIComponent)+ .join("/")}?ref=${encodeURIComponent(branch)}`,+ );+ if (!data.content || data.encoding !== "base64") {+ throw new Error(`GitHub did not return file content for ${path}`);+ }+ const bytes = Uint8Array.from(atob(data.content.replace(/\n/g, "")), (c) => c.charCodeAt(0));+ return new TextDecoder("utf-8").decode(bytes);+}diff --git a/jarvis/ui/web/frontend/src/lib/packageFolder.test.ts b/jarvis/ui/web/frontend/src/lib/packageFolder.test.tsnew file mode 100644index 0000000000..6ca7be44aa--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/packageFolder.test.ts@@ -0,0 +1,124 @@+import { describe, expect, it } from "vitest";+import {+ folderToDraft,+ frontmatterValues,+ MAX_SKILL_MD_BYTES,+ mcpServersMissingType,+} from "./packageFolder";++function namedFile(path: string, text: string) {+ return { path, file: new File([text], path.split("/").pop() ?? path) };+}++const PLUGIN_JSON = JSON.stringify({+ name: "todo-fox",+ version: "1.2.0",+ description: "Tasks and reminders from TodoFox",+});++const SKILL_MD = `---+name: todo-triage+description: Sort an inbox of tasks.+version: 1.0.0+---++Group open tasks by due date.+`;++describe("folderToDraft — the folder is the classification (publishing-plan.md §2)", () => {+ it("classifies a directory with plugin.json as a plugin, bundling its skills", async () => {+ const draft = await folderToDraft([+ namedFile("plugin.json", PLUGIN_JSON),+ namedFile(+ "mcp.json",+ '{"mcpServers":{"todo-fox":{"type":"streamable-http","url":"https://mcp.todofox.example/mcp"}}}',+ ),+ namedFile("skills/todo-triage/SKILL.md", SKILL_MD),+ ]);++ expect(draft.kind).toBe("plugin");+ expect(draft.name).toBe("todo-fox");+ expect(draft.version).toBe("1.2.0");+ expect(draft.skills).toEqual([{ name: "todo-triage", skill_md: SKILL_MD }]);+ expect(draft.warnings).toEqual([]);+ });++ it('warns when an mcp.json server has no "type" — the store requires it', async () => {+ const draft = await folderToDraft([+ namedFile("plugin.json", PLUGIN_JSON),+ namedFile("mcp.json", '{"mcpServers":{"todo-fox":{"url":"https://mcp.todofox.example/mcp"}}}'),+ ]);+ expect(draft.kind).toBe("plugin");+ expect(draft.warnings.some((w) => /missing "type"/.test(w))).toBe(true);+ });++ it("classifies a directory with only a SKILL.md as a skill", async () => {+ const draft = await folderToDraft([namedFile("todo-triage/SKILL.md", SKILL_MD)]);++ expect(draft.kind).toBe("skill");+ expect(draft.name).toBe("todo-triage");+ expect(draft.description).toBe("Sort an inbox of tasks.");+ expect(draft.skill_md).toBe(SKILL_MD);+ });++ it("rejects a folder with neither plugin.json nor SKILL.md instead of silently returning an empty draft", async () => {+ await expect(folderToDraft([namedFile("README.md", "hello")])).rejects.toThrow(+ /no plugin\.json and no skill\.md/i,+ );+ });++ it("warns instead of dropping bundled skills once the 10-skill cap is exceeded", async () => {+ const files = [namedFile("plugin.json", PLUGIN_JSON)];+ for (let i = 0; i < 11; i++) {+ files.push(namedFile(`skills/skill-${i}/SKILL.md`, SKILL_MD));+ }+ const draft = await folderToDraft(files);+ expect(draft.skills).toHaveLength(10);+ expect(draft.warnings.some((w) => /more than 10/i.test(w))).toBe(true);+ });++ it("warns when plugin.json is present but not valid JSON", async () => {+ const draft = await folderToDraft([namedFile("plugin.json", "{not json")]);+ expect(draft.kind).toBe("plugin");+ expect(draft.warnings.some((w) => /not valid json/i.test(w))).toBe(true);+ });+});++describe("frontmatterValues", () => {+ it("reads top-level string pairs from a SKILL.md header", () => {+ expect(frontmatterValues(SKILL_MD)).toMatchObject({+ name: "todo-triage",+ description: "Sort an inbox of tasks.",+ version: "1.0.0",+ });+ });+});++describe("MAX_SKILL_MD_BYTES", () => {+ it("mirrors the store's per-SKILL.md cap (jarvis/marketplace/publish.py MAX_SKILL_BYTES)", () => {+ expect(MAX_SKILL_MD_BYTES).toBe(64 * 1024);+ });+});++describe("mcpServersMissingType", () => {+ it("names every server missing a \"type\" key", () => {+ const text = JSON.stringify({+ mcpServers: {+ "todo-fox": { url: "https://mcp.todofox.example/mcp" },+ "todo-fox-local": { type: "stdio", command: "npx" },+ },+ });+ expect(mcpServersMissingType(text)).toEqual(["todo-fox"]);+ });++ it("returns nothing once every server declares its type", () => {+ const text = JSON.stringify({+ mcpServers: { "todo-fox": { type: "streamable-http", url: "https://mcp.todofox.example/mcp" } },+ });+ expect(mcpServersMissingType(text)).toEqual([]);+ });++ it("returns nothing for invalid JSON — the real error is reported elsewhere", () => {+ expect(mcpServersMissingType("{not json")).toEqual([]);+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/packageFolder.ts b/jarvis/ui/web/frontend/src/lib/packageFolder.tsnew file mode 100644index 0000000000..adf5a91516--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/packageFolder.ts@@ -0,0 +1,260 @@+/**+ * Read a dropped or picked plugin/skill folder into a publish draft.+ *+ * "The folder is the classification" (docs/marketplace/publishing-plan.md §2):+ * the author never declares what kind of package they are uploading — what is+ * inside the directory decides it. A folder with a plugin.json becomes a+ * plugin draft (with mcp.json, bundled skills and the usage card picked up+ * alongside); a folder with only a SKILL.md becomes a skill draft.+ *+ * Everything here is client-side file reading — nothing is uploaded until the+ * user presses Publish, so an author can inspect the prefilled form first.+ */++export interface PackageSkill {+ name: string;+ skill_md: string;+}++export interface FolderDraft {+ kind: "skill" | "plugin";+ name: string;+ version: string;+ title: string;+ description: string;+ categories: string;+ skill_md: string;+ plugin_json_text: string;+ mcp_json_text: string;+ usage_card: string;+ skills: PackageSkill[];+ /** Non-fatal notes shown to the author ("mcp.json not found", …). */+ warnings: string[];+ /** Relative paths that were recognized, for the file chip list. */+ files: string[];+}++interface NamedFile {+ /** Path relative to the dropped root, forward slashes. */+ path: string;+ file: File;+}++const MAX_READ_BYTES = 512 * 1024;++/** Mirrors the store's per-SKILL.md cap (jarvis/marketplace/publish.py+ * MAX_SKILL_BYTES) — used to show the size live, before the Check button+ * round-trips to the real validator. */+export const MAX_SKILL_MD_BYTES = 64 * 1024;++/** Files worth reading at all — everything else in the folder is ignored. */+const INTERESTING = /(^|\/)(plugin\.json|mcp\.json|SKILL\.md|usage-card\.md)$/;++function readText(file: File): Promise<string> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => resolve(String(reader.result ?? ""));+ reader.onerror = () => reject(reader.error ?? new Error("file read failed"));+ reader.readAsText(file);+ });+}++/** Minimal YAML frontmatter reader: top-level `key: value` string pairs. */+export function frontmatterValues(skillMd: string): Record<string, string> {+ const out: Record<string, string> = {};+ if (!skillMd.startsWith("---")) return out;+ const rest = skillMd.slice(3);+ const end = rest.indexOf("\n---");+ if (end === -1) return out;+ for (const line of rest.slice(0, end).split("\n")) {+ const m = /^([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/.exec(line);+ if (!m) continue;+ let value = m[2].trim();+ if (+ (value.startsWith('"') && value.endsWith('"')) ||+ (value.startsWith("'") && value.endsWith("'"))+ ) {+ value = value.slice(1, -1);+ }+ out[m[1]] = value;+ }+ return out;+}++/**+ * Server names in an mcp.json document whose entry has no "type" key.+ *+ * A pre-upload nudge only — the real rule (every server MUST declare+ * "type": "streamable-http" | "stdio" | "sse") lives in publish.py, which+ * now delegates it to agent_plugins_loader.validate_mcp_server, the same+ * function the install path uses. Best-effort JSON parse: invalid JSON is+ * already reported by the plugin.json/mcp.json field errors this function+ * does not duplicate, so it silently yields no warning here instead.+ */+export function mcpServersMissingType(mcpJsonText: string): string[] {+ try {+ const parsed = JSON.parse(mcpJsonText) as { mcpServers?: Record<string, { type?: unknown }> };+ const servers = parsed.mcpServers;+ if (!servers || typeof servers !== "object") return [];+ return Object.entries(servers)+ .filter(([, server]) => !server || typeof server !== "object" || typeof server.type !== "string")+ .map(([name]) => name);+ } catch {+ return [];+ }+}++/** Recursively collect files from a drag-and-drop DataTransfer. */+export async function collectDroppedFiles(items: DataTransferItemList): Promise<NamedFile[]> {+ const roots: FileSystemEntry[] = [];+ for (const item of Array.from(items)) {+ const entry = item.webkitGetAsEntry?.();+ if (entry) roots.push(entry);+ }+ const found: NamedFile[] = [];++ async function walk(entry: FileSystemEntry, prefix: string): Promise<void> {+ if (found.length > 400) return; // runaway folder guard+ if (entry.isFile) {+ const file = await new Promise<File>((resolve, reject) =>+ (entry as FileSystemFileEntry).file(resolve, reject),+ );+ found.push({ path: prefix + entry.name, file });+ return;+ }+ if (entry.isDirectory) {+ const dirReader = (entry as FileSystemDirectoryEntry).createReader();+ // readEntries returns results in batches; loop until empty.+ for (;;) {+ const batch = await new Promise<FileSystemEntry[]>((resolve, reject) =>+ dirReader.readEntries(resolve, reject),+ );+ if (batch.length === 0) break;+ for (const child of batch) await walk(child, prefix + entry.name + "/");+ }+ }+ }++ for (const root of roots) await walk(root, "");+ return found;+}++/** Collect files from an `<input webkitdirectory>` selection. */+export function collectPickedFiles(list: FileList): NamedFile[] {+ return Array.from(list).map((file) => ({+ path: (file.webkitRelativePath || file.name).replace(/\\/g, "/"),+ file,+ }));+}++/**+ * Strip the common leading directory ("my-plugin/…" → "…") so detection works+ * the same whether the user dropped the folder itself or its contents.+ */+function normalizePaths(files: NamedFile[]): NamedFile[] {+ if (files.length === 0) return files;+ const first = files[0].path;+ const slash = first.indexOf("/");+ if (slash === -1) return files;+ const prefix = first.slice(0, slash + 1);+ if (files.every((f) => f.path.startsWith(prefix))) {+ return files.map((f) => ({ ...f, file: f.file, path: f.path.slice(prefix.length) }));+ }+ return files;+}++/** Turn the recognized files of a package directory into a prefilled draft. */+export async function folderToDraft(input: NamedFile[]): Promise<FolderDraft> {+ const files = normalizePaths(input).filter(+ (f) => INTERESTING.test(f.path) && f.file.size <= MAX_READ_BYTES,+ );+ const warnings: string[] = [];+ const used: string[] = [];++ const byPath = (p: string) => files.find((f) => f.path === p);+ const read = async (f: NamedFile | undefined): Promise<string> => {+ if (!f) return "";+ used.push(f.path);+ return (await readText(f.file)).replace(/^/, "");+ };++ const draft: FolderDraft = {+ kind: "skill",+ name: "",+ version: "1.0.0",+ title: "",+ description: "",+ categories: "",+ skill_md: "",+ plugin_json_text: "",+ mcp_json_text: "",+ usage_card: "",+ skills: [],+ warnings,+ files: used,+ };++ const pluginJsonFile = byPath("plugin.json");+ if (pluginJsonFile) {+ // ---- Plugin package -------------------------------------------------+ draft.kind = "plugin";+ draft.plugin_json_text = await read(pluginJsonFile);+ try {+ const manifest = JSON.parse(draft.plugin_json_text) as Record<string, unknown>;+ if (typeof manifest.name === "string") draft.name = manifest.name;+ if (typeof manifest.version === "string") draft.version = manifest.version;+ if (typeof manifest.description === "string") draft.description = manifest.description;+ } catch {+ warnings.push("plugin.json is not valid JSON — fix it before publishing.");+ }+ draft.mcp_json_text = await read(byPath("mcp.json"));+ draft.usage_card = await read(byPath("io.github.personaljarvis/usage-card.md"));+ if (!draft.mcp_json_text) {+ warnings.push(+ "No mcp.json found — fine when the auth block points at a hosted MCP server or the package is skills-only.",+ );+ } else {+ const missingType = mcpServersMissingType(draft.mcp_json_text);+ if (missingType.length > 0) {+ warnings.push(+ `mcp.json server${missingType.length === 1 ? "" : "s"} ` ++ `${missingType.map((n) => `"${n}"`).join(", ")} missing "type" — the store requires ` ++ `"type": "streamable-http" | "stdio" | "sse" on every server.`,+ );+ }+ }+ for (const f of files) {+ const m = /^skills\/([^/]+)\/SKILL\.md$/.exec(f.path);+ if (!m) continue;+ if (draft.skills.length >= 10) {+ warnings.push("More than 10 bundled skills — the store accepts at most 10.");+ break;+ }+ draft.skills.push({ name: m[1], skill_md: await read(f) });+ }+ return draft;+ }++ // ---- Standalone skill ------------------------------------------------+ const skillFile =+ byPath("SKILL.md") ?? files.find((f) => f.path.endsWith("/SKILL.md")) ?? undefined;+ if (!skillFile) {+ throw new Error(+ "No plugin.json and no SKILL.md found — a package folder needs one of the two at its top level.",+ );+ }+ draft.skill_md = await read(skillFile);+ const fm = frontmatterValues(draft.skill_md);+ const dirName = skillFile.path.includes("/") ? skillFile.path.split("/")[0] : "";+ draft.name = fm.name || dirName;+ if (fm.version) draft.version = fm.version;+ draft.description = fm.description ?? "";+ draft.title =+ fm.title ||+ (draft.name ? draft.name.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()) : "");+ if (fm.category) draft.categories = fm.category;+ if (!draft.skill_md.startsWith("---")) {+ warnings.push("SKILL.md does not start with YAML frontmatter (---) — the store requires it.");+ }+ return draft;+}diff --git a/jarvis/ui/web/frontend/src/views/MarketplaceView.test.tsx b/jarvis/ui/web/frontend/src/views/MarketplaceView.test.tsxindex cc768234d2..b2def4f727 100644--- a/jarvis/ui/web/frontend/src/views/MarketplaceView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/MarketplaceView.test.tsx@@ -110,6 +110,9 @@ const CONTENTS = {],};+/** The publishing identity the view asks for; signed out unless a test says so. */+let identity: Record<string, unknown> = { enabled: true, wallpapers_enabled: true, signed_in: false };+function installFetchMock(overrides?: Partial<CommunityResponse>) {const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {const url = String(input);@@ -117,6 +120,22 @@ function installFetchMock(overrides?: Partial<CommunityResponse>) {if (url === "/api/marketplace/community" && method === "GET") {return { ok: true, status: 200, json: async () => ({ ...INDEX, ...overrides }) } as Response;}+ if (url === "/api/marketplace/publish/identity" && method === "GET") {+ return { ok: true, status: 200, json: async () => identity } as Response;+ }+ if (url === "/api/wallpapers/uploads") {+ return { ok: true, status: 200, json: async () => ({ items: [] }) } as Response;+ }+ if (url === "/api/marketplace/publish/signin/start") {+ return {+ ok: true,+ status: 200,+ json: async () => ({ flow_id: "f", user_code: "WXYZ-9876", interval: 60 }),+ } as Response;+ }+ if (url.startsWith("/api/marketplace/publish/signin/poll/")) {+ return { ok: true, status: 200, json: async () => ({ status: "pending" }) } as Response;+ }if (url.endsWith("/contents")) {return { ok: true, status: 200, json: async () => CONTENTS } as Response;}@@ -162,6 +181,7 @@ afterEach(() => {vi.unstubAllGlobals();openExternalUrl.mockReset();setUiLanguage("en");+ identity = { enabled: true, wallpapers_enabled: true, signed_in: false };});describe("MarketplaceView", () => {@@ -296,13 +316,13 @@ describe("MarketplaceView", () => {// The German strings resolve from the locale file, including the count// template whose {count} token this view fills itself.expect(await screen.findByText(/3 veröffentlichte Einträge/)).toBeTruthy();- // The word appears twice on purpose — the filter chip and the shelf head- // name the same thing, and they must agree.- expect(screen.getAllByText("Hintergründe").length).toBe(2);+ // The word appears three times on purpose — the hero count, the filter+ // chip and the shelf head name the same thing, and they must agree.+ expect(screen.getAllByText("Hintergründe").length).toBe(3); // i18n-allowexpect(screen.getByLabelText(/Plugins, Skills und Hintergründe/)).toBeTruthy();setUiLanguage("es");- expect((await screen.findAllByText("Fondos")).length).toBe(2);+ expect((await screen.findAllByText("Fondos")).length).toBe(3);});it("opens the public storefront in a real browser", async () => {@@ -314,4 +334,56 @@ describe("MarketplaceView", () => {expect(openExternalUrl).toHaveBeenCalledWith("https://personaljarvis.ai/marketplace/");});++ it("opens the Publish Studio in the app instead of sending people to the website", async () => {+ installFetchMock();+ renderView();+ await screen.findByText("Sentry");++ fireEvent.click(screen.getByTestId("marketplace-publish"));+ expect(await screen.findByTestId("publish-studio")).toBeTruthy();+ // Nothing left the app: the studio is the publish path now.+ expect(openExternalUrl).not.toHaveBeenCalled();+ });++ it("offers the GitHub sign-in from the header and shows the code", async () => {+ installFetchMock();+ renderView();+ await screen.findByText("Sentry");+ fireEvent.click(await screen.findByTestId("publisher-chip-signed-out"));+ expect(await screen.findByTestId("github-signin-dialog")).toBeTruthy();+ expect(await screen.findByTestId("device-code")).toBeTruthy();+ expect(screen.getByText("WXYZ")).toBeTruthy();+ });++ it("filters to the signed-in account's own publications", async () => {+ identity = {+ enabled: true,+ wallpapers_enabled: true,+ signed_in: true,+ login: "octocat",+ avatar_url: null,+ };+ installFetchMock({+ skills: [+ { ...INDEX.skills[0] },+ {+ ...INDEX.skills[0],+ name: "someone-elses",+ title: "Someone Else's Skill",+ publisher: "stranger",+ },+ ],+ });+ renderView();+ await screen.findByText("Sentry");++ const chip = await screen.findByTestId("publisher-chip");+ expect(chip.textContent).toContain("@octocat");++ fireEvent.click(screen.getByRole("button", { name: /Mine 3/ }));+ expect(screen.getByText("Three Bullet Brief")).toBeTruthy();+ expect(screen.getByText("Sentry")).toBeTruthy();+ expect(screen.queryByText("Someone Else's Skill")).toBeNull();+ });});diff --git a/jarvis/ui/web/frontend/src/views/MarketplaceView.tsx b/jarvis/ui/web/frontend/src/views/MarketplaceView.tsxindex 6c32e52c61..29c1ff2571 100644--- a/jarvis/ui/web/frontend/src/views/MarketplaceView.tsx+++ b/jarvis/ui/web/frontend/src/views/MarketplaceView.tsx@@ -12,6 +12,7 @@ import {Search,Sparkles,Store,+ UploadCloud,Wand2,X,} from "lucide-react";@@ -19,7 +20,13 @@ import {import { Button } from "@/components/ui/button";import { ScrollArea } from "@/components/ui/scroll-area";import { ViewHeader } from "@/views/ChatsView";-import { useT } from "@/i18n";+import {+ GithubSignInDialog,+ PublisherChip,+ usePublishIdentity,+} from "@/components/marketplace/PublishIdentity";+import { PublishStudio } from "@/components/marketplace/PublishStudio";+import { fill, useLocaleChunk, useT } from "@/i18n";import { cn } from "@/lib/utils";import { openExternalUrl } from "@/lib/openExternal";import { useEventStore, type SectionId } from "@/store/events";@@ -55,7 +62,7 @@ import {const MARKETPLACE_WEB_URL = "https://personaljarvis.ai/marketplace/";type Kind = "plugin" | "skill" | "wallpaper";-type KindFilter = "all" | Kind;+type KindFilter = "all" | Kind | "mine";/** One entry of any kind, flattened into what the storefront draws. */interface Entry {@@ -193,11 +200,19 @@ interface InstallResultWire {export function MarketplaceView() {const t = useT();+ // The publish half's strings ride in a lazy chunk (bundle budget); the+ // shelves render from the main file meanwhile, the hero waits for it.+ const localeReady = useLocaleChunk("marketplace");const queryClient = useQueryClient();const [query, setQuery] = useState("");const [kindFilter, setKindFilter] = useState<KindFilter>("all");const [openEntry, setOpenEntry] = useState<Entry | null>(null);const [landing, setLanding] = useState<InstallResultWire | null>(null);+ const [studioOpen, setStudioOpen] = useState(false);+ const [signInOpen, setSignInOpen] = useState(false);+ const identity = usePublishIdentity();+ const login = identity.data?.signed_in ? (identity.data.login ?? null) : null;+ const publishEnabled = identity.data?.enabled !== false;const { data, isLoading, error } = useQuery({queryKey: ["marketplace-community"],@@ -250,12 +265,19 @@ export function MarketplaceView() {}, [data]);const needle = query.trim().toLowerCase();+ const mineCount = useMemo(+ () => (login ? entries.filter((e) => e.publisher === login).length : 0),+ [entries, login],+ );const visible = useMemo(() =>entries.filter(- (e) => (kindFilter === "all" || e.kind === kindFilter) && matches(e, needle),+ (e) =>+ (kindFilter === "all" ||+ (kindFilter === "mine" ? e.publisher === login : e.kind === kindFilter)) &&+ matches(e, needle),),- [entries, kindFilter, needle],+ [entries, kindFilter, needle, login],);const wallpapers = visible.filter((e) => e.kind === "wallpaper");@@ -285,13 +307,27 @@ export function MarketplaceView() {/></Button><Button- variant="outline"+ variant="ghost"size="sm"onClick={() => openExternalUrl(MARKETPLACE_WEB_URL)}+ title={t("marketplace.open_web")}>{t("marketplace.open_web")}<ExternalLink className="ml-1.5 h-3.5 w-3.5" /></Button>+ <PublisherChip+ onSignIn={() => setSignInOpen(true)}+ onMine={() => {+ setKindFilter("mine");+ setQuery("");+ }}+ />+ {publishEnabled && (+ <Button size="sm" onClick={() => setStudioOpen(true)} data-testid="marketplace-publish">+ <UploadCloud className="mr-1.5 h-3.5 w-3.5" />+ {t("marketplace.publish_cta")}+ </Button>+ )}</div>}/>@@ -319,7 +355,9 @@ export function MarketplaceView() {plugin: entries.filter((e) => e.kind === "plugin").length,skill: entries.filter((e) => e.kind === "skill").length,wallpaper: entries.filter((e) => e.kind === "wallpaper").length,+ mine: mineCount,}}+ showMine={login !== null}t={t}/></div>@@ -349,13 +387,26 @@ export function MarketplaceView() {</p>)}+ {!isLoading && !error && localeReady && kindFilter === "all" && !needle && (+ <Hero+ data={data}+ login={login}+ publishEnabled={publishEnabled}+ onPublish={() => setStudioOpen(true)}+ onSignIn={() => setSignInOpen(true)}+ t={t}+ />+ )}+{!isLoading && !error && visible.length === 0 && (<EmptyStatequery={query}+ mine={kindFilter === "mine"}onClear={() => {setQuery("");setKindFilter("all");}}+ onPublish={() => setStudioOpen(true)}t={t}/>)}@@ -414,7 +465,11 @@ export function MarketplaceView() {)}{!isLoading && !error && (- <PublishFooter t={t} />+ <PublishFooter+ enabled={publishEnabled}+ onPublish={() => setStudioOpen(true)}+ t={t}+ />)}</div></ScrollArea>@@ -431,25 +486,15 @@ export function MarketplaceView() {)}{landing && <LandingToast result={landing} onClose={() => setLanding(null)} t={t} />}++ {studioOpen && <PublishStudio onClose={() => setStudioOpen(false)} />}+ {signInOpen && <GithubSignInDialog onClose={() => setSignInOpen(false)} />}</div>);}type Translate = (key: string) => string;-/**- * Fill `{token}` placeholders in a translated string.- *- * The in-house i18n resolver interpolates exactly one token — the assistant's- * name — and takes no variables, so counts and titles are substituted here- * rather than by widening a resolver three locales and every view depend on.- */-function fill(template: string, vars: Record<string, string | number>): string {- return template.replace(/\{(\w+)\}/g, (match, key: string) =>- key in vars ? String(vars[key]) : match,- );-}-/** "12 entries · index 24 · updated 4 days ago", or the honest alternative. */function subtitleFor(t: Translate,@@ -483,11 +528,13 @@ function FilterChips({active,onChange,counts,+ showMine,t,}: {active: KindFilter;onChange: (kind: KindFilter) => void;counts: Record<KindFilter, number>;+ showMine: boolean;t: Translate;}) {const chips: { id: KindFilter; label: string }[] = [@@ -496,6 +543,7 @@ function FilterChips({{ id: "skill", label: t("marketplace.filter_skills") },{ id: "wallpaper", label: t("marketplace.filter_wallpapers") },];+ if (showMine) chips.push({ id: "mine", label: t("marketplace.filter_mine") });return (<div className="flex shrink-0 items-center gap-1">{chips.map((chip) => (@@ -684,13 +732,29 @@ function EntryList({function EmptyState({query,+ mine,onClear,+ onPublish,t,}: {query: string;+ mine: boolean;onClear: () => void;+ onPublish: () => void;t: Translate;}) {+ if (mine && !query) {+ return (+ <div className="py-16 text-center" data-testid="marketplace-empty-mine">+ <UploadCloud className="mx-auto mb-3 h-6 w-6 text-muted-foreground/60" />+ <p className="text-sm text-muted-foreground">{t("marketplace.empty_mine")}</p>+ <Button size="sm" className="mt-3" onClick={onPublish}>+ <UploadCloud className="mr-1.5 h-3.5 w-3.5" />+ {t("marketplace.publish_cta")}+ </Button>+ </div>+ );+ }return (<div className="py-16 text-center"><Package className="mx-auto mb-3 h-6 w-6 text-muted-foreground/60" />@@ -706,18 +770,120 @@ function EmptyState({);}-function PublishFooter({ t }: { t: Translate }) {+/**+ * The storefront's marquee: what the community has put on the shelves, and+ * the one door that matters for anybody who built something — publish, in+ * this app, under their GitHub name. Drawn only on the unfiltered front page+ * so a search never has to scroll past it.+ */+function Hero({+ data,+ login,+ publishEnabled,+ onPublish,+ onSignIn,+ t,+}: {+ data: CommunityResponse | undefined;+ login: string | null;+ publishEnabled: boolean;+ onPublish: () => void;+ onSignIn: () => void;+ t: Translate;+}) {+ const counts = {+ plugins: data?.plugins?.length ?? 0,+ skills: data?.skills?.length ?? 0,+ wallpapers: data?.wallpapers?.length ?? 0,+ };+ return (+ <section+ className="relative mb-8 overflow-hidden rounded-2xl border border-border bg-card/60 p-6 backdrop-blur-sm"+ data-testid="marketplace-hero"+ >+ <div+ aria-hidden+ className="pointer-events-none absolute -right-24 -top-24 h-72 w-72 rounded-full bg-primary/15 blur-3xl"+ />+ <div+ aria-hidden+ className="pointer-events-none absolute -bottom-28 left-1/3 h-64 w-64 rounded-full bg-primary/10 blur-3xl"+ />+ <div className="relative flex flex-wrap items-end gap-6">+ <div className="min-w-0 flex-1">+ <p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">+ {t("marketplace.hero_eyebrow")}+ </p>+ <h3 className="mt-1 font-display text-2xl font-semibold tracking-tight text-foreground">+ {t("marketplace.hero_title")}+ </h3>+ <p className="mt-2 max-w-xl text-sm leading-relaxed text-muted-foreground">+ {t("marketplace.hero_body")}+ </p>+ <div className="mt-4 flex flex-wrap items-center gap-2">+ {publishEnabled && (+ <Button size="sm" onClick={onPublish} data-testid="hero-publish">+ <UploadCloud className="mr-1.5 h-3.5 w-3.5" />+ {login ? t("marketplace.hero_publish_signed_in") : t("marketplace.publish_cta")}+ </Button>+ )}+ {!login && publishEnabled && (+ <Button size="sm" variant="ghost" onClick={onSignIn}>+ {t("marketplace.identity_sign_in")}+ </Button>+ )}+ </div>+ </div>+ <dl className="grid grid-cols-3 gap-3 sm:gap-4">+ <Stat value={counts.plugins} label={t("marketplace.filter_plugins")} />+ <Stat value={counts.skills} label={t("marketplace.filter_skills")} />+ <Stat value={counts.wallpapers} label={t("marketplace.filter_wallpapers")} />+ </dl>+ </div>+ </section>+ );+}++function Stat({ value, label }: { value: number; label: string }) {+ return (+ <div className="rounded-xl border border-border/70 bg-background/50 px-4 py-3 text-center">+ <dd className="font-display text-2xl font-semibold tabular-nums tracking-tight text-foreground">+ {value}+ </dd>+ <dt className="text-[11px] uppercase tracking-wider text-muted-foreground">{label}</dt>+ </div>+ );+}++function PublishFooter({+ enabled,+ onPublish,+ t,+}: {+ enabled: boolean;+ onPublish: () => void;+ t: Translate;+}) {return (<div className="mt-10 flex flex-wrap items-center justify-between gap-3 rounded-xl border border-dashed border-border bg-card/50 px-4 py-3 backdrop-blur-sm"><p className="text-xs text-muted-foreground">{t("marketplace.publish_hint")}</p>- <Button- variant="outline"- size="sm"- onClick={() => openExternalUrl(MARKETPLACE_SUBMIT_URL)}- >- {t("marketplace.publish_cta")}- <ExternalLink className="ml-1.5 h-3.5 w-3.5" />- </Button>+ <div className="flex items-center gap-2">+ <Button+ variant="ghost"+ size="sm"+ onClick={() => openExternalUrl(MARKETPLACE_SUBMIT_URL)}+ title={t("marketplace.publish_on_web")}+ >+ {t("marketplace.publish_on_web")}+ <ExternalLink className="ml-1.5 h-3.5 w-3.5" />+ </Button>+ {enabled && (+ <Button size="sm" onClick={onPublish}>+ <UploadCloud className="mr-1.5 h-3.5 w-3.5" />+ {t("marketplace.publish_cta")}+ </Button>+ )}+ </div></div>);}diff --git a/jarvis/ui/web/frontend/src/views/WallpaperView.share.test.tsx b/jarvis/ui/web/frontend/src/views/WallpaperView.share.test.tsxnew file mode 100644index 0000000000..1701e65586--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/WallpaperView.share.test.tsx@@ -0,0 +1,112 @@+/**+ * The Share button in the wallpaper preview: offered for the owner's own+ * pictures only, when the wallpaper lane is on, and it opens the publish+ * dialog over the picker.+ *+ * A file of its own because it needs the publish identity endpoint to answer+ * something real, which the picker's main harness deliberately leaves blank.+ *+ * No jest-dom in this repo — assertions use toBeTruthy()/toBeNull().+ */+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { ThemeProvider } from "@/hooks/useTheme";+import { WallpaperView } from "@/views/WallpaperView";++const CATALOG = {+ available: true,+ count: 1,+ styles: [{ slug: "03-anime-neon", label: "Cinematic Anime Neon", count: 1 }],+ items: [+ {+ id: "03-anime-neon-01",+ title: "Neon Crossing",+ style: "03-anime-neon",+ styleLabel: "Cinematic Anime Neon",+ theme: "dark" as const,+ },+ ],+};++const OWN = { id: "u000000000000000a", title: "Kitchen Window", theme: "light", createdAt: 1 };+const INSTALLED = {+ id: "u000000000000000b",+ title: "Rain Antenna City",+ theme: "dark",+ createdAt: 2,+ source: "marketplace",+ publisher: "someone",+};++function stubServer(wallpapersEnabled: boolean) {+ const json = (body: unknown) => ({ ok: true, status: 200, json: async () => body });+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: unknown) => {+ const url = String(input);+ if (url === "/api/wallpapers/uploads") return json({ items: [OWN, INSTALLED] });+ if (url === "/api/wallpapers") return json(CATALOG);+ if (url === "/api/marketplace/publish/identity") {+ return json({+ enabled: true,+ wallpapers_enabled: wallpapersEnabled,+ signed_in: true,+ login: "octocat",+ });+ }+ return json({});+ }),+ );+}++function renderView(wallpapersEnabled = true) {+ stubServer(wallpapersEnabled);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(+ <QueryClientProvider client={client}>+ <ThemeProvider>+ <WallpaperView />+ </ThemeProvider>+ </QueryClientProvider>,+ );+}++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe("WallpaperView — share", () => {+ it("offers Share on the owner's own picture and opens the publish dialog", async () => {+ renderView();+ fireEvent.click(await screen.findByAltText("Kitchen Window"));+ const preview = await screen.findByTestId("wallpaper-preview");+ const share = await within(preview).findByTestId("wallpaper-share");+ fireEvent.click(share);+ const dialog = await screen.findByTestId("publish-wallpaper-dialog");+ expect(dialog.textContent).toContain("Share with the community");+ // The title is prefilled from the picker's own name for the picture.+ expect((within(dialog).getByTestId("wallpaper-title") as HTMLInputElement).value).toBe(+ "Kitchen Window",+ );+ });++ it("does not offer Share on a picture installed from the community", async () => {+ renderView();+ fireEvent.click(await screen.findByAltText("Rain Antenna City"));+ const preview = await screen.findByTestId("wallpaper-preview");+ // Give the identity query a tick to settle, then assert absence.+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(within(preview).queryByTestId("wallpaper-share")).toBeNull();+ });++ it("does not offer Share when the wallpaper lane is off", async () => {+ renderView(false);+ fireEvent.click(await screen.findByAltText("Kitchen Window"));+ const preview = await screen.findByTestId("wallpaper-preview");+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(within(preview).queryByTestId("wallpaper-share")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/views/WallpaperView.tsx b/jarvis/ui/web/frontend/src/views/WallpaperView.tsxindex c1dd0fd425..4189b89f1d 100644--- a/jarvis/ui/web/frontend/src/views/WallpaperView.tsx+++ b/jarvis/ui/web/frontend/src/views/WallpaperView.tsx@@ -12,11 +12,12 @@ import {Store,Sun,Trash2,+ Share2,Upload,X,} from "lucide-react";-import { translate } from "@/i18n";+import { translate, useLocaleChunk } from "@/i18n";import { Button } from "@/components/ui/button";import { ScrollArea } from "@/components/ui/scroll-area";import { ViewHeader } from "@/views/ChatsView";@@ -36,6 +37,8 @@ import {UPLOAD_WALLPAPER_STYLE,} from "@/hooks/useWallpaperUploads";import { useApplyWallpaper } from "@/hooks/useApplyWallpaper";+import { usePublishIdentity } from "@/components/marketplace/PublishIdentity";+import { PublishWallpaperDialog } from "@/components/wallpaper/PublishWallpaperDialog";import {installRunning,useWallpaperLibraryInstall,@@ -355,6 +358,7 @@ function WallpaperPreview({onToggleFavorite,onSetTheme,onRemove,+ onShare,onClose,onStep,}: {@@ -366,6 +370,8 @@ function WallpaperPreview({onToggleFavorite: () => void;onSetTheme: (theme: Theme) => void;onRemove: () => void;+ /** Absent when this picture cannot be published — see the caller. */+ onShare?: () => void;onClose: () => void;onStep: (delta: number) => void;}) {@@ -423,6 +429,18 @@ function WallpaperPreview({</SegmentButton></div>)}+ {onShare && (+ <Button+ size="sm"+ variant="outline"+ onClick={onShare}+ data-testid="wallpaper-share"+ aria-label={`Share ${item.title}`}+ >+ <Share2 className="mr-1.5 h-3.5 w-3.5" />+ {translate("marketplace.share_cta")}+ </Button>+ )}{item.isUpload && (<Buttonsize="sm"@@ -527,8 +545,21 @@ export function WallpaperView() {const [style, setStyle] = useState<string | null>(null);const [favoritesOnly, setFavoritesOnly] = useState(false);const [previewId, setPreviewId] = useState<string | null>(null);+ const [shareId, setShareId] = useState<string | null>(null);const fileInput = useRef<HTMLInputElement | null>(null);+ // Only the owner's OWN pictures can be shared. An installed community+ // wallpaper is somebody else's work; the server refuses to republish it,+ // and offering a button the server will refuse is a trap, not a feature.+ // Hidden too when the wallpaper lane is switched off in this deployment.+ const publishIdentity = usePublishIdentity();+ const shareStringsReady = useLocaleChunk("marketplace");+ const canShare = (item: WallpaperEntry): boolean =>+ shareStringsReady &&+ publishIdentity.data?.wallpapers_enabled === true &&+ item.isUpload === true &&+ !item.fromMarketplace;+const ownEntries = useMemo(() => (uploads ?? []).map(uploadAsEntry),[uploads],@@ -873,10 +904,20 @@ export function WallpaperView() {onToggleFavorite={() => toggleFavorite(previewItem.id)}onSetTheme={(next) => onRethemeUpload(previewItem, next)}onRemove={() => onRemoveUpload(previewItem)}+ onShare={canShare(previewItem) ? () => setShareId(previewItem.id) : undefined}onClose={() => setPreviewId(null)}onStep={step}/>)}+ {shareId && (() => {+ // Resolved against the whole catalog, like the preview above: the+ // share dialog is a form somebody is filling in, and a filter change+ // underneath it must not yank the picture out.+ const shareItem = items.find((item) => item.id === shareId) ?? null;+ return shareItem ? (+ <PublishWallpaperDialog item={shareItem} onClose={() => setShareId(null)} />+ ) : null;+ })()}</div>);}