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 wallpapers, and record where an install came from
Harald81c512cf1f40
diff --git a/jarvis/marketplace/community_source.py b/jarvis/marketplace/community_source.pyindex a24b1757e5..c1e5362d07 100644--- a/jarvis/marketplace/community_source.py+++ b/jarvis/marketplace/community_source.py@@ -96,11 +96,48 @@ class CommunitySkillEntry(_Tolerant):return value+class CommunityWallpaperEntry(_Tolerant):+ """One installable wallpaper.++ A wallpaper is the simplest thing the registry publishes: a picture and a+ name. It carries no code, no credentials, and no manifest — installing one+ downloads an image, re-encodes it, and drops it next to the owner's own+ uploads, so it can never be more dangerous than a file the owner dragged+ in themselves.+ """++ name: str+ title: str | None = None+ description: str = ""+ publisher: str | None = None+ version: str | None = None+ published_at: str | None = None+ categories: list[str] = Field(default_factory=list)+ source_url: str | None = None+ # Direct download of the image itself.+ raw_url: str | None = None+ # Light/dark hint from the publisher. Only a hint: the server re-derives+ # the theme from the actual pixels, exactly as it does for an upload, so a+ # wrong or absent value costs nothing.+ theme: str | None = None++ @field_validator("raw_url")+ @classmethod+ def _https_only(cls, value: str | None) -> str | None:+ # Same reasoning as the skill raw_url above: the backend fetches this+ # server-side, so anything but https is an SSRF vector.+ if value is not None and not value.lower().startswith("https://"):+ logger.warning("community index: dropping non-https wallpaper raw_url %r", value)+ return None+ return value++class CommunityIndex(_Tolerant):revision: int = 0generated_at: str | None = Noneplugins: list[CommunityPluginEntry] = Field(default_factory=list)skills: list[CommunitySkillEntry] = Field(default_factory=list)+ wallpapers: list[CommunityWallpaperEntry] = Field(default_factory=list)@field_validator("skills", mode="after")@classmethod@@ -117,6 +154,25 @@ class CommunityIndex(_Tolerant):logger.warning("community index: dropping skill with unsafe name %r", entry.name)return kept+ @field_validator("wallpapers", mode="after")+ @classmethod+ def _drop_unsafe_wallpaper_names(+ cls, value: list[CommunityWallpaperEntry]+ ) -> list[CommunityWallpaperEntry]:+ # A wallpaper name never becomes a path (the store keys by a random+ # id), but it IS the identity the install-by-name route resolves and+ # the "already installed" check compares, so it obeys the same shape+ # as every other entry rather than being a free-form string.+ kept: list[CommunityWallpaperEntry] = []+ for entry in value:+ if _SKILL_NAME_RE.fullmatch(entry.name) and ".." not in entry.name:+ kept.append(entry)+ else:+ logger.warning(+ "community index: dropping wallpaper with unsafe name %r", entry.name+ )+ return kept+def index_url() -> str:"""The configured index URL (empty string = community section disabled)."""diff --git a/jarvis/skills/origin.py b/jarvis/skills/origin.pynew file mode 100644index 0000000000..74960b4560--- /dev/null+++ b/jarvis/skills/origin.py@@ -0,0 +1,94 @@+"""Where an installed skill came from.++A ``SKILL.md`` downloaded from the marketplace is byte-identical to one the+owner wrote: same frontmatter, same body, nothing in it says "installed". The+Skills view still has to be able to show it — so the install path drops a+small receipt next to the file, and the listing reads it back.++The receipt is a sidecar in the skill's own folder rather than a central index+because deleting the folder must delete the fact: a shared index would keep+claiming an origin for a skill that no longer exists, and two installs racing+would fight over one file. ``.marketplace.json`` starts with a dot and sits+beside ``SKILL.md``, not inside ``references/`` or ``scripts/``, so the loader's+resource scan never picks it up as bundle content.++Never raises: an unreadable or hand-mangled receipt costs the badge, never the+skill.+"""++from __future__ import annotations++import json+import logging+from dataclasses import asdict, dataclass+from pathlib import Path+from typing import Any++log = logging.getLogger(__name__)++#: Sidecar file name, beside SKILL.md inside the skill folder.+RECEIPT_NAME = ".marketplace.json"+++@dataclass(frozen=True)+class SkillOrigin:+ """The published entry a skill was installed from."""++ source: str = "marketplace"+ source_id: str = ""+ publisher: str | None = None+ version: str | None = None+ source_url: str | None = None+ installed_at: str | None = None++ def to_json(self) -> dict[str, Any]:+ return asdict(self)+++def receipt_path(skill_root: Path) -> Path:+ return Path(skill_root) / RECEIPT_NAME+++def write_origin(skill_root: Path, origin: SkillOrigin) -> None:+ """Record where this skill came from. Failure is logged, never raised.++ A skill that installed fine but could not write its receipt is still a+ working skill; losing the install over a badge would be the wrong trade.+ """+ try:+ receipt_path(skill_root).write_text(+ json.dumps(origin.to_json(), ensure_ascii=False, indent=2),+ encoding="utf-8",+ )+ except OSError as exc:+ log.warning("skill origin receipt not written for %s: %s", skill_root, exc)+++def read_origin(skill_root: Path) -> SkillOrigin | None:+ """The recorded origin, or None for a skill nobody installed."""+ path = receipt_path(skill_root)+ try:+ raw = json.loads(path.read_text(encoding="utf-8-sig"))+ except FileNotFoundError:+ return None+ except (OSError, ValueError) as exc:+ log.debug("skill origin receipt unreadable at %s: %s", path, exc)+ return None+ if not isinstance(raw, dict):+ return None++ def _opt(key: str) -> str | None:+ text = str(raw.get(key) or "").strip()+ return text[:200] or None++ source_id = str(raw.get("source_id") or "").strip()[:120]+ if not source_id:+ return None+ return SkillOrigin(+ source=str(raw.get("source") or "marketplace").strip()[:40] or "marketplace",+ source_id=source_id,+ publisher=_opt("publisher"),+ version=_opt("version"),+ source_url=_opt("source_url"),+ installed_at=_opt("installed_at"),+ )diff --git a/jarvis/ui/web/marketplace_routes.py b/jarvis/ui/web/marketplace_routes.pyindex e296f1af7f..9c8e6174bc 100644--- a/jarvis/ui/web/marketplace_routes.py+++ b/jarvis/ui/web/marketplace_routes.py@@ -8,7 +8,7 @@ Endpoints:DELETE /api/marketplace/plugins/{id} — disconnectGET /api/marketplace/community — community index browsePOST /api/marketplace/community/refresh — force index re-fetch- POST /api/marketplace/community/install/{id} — install by name (skill OR plugin)+ 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"""@@ -18,6 +18,7 @@ from __future__ import annotationsimport asyncioimport loggingfrom dataclasses import dataclass+from datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any@@ -744,7 +745,8 @@ def _community_payload(uses, so "shown as installable" and "actually installs" cannot drift: anentry the loader rejects renders as an explicit incompatible card insteadof failing later at install time. Skills carry their install state from- the user skills directory.+ the user skills directory, wallpapers from the recorded origin of the+ pictures in the picker's own store."""from jarvis.core.paths import user_skills_dirfrom jarvis.marketplace.agent_plugins_loader import (@@ -757,6 +759,7 @@ def _community_payload(plugins: list[dict[str, Any]] = []skills: list[dict[str, Any]] = []+ wallpapers: list[dict[str, Any]] = []if index is not None:for entry in index.plugins:base = {@@ -815,12 +818,40 @@ def _community_payload(})+ from jarvis.ui.web.wallpapers import WallpaperUploads++ # One listing for the whole loop: the picker's store is a directory+ # scan, and asking it once per published wallpaper would turn browsing+ # into an O(entries x installed) walk of the data directory.+ installed_sources = {+ item.origin.source_id+ for item in WallpaperUploads().list()+ if item.origin is not None+ }+ for paper in index.wallpapers:+ wallpapers.append(+ {+ "name": paper.name,+ "title": paper.title or paper.name,+ "description": paper.description,+ "publisher": paper.publisher,+ "version": paper.version,+ "published_at": paper.published_at,+ "categories": list(paper.categories),+ "source_url": paper.source_url,+ "raw_url": paper.raw_url,+ "theme": paper.theme,+ "installed": paper.name in installed_sources,+ }+ )+return {"status": status,"revision": getattr(index, "revision", None),"generated_at": getattr(index, "generated_at", None),"plugins": plugins,"skills": skills,+ "wallpapers": wallpapers,}@@ -938,6 +969,8 @@ async def _install_community_skill(entry: Any, request: Request) -> dict[str, Anexactly ONE skill install path (download guards, name-slug check, registryhot-swap) rather than a second copy that can drift."""+ from jarvis.core.paths import user_skills_dir+ from jarvis.skills.origin import SkillOrigin, write_originfrom jarvis.ui.web.skills_routes import SkillInstallBody, install_from_catalogbody = SkillInstallBody(@@ -947,6 +980,18 @@ async def _install_community_skill(entry: Any, request: Request) -> dict[str, Antitle=entry.title or entry.name,)result = await install_from_catalog(body, request)+ # Receipt AFTER the install: a downloaded SKILL.md carries nothing that+ # says where it came from, and the Skills view has to be able to show it.+ write_origin(+ user_skills_dir() / entry.name,+ SkillOrigin(+ source_id=entry.name,+ publisher=entry.publisher,+ version=entry.version,+ source_url=entry.source_url,+ installed_at=datetime.now(UTC).isoformat(timespec="seconds"),+ ),+ )summary = result.get("skill") or {}state = str(summary.get("state") or "draft")return {@@ -967,19 +1012,134 @@ async def _install_community_skill(entry: Any, request: Request) -> dict[str, An}+async def _download_image(+ raw_url: str, limit_bytes: int, *, transport: Any = None+) -> bytes:+ """Fetch one image over https, refusing anything bigger than ``limit_bytes``.++ Streamed rather than read whole so an oversized (or endless) body is cut+ off mid-flight instead of being absorbed first. The redirect chain is+ re-checked: the index validator only sees the URL it was given, and a+ 302 to plain http would put the server back on an SSRF path.++ ``transport`` is the injection point tests use (same shape as+ ``community_source.get_index``); production passes nothing.+ """+ async with httpx.AsyncClient(+ follow_redirects=True,+ timeout=httpx.Timeout(connect=5.0, read=20.0, write=20.0, pool=20.0),+ transport=transport,+ ) as client:+ try:+ async with client.stream("GET", raw_url) as resp:+ if resp.url.scheme != "https":+ raise HTTPException(+ status_code=400,+ detail=f"refusing a non-https redirect to {resp.url}",+ )+ resp.raise_for_status()+ chunks: list[bytes] = []+ total = 0+ async for chunk in resp.aiter_bytes():+ total += len(chunk)+ if total > limit_bytes:+ raise HTTPException(+ status_code=400,+ detail=(+ "that image is larger than "+ f"{limit_bytes // (1024 * 1024)} MB"+ ),+ )+ chunks.append(chunk)+ except httpx.HTTPError as exc:+ raise HTTPException(+ status_code=502, detail=f"download from {raw_url} failed: {exc}"+ ) from exc+ return b"".join(chunks)+++async def _install_community_wallpaper(entry: Any) -> dict[str, Any]:+ """Download one wallpaper and store it beside the owner's own uploads.++ It goes through the SAME mill an upload does — Pillow decode, re-encode,+ size ceiling — so an installed picture is never more trusted than a+ dragged-in one. What it gains is a recorded origin, which is the only+ reason the picker can later show where the tile came from.+ """+ from jarvis.ui.web.wallpapers import (+ MAX_UPLOAD_BYTES,+ UploadRejected,+ WallpaperOrigin,+ WallpaperUploads,+ )++ if not entry.raw_url:+ # Either absent or dropped by the index validator for not being https.+ raise HTTPException(+ status_code=400,+ detail=f"wallpaper {entry.name!r} has no downloadable image",+ )+ store = WallpaperUploads()+ existing = store.find_by_source(entry.name)+ if existing is not None:+ raise HTTPException(+ status_code=409,+ detail=(+ f"{entry.name!r} is already in your wallpapers as "+ f"{existing.title!r}. Remove it there before installing again."+ ),+ )+ data = await _download_image(entry.raw_url, MAX_UPLOAD_BYTES)+ try:+ item = store.add(+ data,+ filename=entry.name,+ source="marketplace",+ title=entry.title or "",+ origin=WallpaperOrigin(+ source_id=entry.name,+ publisher=entry.publisher,+ version=entry.version,+ source_url=entry.source_url,+ ),+ )+ except UploadRejected as exc:+ raise HTTPException(status_code=exc.status_code, detail=exc.message) from exc+ return {+ "ok": True,+ "kind": "wallpaper",+ "id": entry.name,+ "title": item.title,+ "publisher": entry.publisher,+ "version": entry.version,+ "source_url": entry.source_url,+ "location": str(item.path),+ "state": "installed",+ # A picture needs nothing else to be usable: it is in the picker now.+ "ready": True,+ "problem": None,+ "next_action": "none",+ "wallpaper": item.to_json(),+ }++def _install_by_name_404(item_id: str, index: Any) -> HTTPException:"""404 that names the closest existing entry instead of a dead end."""import difflibnames: list[str] = []if index is not None:- names = [e.name for e in index.plugins] + [s.name for s in index.skills]+ names = (+ [e.name for e in index.plugins]+ + [s.name for s in index.skills]+ + [w.name for w in index.wallpapers]+ )close = difflib.get_close_matches(item_id, names, n=1, cutoff=0.6)hint = f" Closest match: {close[0]!r}." if close else ""return HTTPException(status_code=404,detail=(- f"No skill or plugin named {item_id!r} in the community "+ f"Nothing named {item_id!r} is published in the community "f"marketplace.{hint}"),)@@ -999,16 +1159,20 @@ async def community_install_by_name(item_id: str, request: Request) -> dict[str,from jarvis.marketplace import community_sourceindex, _ = await community_source.get_index()- plugin_entry = skill_entry = None+ plugin_entry = skill_entry = wallpaper_entry = Noneif index is not None:plugin_entry = next((e for e in index.plugins if e.name == item_id), None)skill_entry = next((s for s in index.skills if s.name == item_id), None)- if plugin_entry is None and skill_entry is None:+ wallpaper_entry = next((w for w in index.wallpapers if w.name == item_id), None)+ if plugin_entry is None and skill_entry is None and wallpaper_entry is None:raise _install_by_name_404(item_id, index)if skill_entry is not None:return await _install_community_skill(skill_entry, request)+ if wallpaper_entry is not None:+ return await _install_community_wallpaper(wallpaper_entry)+item = await _install_community_plugin(item_id)return {"ok": True,diff --git a/jarvis/ui/web/skills_routes.py b/jarvis/ui/web/skills_routes.pyindex 0f5df769a9..ee514678f1 100644--- a/jarvis/ui/web/skills_routes.py+++ b/jarvis/ui/web/skills_routes.py@@ -31,6 +31,7 @@ from jarvis.core.paths import user_skills_dirfrom jarvis.skills.builtin import BUILTIN_SKILL_NAMESfrom jarvis.skills.finder import SearchFilters, SkillFinderfrom jarvis.skills.loader import parse_skill+from jarvis.skills.origin import read_originfrom jarvis.skills.schema import RESOURCE_KINDS, Skill, SkillLifecycleStaterouter = APIRouter(prefix="/api/skills", tags=["skills"])@@ -86,11 +87,15 @@ def _skill_to_summary(s: Skill) -> dict[str, Any]:# resources as a plain dict with lists (instead of tuples) for JSON serializationresources = {k: list(v) for k, v in s.resources.items()}resource_count = sum(len(v) for v in resources.values())+ # One stat per skill for the ones nobody installed (the common case); the+ # read only happens for a skill that actually carries a receipt.+ origin = read_origin(s.root)return {"name": s.name,"state": s.state.value,"is_builtin": _is_builtin(s.name),"error": s.error,+ "origin": origin.to_json() if origin is not None else None,"description": fm.description if fm else "","category": fm.category if fm else "unknown","version": fm.version if fm else "",diff --git a/jarvis/ui/web/wallpapers.py b/jarvis/ui/web/wallpapers.pyindex 65f9f6aa4f..4fb7b28283 100644--- a/jarvis/ui/web/wallpapers.py+++ b/jarvis/ui/web/wallpapers.py@@ -40,7 +40,7 @@ import timeimport urllib.errorimport urllib.requestimport zipfile-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom pathlib import Pathfrom typing import Any@@ -286,23 +286,55 @@ class UploadRejected(Exception):self.status_code = status_code+@dataclass(frozen=True)+class WallpaperOrigin:+ """Where a stored wallpaper came from, when it was not the owner's own file.++ Recorded at install time and carried in the sidecar, because "this came+ from the marketplace" is something the picker must be able to SHOW — and+ nothing about the finished ``.webp`` on disk could tell it apart from a+ dragged-in photograph afterwards.+ """++ source_id: str+ publisher: str | None = None+ version: str | None = None+ source_url: str | None = None++@dataclass(frozen=True)class UploadedWallpaper:- """One wallpaper the owner brought themselves."""+ """One wallpaper outside the generated library: an upload or an install."""id: strtitle: strtheme: strcreated_at: floatpath: Path+ #: "own" for a file the owner brought, "marketplace" for an installed one.+ source: str = "own"+ origin: WallpaperOrigin | None = Nonedef to_json(self) -> dict[str, Any]:- return {+ payload: dict[str, Any] = {"id": self.id,"title": self.title,"theme": self.theme,"createdAt": self.created_at,+ "source": self.source,}+ if self.origin is not None:+ payload["sourceId"] = self.origin.source_id+ payload["publisher"] = self.origin.publisher+ payload["version"] = self.origin.version+ payload["sourceUrl"] = self.origin.source_url+ return payload+++def _opt_str(value: Any) -> str | None:+ """A trimmed, length-capped string from sidecar JSON — or None."""+ text = str(value or "").strip()+ return text[:200] or Nonedef _clean_title(filename: str) -> str:@@ -375,8 +407,24 @@ class WallpaperUploads:except OSError:# An unreadable mtime only costs sort order, never the picture.created = 0.0+ source = "own"+ origin: WallpaperOrigin | None = None+ if isinstance(meta, dict) and str(meta.get("sourceId", "")).strip():+ source = "marketplace" if str(meta.get("source")) == "marketplace" else "own"+ origin = WallpaperOrigin(+ source_id=str(meta["sourceId"]).strip()[:120],+ publisher=_opt_str(meta.get("publisher")),+ version=_opt_str(meta.get("version")),+ source_url=_opt_str(meta.get("sourceUrl")),+ )return UploadedWallpaper(- id=upload_id, title=title, theme=theme, created_at=created, path=image+ id=upload_id,+ title=title,+ theme=theme,+ created_at=created,+ path=image,+ source=source,+ origin=origin,)def _write_meta(self, item: UploadedWallpaper) -> None:@@ -405,13 +453,38 @@ class WallpaperUploads:return Nonereturn self._read(upload_id)- def add(self, data: bytes, filename: str = "") -> UploadedWallpaper:- """Validate, re-encode, and store one uploaded picture.+ def find_by_source(self, source_id: str) -> UploadedWallpaper | None:+ """The installed wallpaper carrying this marketplace name, if any.++ The store keys by a random id, so identity across an install is the+ recorded ``source_id`` — this is what stops a second install of the+ same entry from stacking duplicate tiles in the picker.+ """+ wanted = str(source_id or "").strip()+ if not wanted:+ return None+ for item in self.list():+ if item.origin is not None and item.origin.source_id == wanted:+ return item+ return None++ def add(+ self,+ data: bytes,+ filename: str = "",+ *,+ source: str = "own",+ origin: WallpaperOrigin | None = None,+ title: str = "",+ ) -> UploadedWallpaper:+ """Validate, re-encode, and store one picture — an upload or an install.The incoming bytes are decoded by Pillow rather than trusted by theirdeclared type, and what is written is the *re-encoded* image — sowhatever else the upload carried (a forged header, an appended- payload, EXIF) does not survive the round trip onto disk.+ payload, EXIF) does not survive the round trip onto disk. A marketplace+ download is put through the exact same mill: an installed wallpaper is+ never more trusted than a dragged-in file."""if not data:raise UploadRejected("That file is empty.")@@ -431,9 +504,12 @@ class WallpaperUploads:try:with Image.open(io.BytesIO(data)) as probe:probe.verify()- with Image.open(io.BytesIO(data)) as source:- source.load()- prepared = source.convert("RGB")+ # Named `decoded`, not `source`: `source` is this method's caller-+ # facing parameter, and shadowing it here silently turned every+ # marketplace install back into an "own" upload.+ with Image.open(io.BytesIO(data)) as decoded:+ decoded.load()+ prepared = decoded.convert("RGB")except Exception as exc: # noqa: BLE001 — any decode failure = not an imageraise UploadRejected("That file is not an image the app can read (PNG, JPEG, WebP, GIF or BMP)."@@ -458,10 +534,12 @@ class WallpaperUploads:upload_id = f"u{secrets.token_hex(8)}"item = UploadedWallpaper(id=upload_id,- title=_clean_title(filename),+ title=(title.strip()[:60] or _clean_title(filename)),theme=theme,created_at=time.time(),path=self._image_path(upload_id),+ source="marketplace" if origin is not None and source == "marketplace" else "own",+ origin=origin,)try:_atomic_write(item.path, buffer.getvalue(), prefix=".upload.", suffix=".webp")@@ -481,13 +559,10 @@ class WallpaperUploads:item = self.get(upload_id)if item is None:return None- updated = UploadedWallpaper(- id=item.id,- title=item.title,- theme=theme,- created_at=item.created_at,- path=item.path,- )+ # replace() rather than a fresh construction: a field added later+ # (the marketplace origin was exactly that) must not silently fall+ # out of the sidecar the first time somebody flips light/dark.+ updated = replace(item, theme=theme)try:self._write_meta(updated)except OSError as exc:diff --git a/tests/unit/marketplace/test_community_install_kinds.py b/tests/unit/marketplace/test_community_install_kinds.pynew file mode 100644index 0000000000..0e7596284c--- /dev/null+++ b/tests/unit/marketplace/test_community_install_kinds.py@@ -0,0 +1,326 @@+"""Install-by-name across all three published kinds, and the origin it records.++A marketplace page prints one line to copy for a plugin, a skill, and a+wallpaper alike. These tests pin the part the user actually sees afterwards:+the thing lands in the right store, and it is marked as having come from the+marketplace — which is the only way any view can say so later.++Runs against the real routers with a pre-seeded index cache and every store+redirected into tmp. The network is never touched.+"""++from __future__ import annotations++import io+import json+import time+from pathlib import Path+from typing import Any++import httpx+import pytest+from fastapi import FastAPI, HTTPException++from jarvis.marketplace import catalog_data, community_source+from jarvis.marketplace.usage_cards import loader as cards_loader+from jarvis.ui.web import marketplace_routes+from jarvis.ui.web import wallpapers as wallpapers_mod+from jarvis.ui.web.marketplace_routes import _download_image+from jarvis.ui.web.marketplace_routes import router as market_router+from jarvis.ui.web.skills_routes import router as skills_router++_SKILL_MD = """---+schema_version: "1"+name: three-point-check+version: "1.0.0"+description: Summarize any topic in exactly three bullets plus a takeaway.+when_to_use: When someone asks for a brief, a TLDR, or the short version.+category: productivity+---++# Three Point Check++Produce three bullets and one takeaway line.+"""+++def _index_payload() -> dict[str, Any]:+ return {+ "revision": 1,+ "generated_at": "2026-08-16T12:00:00Z",+ "plugins": [],+ "skills": [+ {+ "name": "three-point-check",+ "title": "Three Point Check",+ "description": "Summarize any topic in three bullets",+ "publisher": "octocat",+ "version": "1.0.0",+ "raw_url": "https://raw.example/skills/three-point-check/SKILL.md",+ "source_url": "https://github.com/PersonalJarvis/marketplace",+ }+ ],+ "wallpapers": [+ {+ "name": "moonlit-wave",+ "title": "Moonlit Wave",+ "description": "A dark wave under a full moon",+ "publisher": "octocat",+ "version": "1.0.0",+ "raw_url": "https://raw.example/wallpapers/moonlit-wave.png",+ "source_url": "https://github.com/PersonalJarvis/marketplace",+ "theme": "dark",+ }+ ],+ }+++def _png_bytes(size: tuple[int, int] = (32, 18)) -> bytes:+ from PIL import Image++ buffer = io.BytesIO()+ Image.new("RGB", size, (12, 12, 20)).save(buffer, "PNG")+ return buffer.getvalue()+++def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """Every store in tmp, one fresh index in the cache, no network."""+ cache = tmp_path / "marketplace_index.json"+ cache.write_text(+ json.dumps({"fetched_at": time.time(), "index": _index_payload()}),+ encoding="utf-8",+ )+ monkeypatch.setattr(community_source, "_CACHE_PATH", cache)+ monkeypatch.setattr(community_source, "index_url", lambda: "https://reg.example/index.json")+ monkeypatch.setattr(catalog_data, "_DEFAULT_CATALOG_PATH", tmp_path / "plugin_catalog.json")+ monkeypatch.setattr(cards_loader, "_DATA_CARDS_DIR", tmp_path / "usage_cards")+ monkeypatch.setattr("jarvis.core.paths.user_skills_dir", lambda: tmp_path / "skills")+ # The picker's own store: DATA_DIR is read when WallpaperUploads is built,+ # so patching the module attribute is enough to relocate it.+ monkeypatch.setattr(wallpapers_mod, "DATA_DIR", tmp_path / "wpdata")+ catalog_data.clear_cache()+ yield tmp_path+ catalog_data.clear_cache()+++def offline_downloads(monkeypatch: pytest.MonkeyPatch, env: Path) -> None:+ """Serve both downloads locally: a SKILL.md and an image."""+ from jarvis.skills.finder import SkillFinder++ async def fake_skill_install(self: Any, candidate: Any) -> Path:+ target_dir = env / "skills" / candidate.name+ target_dir.mkdir(parents=True, exist_ok=True)+ target = target_dir / "SKILL.md"+ target.write_text(_SKILL_MD, encoding="utf-8")+ return target++ async def fake_image(raw_url: str, limit_bytes: int, **_: Any) -> bytes:+ return _png_bytes()++ monkeypatch.setattr(SkillFinder, "install", fake_skill_install)+ monkeypatch.setattr(marketplace_routes, "_download_image", fake_image)+++def _client(env: Path) -> httpx.AsyncClient:+ from jarvis.skills.registry import SkillRegistry++ app = FastAPI()+ app.include_router(market_router)+ app.include_router(skills_router)+ skills_root = env / "skills"+ skills_root.mkdir(parents=True, exist_ok=True)+ registry = SkillRegistry(root=skills_root)+ registry.reload_sync()+ app.state.skill_registry = registry+ return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test")+++# ----------------------------------------------------------------------+# Wallpapers+# ----------------------------------------------------------------------+++async def test_browse_lists_published_wallpapers(env: Path) -> None:+ async with _client(env) as client:+ resp = await client.get("/api/marketplace/community")+ paper = resp.json()["wallpapers"][0]+ assert paper["name"] == "moonlit-wave"+ assert paper["title"] == "Moonlit Wave"+ assert paper["installed"] is False+++async def test_install_stores_a_wallpaper_with_its_origin(+ env: Path, offline_downloads: None+) -> None:+ from jarvis.ui.web.wallpapers import WallpaperUploads++ async with _client(env) as client:+ resp = await client.post("/api/marketplace/community/install/moonlit-wave")+ assert resp.status_code == 200+ data = resp.json()+ assert data["kind"] == "wallpaper"+ assert data["title"] == "Moonlit Wave"+ # A picture needs no connect step and no validation: usable at once.+ assert data["ready"] is True+ assert data["next_action"] == "none"++ browse = await client.get("/api/marketplace/community")+ assert browse.json()["wallpapers"][0]["installed"] is True++ stored = WallpaperUploads().list()+ assert len(stored) == 1+ item = stored[0]+ assert item.source == "marketplace"+ assert item.origin is not None+ assert item.origin.source_id == "moonlit-wave"+ assert item.origin.publisher == "octocat"+ assert item.to_json()["sourceId"] == "moonlit-wave"+ # Re-encoded on the way in, exactly like a dragged-in file.+ assert item.path.suffix == ".webp"+++async def test_installing_the_same_wallpaper_twice_409s(+ env: Path, offline_downloads: None+) -> None:+ async with _client(env) as client:+ first = await client.post("/api/marketplace/community/install/moonlit-wave")+ assert first.status_code == 200+ second = await client.post("/api/marketplace/community/install/moonlit-wave")+ assert second.status_code == 409+ assert "already" in second.json()["detail"]+++async def test_theme_change_keeps_the_marketplace_origin(+ env: Path, offline_downloads: None+) -> None:+ """Flipping light/dark rewrites the sidecar — the origin must survive it."""+ from jarvis.ui.web.wallpapers import WallpaperUploads++ async with _client(env) as client:+ await client.post("/api/marketplace/community/install/moonlit-wave")+ store = WallpaperUploads()+ installed = store.list()[0]+ store.set_theme(installed.id, "light")+ reread = store.get(installed.id)+ assert reread is not None+ assert reread.theme == "light"+ assert reread.source == "marketplace"+ assert reread.origin is not None+ assert reread.origin.source_id == "moonlit-wave"+++async def test_an_ordinary_upload_stays_marked_as_the_owners_own(env: Path) -> None:+ from jarvis.ui.web.wallpapers import WallpaperUploads++ item = WallpaperUploads().add(_png_bytes(), filename="my-photo.png")+ assert item.source == "own"+ assert item.origin is None+ assert "sourceId" not in item.to_json()+++# ----------------------------------------------------------------------+# Skills+# ----------------------------------------------------------------------+++async def test_install_writes_a_receipt_for_a_skill(+ env: Path, offline_downloads: None+) -> None:+ """A downloaded SKILL.md says nothing about its origin — the receipt does."""+ from jarvis.skills.origin import read_origin++ async with _client(env) as client:+ await client.post("/api/marketplace/community/install/three-point-check")+ origin = read_origin(env / "skills" / "three-point-check")+ assert origin is not None+ assert origin.source == "marketplace"+ assert origin.source_id == "three-point-check"+ assert origin.publisher == "octocat"+ assert origin.installed_at+++async def test_skill_listing_carries_the_origin(env: Path, offline_downloads: None) -> None:+ async with _client(env) as client:+ await client.post("/api/marketplace/community/install/three-point-check")+ listed = await client.get("/api/skills")+ entry = next(s for s in listed.json()["skills"] if s["name"] == "three-point-check")+ assert entry["origin"]["source"] == "marketplace"+ assert entry["origin"]["publisher"] == "octocat"+++def test_a_hand_written_skill_has_no_origin(env: Path) -> None:+ from jarvis.skills.origin import read_origin++ folder = env / "skills" / "mine"+ folder.mkdir(parents=True)+ (folder / "SKILL.md").write_text(_SKILL_MD, encoding="utf-8")+ assert read_origin(folder) is None+++def test_an_unreadable_receipt_costs_the_badge_not_the_skill(env: Path) -> None:+ from jarvis.skills.origin import RECEIPT_NAME, read_origin++ folder = env / "skills" / "broken-receipt"+ folder.mkdir(parents=True)+ (folder / "SKILL.md").write_text(_SKILL_MD, encoding="utf-8")+ (folder / RECEIPT_NAME).write_text("{not json", encoding="utf-8")+ assert read_origin(folder) is None+++# ----------------------------------------------------------------------+# The image download itself+# ----------------------------------------------------------------------+++async def test_download_refuses_an_oversized_image() -> None:+ """The ceiling is enforced mid-stream, not after the body is absorbed."""++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, content=b"x" * 5000)++ with pytest.raises(HTTPException) as excinfo:+ await _download_image(+ "https://raw.example/big.png", 1000, transport=httpx.MockTransport(handler)+ )+ assert excinfo.value.status_code == 400+ assert "larger than" in str(excinfo.value.detail)+++async def test_download_refuses_a_redirect_off_https() -> None:+ """The index checks the URL it was given; the redirect chain needs it too."""++ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.scheme == "https":+ return httpx.Response(302, headers={"location": "http://plain.example/x.png"})+ return httpx.Response(200, content=b"never reached")++ with pytest.raises(HTTPException) as excinfo:+ await _download_image(+ "https://raw.example/x.png", 10_000, transport=httpx.MockTransport(handler)+ )+ assert excinfo.value.status_code == 400+ assert "non-https" in str(excinfo.value.detail)+++async def test_download_returns_the_bytes_it_was_served() -> None:+ payload = _png_bytes()++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, content=payload)++ got = await _download_image(+ "https://raw.example/ok.png", 10_000_000, transport=httpx.MockTransport(handler)+ )+ assert got == payload