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(web-ui): add a desktop wallpaper picker
rubenluetke10-beep4aa1e542d3e3
diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsxindex e56f01b816..e40f2111cc 100644--- a/jarvis/ui/web/frontend/src/App.tsx+++ b/jarvis/ui/web/frontend/src/App.tsx@@ -27,7 +27,8 @@ import { CliConnectPoller } from "@/components/CliConnectPoller";import { OnboardingGate } from "@/components/onboarding/OnboardingGate";import { installDictationFocusTracker } from "@/lib/dictationTarget";import { SubscriptionRealtimeTransportBroker } from "@/components/voice/SubscriptionRealtimeTransportBroker";-import jarvisDesktopWallpaper from "@/assets/jarvis-desktop-wallpaper.webp";+import { useDesktopWallpaper } from "@/hooks/useDesktopWallpaper";+import { installWallpaperSync } from "@/store/wallpaper";/** Where the collapsed/expanded choice for the nav sidebar is remembered. */const NAV_COLLAPSED_KEY = "jarvis.sidebar.collapsed.v1";@@ -38,8 +39,13 @@ const NAV_COLLAPSED_KEY = "jarvis.sidebar.collapsed.v1";* The image and its theme veil are separate layers: the artwork can stay crisp* while light and dark mode independently tune contrast through semantic theme* channels in index.css. Focused workspaces keep their content surfaces on top.+ *+ * Which artwork is shown belongs to the user — see the Wallpaper section. The+ * picture that ships with the app remains the default, and the one every+ * failure path returns to.*/function DesktopWallpaper() {+ const wallpaperUrl = useDesktopWallpaper();return (<divaria-hidden@@ -48,7 +54,7 @@ function DesktopWallpaper() {><divclassName="jarvis-desktop-wallpaper absolute inset-0"- style={{ backgroundImage: `url(${jarvisDesktopWallpaper})` }}+ style={{ backgroundImage: `url(${wallpaperUrl})` }}/><div className="jarvis-desktop-wallpaper-veil absolute inset-0" /></div>@@ -84,6 +90,13 @@ export default function App() {*/useEffect(() => installDictationFocusTracker(), []);+ /*+ * Follow the wallpaper choice across windows. Picking one in the main window+ * should not leave a detached window wearing the previous picture until it+ * happens to reload.+ */+ useEffect(() => installWallpaperSync(), []);+/** Resync the detached-window registry once per document. The WS events keep* it live afterwards; this fetch covers the window that (re)loaded after thediff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.tsxindex 88c2bc6956..ff8c40a169 100644--- a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx@@ -148,6 +148,9 @@ const TelephonySetupView = lazyView(() =>default: m.TelephonySetupView,})),);+const WallpaperView = lazyView(() =>+ import("@/views/WallpaperView").then((m) => ({ default: m.WallpaperView })),+);type IdleWindow = Window & {requestIdleCallback?: (@@ -418,6 +421,8 @@ function SwitchOnActiveSection({ active }: { active: string }) {return <FeedbackView />;case "agent-instructions":return <AgentInstructionsView />;+ case "wallpaper":+ return <WallpaperView />;// Deliberately nothing: the coding workspace is rendered by the STICKY// branch in `MainView` above, which keeps it mounted across section// changes. This switch is not rendered at all while one of those ids isdiff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsxindex bd3647e77d..550912e91d 100644--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx@@ -18,6 +18,7 @@ import {MessageSquareWarning,ScrollText,MessagesSquare,+ Image as ImageIcon,Loader2,type LucideIcon,ChevronRight,@@ -145,6 +146,14 @@ const NAV_GROUPS: NavItem[][] = [fallbackLabel: "Voice",},{ id: "outputs", labelKey: "nav.outputs", icon: FolderOpen },+ // Appearance. Sits with the configuration group rather than with the+ // content views: it changes how the app looks, not what it holds.+ {+ id: "wallpaper",+ labelKey: "nav.wallpaper",+ icon: ImageIcon,+ fallbackLabel: "Wallpaper",+ },],// 4) Social links + in-app feedback.[diff --git a/jarvis/ui/web/frontend/src/hooks/useDesktopWallpaper.test.tsx b/jarvis/ui/web/frontend/src/hooks/useDesktopWallpaper.test.tsxnew file mode 100644index 0000000000..5266386b30--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useDesktopWallpaper.test.tsx@@ -0,0 +1,88 @@+import { act, cleanup, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import {+ DEFAULT_WALLPAPER_URL,+ useDesktopWallpaper,+} from "@/hooks/useDesktopWallpaper";+import { useWallpaperStore } from "@/store/wallpaper";++/**+ * jsdom never loads images, so the test drives the outcome by hand: an+ * instance is captured on construction and its `onload`/`onerror` fired when+ * the test wants the swap to succeed or fail.+ */+let pending: HTMLImageElement[] = [];++class TestImage {+ onload: (() => void) | null = null;+ onerror: (() => void) | null = null;+ complete = false;+ naturalWidth = 0;+ #src = "";++ constructor() {+ pending.push(this as unknown as HTMLImageElement);+ }++ get src() {+ return this.#src;+ }++ set src(value: string) {+ this.#src = value;+ }+}++function Probe() {+ return <span data-testid="url">{useDesktopWallpaper()}</span>;+}++beforeEach(() => {+ pending = [];+ window.localStorage.clear();+ useWallpaperStore.setState({ selectedId: null });+ vi.stubGlobal("Image", TestImage);+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe("useDesktopWallpaper", () => {+ it("starts on the bundled wallpaper", () => {+ render(<Probe />);++ expect(screen.getByTestId("url").textContent).toBe(DEFAULT_WALLPAPER_URL);+ expect(pending).toHaveLength(0);+ });++ it("keeps the old picture on screen until the new one has loaded", async () => {+ render(<Probe />);+ act(() => useWallpaperStore.getState().select("03-anime-neon-01"));++ // Requested, but not yet painted — the shell must not go blank meanwhile.+ expect(pending[0]?.src).toBe("/api/wallpapers/03-anime-neon-01/full");+ expect(screen.getByTestId("url").textContent).toBe(DEFAULT_WALLPAPER_URL);++ act(() => pending[0]?.onload?.(new Event("load") as never));++ await waitFor(() =>+ expect(screen.getByTestId("url").textContent).toBe(+ "/api/wallpapers/03-anime-neon-01/full",+ ),+ );+ });++ it("falls back to the bundled wallpaper when the library is missing", async () => {+ useWallpaperStore.setState({ selectedId: "03-anime-neon-01" });+ render(<Probe />);++ act(() => pending[0]?.onerror?.(new Event("error") as never));++ await waitFor(() =>+ expect(screen.getByTestId("url").textContent).toBe(DEFAULT_WALLPAPER_URL),+ );+ });+});diff --git a/jarvis/ui/web/frontend/src/hooks/useDesktopWallpaper.ts b/jarvis/ui/web/frontend/src/hooks/useDesktopWallpaper.tsnew file mode 100644index 0000000000..c89b6981aa--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useDesktopWallpaper.ts@@ -0,0 +1,55 @@+import { useEffect, useState } from "react";++import jarvisDesktopWallpaper from "@/assets/jarvis-desktop-wallpaper.webp";+import { useWallpaperStore, wallpaperFullUrl } from "@/store/wallpaper";++/** The artwork that ships inside the bundle — the default and the fallback. */+export const DEFAULT_WALLPAPER_URL = jarvisDesktopWallpaper;++/**+ * The background-image URL the app shell should currently paint.+ *+ * A chosen wallpaper is a ~300 KB download from the library, and swapping the+ * CSS URL before those bytes arrive paints the shell empty for as long as the+ * transfer takes. So the new image is fetched into the browser cache first and+ * the switch happens only once it can be drawn — the visible change is then a+ * single repaint, with no gap in between.+ *+ * A failed load falls back to the bundled artwork instead of leaving the shell+ * bare. That is the ordinary case on a machine where the wallpaper library was+ * never generated: the id in localStorage is still valid, the files simply are+ * not there.+ */+export function useDesktopWallpaper(): string {+ const selectedId = useWallpaperStore((state) => state.selectedId);+ const [url, setUrl] = useState(DEFAULT_WALLPAPER_URL);++ useEffect(() => {+ if (!selectedId) {+ setUrl(DEFAULT_WALLPAPER_URL);+ return;+ }++ const target = wallpaperFullUrl(selectedId);+ let cancelled = false;+ const image = new Image();+ image.onload = () => {+ if (!cancelled) setUrl(target);+ };+ image.onerror = () => {+ if (!cancelled) setUrl(DEFAULT_WALLPAPER_URL);+ };+ image.src = target;+ // A cached image can be complete before the handlers are attached — in+ // that case no event will ever fire, so adopt it straight away.+ if (image.complete && image.naturalWidth > 0) setUrl(target);++ return () => {+ cancelled = true;+ image.onload = null;+ image.onerror = null;+ };+ }, [selectedId]);++ return url;+}diff --git a/jarvis/ui/web/frontend/src/hooks/useWallpaperCatalog.ts b/jarvis/ui/web/frontend/src/hooks/useWallpaperCatalog.tsnew file mode 100644index 0000000000..d1b20f6aec--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useWallpaperCatalog.ts@@ -0,0 +1,61 @@+import { useQuery } from "@tanstack/react-query";++/** One wallpaper as the browse grid knows it — metadata only, no pixels. */+export interface WallpaperEntry {+ id: string;+ title: string;+ /** Directory slug, e.g. `03-anime-neon`. Stable; used as the filter key. */+ style: string;+ /** Written-out style name for the filter chips, e.g. `Cinematic Anime Neon`. */+ styleLabel: string;+ theme: "light" | "dark";+}++export interface WallpaperStyle {+ slug: string;+ label: string;+ count: number;+}++export interface WallpaperCatalog {+ /** False when the generated library is not installed on this machine. */+ available: boolean;+ count: number;+ styles: WallpaperStyle[];+ items: WallpaperEntry[];+}++const EMPTY_CATALOG: WallpaperCatalog = {+ available: false,+ count: 0,+ styles: [],+ items: [],+};++/**+ * Fetch the wallpaper catalog.+ *+ * The payload is a few dozen kilobytes of metadata for five hundred entries+ * and it only changes when the library on disk is regenerated, so it is+ * fetched once per session and kept — refetching it on every visit to the+ * section would buy nothing.+ */+export function useWallpaperCatalog() {+ return useQuery<WallpaperCatalog>({+ queryKey: ["wallpapers"],+ staleTime: Infinity,+ retry: 1,+ queryFn: async () => {+ const response = await fetch("/api/wallpapers");+ if (!response.ok) throw new Error(`Wallpaper catalog failed: ${response.status}`);+ const data = (await response.json()) as Partial<WallpaperCatalog> | null;+ if (!data || !Array.isArray(data.items)) return EMPTY_CATALOG;+ return {+ available: Boolean(data.available),+ count: typeof data.count === "number" ? data.count : data.items.length,+ styles: Array.isArray(data.styles) ? data.styles : [],+ items: data.items,+ };+ },+ });+}diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.tsindex bb73709a61..561fdc469c 100644--- a/jarvis/ui/web/frontend/src/store/events.ts+++ b/jarvis/ui/web/frontend/src/store/events.ts@@ -67,6 +67,7 @@ export type SectionId =| "contacts"| "feedback"| "agent-instructions"+ | "wallpaper"| "dictionary"| "dictation"// The three tabs added by the merged voice section. "dictation" (default@@ -111,6 +112,7 @@ export const SECTION_IDS = ["contacts","feedback","agent-instructions",+ "wallpaper","dictionary","dictation",// `satisfies` only catches array entries that are missing from the union,@@ -175,6 +177,7 @@ export const SECTION_LABELS: Record<SectionId, string> = {contacts: "Contacts",feedback: "Feedback","agent-instructions": "Agent Instructions",+ wallpaper: "Wallpaper",dictionary: "Dictionary",dictation: "Dictation",// Plain English, deliberately NOT the "{name} Voice" brand: these labels arediff --git a/jarvis/ui/web/frontend/src/store/wallpaper.ts b/jarvis/ui/web/frontend/src/store/wallpaper.tsnew file mode 100644index 0000000000..9d1eaa7b8b--- /dev/null+++ b/jarvis/ui/web/frontend/src/store/wallpaper.ts@@ -0,0 +1,77 @@+import { create } from "zustand";++/**+ * Which desktop wallpaper the app is wearing.+ *+ * The bundled artwork stays the default and the fallback: an empty selection+ * means "the one that ships with the app", so a fresh profile, a cleared+ * browser storage, and a checkout without the generated library all land on+ * the same known-good picture rather than on a blank shell.+ *+ * The choice lives in localStorage rather than on the server. It is a per-+ * screen cosmetic preference with no backend meaning, and localStorage is the+ * one store every window of the app — including the detached solo windows —+ * already shares.+ */+const STORAGE_KEY = "jarvis.wallpaper.v1";++/** Where a chosen wallpaper's full-size file is served from. */+export function wallpaperFullUrl(id: string): string {+ return `/api/wallpapers/${encodeURIComponent(id)}/full`;+}++/** Where a chosen wallpaper's grid thumbnail is served from. */+export function wallpaperThumbUrl(id: string): string {+ return `/api/wallpapers/${encodeURIComponent(id)}/thumb`;+}++function readStoredId(): string | null {+ try {+ const stored = window.localStorage.getItem(STORAGE_KEY);+ return stored && stored.trim() ? stored : null;+ } catch {+ // Private mode, or storage disabled by policy — the default is a fine+ // answer, and a wallpaper is not worth failing a mount over.+ return null;+ }+}++interface WallpaperStore {+ /** The chosen wallpaper's id, or null for the bundled default. */+ selectedId: string | null;+ /** Persist a choice. Pass null to go back to the bundled default. */+ select: (id: string | null) => void;+ /** Adopt a choice made in another window. Does not write back. */+ adopt: (id: string | null) => void;+}++export const useWallpaperStore = create<WallpaperStore>((set) => ({+ selectedId: typeof window === "undefined" ? null : readStoredId(),+ select: (id) => {+ try {+ if (id) window.localStorage.setItem(STORAGE_KEY, id);+ else window.localStorage.removeItem(STORAGE_KEY);+ } catch {+ /* the choice still applies to this window, it just will not survive */+ }+ set({ selectedId: id });+ },+ adopt: (id) => set({ selectedId: id }),+}));++/**+ * Keep every window on the same wallpaper.+ *+ * A `storage` event fires in the *other* documents of the origin, which is+ * exactly the set of windows that need to repaint: pick a wallpaper in the+ * main window and the detached ones follow without a reload.+ */+export function installWallpaperSync(): () => void {+ if (typeof window === "undefined") return () => {};+ const onStorage = (event: StorageEvent) => {+ if (event.key !== null && event.key !== STORAGE_KEY) return;+ useWallpaperStore.getState().adopt(readStoredId());+ };+ window.addEventListener("storage", onStorage);+ return () => window.removeEventListener("storage", onStorage);+}diff --git a/jarvis/ui/web/frontend/src/views/WallpaperView.test.tsx b/jarvis/ui/web/frontend/src/views/WallpaperView.test.tsxnew file mode 100644index 0000000000..b485e14fe0--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/WallpaperView.test.tsx@@ -0,0 +1,156 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { WallpaperView } from "@/views/WallpaperView";+import { useWallpaperStore } from "@/store/wallpaper";++const CATALOG = {+ available: true,+ count: 3,+ styles: [+ { slug: "01-cinematic-photoreal", label: "Cinematic Photorealistic", count: 2 },+ { slug: "03-anime-neon", label: "Cinematic Anime Neon", count: 1 },+ ],+ items: [+ {+ id: "01-cinematic-photoreal-01",+ title: "Flooded Observatory",+ style: "01-cinematic-photoreal",+ styleLabel: "Cinematic Photorealistic",+ theme: "dark" as const,+ },+ {+ id: "01-cinematic-photoreal-02",+ title: "Morning Atrium",+ style: "01-cinematic-photoreal",+ styleLabel: "Cinematic Photorealistic",+ theme: "light" as const,+ },+ {+ id: "03-anime-neon-01",+ title: "Neon Crossing",+ style: "03-anime-neon",+ styleLabel: "Cinematic Anime Neon",+ theme: "dark" as const,+ },+ ],+};++function renderView(catalog: unknown = CATALOG) {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({ ok: true, json: async () => catalog }),+ );+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>+ <WallpaperView />+ </QueryClientProvider>,+ );+}++/** Every `<img>` the grid and preview have actually asked the browser for. */+function requestedSources(): string[] {+ return Array.from(document.querySelectorAll("img")).map((img) =>+ img.getAttribute("src") ?? "",+ );+}++beforeEach(() => {+ window.localStorage.clear();+ useWallpaperStore.setState({ selectedId: null });+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe("WallpaperView", () => {+ it("browses on thumbnails alone — no full-size image is requested", async () => {+ renderView();++ await screen.findByAltText("Flooded Observatory");+ const sources = requestedSources();++ expect(sources).toHaveLength(3);+ expect(sources.every((src) => src.endsWith("/thumb"))).toBe(true);+ expect(sources.some((src) => src.endsWith("/full"))).toBe(false);+ });++ it("downloads the full-size image only once a wallpaper is previewed", async () => {+ renderView();++ fireEvent.click(await screen.findByAltText("Neon Crossing"));++ await screen.findByTestId("wallpaper-preview");+ expect(requestedSources()).toContain("/api/wallpapers/03-anime-neon-01/full");+ });++ it("applies the previewed wallpaper and remembers it", async () => {+ renderView();++ fireEvent.click(await screen.findByAltText("Morning Atrium"));+ fireEvent.click(await screen.findByRole("button", { name: "Use this wallpaper" }));++ await waitFor(() => {+ expect(useWallpaperStore.getState().selectedId).toBe(+ "01-cinematic-photoreal-02",+ );+ });+ expect(window.localStorage.getItem("jarvis.wallpaper.v1")).toBe(+ "01-cinematic-photoreal-02",+ );+ });++ it("returns to the bundled default", async () => {+ renderView();+ act(() => useWallpaperStore.getState().select("03-anime-neon-01"));++ fireEvent.click(await screen.findByRole("button", { name: /Default/ }));++ expect(useWallpaperStore.getState().selectedId).toBeNull();+ expect(window.localStorage.getItem("jarvis.wallpaper.v1")).toBeNull();+ });++ it("filters by style and by theme", async () => {+ renderView();++ fireEvent.click(await screen.findByRole("button", { name: "Cinematic Anime Neon" }));+ await waitFor(() => expect(requestedSources()).toHaveLength(1));+ expect(screen.getByAltText("Neon Crossing")).toBeTruthy();++ fireEvent.click(screen.getByRole("button", { name: "All styles" }));+ fireEvent.click(screen.getByRole("button", { name: /Light/ }));+ await waitFor(() => expect(requestedSources()).toHaveLength(1));+ expect(screen.getByAltText("Morning Atrium")).toBeTruthy();+ });++ it("keeps the same shuffled order across renders", async () => {+ const first = renderView();+ await screen.findByAltText("Flooded Observatory");+ const before = requestedSources();+ first.unmount();++ renderView();+ await screen.findByAltText("Flooded Observatory");++ expect(requestedSources()).toEqual(before);+ });++ it("explains itself instead of breaking when the library is absent", async () => {+ renderView({ available: false, count: 0, styles: [], items: [] });++ expect(await screen.findByText("No wallpaper library installed")).toBeTruthy();+ });+});diff --git a/jarvis/ui/web/frontend/src/views/WallpaperView.tsx b/jarvis/ui/web/frontend/src/views/WallpaperView.tsxnew file mode 100644index 0000000000..70ee3befe0--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/WallpaperView.tsx@@ -0,0 +1,429 @@+import { useCallback, useEffect, useMemo, useState } from "react";+import {+ Check,+ ChevronLeft,+ ChevronRight,+ Image as ImageIcon,+ Loader2,+ Moon,+ RotateCcw,+ Sun,+ X,+} from "lucide-react";++import { Button } from "@/components/ui/button";+import { ScrollArea } from "@/components/ui/scroll-area";+import { ViewHeader } from "@/views/ChatsView";+import {+ useWallpaperCatalog,+ type WallpaperEntry,+} from "@/hooks/useWallpaperCatalog";+import {+ useWallpaperStore,+ wallpaperFullUrl,+ wallpaperThumbUrl,+} from "@/store/wallpaper";+import { cn } from "@/lib/utils";++type ThemeFilter = "all" | "light" | "dark";+type Ordering = "mixed" | "style";++/**+ * A stable pseudo-random rank for a wallpaper id (FNV-1a).+ *+ * The default order is shuffled on purpose: the library is stored twenty-five+ * wallpapers to a style, and listing it in storage order means scrolling past+ * twenty-five variations of the same look before seeing a different one. What+ * it must not be is *re*-shuffled — an order that changed on every render, or+ * on every visit, would move a tile the moment someone reached for it. Hashing+ * the id gives an order that looks random and never moves.+ */+function shuffleRank(id: string): number {+ let hash = 0x811c9dc5;+ for (let index = 0; index < id.length; index += 1) {+ hash ^= id.charCodeAt(index);+ hash = Math.imul(hash, 0x01000193) >>> 0;+ }+ return hash;+}++/** The segmented filter/ordering controls share one look. */+function SegmentButton({+ active,+ onClick,+ children,+}: {+ active: boolean;+ onClick: () => void;+ children: React.ReactNode;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ aria-pressed={active}+ className={cn(+ "flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs transition-colors",+ active+ ? "bg-primary/15 text-primary"+ : "text-muted-foreground hover:bg-secondary/60 hover:text-foreground",+ )}+ >+ {children}+ </button>+ );+}++/**+ * One grid tile.+ *+ * The image is the 480 px thumbnail and it is lazy: five hundred tiles must+ * cost only what is actually scrolled past. The full-size file is not touched+ * here at all — that download belongs to the preview.+ */+function WallpaperTile({+ item,+ active,+ onOpen,+}: {+ item: WallpaperEntry;+ active: boolean;+ onOpen: () => void;+}) {+ return (+ <button+ type="button"+ onClick={onOpen}+ title={`${item.title} — ${item.styleLabel}`}+ className={cn(+ "group relative overflow-hidden rounded-lg border text-left transition-all",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",+ active+ ? "border-primary ring-2 ring-primary/60"+ : "border-border hover:border-primary/50",+ )}+ >+ <img+ src={wallpaperThumbUrl(item.id)}+ alt={item.title}+ loading="lazy"+ decoding="async"+ width={480}+ height={270}+ className="aspect-video w-full bg-secondary/40 object-cover transition-transform duration-300 group-hover:scale-[1.03]"+ />+ <span className="pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/75 to-transparent px-2.5 pb-1.5 pt-6">+ <span className="block truncate text-[11px] font-medium text-white">+ {item.title}+ </span>+ <span className="block truncate text-[10px] text-white/65">+ {item.styleLabel}+ </span>+ </span>+ {active && (+ <span className="absolute right-2 top-2 flex h-6 w-6 items-center justify-center rounded-full bg-primary text-primary-foreground shadow">+ <Check className="h-3.5 w-3.5" />+ </span>+ )}+ </button>+ );+}++/**+ * The full-size preview.+ *+ * This is the only place the real 1920x1080 file is requested, which is the+ * whole point of the two-tier delivery: browsing costs thumbnails, and a+ * wallpaper is downloaded when someone actually wants to look at it. The+ * spinner stays until the image reports itself loaded so the frame never shows+ * a half-painted picture.+ */+function WallpaperPreview({+ item,+ applied,+ onApply,+ onClose,+ onStep,+}: {+ item: WallpaperEntry;+ applied: boolean;+ onApply: () => void;+ onClose: () => void;+ onStep: (delta: number) => void;+}) {+ const [loaded, setLoaded] = useState(false);++ // The preview is keyed on the wallpaper, so a step to the next one remounts+ // this state — but an explicit reset keeps that guarantee local.+ useEffect(() => setLoaded(false), [item.id]);++ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") onClose();+ else if (event.key === "ArrowLeft") onStep(-1);+ else if (event.key === "ArrowRight") onStep(1);+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [onClose, onStep]);++ return (+ <div+ role="dialog"+ aria-modal="true"+ aria-label={`${item.title} preview`}+ data-testid="wallpaper-preview"+ className="fixed inset-0 z-50 flex flex-col bg-background/85 backdrop-blur-xl"+ >+ <header className="flex items-center gap-3 border-b border-border px-6 py-3">+ <div className="min-w-0 flex-1">+ <h3 className="truncate text-sm font-semibold">{item.title}</h3>+ <p className="truncate text-xs text-muted-foreground">+ {item.styleLabel} · {item.theme === "dark" ? "Dark" : "Light"}+ </p>+ </div>+ <Button+ size="sm"+ variant={applied ? "secondary" : "default"}+ onClick={onApply}+ disabled={applied}+ >+ {applied ? (+ <>+ <Check className="mr-1.5 h-3.5 w-3.5" /> In use+ </>+ ) : (+ "Use this wallpaper"+ )}+ </Button>+ <Button size="sm" variant="ghost" onClick={onClose} aria-label="Close preview">+ <X className="h-4 w-4" />+ </Button>+ </header>++ <div className="relative flex flex-1 items-center justify-center overflow-hidden p-6">+ {!loaded && (+ <Loader2 className="absolute h-6 w-6 animate-spin text-muted-foreground" />+ )}+ <img+ key={item.id}+ src={wallpaperFullUrl(item.id)}+ alt={item.title}+ onLoad={() => setLoaded(true)}+ onError={() => setLoaded(true)}+ className={cn(+ "max-h-full max-w-full rounded-lg object-contain shadow-2xl transition-opacity duration-200",+ loaded ? "opacity-100" : "opacity-0",+ )}+ />+ <button+ type="button"+ onClick={() => onStep(-1)}+ aria-label="Previous wallpaper"+ className="absolute left-3 flex h-10 w-10 items-center justify-center rounded-full border border-border bg-background/70 text-foreground transition-colors hover:bg-background"+ >+ <ChevronLeft className="h-5 w-5" />+ </button>+ <button+ type="button"+ onClick={() => onStep(1)}+ aria-label="Next wallpaper"+ className="absolute right-3 flex h-10 w-10 items-center justify-center rounded-full border border-border bg-background/70 text-foreground transition-colors hover:bg-background"+ >+ <ChevronRight className="h-5 w-5" />+ </button>+ </div>+ </div>+ );+}++/**+ * The Wallpaper section: browse the generated library, preview one at full+ * size, and adopt it as the app's ground.+ *+ * Nothing here writes to the server. The choice is a local preference and the+ * bundled artwork is always one click away again, so trying a wallpaper is+ * meant to feel as reversible as it actually is.+ */+export function WallpaperView() {+ const { data, isLoading, isError } = useWallpaperCatalog();+ const selectedId = useWallpaperStore((state) => state.selectedId);+ const select = useWallpaperStore((state) => state.select);++ const [theme, setTheme] = useState<ThemeFilter>("all");+ const [ordering, setOrdering] = useState<Ordering>("mixed");+ const [style, setStyle] = useState<string | null>(null);+ const [previewId, setPreviewId] = useState<string | null>(null);++ const items = data?.items ?? [];+ const styles = data?.styles ?? [];++ const visible = useMemo(() => {+ const filtered = items.filter(+ (item) =>+ (theme === "all" || item.theme === theme) &&+ (style === null || item.style === style),+ );+ return filtered.sort((left, right) => {+ if (ordering === "style") {+ const byStyle = left.style.localeCompare(right.style);+ if (byStyle !== 0) return byStyle;+ return left.id.localeCompare(right.id);+ }+ return shuffleRank(left.id) - shuffleRank(right.id);+ });+ }, [items, ordering, style, theme]);++ const previewIndex = previewId+ ? visible.findIndex((item) => item.id === previewId)+ : -1;+ const previewItem = previewIndex >= 0 ? visible[previewIndex] : null;++ // Stepping wraps around, so the arrow keys never dead-end at either edge of+ // whatever the current filter happens to be showing.+ const step = useCallback(+ (delta: number) => {+ if (previewIndex < 0 || visible.length === 0) return;+ const next = (previewIndex + delta + visible.length) % visible.length;+ setPreviewId(visible[next].id);+ },+ [previewIndex, visible],+ );++ const header = (+ <ViewHeader+ icon={<ImageIcon className="h-4 w-4 text-primary" />}+ title="Wallpaper"+ subtitle={+ data?.available+ ? `${data.count} wallpapers · ${styles.length} styles · previews load on demand`+ : "The app's desktop background"+ }+ right={+ selectedId ? (+ <Button size="sm" variant="outline" onClick={() => select(null)}>+ <RotateCcw className="mr-1.5 h-3.5 w-3.5" />+ Default+ </Button>+ ) : undefined+ }+ />+ );++ if (isLoading) {+ return (+ <div className="flex h-full flex-col">+ {header}+ <div className="flex flex-1 items-center justify-center">+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />+ </div>+ </div>+ );+ }++ if (isError || !data?.available) {+ return (+ <div className="flex h-full flex-col">+ {header}+ <div className="flex flex-1 items-center justify-center px-6">+ <div className="max-w-md text-center">+ <p className="text-sm font-medium">No wallpaper library installed</p>+ <p className="mt-1 text-xs text-muted-foreground">+ The generated collection lives in{" "}+ <code className="rounded bg-secondary/60 px-1 py-0.5">+ data/jarvis-wallpaper-gallery+ </code>+ , which is not part of the repository. The app keeps its built-in+ wallpaper until that folder is present.+ </p>+ </div>+ </div>+ </div>+ );+ }++ return (+ <div className="flex h-full flex-col">+ {header}++ <div className="flex flex-wrap items-center gap-x-4 gap-y-2 border-b border-border px-6 py-3">+ <div className="flex items-center gap-1 rounded-lg border border-border p-0.5">+ <SegmentButton active={theme === "all"} onClick={() => setTheme("all")}>+ All+ </SegmentButton>+ <SegmentButton active={theme === "dark"} onClick={() => setTheme("dark")}>+ <Moon className="h-3 w-3" /> Dark+ </SegmentButton>+ <SegmentButton active={theme === "light"} onClick={() => setTheme("light")}>+ <Sun className="h-3 w-3" /> Light+ </SegmentButton>+ </div>++ <div className="flex items-center gap-1 rounded-lg border border-border p-0.5">+ <SegmentButton+ active={ordering === "mixed"}+ onClick={() => setOrdering("mixed")}+ >+ Mixed+ </SegmentButton>+ <SegmentButton+ active={ordering === "style"}+ onClick={() => setOrdering("style")}+ >+ By style+ </SegmentButton>+ </div>++ <span className="ml-auto text-xs text-muted-foreground">+ {visible.length} shown+ </span>+ </div>++ <div className="flex flex-wrap gap-1.5 border-b border-border px-6 py-2.5">+ <SegmentButton active={style === null} onClick={() => setStyle(null)}>+ All styles+ </SegmentButton>+ {styles.map((entry) => (+ <SegmentButton+ key={entry.slug}+ active={style === entry.slug}+ onClick={() => setStyle(entry.slug)}+ >+ {entry.label}+ </SegmentButton>+ ))}+ </div>++ <ScrollArea className="flex-1">+ <div+ data-testid="wallpaper-grid"+ className="grid gap-3 p-6 [grid-template-columns:repeat(auto-fill,minmax(210px,1fr))]"+ >+ {visible.map((item) => (+ <WallpaperTile+ key={item.id}+ item={item}+ active={item.id === selectedId}+ onOpen={() => setPreviewId(item.id)}+ />+ ))}+ </div>+ {visible.length === 0 && (+ <p className="px-6 pb-6 text-xs text-muted-foreground">+ No wallpaper matches this filter.+ </p>+ )}+ </ScrollArea>++ {previewItem && (+ <WallpaperPreview+ item={previewItem}+ applied={previewItem.id === selectedId}+ onApply={() => select(previewItem.id)}+ onClose={() => setPreviewId(null)}+ onStep={step}+ />+ )}+ </div>+ );+}diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 2973b2ba81..4660249aba 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -56,6 +56,7 @@ from .schema import (event_to_ws_envelope,)from .surface_security import SurfaceSecurity, set_browser_login_required+from .wallpapers import register_wallpaper_routesif TYPE_CHECKING:import uvicorn@@ -1424,6 +1425,11 @@ class WebServer:]}+ # The wallpaper picker. Registered here, with the REST routes, rather+ # than beside the static mounts: those are skipped entirely in dev mode,+ # and the picker has to work against the Vite dev server too.+ register_wallpaper_routes(app)+# ------------------------------------------------------------------# WebSocket# ------------------------------------------------------------------diff --git a/jarvis/ui/web/wallpapers.py b/jarvis/ui/web/wallpapers.pynew file mode 100644index 0000000000..4c792d9297--- /dev/null+++ b/jarvis/ui/web/wallpapers.py@@ -0,0 +1,269 @@+"""The desktop-wallpaper library: catalog, thumbnails, and full-size delivery.++The 500 generated wallpapers are *content*, not source. They live under+``data/jarvis-wallpaper-gallery`` — a git-ignored directory — and are served+from there instead of being copied into the frontend's ``public/`` folder:+147 MB of artwork in the repository would be paid for by every clone, every+build, and every packaged desktop app, including the ones whose owner never+opens the picker.++Two consequences shape this module:++* The library is *optional*. A checkout without it is normal, not broken, so+ the catalog endpoint answers ``available: false`` and the app keeps its+ bundled default wallpaper. Nothing here raises on a missing directory.+* The browse grid must never pull full-size art. Every wallpaper is 1920x1080+ and averages 300 KB; five hundred of those is a 147 MB scroll. Thumbnails are+ derived once, cached on disk, and are what the grid actually requests — the+ full image is downloaded only when a visitor previews or applies one.+"""++from __future__ import annotations++import json+import re+import threading+from dataclasses import dataclass+from pathlib import Path+from typing import Any++from fastapi import FastAPI+from fastapi.responses import FileResponse, JSONResponse+from loguru import logger++from jarvis.core.config import DATA_DIR++#: Where the generated library lives, relative to the project data directory.+LIBRARY_DIRNAME = "jarvis-wallpaper-gallery"++#: Derived thumbnails are cached beside the originals. The leading dot keeps+#: them out of the manifest builder's ``images/`` scan.+THUMBS_DIRNAME = ".thumbs"++#: Long edge of a grid thumbnail. 480 px covers a 240 px tile on a 2x display,+#: which is the widest the grid goes before it adds a column instead.+THUMB_WIDTH = 480++#: Quality for the derived thumbnails. At tile size the difference from 90 is+#: invisible and the file is roughly a third of the size.+THUMB_QUALITY = 72++#: A wallpaper id as written by the manifest builder, e.g.+#: ``01-cinematic-photoreal-07``. Validating against this *and* against the+#: loaded catalog is what keeps a request from reaching outside the library.+_ID_PATTERN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*-\d{2}$")++#: Immutable content: the files are generated once and never edited in place.+_CACHE_HEADERS = {"Cache-Control": "public, max-age=31536000, immutable"}+++@dataclass(frozen=True)+class Wallpaper:+ """One entry of the library, as the browse grid needs to know it."""++ id: str+ title: str+ style: str+ style_label: str+ theme: str+ path: Path+++def library_root() -> Path:+ """Absolute path of the wallpaper library (may not exist)."""+ return DATA_DIR / LIBRARY_DIRNAME+++def _humanize(slug: str) -> str:+ """Turn a directory slug into a display label.++ Used as the fallback when a manifest's ``style`` field is itself a slug+ rather than a written-out name — one of the twenty manifests is, and a+ filter chip reading "bright-photoreal" next to "Watercolor & Ink" looks+ like a bug to the person reading it.+ """+ words = slug.split("-", 1)[-1].split("-")+ return " ".join(word.capitalize() for word in words if word)+++class WallpaperLibrary:+ """Loads the manifests once and answers lookups from memory.++ The catalog is read lazily on first request rather than at import time:+ boot should not pay for twenty JSON files that most sessions never touch.+ """++ def __init__(self, root: Path | None = None) -> None:+ self._root = root or library_root()+ self._lock = threading.Lock()+ self._items: dict[str, Wallpaper] | None = None++ @property+ def root(self) -> Path:+ return self._root++ def _load(self) -> dict[str, Wallpaper]:+ manifests_dir = self._root / "manifests"+ images_dir = self._root / "images"+ if not manifests_dir.is_dir() or not images_dir.is_dir():+ return {}++ items: dict[str, Wallpaper] = {}+ for manifest in sorted(manifests_dir.glob("*.json")):+ try:+ entries = json.loads(manifest.read_text(encoding="utf-8"))+ except (OSError, ValueError) as exc:+ logger.warning("Skipping unreadable wallpaper manifest {}: {}", manifest, exc)+ continue+ if not isinstance(entries, list):+ continue+ style_slug = manifest.stem+ for entry in entries:+ item = self._parse(entry, style_slug)+ if item is not None and item.id not in items:+ items[item.id] = item+ if items:+ logger.debug("Wallpaper library: {} entries from {}", len(items), self._root)+ return items++ def _parse(self, entry: Any, style_slug: str) -> Wallpaper | None:+ if not isinstance(entry, dict):+ return None+ item_id = str(entry.get("id", "")).strip()+ rel = str(entry.get("file", "")).strip()+ theme = str(entry.get("theme", "")).strip()+ if not _ID_PATTERN.match(item_id) or theme not in {"light", "dark"}:+ return None++ # The manifest's own path is untrusted input as far as this loader is+ # concerned — a hand-edited "file" must not be able to point the server+ # at an arbitrary file on disk.+ if not rel.startswith("images/") or ".." in rel or not rel.endswith(".webp"):+ return None+ path = (self._root / rel).resolve()+ try:+ path.relative_to((self._root / "images").resolve())+ except ValueError:+ return None+ if not path.is_file():+ return None++ style_label = str(entry.get("style", "")).strip()+ if not style_label or style_label == style_label.lower().replace(" ", "-"):+ style_label = _humanize(style_slug)+ return Wallpaper(+ id=item_id,+ title=str(entry.get("title", "")).strip() or item_id,+ style=style_slug,+ style_label=style_label,+ theme=theme,+ path=path,+ )++ def items(self) -> dict[str, Wallpaper]:+ with self._lock:+ if self._items is None:+ self._items = self._load()+ return self._items++ def get(self, item_id: str) -> Wallpaper | None:+ if not _ID_PATTERN.match(item_id):+ return None+ return self.items().get(item_id)++ def catalog(self) -> dict[str, Any]:+ """The payload the browse grid is built from — metadata only, no bytes."""+ items = list(self.items().values())+ styles: dict[str, dict[str, Any]] = {}+ for item in items:+ bucket = styles.setdefault(+ item.style,+ {"slug": item.style, "label": item.style_label, "count": 0},+ )+ bucket["count"] += 1+ return {+ "available": bool(items),+ "count": len(items),+ "styles": sorted(styles.values(), key=lambda style: str(style["slug"])),+ "items": [+ {+ "id": item.id,+ "title": item.title,+ "style": item.style,+ "styleLabel": item.style_label,+ "theme": item.theme,+ }+ for item in items+ ],+ }++ def thumbnail(self, item: Wallpaper) -> Path:+ """Return a cached grid thumbnail, deriving it on first request.++ Falls back to the original file when Pillow is unavailable or the+ resize fails: a heavier grid is a far better outcome than an empty one.+ """+ target = self._root / THUMBS_DIRNAME / item.style / f"{item.id}.webp"+ try:+ if target.is_file() and target.stat().st_mtime >= item.path.stat().st_mtime:+ return target+ except OSError:+ return item.path++ try:+ from PIL import Image+ except ImportError:+ return item.path++ try:+ target.parent.mkdir(parents=True, exist_ok=True)+ with Image.open(item.path) as source:+ source.load()+ thumb = source.convert("RGB")+ height = max(1, round(thumb.height * THUMB_WIDTH / thumb.width))+ thumb = thumb.resize((THUMB_WIDTH, height), Image.Resampling.LANCZOS)+ # Write via a per-item temporary name: two browsers scrolling+ # the same row must not read a half-written file.+ staging = target.with_suffix(".webp.part")+ thumb.save(staging, "WEBP", quality=THUMB_QUALITY, method=4)+ staging.replace(target)+ return target+ except (OSError, ValueError) as exc:+ logger.warning("Could not derive wallpaper thumbnail for {}: {}", item.id, exc)+ return item.path+++def register_wallpaper_routes(app: FastAPI, library: WallpaperLibrary | None = None) -> None:+ """Mount the wallpaper endpoints under ``/api``.++ Deliberately under ``/api`` rather than a static mount of its own: that+ prefix is already proxied by the Vite dev server, so the picker behaves+ identically in development and in the packaged app.+ """+ lib = library or WallpaperLibrary()++ @app.get("/api/wallpapers")+ async def list_wallpapers() -> dict[str, Any]:+ return lib.catalog()++ @app.get("/api/wallpapers/{item_id}/thumb", response_model=None)+ async def wallpaper_thumb(item_id: str) -> FileResponse | JSONResponse:+ item = lib.get(item_id)+ if item is None:+ return JSONResponse({"detail": "Not Found"}, status_code=404)+ return FileResponse(+ str(lib.thumbnail(item)),+ media_type="image/webp",+ headers=_CACHE_HEADERS,+ )++ @app.get("/api/wallpapers/{item_id}/full", response_model=None)+ async def wallpaper_full(item_id: str) -> FileResponse | JSONResponse:+ item = lib.get(item_id)+ if item is None:+ return JSONResponse({"detail": "Not Found"}, status_code=404)+ return FileResponse(+ str(item.path),+ media_type="image/webp",+ headers=_CACHE_HEADERS,+ )diff --git a/scripts/build_wallpaper_thumbs.py b/scripts/build_wallpaper_thumbs.pynew file mode 100644index 0000000000..6bc61e17d2--- /dev/null+++ b/scripts/build_wallpaper_thumbs.py@@ -0,0 +1,46 @@+"""Pre-derive the grid thumbnails for the desktop-wallpaper library.++The server derives a missing thumbnail on demand, so this script is an+optimisation, not a prerequisite: it moves five hundred resizes off the first+visit to the Wallpaper section, where they would otherwise trickle in as the+grid scrolls.++ python scripts/build_wallpaper_thumbs.py++Re-running is cheap — thumbnails newer than their source are left alone.+"""++from __future__ import annotations++import sys+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from jarvis.ui.web.wallpapers import WallpaperLibrary # noqa: E402+++def main() -> int:+ library = WallpaperLibrary()+ items = list(library.items().values())+ if not items:+ print(f"No wallpaper library found at {library.root} — nothing to do.")+ return 0++ print(f"Deriving thumbnails for {len(items)} wallpapers…")+ derived = 0+ # Pillow releases the GIL around encode/decode, so threads genuinely help+ # here; the work is IO plus C-level image code, not Python bytecode.+ with ThreadPoolExecutor() as pool:+ for item, thumb in zip(items, pool.map(library.thumbnail, items), strict=True):+ if thumb != item.path:+ derived += 1+ else:+ print(f" ! fell back to the full image for {item.id}")+ print(f"Done: {derived}/{len(items)} thumbnails available.")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/unit/ui/test_wallpaper_routes.py b/tests/unit/ui/test_wallpaper_routes.pynew file mode 100644index 0000000000..f464c5bf4e--- /dev/null+++ b/tests/unit/ui/test_wallpaper_routes.py@@ -0,0 +1,209 @@+"""Tests for the desktop-wallpaper library endpoints.++Contract (see jarvis/ui/web/wallpapers.py):+- GET /api/wallpapers -> catalog metadata; ``available: false``+ instead of an error when the generated+ library is not installed.+- GET /api/wallpapers/{id}/thumb -> a small derived WebP for the browse+ grid, cached on disk after the first+ request. Never the full-size file when+ Pillow is available.+- GET /api/wallpapers/{id}/full -> the original 1920x1080 artwork.+- Unknown or malformed ids -> 404, including ids that try to walk out+ of the library directory.++The library itself is content living under a git-ignored ``data/`` directory,+so these tests build a miniature one in a tmp_path rather than depending on the+five hundred generated files being present.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.ui.web.wallpapers import (+ THUMB_WIDTH,+ WallpaperLibrary,+ register_wallpaper_routes,+)+++def _write_wallpaper(path: Path, color: tuple[int, int, int]) -> None:+ from PIL import Image++ path.parent.mkdir(parents=True, exist_ok=True)+ Image.new("RGB", (1920, 1080), color).save(path, "WEBP", quality=80)+++def library(tmp_path: Path) -> WallpaperLibrary:+ """A two-entry library with the same shape as the generated one."""+ root = tmp_path / "jarvis-wallpaper-gallery"+ _write_wallpaper(root / "images" / "01-cinematic-photoreal" / "01.webp", (12, 18, 30))+ _write_wallpaper(root / "images" / "03-anime-neon" / "01.webp", (220, 90, 200))++ manifests = root / "manifests"+ manifests.mkdir(parents=True)+ (manifests / "01-cinematic-photoreal.json").write_text(+ json.dumps(+ [+ {+ "id": "01-cinematic-photoreal-01",+ "title": "Flooded Observatory",+ "style": "Cinematic Photorealistic",+ "theme": "dark",+ "file": "images/01-cinematic-photoreal/01.webp",+ "prompt": "…",+ }+ ]+ ),+ encoding="utf-8",+ )+ # A manifest whose `style` is still a slug — the loader is expected to make+ # it presentable rather than show "anime-neon" beside written-out names.+ (manifests / "03-anime-neon.json").write_text(+ json.dumps(+ [+ {+ "id": "03-anime-neon-01",+ "title": "Neon Crossing",+ "style": "anime-neon",+ "theme": "light",+ "file": "images/03-anime-neon/01.webp",+ "prompt": "…",+ }+ ]+ ),+ encoding="utf-8",+ )+ return WallpaperLibrary(root)+++def client(library: WallpaperLibrary) -> TestClient:+ app = FastAPI()+ register_wallpaper_routes(app, library)+ return TestClient(app)+++def test_catalog_lists_every_entry(client: TestClient) -> None:+ payload = client.get("/api/wallpapers").json()++ assert payload["available"] is True+ assert payload["count"] == 2+ assert {item["id"] for item in payload["items"]} == {+ "01-cinematic-photoreal-01",+ "03-anime-neon-01",+ }+ assert {style["slug"] for style in payload["styles"]} == {+ "01-cinematic-photoreal",+ "03-anime-neon",+ }+++def test_catalog_carries_no_image_bytes(client: TestClient) -> None:+ """The grid is built from metadata; the pictures come later, one by one."""+ payload = client.get("/api/wallpapers").json()++ assert set(payload["items"][0]) == {"id", "title", "style", "styleLabel", "theme"}+++def test_slug_style_labels_are_made_readable(client: TestClient) -> None:+ payload = client.get("/api/wallpapers").json()+ labels = {item["id"]: item["styleLabel"] for item in payload["items"]}++ assert labels["03-anime-neon-01"] == "Anime Neon"+++def test_missing_library_reports_itself_absent(tmp_path: Path) -> None:+ app = FastAPI()+ register_wallpaper_routes(app, WallpaperLibrary(tmp_path / "nothing-here"))++ payload = TestClient(app).get("/api/wallpapers").json()++ assert payload == {"available": False, "count": 0, "styles": [], "items": []}+++def test_thumbnail_is_far_smaller_than_the_original(+ client: TestClient, library: WallpaperLibrary+) -> None:+ from PIL import Image++ response = client.get("/api/wallpapers/01-cinematic-photoreal-01/thumb")++ assert response.status_code == 200+ assert response.headers["content-type"] == "image/webp"+ original = library.get("01-cinematic-photoreal-01")+ assert original is not None+ assert len(response.content) < original.path.stat().st_size++ import io++ with Image.open(io.BytesIO(response.content)) as thumb:+ assert thumb.width == THUMB_WIDTH+++def test_thumbnail_is_cached_on_disk(client: TestClient, library: WallpaperLibrary) -> None:+ client.get("/api/wallpapers/01-cinematic-photoreal-01/thumb")++ cached = library.root / ".thumbs" / "01-cinematic-photoreal" / "01-cinematic-photoreal-01.webp"+ assert cached.is_file()+ # No leftover staging files from the atomic write.+ assert not list(cached.parent.glob("*.part"))+++def test_full_serves_the_original_artwork(client: TestClient, library: WallpaperLibrary) -> None:+ response = client.get("/api/wallpapers/01-cinematic-photoreal-01/full")++ original = library.get("01-cinematic-photoreal-01")+ assert original is not None+ assert response.status_code == 200+ assert response.content == original.path.read_bytes()+++ "item_id",+ [+ "does-not-exist-01",+ "../../../etc/passwd",+ "01-cinematic-photoreal-01/../../../secret",+ "",+ ],+)+def test_unknown_ids_are_refused(client: TestClient, item_id: str) -> None:+ assert client.get(f"/api/wallpapers/{item_id}/full").status_code == 404+++def test_manifest_paths_pointing_outside_the_library_are_dropped(+ tmp_path: Path,+) -> None:+ """A hand-edited manifest must not turn the server into a file browser."""+ root = tmp_path / "gallery"+ _write_wallpaper(root / "images" / "01-style" / "01.webp", (1, 2, 3))+ secret = tmp_path / "secret.webp"+ _write_wallpaper(secret, (9, 9, 9))++ manifests = root / "manifests"+ manifests.mkdir(parents=True)+ (manifests / "01-style.json").write_text(+ json.dumps(+ [+ {+ "id": "01-style-01",+ "title": "Escape",+ "style": "Style",+ "theme": "dark",+ "file": "images/../../secret.webp",+ "prompt": "…",+ }+ ]+ ),+ encoding="utf-8",+ )++ assert WallpaperLibrary(root).items() == {}