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): drop your own plugin in
Haraldab718c857f56
diff --git a/jarvis/ui/web/frontend/src/components/UploadDropzone.tsx b/jarvis/ui/web/frontend/src/components/UploadDropzone.tsxnew file mode 100644index 0000000000..c798b476bc--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/UploadDropzone.tsx@@ -0,0 +1,116 @@+import { useRef } from "react";+import { FileArchive, FolderOpen, Upload } from "lucide-react";+import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";+import { filesFromInput, type PickedFile } from "@/lib/filePicking";++/**+ * The "drop a folder here" surface, shared by every upload flow.+ *+ * Skills and plugins want the same three ways in — drag a folder, pick a+ * folder, hand over an archive — and only differ in the words on the label.+ * Keeping one surface means a fix to any of the three fiddly parts (the+ * `webkitdirectory` attribute React refuses to render, the archive accept+ * list, the drag highlight) lands everywhere at once.+ */++/**+ * The two hidden file inputs plus the handles to open them.+ *+ * They live in a hook rather than inside the dropzone because the caller needs+ * to reopen the folder picker from elsewhere too — a "Replace" button sits+ * next to the file list, long after the dropzone is gone.+ */+export function useUploadInputs(+ onPick: (files: PickedFile[]) => void,+ testIdPrefix: string,+) {+ const folderRef = useRef<HTMLInputElement | null>(null);+ const archiveRef = useRef<HTMLInputElement | null>(null);++ // React does not know `webkitdirectory` and drops it from JSX without a+ // word, so it has to be set on the node itself.+ const setFolderRef = (node: HTMLInputElement | null) => {+ folderRef.current = node;+ if (node) {+ node.setAttribute("webkitdirectory", "");+ node.setAttribute("directory", "");+ }+ };++ const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ onPick(filesFromInput(event.target.files));+ // Cleared so picking the same folder twice in a row still fires a change.+ event.target.value = "";+ };++ const inputs = (+ <>+ <input+ ref={setFolderRef}+ type="file"+ multiple+ className="sr-only"+ data-testid={`${testIdPrefix}-folder-input`}+ onChange={handleChange}+ />+ <input+ ref={archiveRef}+ type="file"+ accept=".zip,.tgz,.tar.gz"+ className="sr-only"+ data-testid={`${testIdPrefix}-archive-input`}+ onChange={handleChange}+ />+ </>+ );++ return {+ inputs,+ openFolder: () => folderRef.current?.click(),+ openArchive: () => archiveRef.current?.click(),+ };+}++export function UploadDropzone({+ dragging,+ title,+ hint,+ folderLabel,+ archiveLabel,+ onChooseFolder,+ onChooseArchive,+}: {+ dragging: boolean;+ title: string;+ hint: string;+ folderLabel: string;+ archiveLabel: string;+ onChooseFolder: () => void;+ onChooseArchive: () => void;+}) {+ return (+ <div+ className={cn(+ "flex flex-col items-center gap-3 rounded-lg border-2 border-dashed px-6 py-10 text-center transition-colors",+ dragging ? "border-primary bg-primary/5" : "border-border bg-muted/20",+ )}+ >+ <Upload className="h-5 w-5 text-muted-foreground" />+ <div>+ <p className="text-sm font-medium">{title}</p>+ <p className="mt-1 text-xs text-muted-foreground">{hint}</p>+ </div>+ <div className="mt-1 flex items-center gap-2">+ <Button size="sm" variant="outline" onClick={onChooseFolder} className="gap-1.5">+ <FolderOpen className="h-3.5 w-3.5" />+ {folderLabel}+ </Button>+ <Button size="sm" variant="ghost" onClick={onChooseArchive} className="gap-1.5">+ <FileArchive className="h-3.5 w-3.5" />+ {archiveLabel}+ </Button>+ </div>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 07ef176f49..cff744d2d6 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -4276,6 +4276,7 @@"view_source": "Eintrag ansehen"},"skill_upload": {+ "blocked": "Kann so nicht installiert werden.","button": "Hochladen","title": "Skill hinzufügen","subtitle": "Lade einen eigenen Skill hoch oder hole ihn über einen Link.",@@ -4304,5 +4305,27 @@"blocker_no_files": "Noch nichts ausgewählt.","will_land_as_draft": "Wird als Entwurf abgelegt.","ready": "Bereit zum Installieren."+ },+ "plugin_upload": {+ "blocked": "Kann so nicht installiert werden.",+ "button": "Hochladen",+ "title": "Plugin hinzufügen",+ "subtitle": "Lade ein eigenes Plugin-Manifest hoch — eine plugin.json, optional mit mcp.json.",+ "drop_title": "Plugin-Ordner hier ablegen",+ "drop_hint": "Ein Ordner mit plugin.json, oder ein .zip- bzw. .tar.gz-Archiv.",+ "choose_folder": "Ordner wählen",+ "choose_archive": "Archiv wählen",+ "install": "Installieren",+ "inspecting": "Upload wird gelesen",+ "files": "Dateien",+ "replace": "Ersetzen",+ "clear": "Verwerfen",+ "auth_mode": "Anmeldung",+ "with_mcp": "mit MCP-Server",+ "no_plugin_detected": "In diesem Upload steckt keine lesbare plugin.json.",+ "self_badge": "Selbst",+ "unreviewed": "Selbst hochgeladen: niemand hat dieses Plugin geprüft, und es trägt keinen Herausgeber.",+ "blocker_no_files": "Noch nichts ausgewählt.",+ "ready": "Bereit zum Installieren."}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex c60772b0d1..078911206b 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -4276,6 +4276,7 @@"view_source": "view listing"},"skill_upload": {+ "blocked": "Cannot be installed as is.","button": "Upload","title": "Add a skill","subtitle": "Upload a skill of your own, or fetch one from a link.",@@ -4304,5 +4305,27 @@"blocker_no_files": "Nothing chosen yet.","will_land_as_draft": "Will land as a draft.","ready": "Ready to install."+ },+ "plugin_upload": {+ "blocked": "Cannot be installed as is.",+ "button": "Upload",+ "title": "Add a plugin",+ "subtitle": "Upload a plugin manifest of your own — a plugin.json, optionally with an mcp.json.",+ "drop_title": "Drop a plugin folder here",+ "drop_hint": "A folder holding plugin.json, or a .zip / .tar.gz archive.",+ "choose_folder": "Choose folder",+ "choose_archive": "Choose archive",+ "install": "Install",+ "inspecting": "Reading the upload",+ "files": "files",+ "replace": "Replace",+ "clear": "Discard",+ "auth_mode": "Sign-in",+ "with_mcp": "with an MCP server",+ "no_plugin_detected": "This upload holds no readable plugin.json.",+ "self_badge": "Self-added",+ "unreviewed": "Self-uploaded: nobody reviewed this plugin, and it carries no publisher.",+ "blocker_no_files": "Nothing chosen yet.",+ "ready": "Ready to install."}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex f5e93ab858..0dcb86b418 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -4276,6 +4276,7 @@"view_source": "ver publicación"},"skill_upload": {+ "blocked": "No se puede instalar así.","button": "Subir","title": "Añadir una skill","subtitle": "Sube una skill propia u obtenla desde un enlace.",@@ -4304,5 +4305,27 @@"blocker_no_files": "Aún no has elegido nada.","will_land_as_draft": "Se guardará como borrador.","ready": "Lista para instalar."+ },+ "plugin_upload": {+ "blocked": "No se puede instalar así.",+ "button": "Subir",+ "title": "Añadir un plugin",+ "subtitle": "Sube un manifiesto de plugin propio: un plugin.json, opcionalmente con un mcp.json.",+ "drop_title": "Suelta aquí una carpeta de plugin",+ "drop_hint": "Una carpeta con plugin.json, o un archivo .zip o .tar.gz.",+ "choose_folder": "Elegir carpeta",+ "choose_archive": "Elegir archivo",+ "install": "Instalar",+ "inspecting": "Leyendo la subida",+ "files": "archivos",+ "replace": "Reemplazar",+ "clear": "Descartar",+ "auth_mode": "Acceso",+ "with_mcp": "con servidor MCP",+ "no_plugin_detected": "Esta subida no contiene ningún plugin.json legible.",+ "self_badge": "Propio",+ "unreviewed": "Subido por ti: nadie ha revisado este plugin y no lleva editor.",+ "blocker_no_files": "Aún no has elegido nada.",+ "ready": "Listo para instalar."}}diff --git a/jarvis/ui/web/frontend/src/lib/pluginUpload.ts b/jarvis/ui/web/frontend/src/lib/pluginUpload.tsnew file mode 100644index 0000000000..7453777eb5--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/pluginUpload.ts@@ -0,0 +1,68 @@+/**+ * Talking to `/api/marketplace/plugins/upload` — inspect first, install second.+ *+ * Same two-call shape as the skill flow and for the same reason: the dialog+ * has to be able to say what will happen before it happens. What differs is+ * what there is to report. A plugin is a manifest, so the interesting facts+ * are the catalog card it will produce and the authentication mode it will+ * ask the owner for.+ */++import type { PickedFile } from "@/lib/filePicking";++export type DetectedPlugin = {+ id: string;+ display_name: string;+ description: string;+ category: string;+ /** Which of the catalog auth modes the plugin will ask for. */+ auth_mode: string;+ longevity: string;+};++export type PluginUploadReport = {+ ready: boolean;+ problems: string[];+ plugin: DetectedPlugin | null;+ /** True when an mcp.json sat beside the manifest and travels with it. */+ has_mcp: boolean;+ files: string[];+ ignored: string[];+ stripped_root: string | null;+ total_bytes: number;+ limits: { max_file_bytes: number; max_total_bytes: number; max_file_count: number };+};++export type PluginUploadResult = {+ ok: boolean;+ plugin: { id: string; display_name: string; source: string };+};++function buildUploadBody(picked: PickedFile[]): FormData {+ const body = new FormData();+ for (const { file } of picked) body.append("files", file);+ body.append("paths", JSON.stringify(picked.map((entry) => entry.path)));+ return body;+}++async function postUpload<T>(url: string, picked: PickedFile[]): Promise<T> {+ const res = await fetch(url, { method: "POST", body: buildUploadBody(picked) });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.detail ?? `HTTP ${res.status}`);+ }+ return res.json();+}++/** Reports what the upload holds. Writes nothing. */+export function inspectPluginUpload(picked: PickedFile[]): Promise<PluginUploadReport> {+ return postUpload<PluginUploadReport>(+ "/api/marketplace/plugins/upload/inspect",+ picked,+ );+}++/** Installs the manifest into the local catalog. */+export function uploadPlugin(picked: PickedFile[]): Promise<PluginUploadResult> {+ return postUpload<PluginUploadResult>("/api/marketplace/plugins/upload", picked);+}diff --git a/jarvis/ui/web/frontend/src/views/PluginUploadDialog.test.tsx b/jarvis/ui/web/frontend/src/views/PluginUploadDialog.test.tsxnew file mode 100644index 0000000000..9eb31b3438--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/PluginUploadDialog.test.tsx@@ -0,0 +1,153 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import type { ReactElement } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { setUiLanguage } from "@/i18n";+import { PluginUploadDialog } from "@/views/PluginUploadDialog";++/**+ * A plugin the owner drops in has no publisher and no review behind it. The+ * dialog's job is to say that out loud while the decision is still open —+ * afterwards the card carries the mark, but by then the yes has happened.+ */++const READY_REPORT = {+ ready: true,+ problems: [],+ plugin: {+ id: "todo-fox",+ display_name: "TodoFox",+ description: "Tasks and reminders from TodoFox",+ category: "Lists & Tasks",+ auth_mode: "pat_paste",+ longevity: "permanent",+ },+ has_mcp: true,+ files: ["plugin.json", "mcp.json"],+ ignored: [],+ stripped_root: "todo-fox",+ total_bytes: 900,+ limits: { max_file_bytes: 10485760, max_total_bytes: 52428800, max_file_count: 2000 },+};++function jsonResponse(body: unknown, ok = true, status = 200): Response {+ return { ok, status, json: async () => body } as Response;+}++let fetchMock: ReturnType<typeof vi.fn>;++function stubFetch(responses: Record<string, unknown>) {+ fetchMock = vi.fn(async (url: string) => {+ const key = Object.keys(responses).find((candidate) => url.includes(candidate));+ if (!key) return jsonResponse({ detail: "unexpected call" }, false, 404);+ return jsonResponse(responses[key]);+ });+ (globalThis as unknown as { fetch: typeof fetch }).fetch =+ fetchMock as unknown as typeof fetch;+}++function withClient(node: ReactElement) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ return <QueryClientProvider client={client}>{node}</QueryClientProvider>;+}++function pickFolder(files: File[]) {+ const input = screen.getByTestId("plugin-folder-input") as HTMLInputElement;+ Object.defineProperty(input, "files", { value: files, configurable: true });+ fireEvent.change(input);+}++function manifestFile(relativePath: string): File {+ const file = new File(["{}"], relativePath.split("/").pop()!);+ Object.defineProperty(file, "webkitRelativePath", { value: relativePath });+ return file;+}++beforeEach(() => {+ setUiLanguage("en");+ stubFetch({ "/upload/inspect": READY_REPORT });+});++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe("PluginUploadDialog", () => {+ it("asks for the manifest before anything else", () => {+ render(withClient(<PluginUploadDialog open onClose={() => {}} />));++ expect(screen.getByText("Drop a plugin folder here")).toBeTruthy();+ expect(screen.getByText("Install").closest("button")?.disabled).toBe(true);+ });++ it("shows the card the manifest will produce, and how it signs in", async () => {+ render(withClient(<PluginUploadDialog open onClose={() => {}} />));++ pickFolder([manifestFile("todo-fox/plugin.json"), manifestFile("todo-fox/mcp.json")]);++ await waitFor(() => expect(screen.getByText("TodoFox")).toBeTruthy());+ // The auth mode is the one thing an owner cannot discover afterwards+ // without connecting, so it belongs on the preview.+ expect(screen.getByText(/pat_paste/)).toBeTruthy();+ expect(screen.getByText(/with an MCP server/)).toBeTruthy();+ });++ it("says nobody reviewed this before the yes, not after", async () => {+ render(withClient(<PluginUploadDialog open onClose={() => {}} />));++ pickFolder([manifestFile("todo-fox/plugin.json")]);++ await waitFor(() => expect(screen.getByText(/nobody reviewed this plugin/)).toBeTruthy());+ expect(screen.getByText("Install").closest("button")?.disabled).toBe(false);+ });++ it("refuses to offer an install the server has blocked", async () => {+ stubFetch({+ "/upload/inspect": {+ ...READY_REPORT,+ ready: false,+ plugin: null,+ problems: ["plugin.json needs the Jarvis auth block"],+ },+ });+ render(withClient(<PluginUploadDialog open onClose={() => {}} />));++ pickFolder([manifestFile("plugin.json")]);++ await waitFor(() =>+ expect(screen.getByText("plugin.json needs the Jarvis auth block")).toBeTruthy(),+ );+ expect(screen.getByText("Install").closest("button")?.disabled).toBe(true);+ // No unreviewed note either: there is nothing to install to warn about.+ expect(screen.queryByText(/nobody reviewed this plugin/)).toBeNull();+ });++ it("installs and reports the id back", async () => {+ stubFetch({+ "/upload/inspect": READY_REPORT,+ "/api/marketplace/plugins/upload": {+ ok: true,+ plugin: { id: "todo-fox", display_name: "TodoFox", source: "local" },+ },+ });+ const onInstalled = vi.fn();+ const onClose = vi.fn();+ render(+ withClient(+ <PluginUploadDialog open onClose={onClose} onInstalled={onInstalled} />,+ ),+ );++ pickFolder([manifestFile("todo-fox/plugin.json")]);+ await waitFor(() => expect(screen.getByText("TodoFox")).toBeTruthy());++ fireEvent.click(screen.getByText("Install"));++ await waitFor(() => expect(onInstalled).toHaveBeenCalledWith("todo-fox"));+ expect(onClose).toHaveBeenCalled();+ });+});diff --git a/jarvis/ui/web/frontend/src/views/PluginUploadDialog.tsx b/jarvis/ui/web/frontend/src/views/PluginUploadDialog.tsxnew file mode 100644index 0000000000..306fc9ad59--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/PluginUploadDialog.tsx@@ -0,0 +1,265 @@+import { useCallback, useEffect, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { AlertTriangle, Check, Loader2, Plug, Upload, X } from "lucide-react";+import { Button } from "@/components/ui/button";+import { ScrollArea } from "@/components/ui/scroll-area";+import { UploadDropzone, useUploadInputs } from "@/components/UploadDropzone";+import { useT } from "@/i18n";+import { collectDroppedFiles, formatBytes, type PickedFile } from "@/lib/filePicking";+import {+ inspectPluginUpload,+ uploadPlugin,+ type PluginUploadReport,+} from "@/lib/pluginUpload";++/**+ * Bringing your own plugin in.+ *+ * Shorter than the skill flow, because a plugin here is a *manifest* rather+ * than a code package: a `plugin.json`, optionally with an `mcp.json` beside+ * it. There is no folder of code to review, so the preview shows what the+ * catalog card will say — name, category, and above all which authentication+ * mode the plugin will ask you for.+ *+ * The one thing it must not do is imply a review that never happened. An+ * uploaded plugin carries no publisher and no source URL, because there is+ * nothing here to vouch for either — and the dialog says so before the yes.+ */+export function PluginUploadDialog({+ open,+ onClose,+ onInstalled,+}: {+ open: boolean;+ onClose: () => void;+ onInstalled?: (id: string) => void;+}) {+ const t = useT();+ const qc = useQueryClient();+ const [picked, setPicked] = useState<PickedFile[]>([]);+ const [report, setReport] = useState<PluginUploadReport | null>(null);+ const [inspecting, setInspecting] = useState(false);+ const [installing, setInstalling] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [dragging, setDragging] = useState(false);++ const reset = useCallback(() => {+ setPicked([]);+ setReport(null);+ setInspecting(false);+ setInstalling(false);+ setError(null);+ setDragging(false);+ }, []);++ useEffect(() => {+ if (!open) reset();+ }, [open, reset]);++ const inspect = useCallback(async (files: PickedFile[]) => {+ setPicked(files);+ setReport(null);+ setError(null);+ if (files.length === 0) return;+ setInspecting(true);+ try {+ setReport(await inspectPluginUpload(files));+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setInspecting(false);+ }+ }, []);++ const { inputs, openFolder, openArchive } = useUploadInputs(+ (files) => void inspect(files),+ "plugin",+ );++ const install = async () => {+ if (picked.length === 0) return;+ setInstalling(true);+ setError(null);+ try {+ const result = await uploadPlugin(picked);+ await qc.invalidateQueries({ queryKey: ["marketplace", "plugins"] });+ onInstalled?.(result.plugin.id);+ onClose();+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setInstalling(false);+ }+ };++ if (!open) return null;++ // A short state, not the reason. The reason is already on screen in red,+ // right above this line — repeating it verbatim reads as two problems.+ const blocker =+ picked.length === 0+ ? t("plugin_upload.blocker_no_files")+ : report+ ? report.problems.length > 0+ ? t("plugin_upload.blocked")+ : t("plugin_upload.ready")+ : "";++ return (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-scrim/60 p-6"+ onDragOver={(event) => {+ event.preventDefault();+ setDragging(true);+ }}+ onDragLeave={() => setDragging(false)}+ onDrop={(event) => {+ event.preventDefault();+ setDragging(false);+ void collectDroppedFiles(event.dataTransfer).then(inspect);+ }}+ >+ <div className="flex max-h-full w-[640px] flex-col overflow-hidden rounded-lg border border-border bg-card shadow-xl">+ <header className="flex items-start justify-between gap-4 border-b border-border px-6 py-4">+ <div>+ <h3 className="flex items-center gap-2 text-base font-semibold">+ <Upload className="h-4 w-4 text-primary" />+ {t("plugin_upload.title")}+ </h3>+ <p className="mt-1 text-sm text-muted-foreground">+ {t("plugin_upload.subtitle")}+ </p>+ </div>+ <Button size="sm" variant="ghost" onClick={onClose} aria-label={t("common.cancel")}>+ <X className="h-4 w-4" />+ </Button>+ </header>++ <ScrollArea className="min-h-0 flex-1">+ <div className="flex flex-col gap-4 px-6 py-5">+ {inputs}++ {picked.length === 0 ? (+ <UploadDropzone+ dragging={dragging}+ title={t("plugin_upload.drop_title")}+ hint={t("plugin_upload.drop_hint")}+ folderLabel={t("plugin_upload.choose_folder")}+ archiveLabel={t("plugin_upload.choose_archive")}+ onChooseFolder={openFolder}+ onChooseArchive={openArchive}+ />+ ) : inspecting || !report ? (+ <div className="flex items-center gap-2 rounded-lg border border-border bg-muted/20 px-4 py-6 text-sm text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin" />+ {t("plugin_upload.inspecting")}+ </div>+ ) : (+ <>+ <div className="flex items-start justify-between gap-4 rounded-lg border border-border bg-muted/20 px-4 py-3">+ <div className="min-w-0">+ {report.plugin ? (+ <>+ <p className="flex items-center gap-1.5 truncate text-sm font-semibold">+ <Plug className="h-3.5 w-3.5 shrink-0 text-primary" />+ {report.plugin.display_name}+ </p>+ <p className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">+ {report.plugin.description}+ </p>+ <p className="mt-1.5 text-[11px] text-muted-foreground">+ {`${report.plugin.category} · ${t("plugin_upload.auth_mode")}: ${report.plugin.auth_mode}`}+ {report.has_mcp ? ` · ${t("plugin_upload.with_mcp")}` : ""}+ </p>+ </>+ ) : (+ <p className="text-sm font-medium text-muted-foreground">+ {t("plugin_upload.no_plugin_detected")}+ </p>+ )}+ <p className="mt-1.5 text-[11px] text-muted-foreground">+ {`${report.files.length} ${t("plugin_upload.files")} · ${formatBytes(report.total_bytes)}`}+ </p>+ </div>+ <div className="flex shrink-0 items-center gap-1">+ <Button size="sm" variant="outline" onClick={openFolder}>+ {t("plugin_upload.replace")}+ </Button>+ <Button size="sm" variant="ghost" onClick={() => void inspect([])}>+ {t("plugin_upload.clear")}+ </Button>+ </div>+ </div>++ {report.files.length > 0 && (+ <div className="max-h-[180px] overflow-y-auto rounded-lg border border-border bg-background">+ <ul className="flex flex-col gap-0.5 p-2">+ {report.files.map((path) => (+ <li+ key={path}+ className="truncate rounded px-2 py-1 font-mono text-[11px] text-muted-foreground"+ title={path}+ >+ {path}+ </li>+ ))}+ </ul>+ </div>+ )}++ {report.problems.map((problem) => (+ <p+ key={problem}+ role="alert"+ className="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive"+ >+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ {problem}+ </p>+ ))}++ {report.ready && (+ // Said before the yes, not discovered after it: nobody+ // vouched for this entry, and the card will show no+ // publisher because there is none to show.+ <p className="rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">+ {t("plugin_upload.unreviewed")}+ </p>+ )}+ </>+ )}++ {error && (+ <p className="flex items-start gap-2 text-sm text-destructive" role="alert">+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ {error}+ </p>+ )}+ </div>+ </ScrollArea>++ <footer className="flex items-center justify-between gap-4 border-t border-border px-6 py-4">+ <p className="min-w-0 text-xs text-muted-foreground">{blocker}</p>+ <div className="flex shrink-0 items-center gap-2">+ <Button size="sm" variant="ghost" onClick={onClose}>+ {t("common.cancel")}+ </Button>+ <Button+ size="sm"+ onClick={() => void install()}+ disabled={!report?.ready || installing || inspecting}+ className="gap-1.5"+ >+ {installing ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Check className="h-3.5 w-3.5" />+ )}+ {t("plugin_upload.install")}+ </Button>+ </div>+ </footer>+ </div>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx b/jarvis/ui/web/frontend/src/views/PluginsView.test.tsxindex 7a5646b6a7..722606bae3 100644--- a/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx@@ -792,6 +792,7 @@ describe("plugin search matches more than the display name", () => {longevity: "permanent",oauthClientConfigured: false,fromMarketplace: false,+ selfUploaded: false,...extra,});@@ -857,6 +858,7 @@ describe("plugin status filter", () => {longevity: "permanent",oauthClientConfigured: false,fromMarketplace: false,+ selfUploaded: false,});it("lets everything through on 'all'", () => {diff --git a/jarvis/ui/web/frontend/src/views/PluginsView.tsx b/jarvis/ui/web/frontend/src/views/PluginsView.tsxindex e627299374..20d29d7685 100644--- a/jarvis/ui/web/frontend/src/views/PluginsView.tsx+++ b/jarvis/ui/web/frontend/src/views/PluginsView.tsx@@ -20,9 +20,12 @@ import {X,Loader2,AlertTriangle,+ Upload,} from "lucide-react";import { ViewHeader } from "@/views/ChatsView";import { CommunityTab } from "@/views/PluginsCommunity";+import { PluginUploadDialog } from "@/views/PluginUploadDialog";+import { translate } from "@/i18n";import { ScrollArea } from "@/components/ui/scroll-area";import { Button } from "@/components/ui/button";import { BrandedSelect } from "@/components/ui/select";@@ -215,6 +218,8 @@ export interface Plugin {oauthClientConfigured: boolean;/** True for a plugin installed from the community marketplace. */fromMarketplace: boolean;+ /** True for a plugin the owner uploaded here — no registry, no review. */+ selfUploaded: boolean;publisher?: string;sourceUrl?: string;}@@ -240,6 +245,7 @@ function adapt(p: CatalogPlugin): Plugin {reauthAt: p.reauth_at ?? undefined,oauthClientConfigured: p.oauth_client_configured ?? false,fromMarketplace: p.source === "community",+ selfUploaded: p.source === "local",publisher: p.publisher ?? undefined,sourceUrl: p.source_url ?? undefined,};@@ -439,6 +445,7 @@ export function matchesStatus(plugin: Plugin, status: StatusFilterId): boolean {export function PluginsView() {const qc = useQueryClient();const [tab, setTab] = useState<TabId>("browse");+ const [uploadOpen, setUploadOpen] = useState(false);const [query, setQuery] = useState("");const [filter, setFilter] = useState<FilterId>("all");const [statusFilter, setStatusFilter] = useState<StatusFilterId>("all");@@ -770,18 +777,38 @@ export function PluginsView() {}`}right={- <Button- size="sm"- variant="ghost"- onClick={() => refetch()}- disabled={isFetching}- title="Refresh catalog"- >- <RefreshCw className={cn("h-3.5 w-3.5", isFetching && "animate-spin")} />- </Button>+ <div className="flex items-center gap-1">+ <Button+ size="sm"+ variant="outline"+ onClick={() => setUploadOpen(true)}+ className="gap-1.5"+ >+ <Upload className="h-3.5 w-3.5" />+ {translate("plugin_upload.button")}+ </Button>+ <Button+ size="sm"+ variant="ghost"+ onClick={() => refetch()}+ disabled={isFetching}+ title="Refresh catalog"+ >+ <RefreshCw className={cn("h-3.5 w-3.5", isFetching && "animate-spin")} />+ </Button>+ </div>}/>+ <PluginUploadDialog+ open={uploadOpen}+ onClose={() => setUploadOpen(false)}+ onInstalled={() => {+ setTab("installed");+ void refetch();+ }}+ />+<div className="flex items-center gap-6 border-b border-border px-6"><Tablabel="Browse"@@ -1649,6 +1676,19 @@ function PluginRow({{plugin.fromMarketplace && (<MarketplaceBadge publisher={plugin.publisher} />)}+ {plugin.selfUploaded && (+ // Without this a plugin the owner dropped in themselves would+ // read exactly like one the app ships — same card, same absence+ // of a badge. The mark is what keeps "reviewed by nobody"+ // visible after the install dialog is long gone.+ <span+ title={translate("plugin_upload.unreviewed")}+ className="inline-flex shrink-0 items-center gap-1 rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-amber-700 dark:text-amber-300"+ >+ <Upload className="h-3 w-3" aria-hidden />+ {translate("plugin_upload.self_badge")}+ </span>+ )}</div>{needsReauth ? (<ReauthExplanation plugin={plugin} />diff --git a/jarvis/ui/web/frontend/src/views/SkillUploadDialog.test.tsx b/jarvis/ui/web/frontend/src/views/SkillUploadDialog.test.tsxindex 9bb9a72b4d..a507522944 100644--- a/jarvis/ui/web/frontend/src/views/SkillUploadDialog.test.tsx+++ b/jarvis/ui/web/frontend/src/views/SkillUploadDialog.test.tsx@@ -133,7 +133,7 @@ describe("SkillUploadDialog", () => {pickFolder([skillFile("my-skill/SKILL.md")]);await waitFor(() =>- expect(screen.getAllByText("Skill 'my-skill' already exists.").length).toBeGreaterThan(0),+ expect(screen.getByText("Skill 'my-skill' already exists.")).toBeTruthy(),);expect(screen.getByText("Install").closest("button")?.disabled).toBe(true);});diff --git a/jarvis/ui/web/frontend/src/views/SkillUploadDialog.tsx b/jarvis/ui/web/frontend/src/views/SkillUploadDialog.tsxindex 210b62d387..5ef8132ba6 100644--- a/jarvis/ui/web/frontend/src/views/SkillUploadDialog.tsx+++ b/jarvis/ui/web/frontend/src/views/SkillUploadDialog.tsx@@ -1,11 +1,10 @@-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useState } from "react";import { useQueryClient } from "@tanstack/react-query";import {AlertTriangle,ArrowLeft,ArrowRight,Check,- FileArchive,FolderOpen,Link2,Loader2,@@ -15,15 +14,11 @@ import {} from "lucide-react";import { Button } from "@/components/ui/button";import { ScrollArea } from "@/components/ui/scroll-area";+import { UploadDropzone, useUploadInputs } from "@/components/UploadDropzone";import { cn } from "@/lib/utils";import { useT } from "@/i18n";import { useImportSkill } from "@/hooks/useSkills";-import {- collectDroppedFiles,- filesFromInput,- formatBytes,- type PickedFile,-} from "@/lib/filePicking";+import { collectDroppedFiles, formatBytes, type PickedFile } from "@/lib/filePicking";import {inspectSkillUpload,uploadSkill,@@ -70,8 +65,6 @@ export function SkillUploadDialog({const [error, setError] = useState<string | null>(null);const [dragging, setDragging] = useState(false);const [link, setLink] = useState("");- const folderInput = useRef<HTMLInputElement | null>(null);- const archiveInput = useRef<HTMLInputElement | null>(null);const importFromLink = useImportSkill();const reset = useCallback(() => {@@ -89,16 +82,6 @@ export function SkillUploadDialog({if (!open) reset();}, [open, reset]);- // `webkitdirectory` has to be set through a ref: React does not know the- // attribute, and writing it into JSX drops it silently.- const setFolderInput = (node: HTMLInputElement | null) => {- folderInput.current = node;- if (node) {- node.setAttribute("webkitdirectory", "");- node.setAttribute("directory", "");- }- };-const inspect = useCallback(async (files: PickedFile[]) => {setPicked(files);@@ -117,6 +100,11 @@ export function SkillUploadDialog({[],);+ const { inputs, openFolder, openArchive } = useUploadInputs(+ (files) => void inspect(files),+ "skill",+ );+const onDrop = (event: React.DragEvent) => {event.preventDefault();setDragging(false);@@ -207,66 +195,24 @@ export function SkillUploadDialog({<div className="flex flex-col gap-4"><BackLink label={t("skill_upload.back")} onClick={reset} />- <input- ref={setFolderInput}- type="file"- multiple- className="sr-only"- data-testid="skill-folder-input"- onChange={(event) => void inspect(filesFromInput(event.target.files))}- />- <input- ref={archiveInput}- type="file"- accept=".zip,.tgz,.tar.gz"- className="sr-only"- data-testid="skill-archive-input"- onChange={(event) => void inspect(filesFromInput(event.target.files))}- />+ {inputs}{picked.length === 0 ? (- <div- className={cn(- "flex flex-col items-center gap-3 rounded-lg border-2 border-dashed px-6 py-10 text-center transition-colors",- dragging- ? "border-primary bg-primary/5"- : "border-border bg-muted/20",- )}- >- <Upload className="h-5 w-5 text-muted-foreground" />- <div>- <p className="text-sm font-medium">{t("skill_upload.drop_title")}</p>- <p className="mt-1 text-xs text-muted-foreground">- {t("skill_upload.drop_hint")}- </p>- </div>- <div className="mt-1 flex items-center gap-2">- <Button- size="sm"- variant="outline"- onClick={() => folderInput.current?.click()}- className="gap-1.5"- >- <FolderOpen className="h-3.5 w-3.5" />- {t("skill_upload.choose_folder")}- </Button>- <Button- size="sm"- variant="ghost"- onClick={() => archiveInput.current?.click()}- className="gap-1.5"- >- <FileArchive className="h-3.5 w-3.5" />- {t("skill_upload.choose_archive")}- </Button>- </div>- </div>+ <UploadDropzone+ dragging={dragging}+ title={t("skill_upload.drop_title")}+ hint={t("skill_upload.drop_hint")}+ folderLabel={t("skill_upload.choose_folder")}+ archiveLabel={t("skill_upload.choose_archive")}+ onChooseFolder={openFolder}+ onChooseArchive={openArchive}+ />) : (<UploadReportreport={report}inspecting={inspecting}fileCount={picked.length}- onReplace={() => folderInput.current?.click()}+ onReplace={openFolder}onClear={() => void inspect([])}/>)}@@ -351,7 +297,13 @@ export function SkillUploadDialog({);}-/** What is stopping the install, in one sentence — or what will happen. */+/**+ * Where the install stands, in one line.+ *+ * A short state, not the reason: when something blocks, the reason is already+ * on screen in red right above this line, and repeating it verbatim reads as+ * two separate problems.+ */function describeBlocker(report: SkillUploadReport | null,fileCount: number,@@ -359,7 +311,7 @@ function describeBlocker(): string {if (fileCount === 0) return t("skill_upload.blocker_no_files");if (!report) return "";- if (report.problems.length > 0) return report.problems[0];+ if (report.problems.length > 0) return t("skill_upload.blocked");if (report.lint_findings.length > 0) return t("skill_upload.will_land_as_draft");return t("skill_upload.ready");}diff --git a/jarvis/ui/web/marketplace_routes.py b/jarvis/ui/web/marketplace_routes.pyindex 0d764facc9..75e9679b9a 100644--- a/jarvis/ui/web/marketplace_routes.py+++ b/jarvis/ui/web/marketplace_routes.py@@ -12,6 +12,8 @@ Endpoints:POST /api/marketplace/community/install/{id} — install by name (any kind)POST /api/marketplace/community/plugins/{id}/install — one-click installDELETE /api/marketplace/community/plugins/{id} — uninstall + revoke+ POST /api/marketplace/plugins/upload/inspect — read a dropped manifest+ POST /api/marketplace/plugins/upload — install a dropped manifest"""from __future__ import annotations@@ -26,11 +28,21 @@ from pathlib import Pathfrom typing import Anyimport httpx-from fastapi import APIRouter, BackgroundTasks, HTTPException, Request, Response+from fastapi import (+ APIRouter,+ BackgroundTasks,+ File,+ Form,+ HTTPException,+ Request,+ Response,+ UploadFile,+)from fastapi.responses import HTMLResponsefrom pydantic import BaseModel, Fieldfrom jarvis.core.process_utils import resolve_executable+from jarvis.core.uploads import UploadRejected, stage_uploadfrom jarvis.marketplace.auth import (DcrConfig,DeviceFlowConfig,@@ -61,6 +73,11 @@ from jarvis.marketplace.telegram_connect import (on_telegram_disconnected,)from jarvis.marketplace.token_store import Tokens, TokenStore+from jarvis.ui.web.upload_intake import (+ read_upload_entries,+ upload_http_error,+ upload_limits,+)# Marketplace plugin ids whose "connect" enables an in-repo bidirectional chat# channel (token + config), not just a stored token. Kept in sync with the@@ -1412,3 +1429,213 @@ async def community_uninstall(plugin_id: str) -> dict[str, Any]:log.info("plugin %s revocation skipped: %s", plugin_id, exc)revocation = "failed"return {"ok": True, "removed": removed, "revocation": revocation}+# ----------------------------------------------------------------------+# Upload — a plugin manifest dropped onto the UI+# ----------------------------------------------------------------------++#: What ``source`` a self-uploaded plugin carries. Deliberately not+#: "community": it never passed through the registry, so claiming that origin+#: would put a badge on the card naming a review nobody did.+LOCAL_PLUGIN_SOURCE = "local"++_MANIFEST_NAMES = {"plugin.json": "plugin", "mcp.json": "mcp"}+++def _locate_plugin_manifests(staged_root: Path) -> dict[str, Path]:+ """Finds ``plugin.json`` (and its optional ``mcp.json``) in a staged upload.++ A plugin here is a manifest, not a code package, so the upload may be a+ bare pair of files, a folder holding them, or a repository ZIP with them a+ few levels down. A single ``plugin.json`` anywhere names the plugin; more+ than one means the upload holds a catalog, which is refused with the paths+ listed rather than guessed at.+ """+ found: dict[str, list[Path]] = {"plugin": [], "mcp": []}+ for path in sorted(staged_root.rglob("*")):+ if not path.is_file():+ continue+ kind = _MANIFEST_NAMES.get(path.name.lower())+ if kind:+ found[kind].append(path)++ if not found["plugin"]:+ raise HTTPException(status_code=400, detail="No plugin.json found in the upload.")+ if len(found["plugin"]) > 1:+ listed = ", ".join(+ str(path.relative_to(staged_root)).replace("\\", "/")+ for path in found["plugin"][:5]+ )+ suffix = ", ..." if len(found["plugin"]) > 5 else ""+ raise HTTPException(+ status_code=400,+ detail=(+ f"The upload holds {len(found['plugin'])} plugins "+ f"({listed}{suffix}). Upload one plugin at a time."+ ),+ )++ manifest = found["plugin"][0]+ out = {"plugin": manifest}+ # Only an mcp.json sitting BESIDE the manifest belongs to it. One from a+ # different folder would silently graft another plugin's server onto this+ # one — the kind of mix-up that shows up much later as a wrong tool call.+ sibling = manifest.parent / "mcp.json"+ for candidate in found["mcp"]:+ if candidate == sibling:+ out["mcp"] = candidate+ break+ return out+++def _read_manifest(path: Path) -> dict[str, Any]:+ try:+ parsed = json.loads(path.read_text(encoding="utf-8-sig"))+ except (OSError, ValueError) as exc:+ raise HTTPException(+ status_code=400, detail=f"{path.name} could not be read: {exc}"+ ) from exc+ if not isinstance(parsed, dict):+ raise HTTPException(status_code=400, detail=f"{path.name} must be a JSON object.")+ return parsed+++def _describe_staged_plugin(staged_root: Path) -> dict[str, Any]:+ """What this upload would install — validated, but nothing written.++ Returns collision problems instead of raising, so the dialog can show+ every blocker at once. A manifest that does not convert at all is a+ different matter: there is nothing left to describe, so it comes back as+ the single problem it is.+ """+ from jarvis.marketplace.agent_plugins_loader import AgentPluginError, convert_manifest+ from jarvis.marketplace.community_install import seed_plugin_ids++ manifests = _locate_plugin_manifests(staged_root)+ plugin_json = _read_manifest(manifests["plugin"])+ mcp_json = _read_manifest(manifests["mcp"]) if "mcp" in manifests else None++ try:+ # publisher/version/source_url stay unset on purpose. On the community+ # path they come from the registry index so a manifest cannot claim+ # someone else's identity; a local upload has no such witness, and+ # letting the file name its own publisher would invent exactly the+ # authority that check exists to deny.+ spec = convert_manifest(plugin_json, mcp_json)+ except AgentPluginError as exc:+ return {+ "plugin": None,+ "problems": [str(exc)],+ "has_mcp": mcp_json is not None,+ "ready": False,+ }++ problems: list[str] = []+ if spec.id in seed_plugin_ids():+ problems.append(f"'{spec.id}' is a built-in plugin id and cannot be uploaded.")+ else:+ existing = load_catalog().by_id(spec.id)+ if existing is not None and existing.source not in (+ "community",+ LOCAL_PLUGIN_SOURCE,+ ):+ problems.append(f"'{spec.id}' already exists in the local catalog.")++ return {+ "plugin": {+ "id": spec.id,+ "display_name": spec.display_name,+ "description": spec.description,+ "category": spec.category,+ "auth_mode": spec.auth.mode,+ "longevity": spec.longevity,+ },+ "problems": problems,+ "has_mcp": mcp_json is not None,+ "ready": not problems,+ }++[email protected]("/plugins/upload/inspect", openapi_extra={"x-jarvis-readonly": True})+async def inspect_plugin_upload(+ files: list[UploadFile] = File(...), # noqa: B008 — FastAPI dependency default+ paths: str | None = Form(default=None), # noqa: B008 — same+) -> dict[str, Any]:+ """Reports what a dropped plugin manifest holds, without installing it."""+ import tempfile++ entries = await read_upload_entries(files, paths)++ def _work() -> dict[str, Any]:+ with tempfile.TemporaryDirectory(prefix="jarvis-plugin-inspect-") as tmp:+ try:+ staged = stage_upload(entries, Path(tmp) / "plugin")+ except UploadRejected as exc:+ raise upload_http_error(exc) from exc+ described = _describe_staged_plugin(staged.root)+ described["files"] = list(staged.files)+ described["ignored"] = list(staged.ignored)+ described["stripped_root"] = staged.stripped_root+ described["total_bytes"] = staged.total_bytes+ described["limits"] = upload_limits()+ return described++ return await asyncio.to_thread(_work)++[email protected]("/plugins/upload")+async def upload_plugin(+ files: list[UploadFile] = File(...), # noqa: B008 — FastAPI dependency default+ paths: str | None = Form(default=None), # noqa: B008 — same+) -> dict[str, Any]:+ """Installs a plugin manifest dropped onto the UI.++ The entry lands in the same override catalog a community install writes+ to, so afterwards it behaves like any other plugin — connect flows,+ relevance gate, worker bridge. What differs is its ``source``, which stays+ honest about where it came from: this machine, reviewed by nobody.+ """+ import tempfile++ from jarvis.marketplace.agent_plugins_loader import AgentPluginError, convert_manifest+ from jarvis.marketplace.community_install import install_plugin_spec++ entries = await read_upload_entries(files, paths)++ def _work() -> dict[str, Any]:+ with tempfile.TemporaryDirectory(prefix="jarvis-plugin-upload-") as tmp:+ try:+ staged = stage_upload(entries, Path(tmp) / "plugin")+ except UploadRejected as exc:+ raise upload_http_error(exc) from exc++ described = _describe_staged_plugin(staged.root)+ if not described["ready"]:+ # A collision is a 409; a manifest that never converted is a+ # 400 — the client can tell "yours is fine but taken" from+ # "yours does not parse" without reading the sentence.+ raise HTTPException(+ status_code=409 if described["plugin"] else 400,+ detail=described["problems"][0],+ )++ manifests = _locate_plugin_manifests(staged.root)+ plugin_json = _read_manifest(manifests["plugin"])+ mcp_json = _read_manifest(manifests["mcp"]) if "mcp" in manifests else None+ try:+ spec = convert_manifest(plugin_json, mcp_json)+ except AgentPluginError as exc: # already validated — belt and braces+ raise HTTPException(status_code=400, detail=str(exc)) from exc++ spec = spec.model_copy(update={"source": LOCAL_PLUGIN_SOURCE})+ try:+ install_plugin_spec(spec)+ except RuntimeError as exc:+ raise HTTPException(status_code=500, detail=str(exc)) from exc+ return {"spec": spec, "upload": staged.to_json()}++ result = await asyncio.to_thread(_work)+ spec = result["spec"]+ _refresh_plugin_in_live_registry(spec.id)+ item = spec.model_dump(mode="json")+ item["status"] = "not_connected"+ return {"ok": True, "plugin": item, "upload": result["upload"]}diff --git a/tests/unit/marketplace/test_plugin_upload_route.py b/tests/unit/marketplace/test_plugin_upload_route.pynew file mode 100644index 0000000000..8b3aa03053--- /dev/null+++ b/tests/unit/marketplace/test_plugin_upload_route.py@@ -0,0 +1,299 @@+"""``POST /api/marketplace/plugins/upload`` — dropping your own plugin in.++A plugin here is a *manifest*, not a code package: `plugin.json` plus an+optional `mcp.json` beside it. That makes the upload flow shorter than the+skill one but adds a question the skill flow never faces — who published this?++On the community path the answer comes from the registry index, precisely so a+manifest cannot claim someone else's identity. A local upload has no such+witness. These tests pin that the route does not invent one: no publisher, no+version, no source URL, and a `source` that says "local" rather than borrowing+the community badge and the review it implies.+"""+from __future__ import annotations++import io+import json+import zipfile+from pathlib import Path++import pytest+from fastapi import HTTPException, UploadFile++from jarvis.marketplace.agent_plugins_loader import EXTENSION_NAMESPACE+from jarvis.ui.web import marketplace_routes as routes+++def _plugin_json(name: str = "todo-fox") -> dict:+ return {+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",+ "name": name,+ "description": "Tasks and reminders from TodoFox",+ "version": "1.2.0",+ "license": "MIT",+ "extensions": {+ EXTENSION_NAMESPACE: {+ "display_name": "TodoFox",+ "category": "Lists & Tasks",+ "logo_slug": "todofox",+ "auth": {+ "mode": "pat_paste",+ "token_creation_url": "https://todofox.example/settings/tokens",+ "token_prefix": "tfx_",+ "validation_endpoint": "https://api.todofox.example/v1/me",+ "instruction_md": "Create a token in Settings.",+ },+ "mcp_auth_header_template": (+ "Authorization: Bearer ${plugin_todo-fox_access_token}"+ ),+ }+ },+ }+++def _mcp_json() -> dict:+ return {+ "mcpServers": {+ "todo-fox": {+ "type": "streamable-http",+ "url": "https://mcp.todofox.example/mcp",+ }+ }+ }+++def _upload(path: str, data: bytes) -> UploadFile:+ return UploadFile(filename=Path(path).name, file=io.BytesIO(data))+++def _parts(entries: dict[str, bytes]) -> tuple[list[UploadFile], str]:+ files = [_upload(path, data) for path, data in entries.items()]+ return files, json.dumps(list(entries))+++def _blob(payload: dict) -> bytes:+ return json.dumps(payload).encode("utf-8")+++def _zip_bytes(entries: dict[str, bytes]) -> bytes:+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:+ for path, data in entries.items():+ archive.writestr(path, data)+ return buffer.getvalue()+++def installed(monkeypatch: pytest.MonkeyPatch) -> list:+ """Captures what would be written, so nothing touches the real catalog."""+ saved: list = []+ monkeypatch.setattr(+ "jarvis.marketplace.community_install.install_plugin_spec",+ lambda spec: saved.append(spec),+ )+ monkeypatch.setattr(routes, "_refresh_plugin_in_live_registry", lambda plugin_id: None)+ return saved+++# ----------------------------------------------------------------------+# Installing+# ----------------------------------------------------------------------++async def test_a_dropped_manifest_is_installed(installed: list) -> None:+ files, paths = _parts({"plugin.json": _blob(_plugin_json())})++ result = await routes.upload_plugin(files, paths)++ assert result["ok"] is True+ assert result["plugin"]["id"] == "todo-fox"+ assert result["plugin"]["status"] == "not_connected"+ assert [spec.id for spec in installed] == ["todo-fox"]+++async def test_the_upload_claims_no_publisher_it_cannot_prove(installed: list) -> None:+ """The whole reason the community path takes identity from the index."""+ files, paths = _parts({"plugin.json": _blob(_plugin_json())})++ await routes.upload_plugin(files, paths)++ spec = installed[0]+ assert spec.source == "local"+ assert spec.publisher is None+ assert spec.source_url is None+++async def test_an_mcp_json_beside_the_manifest_travels_with_it(installed: list) -> None:+ files, paths = _parts(+ {+ "todo-fox/plugin.json": _blob(_plugin_json()),+ "todo-fox/mcp.json": _blob(_mcp_json()),+ }+ )++ await routes.upload_plugin(files, paths)++ assert installed[0].mcp_server is not None+++async def test_an_mcp_json_from_another_folder_is_not_grafted_on(+ installed: list,+) -> None:+ """A stray server from elsewhere in the tree must not attach itself."""+ files, paths = _parts(+ {+ "plugins/todo-fox/plugin.json": _blob(_plugin_json()),+ "plugins/other-thing/mcp.json": _blob(_mcp_json()),+ }+ )++ await routes.upload_plugin(files, paths)++ assert installed[0].mcp_server is None+++async def test_a_manifest_buried_in_a_repository_zip_is_found(installed: list) -> None:+ archive = _zip_bytes(+ {+ "repo-main/README.md": b"# repo",+ "repo-main/plugins/todo-fox/plugin.json": _blob(_plugin_json()),+ }+ )++ result = await routes.upload_plugin([_upload("repo.zip", archive)], None)++ assert result["plugin"]["id"] == "todo-fox"+++# ----------------------------------------------------------------------+# Refusing+# ----------------------------------------------------------------------++async def test_an_upload_without_a_manifest_is_a_400(installed: list) -> None:+ files, paths = _parts({"readme.md": b"no manifest here"})++ with pytest.raises(HTTPException) as exc:+ await routes.upload_plugin(files, paths)+ assert exc.value.status_code == 400+ assert "plugin.json" in exc.value.detail+ assert installed == []+++async def test_an_upload_holding_several_plugins_is_refused_by_name(+ installed: list,+) -> None:+ archive = _zip_bytes(+ {+ "catalog/one/plugin.json": _blob(_plugin_json("one-fox")),+ "catalog/two/plugin.json": _blob(_plugin_json("two-fox")),+ }+ )++ with pytest.raises(HTTPException) as exc:+ await routes.upload_plugin([_upload("catalog.zip", archive)], None)+ assert exc.value.status_code == 400+ assert "2 plugins" in exc.value.detail+ assert installed == []+++async def test_a_manifest_that_does_not_convert_is_a_400(installed: list) -> None:+ """No Jarvis auth block — the manifest is not one we can install."""+ broken = _plugin_json()+ broken["extensions"] = {}+ files, paths = _parts({"plugin.json": _blob(broken)})++ with pytest.raises(HTTPException) as exc:+ await routes.upload_plugin(files, paths)+ assert exc.value.status_code == 400+ assert installed == []+++async def test_a_built_in_plugin_id_is_refused(+ installed: list, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(+ "jarvis.marketplace.community_install.seed_plugin_ids",+ lambda: frozenset({"todo-fox"}),+ )+ files, paths = _parts({"plugin.json": _blob(_plugin_json())})++ with pytest.raises(HTTPException) as exc:+ await routes.upload_plugin(files, paths)+ assert exc.value.status_code == 409+ assert "built-in" in exc.value.detail+ assert installed == []+++async def test_broken_json_is_refused_with_the_file_named(installed: list) -> None:+ files, paths = _parts({"plugin.json": b"{not json"})++ with pytest.raises(HTTPException) as exc:+ await routes.upload_plugin(files, paths)+ assert exc.value.status_code == 400+ assert "plugin.json" in exc.value.detail+++async def test_a_zip_that_walks_out_of_the_folder_is_refused(+ installed: list, tmp_path: Path+) -> None:+ archive = _zip_bytes(+ {"plugin.json": _blob(_plugin_json()), "../../escaped.json": b"evil"}+ )++ with pytest.raises(HTTPException) as exc:+ await routes.upload_plugin([_upload("evil.zip", archive)], None)+ assert exc.value.status_code == 400+ assert installed == []+++# ----------------------------------------------------------------------+# Inspecting+# ----------------------------------------------------------------------++async def test_inspect_reports_the_plugin_without_installing_it(+ installed: list,+) -> None:+ files, paths = _parts(+ {+ "todo-fox/plugin.json": _blob(_plugin_json()),+ "todo-fox/mcp.json": _blob(_mcp_json()),+ "todo-fox/.DS_Store": b"junk",+ }+ )++ report = await routes.inspect_plugin_upload(files, paths)++ assert report["ready"] is True+ assert report["problems"] == []+ assert report["plugin"]["id"] == "todo-fox"+ assert report["plugin"]["display_name"] == "TodoFox"+ assert report["plugin"]["auth_mode"] == "pat_paste"+ assert report["has_mcp"] is True+ assert set(report["files"]) == {"plugin.json", "mcp.json"}+ assert report["ignored"] == [".DS_Store"]+ assert installed == []+++async def test_inspect_reports_a_bad_manifest_as_a_problem(installed: list) -> None:+ """The dialog shows the reason instead of dying on an exception."""+ broken = _plugin_json()+ broken["extensions"] = {}+ files, paths = _parts({"plugin.json": _blob(broken)})++ report = await routes.inspect_plugin_upload(files, paths)++ assert report["ready"] is False+ assert report["plugin"] is None+ assert report["problems"]