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(pets): My Pets settings page, pet style card and live event wiring
rubenluetke10-beep2ab5deb29124
diff --git a/jarvis/ui/web/frontend/src/components/agentic/VoiceBubble.tsx b/jarvis/ui/web/frontend/src/components/agentic/VoiceBubble.tsxindex 610bd7ad97..d7468a17dd 100644--- a/jarvis/ui/web/frontend/src/components/agentic/VoiceBubble.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/VoiceBubble.tsx@@ -66,6 +66,7 @@ import {} from "lucide-react";import { cn } from "@/lib/utils";import { useEventStore, type VoiceState } from "@/store/events";+import { SPEAKER_MUTE_EVENT } from "@/lib/speakerMute";import {fetchTtsVolume,requestVoiceHangup,@@ -433,6 +434,18 @@ export function VoiceBubble({};}, [mounted]);+ // A mute from anywhere else (the desktop pet's speaker disc, another+ // window) arrives as the backend's VoiceSpeakerMuteChanged; mirror it.+ useEffect(() => {+ if (!mounted) return;+ const onMuteChanged = (event: Event) => {+ const muted = (event as CustomEvent<{ muted?: unknown }>).detail?.muted;+ if (typeof muted === "boolean") setMuted(muted);+ };+ window.addEventListener(SPEAKER_MUTE_EVENT, onMuteChanged);+ return () => window.removeEventListener(SPEAKER_MUTE_EVENT, onMuteChanged);+ }, [mounted]);+// Only a parent that can actually move the grid makes the card a link —// otherwise it stays a plain report, because a link that goes nowhere is// worse than no link.diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsxindex 2b5ff05851..4316cae25c 100644--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx@@ -26,7 +26,6 @@ import { cn } from "@/lib/utils";import { useMemo, useRef, useState, type ReactNode } from "react";import { useT } from "@/i18n";import { RecentChats } from "@/components/home/RecentChats";-import { useConversations } from "@/hooks/useConversations";import { useHomeStore } from "@/store/home";import { useAgentChatStore } from "@/store/agentChat";import { IdeProjectTree } from "@/components/agentic/IdeProjectTree";@@ -36,6 +35,7 @@ import { usePublishIdentity } from "@/components/marketplace/PublishIdentity";import { GigiMark } from "@/components/GigiMark";import * as Dialog from "@radix-ui/react-dialog";import { startNewVoiceRun } from "@/lib/chatsApi";+import { startNewTextChat } from "@/lib/newChat";/** Why `clsx` and not `cn` on the rows below.@@ -180,7 +180,6 @@ export function Sidebar({const appInstance = useAppInstance();const devTag = appInstance?.isDev ? appInstance.name.toUpperCase() : null;// New chat offers both conversation types independently of the current view.- const { newChat } = useConversations();const newAgentChat = useAgentChatStore((s) => s.newChat);const setSurface = useHomeStore((s) => s.setSurface);// The front page's nav row names the face the switch picked (Voice / Chat),@@ -226,10 +225,7 @@ export function Sidebar({const startingVoiceRef = useRef(false);const identity = usePublishIdentity();const startNewChat = () => {- newChat();- newAgentChat();- setSurface("chat");- setActive("chats");+ startNewTextChat();setNewChatOpen(false);};const startVoiceChat = async () => {diff --git a/jarvis/ui/web/frontend/src/components/layout/navGroups.ts b/jarvis/ui/web/frontend/src/components/layout/navGroups.tsindex 2f06486a8c..8e26cb9307 100644--- a/jarvis/ui/web/frontend/src/components/layout/navGroups.ts+++ b/jarvis/ui/web/frontend/src/components/layout/navGroups.ts@@ -32,6 +32,7 @@ import {Users,Wallet,Workflow,+ PawPrint,ScanLine,ShieldCheck,type LucideIcon,@@ -267,6 +268,7 @@ export const NAV_FOOTER_ITEMS: NavItem[] = [*/export const SETTINGS_HUB_ONLY_ITEMS: NavItem[] = [{ id: "appshots", labelKey: "nav.appshots", icon: ScanLine, fallbackLabel: "Appshots" },+ { id: "pets", labelKey: "nav.pets", icon: PawPrint, fallbackLabel: "My Pets" },{id: "jarvis-actions",labelKey: "nav.jarvis_actions",@@ -299,6 +301,7 @@ export const SETTINGS_HUB_IDS: readonly SectionId[] = ["local-models","computers","appshots",+ "pets","jarvis-actions","costs","feedback",diff --git a/jarvis/ui/web/frontend/src/components/overlay/OverlayStylePreviews.tsx b/jarvis/ui/web/frontend/src/components/overlay/OverlayStylePreviews.tsxindex e4b0c1e1d4..073d1cd796 100644--- a/jarvis/ui/web/frontend/src/components/overlay/OverlayStylePreviews.tsx+++ b/jarvis/ui/web/frontend/src/components/overlay/OverlayStylePreviews.tsx@@ -18,7 +18,7 @@ import {/*** Shared visual previews for the on-screen overlay styles (Bar / Mascot /- * Voice orb / None).+ * Voice orb / Pet / None).** Lifted out of ``views/settings/OverlayTaskbarGroup.tsx`` so both the Settings* panel and the onboarding "System Style" step can render the same graphics@@ -55,6 +55,7 @@ export function StylePreview({ style }: { style: OverlayStyle }) {// runs, at thumbnail size. Held at "idle" so the picker shows the calm// resting look rather than pretending a session is live.if (style === "voice_orb") return <VoiceOrb state="idle" size={46} />;+ if (style === "pet") return <PetPreview />;if (style === "jarvis_bar") return <BarPreview />;return <NonePreview />;}@@ -91,6 +92,56 @@ export function BarPreview() {);}+/*+ * A pixel pet, one row per string: "#" is a filled pixel. Drawn here rather+ * than cut from a real sprite sheet because the picker renders before (and+ * without) the pets API; the page that picks the actual pet shows the real one.+ */+const PET_PIXELS = [+ "..####..",+ ".######.",+ "########",+ "##.##.##",+ "########",+ "########",+ "#..##..#",+];+const PET_PX = 3;++/**+ * The pet style: a pixel companion above its control strip — the pen disc,+ * then the pill with microphone, talk orb and speaker. Same desktop palette as+ * the bar thumbnail, for the same reason.+ */+export function PetPreview() {+ const petW = PET_PIXELS[0].length * PET_PX;+ const petX = (56 - petW) / 2;+ return (+ <svg viewBox="0 0 56 46" className="h-14" aria-hidden="true">+ {PET_PIXELS.flatMap((line, y) =>+ [...line].map((cell, x) =>+ cell === "#" ? (+ <rect+ key={`px-${x}-${y}`}+ x={petX + x * PET_PX}+ y={2 + y * PET_PX}+ width={PET_PX}+ height={PET_PX}+ fill={PREVIEW_BAR}+ />+ ) : null,+ ),+ )}+ <circle cx="11" cy="37" r="5.5" fill={PREVIEW_BG} stroke={PREVIEW_RIM} strokeWidth="1" />+ <rect x="9.5" y="34.5" width="3" height="5" rx="0.8" fill={PREVIEW_BAR} transform="rotate(35 11 37)" />+ <rect x="19" y="31.5" width="33" height="11" rx="5.5" fill={PREVIEW_BG} stroke={PREVIEW_RIM} strokeWidth="1" />+ <rect x="25" y="34.5" width="3" height="5" rx="1.5" fill={PREVIEW_BAR} />+ <circle cx="35.5" cy="37" r="3.2" fill={PREVIEW_BAR} />+ <path d="M43 35.5h1.6l2-1.8v6.6l-2-1.8H43z" fill={PREVIEW_BAR} />+ </svg>+ );+}+export function NonePreview() {return (<svgdiff --git a/jarvis/ui/web/frontend/src/components/pets/CreatePetDialog.test.tsx b/jarvis/ui/web/frontend/src/components/pets/CreatePetDialog.test.tsxnew file mode 100644index 0000000000..8c27b8a9b0--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/pets/CreatePetDialog.test.tsx@@ -0,0 +1,140 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { CreatePetDialog, fieldForDetail } from "@/components/pets/CreatePetDialog";++function png(name = "sheet.png", bytes = 64): File {+ return new File([new Uint8Array(bytes)], name, { type: "image/png" });+}++function renderDialog(onCreated = vi.fn()) {+ const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });+ render(+ <QueryClientProvider client={client}>+ <CreatePetDialog open onOpenChange={vi.fn()} onCreated={onCreated} />+ </QueryClientProvider>,+ );+ return onCreated;+}++function fill(name: string, file: File) {+ fireEvent.change(screen.getByTestId("create-pet-name"), { target: { value: name } });+ fireEvent.change(screen.getByTestId("create-pet-sheet"), { target: { files: [file] } });+}++beforeEach(() => {+ // jsdom has no object URLs; the preview only needs a string.+ URL.createObjectURL = vi.fn(() => "blob:preview");+ URL.revokeObjectURL = vi.fn();+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe("CreatePetDialog", () => {+ it("lists the sheet rows in state order", () => {+ renderDialog();+ const rows = screen.getByTestId("create-pet-rows").textContent ?? "";+ expect(rows.indexOf("Idle")).toBeLessThan(rows.indexOf("Listening"));+ expect(rows.indexOf("Error")).toBeLessThan(rows.indexOf("Sleeping"));+ });++ it("offers the empty template sheet as a download", () => {+ renderDialog();+ const link = screen.getByTestId("create-pet-template");+ expect(link.getAttribute("href")).toBe("/api/pets/template.png");+ expect(link.hasAttribute("download")).toBe(true);+ expect(link.textContent).toBe("Download template");+ });++ it("refuses a file that is not a PNG before uploading anything", () => {+ const fetchSpy = vi.fn();+ vi.stubGlobal("fetch", fetchSpy);+ renderDialog();++ fireEvent.change(screen.getByTestId("create-pet-sheet"), {+ target: { files: [new File(["x"], "sheet.gif", { type: "image/gif" })] },+ });++ expect(screen.getByRole("alert").textContent).toBe("Choose a PNG image.");+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it("refuses a sheet over 2 MB", () => {+ renderDialog();+ fireEvent.change(screen.getByTestId("create-pet-sheet"), {+ target: { files: [png("big.png", 2 * 1024 * 1024 + 1)] },+ });+ expect(screen.getByRole("alert").textContent).toBe("This image is larger than 2 MB.");+ });++ it("asks for a name before uploading", () => {+ const fetchSpy = vi.fn();+ vi.stubGlobal("fetch", fetchSpy);+ renderDialog();+ fireEvent.change(screen.getByTestId("create-pet-sheet"), { target: { files: [png()] } });+ fireEvent.click(screen.getByTestId("create-pet-submit"));+ expect(screen.getByRole("alert").textContent).toBe("Give your pet a name.");+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it("uploads the form and hands the new pet back", async () => {+ const created = {+ id: "u0123456789abcdef",+ name: "Pixel",+ description: "",+ builtin: false,+ frame_size: 32,+ animations: {},+ sheet_url: "/api/pets/u0123456789abcdef/sheet.png",+ };+ const fetchSpy = vi.fn(async () => ({ ok: true, status: 201, json: async () => created }));+ vi.stubGlobal("fetch", fetchSpy);+ const onCreated = renderDialog();++ fill("Pixel", png());+ fireEvent.click(screen.getByTestId("create-pet-frame-32"));+ fireEvent.click(screen.getByTestId("create-pet-submit"));++ await waitFor(() => expect(onCreated).toHaveBeenCalledWith(created));+ const [url, init] = fetchSpy.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toBe("/api/pets");+ expect(init.method).toBe("POST");+ const form = init.body as FormData;+ expect(form.get("name")).toBe("Pixel");+ expect(form.get("frame_size")).toBe("32");+ expect(form.get("sheet")).toBeInstanceOf(File);+ expect(form.get("manifest")).toBeNull();+ });++ it("shows the server's refusal at the field it names", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => ({+ ok: false,+ status: 400,+ json: async () => ({ detail: "The sheet is 600 × 600 pixels; the limit is 512 × 512." }),+ })),+ );+ renderDialog();++ fill("Pixel", png());+ fireEvent.click(screen.getByTestId("create-pet-submit"));++ const alert = await screen.findByRole("alert");+ expect(alert.textContent).toContain("the limit is 512");+ expect(alert.id).toContain("sheet");+ });+});++describe("fieldForDetail", () => {+ it("routes a refusal to the part it is about", () => {+ expect(fieldForDetail("manifest: idle is required")).toBe("manifest");+ expect(fieldForDetail("description is longer than 140 characters")).toBe("description");+ expect(fieldForDetail("name must be 1-40 characters")).toBe("name");+ expect(fieldForDetail("not a PNG")).toBe("sheet");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/pets/CreatePetDialog.tsx b/jarvis/ui/web/frontend/src/components/pets/CreatePetDialog.tsxnew file mode 100644index 0000000000..7dfd69daf9--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/pets/CreatePetDialog.tsx@@ -0,0 +1,414 @@+import { useEffect, useId, useRef, useState } from "react";+import * as Dialog from "@radix-ui/react-dialog";+import { Download, FileJson, ImageUp, Loader2, X } from "lucide-react";++import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { useCreatePet } from "@/hooks/usePets";+import { useT } from "@/i18n";+import { FRAME_SIZES, MAX_FRAMES_PER_STATE, PET_STATES } from "@/lib/petStates";+import { PET_TEMPLATE_URL, PetsRequestError, type Pet } from "@/lib/petsApi";+import { cn } from "@/lib/utils";++/** Mirrors the loader's limits (`jarvis/ui/pets/manifest.py`, docs/pets.md). */+const MAX_NAME = 40;+const MAX_DESCRIPTION = 140;+const MAX_SHEET_BYTES = 2 * 1024 * 1024;+const DEFAULT_FRAME_SIZE = 48;++type Field = "name" | "description" | "sheet" | "manifest";++/**+ * Which field a server refusal belongs to, read from its `detail`. The+ * backend names the part it rejected ("manifest: …", "name must be …"); a+ * detail that names none is about the picture, the part most likely wrong.+ */+export function fieldForDetail(detail: string): Field {+ const text = detail.toLowerCase();+ if (text.includes("manifest") || text.includes("pet.json")) return "manifest";+ if (text.includes("description")) return "description";+ if (/\bname\b/.test(text)) return "name";+ return "sheet";+}++function isPng(file: File): boolean {+ return file.type === "image/png" || file.name.toLowerCase().endsWith(".png");+}++function isJson(file: File): boolean {+ return file.type === "application/json" || file.name.toLowerCase().endsWith(".json");+}++/**+ * "Create pet": upload a sprite sheet in the `jarvis-pet/1` layout, name it,+ * and it joins the grid (and becomes the active pet). The checks here are the+ * cheap ones — type and size — so a wrong file is caught before an upload;+ * the backend loader stays the authority and its `detail` lands at the field+ * it is about.+ */+export function CreatePetDialog({+ open,+ onOpenChange,+ onCreated,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onCreated: (pet: Pet) => void;+}) {+ const t = useT();+ const create = useCreatePet();+ const formId = useId();+ const sheetInput = useRef<HTMLInputElement>(null);+ const manifestInput = useRef<HTMLInputElement>(null);++ const [name, setName] = useState("");+ const [description, setDescription] = useState("");+ const [sheet, setSheet] = useState<File | null>(null);+ const [sheetUrl, setSheetUrl] = useState<string | null>(null);+ const [frameSize, setFrameSize] = useState<number>(DEFAULT_FRAME_SIZE);+ const [manifest, setManifest] = useState<File | null>(null);+ const [errors, setErrors] = useState<Partial<Record<Field, string>>>({});++ // A fresh form every time the dialog opens.+ useEffect(() => {+ if (!open) return;+ setName("");+ setDescription("");+ setSheet(null);+ setFrameSize(DEFAULT_FRAME_SIZE);+ setManifest(null);+ setErrors({});+ }, [open]);++ // The preview is a local object URL; release it when the file changes.+ useEffect(() => {+ if (!sheet) {+ setSheetUrl(null);+ return;+ }+ const url = URL.createObjectURL(sheet);+ setSheetUrl(url);+ return () => URL.revokeObjectURL(url);+ }, [sheet]);++ function pickSheet(file: File | undefined) {+ if (!file) return;+ if (!isPng(file)) {+ setErrors((e) => ({ ...e, sheet: t("pets.create_dialog.error_not_png") }));+ return;+ }+ if (file.size > MAX_SHEET_BYTES) {+ setErrors((e) => ({ ...e, sheet: t("pets.create_dialog.error_too_big") }));+ return;+ }+ setErrors((e) => ({ ...e, sheet: undefined }));+ setSheet(file);+ }++ function pickManifest(file: File | undefined) {+ if (!file) return;+ if (!isJson(file)) {+ setErrors((e) => ({ ...e, manifest: t("pets.create_dialog.error_manifest") }));+ return;+ }+ setErrors((e) => ({ ...e, manifest: undefined }));+ setManifest(file);+ }++ async function submit(event: React.FormEvent) {+ event.preventDefault();+ const trimmed = name.trim();+ const next: Partial<Record<Field, string>> = {};+ if (!trimmed) next.name = t("pets.create_dialog.error_name");+ if (!sheet) next.sheet = t("pets.create_dialog.error_no_sheet");+ if (next.name || next.sheet) {+ setErrors(next);+ return;+ }+ setErrors({});+ try {+ const manifestText = manifest ? await manifest.text() : null;+ const pet = await create.mutateAsync({+ sheet: sheet as File,+ name: trimmed,+ description: description.trim(),+ frameSize,+ manifest: manifestText,+ });+ onCreated(pet);+ onOpenChange(false);+ } catch (error) {+ const message = (error as Error).message;+ if (error instanceof PetsRequestError && error.status === 400) {+ setErrors({ [fieldForDetail(message)]: message });+ } else {+ setErrors({ sheet: message });+ }+ }+ }++ const busy = create.isPending;+ const errorId = (field: Field) => `${formId}-${field}-error`;+ const fieldError = (field: Field) =>+ errors[field] ? (+ <p id={errorId(field)} role="alert" className="mt-1.5 text-sm text-destructive">+ {errors[field]}+ </p>+ ) : null;++ return (+ <Dialog.Root open={open} onOpenChange={(next) => !busy && onOpenChange(next)}>+ <Dialog.Portal>+ <Dialog.Overlay className="fixed inset-0 z-[80] bg-scrim/75 backdrop-blur-sm data-[state=open]:animate-in data-[state=open]:fade-in-0 motion-reduce:animate-none" />+ <Dialog.Content+ data-testid="create-pet-dialog"+ className="fixed inset-0 z-[80] m-auto flex h-fit max-h-[min(90dvh,760px)] w-[min(560px,calc(100vw-32px))] flex-col overflow-hidden rounded-2xl border border-border bg-popover text-popover-foreground shadow-float outline-none data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 motion-reduce:animate-none"+ >+ <div className="flex items-start justify-between gap-4 border-b border-border px-6 py-4">+ <div className="min-w-0">+ <Dialog.Title className="text-lg font-semibold text-foreground-strong">+ {t("pets.create_dialog.title")}+ </Dialog.Title>+ <Dialog.Description className="mt-0.5 text-sm text-muted-foreground">+ {t("pets.create_dialog.description")}+ </Dialog.Description>+ </div>+ <Dialog.Close+ disabled={busy}+ aria-label={t("common.close")}+ className="grid h-8 w-8 shrink-0 place-items-center rounded-lg text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"+ >+ <X className="h-4 w-4" aria-hidden />+ </Dialog.Close>+ </div>++ <form+ id={formId}+ noValidate+ onSubmit={(event) => void submit(event)}+ className="min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5 scrollbar-jarvis"+ >+ <div>+ <div className="flex items-baseline justify-between gap-3">+ <label htmlFor={`${formId}-name`} className="text-sm font-medium text-foreground">+ {t("pets.create_dialog.name_label")}+ </label>+ <span className="text-xs text-foreground-faint">{`${name.length}/${MAX_NAME}`}</span>+ </div>+ <Input+ id={`${formId}-name`}+ data-testid="create-pet-name"+ className="mt-1.5"+ value={name}+ maxLength={MAX_NAME}+ placeholder={t("pets.create_dialog.name_placeholder")}+ aria-invalid={errors.name ? true : undefined}+ aria-describedby={errors.name ? errorId("name") : undefined}+ onChange={(event) => setName(event.target.value)}+ />+ {fieldError("name")}+ </div>++ <div>+ <div className="flex items-baseline justify-between gap-3">+ <label+ htmlFor={`${formId}-description`}+ className="text-sm font-medium text-foreground"+ >+ {t("pets.create_dialog.description_label")}+ </label>+ <span className="text-xs text-foreground-faint">+ {`${description.length}/${MAX_DESCRIPTION}`}+ </span>+ </div>+ <Input+ id={`${formId}-description`}+ data-testid="create-pet-description"+ className="mt-1.5"+ value={description}+ maxLength={MAX_DESCRIPTION}+ placeholder={t("pets.create_dialog.description_placeholder")}+ aria-invalid={errors.description ? true : undefined}+ aria-describedby={errors.description ? errorId("description") : undefined}+ onChange={(event) => setDescription(event.target.value)}+ />+ {fieldError("description")}+ </div>++ <div>+ <p className="text-sm font-medium text-foreground">+ {t("pets.create_dialog.sheet_label")}+ </p>+ <div className="mt-1.5 flex items-center gap-4 rounded-lg border border-dashed border-border-strong p-3">+ <div className="grid h-20 w-20 shrink-0 place-items-center overflow-hidden rounded-md bg-secondary">+ {sheetUrl ? (+ <img+ src={sheetUrl}+ alt={t("pets.create_dialog.sheet_preview_alt")}+ className="max-h-full max-w-full object-contain [image-rendering:pixelated]"+ />+ ) : (+ <ImageUp className="h-6 w-6 text-muted-foreground" aria-hidden />+ )}+ </div>+ <div className="min-w-0 flex-1">+ {sheet && (+ <p className="truncate text-sm font-medium text-foreground">{sheet.name}</p>+ )}+ <p className="text-xs text-muted-foreground">+ {t("pets.create_dialog.sheet_hint")}+ </p>+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="mt-2"+ onClick={() => sheetInput.current?.click()}+ >+ {sheet ? t("pets.create_dialog.sheet_change") : t("pets.create_dialog.sheet_choose")}+ </Button>+ <input+ ref={sheetInput}+ type="file"+ accept="image/png"+ className="sr-only"+ tabIndex={-1}+ data-testid="create-pet-sheet"+ aria-label={t("pets.create_dialog.sheet_label")}+ onChange={(event) => {+ pickSheet(event.target.files?.[0]);+ event.target.value = "";+ }}+ />+ </div>+ </div>+ {fieldError("sheet")}+ </div>++ <div>+ <p id={`${formId}-frame`} className="text-sm font-medium text-foreground">+ {t("pets.create_dialog.frame_size_label")}+ </p>+ <div+ role="radiogroup"+ aria-labelledby={`${formId}-frame`}+ className="mt-1.5 inline-flex rounded-lg border border-border bg-background p-0.5"+ >+ {FRAME_SIZES.map((size) => (+ <button+ key={size}+ type="button"+ role="radio"+ aria-checked={frameSize === size}+ data-testid={`create-pet-frame-${size}`}+ onClick={() => setFrameSize(size)}+ className={cn(+ "rounded-md px-3 py-1.5 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ frameSize === size+ ? "bg-secondary text-foreground-strong"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {t("pets.create_dialog.frame_size_option").replaceAll("{0}", String(size))}+ </button>+ ))}+ </div>+ </div>++ <div className="rounded-lg bg-secondary/60 p-4">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <p className="text-sm font-medium text-foreground">+ {t("pets.create_dialog.layout_title")}+ </p>+ <a+ href={PET_TEMPLATE_URL}+ download="pet-template.png"+ data-testid="create-pet-template"+ className="inline-flex items-center gap-1.5 rounded-md text-sm font-medium text-accent hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <Download className="h-3.5 w-3.5" aria-hidden />+ {t("pets.create_dialog.template_download")}+ </a>+ </div>+ <p className="mt-1 text-sm text-muted-foreground">+ {t("pets.create_dialog.layout_body").replace("{0}", String(MAX_FRAMES_PER_STATE))}+ </p>+ <ol className="mt-3 flex flex-wrap gap-1.5" data-testid="create-pet-rows">+ {PET_STATES.map((state, row) => (+ <li+ key={state}+ className="flex items-center gap-1.5 rounded-md border border-border bg-background px-2 py-1 text-xs text-foreground"+ >+ <span className="font-mono text-foreground-faint">{row + 1}</span>+ {t(`pets.states.${state}`)}+ </li>+ ))}+ </ol>+ </div>++ <div>+ <p className="text-sm font-medium text-foreground">+ {t("pets.create_dialog.manifest_label")}+ </p>+ <p className="mt-0.5 text-xs text-muted-foreground">+ {t("pets.create_dialog.manifest_hint")}+ </p>+ <div className="mt-2 flex flex-wrap items-center gap-2">+ {manifest ? (+ <>+ <span className="inline-flex min-w-0 items-center gap-1.5 rounded-md border border-border bg-background px-2 py-1 text-sm text-foreground">+ <FileJson className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />+ <span className="truncate">{manifest.name}</span>+ </span>+ <Button type="button" variant="ghost" size="sm" onClick={() => setManifest(null)}>+ {t("pets.create_dialog.manifest_remove")}+ </Button>+ </>+ ) : (+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => manifestInput.current?.click()}+ >+ <FileJson aria-hidden />+ {t("pets.create_dialog.manifest_choose")}+ </Button>+ )}+ <input+ ref={manifestInput}+ type="file"+ accept=".json,application/json"+ className="sr-only"+ tabIndex={-1}+ data-testid="create-pet-manifest"+ aria-label={t("pets.create_dialog.manifest_label")}+ onChange={(event) => {+ pickManifest(event.target.files?.[0]);+ event.target.value = "";+ }}+ />+ </div>+ {fieldError("manifest")}+ </div>+ </form>++ <div className="flex justify-end gap-2 border-t border-border px-6 py-4">+ <Button+ type="button"+ variant="ghost"+ disabled={busy}+ onClick={() => onOpenChange(false)}+ >+ {t("common.cancel")}+ </Button>+ <Button type="submit" form={formId} disabled={busy} data-testid="create-pet-submit">+ {busy && <Loader2 className="animate-spin" aria-hidden />}+ {busy ? t("pets.create_dialog.creating") : t("pets.create_dialog.create")}+ </Button>+ </div>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/pets/PetControlStripPreview.tsx b/jarvis/ui/web/frontend/src/components/pets/PetControlStripPreview.tsxnew file mode 100644index 0000000000..2e6df9b58e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/pets/PetControlStripPreview.tsx@@ -0,0 +1,52 @@+import { Mic, PenLine, Volume2 } from "lucide-react";++import { cn } from "@/lib/utils";++/**+ * A still picture of the control strip the desktop pet carries: the pen disc+ * (new chat), then one pill holding the microphone, the talk orb and the+ * speaker. Shown on the settings page so the user knows what sits under the+ * pet before switching it on.+ *+ * Deliberately NOT a set of buttons: the real controls live on the desktop,+ * and a look-alike that reacted to clicks here would promise something it+ * cannot do. Hence no roles, no focus, and `aria-hidden`.+ */+export function PetControlStripPreview({+ size = "md",+ className,+}: {+ size?: "sm" | "md";+ className?: string;+}) {+ const small = size === "sm";+ const disc = small ? "h-6 w-6" : "h-8 w-8";+ const icon = small ? "h-3 w-3" : "h-3.5 w-3.5";+ const orb = small ? "h-3.5 w-3.5" : "h-[18px] w-[18px]";+ return (+ <div+ aria-hidden+ data-testid="pet-strip-preview"+ className={cn("pointer-events-none flex select-none items-center gap-1.5", className)}+ >+ <span+ className={cn(+ "grid place-items-center rounded-full border border-border-strong bg-card text-foreground-secondary shadow-rim",+ disc,+ )}+ >+ <PenLine className={icon} />+ </span>+ <span+ className={cn(+ "flex items-center rounded-full border border-border-strong bg-card text-foreground-secondary shadow-rim",+ small ? "h-6 gap-2 px-2" : "h-8 gap-3 px-3",+ )}+ >+ <Mic className={icon} />+ <span className={cn("rounded-full bg-accent ring-2 ring-accent/25", orb)} />+ <Volume2 className={icon} />+ </span>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/pets/PetSprite.test.tsx b/jarvis/ui/web/frontend/src/components/pets/PetSprite.test.tsxnew file mode 100644index 0000000000..e0568000b7--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/pets/PetSprite.test.tsx@@ -0,0 +1,94 @@+import { act, cleanup, render, screen } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const motion = vi.hoisted(() => ({ reduced: false }));+vi.mock("framer-motion", () => ({ useReducedMotion: () => motion.reduced }));++import { PetSprite, integerScaleFor } from "@/components/pets/PetSprite";+import { resolvePetAnimation, type PetAnimation } from "@/lib/petStates";++const ANIMATIONS: Record<string, PetAnimation> = {+ idle: { row: 0, frames: 4, fps: 4, loop: true },+ listening: { row: 1, frames: 2, fps: 8, loop: true },+ success: { row: 4, frames: 3, fps: 10, loop: false },+};++const PET = { sheet_url: "/api/pets/gigi/sheet.png", frame_size: 48, animations: ANIMATIONS };++function cell(): HTMLElement {+ return screen.getByTestId("pet-sprite-cell");+}++beforeEach(() => {+ motion.reduced = false;+ vi.useFakeTimers();+});++afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++describe("resolvePetAnimation", () => {+ it("uses a state's own row when the manifest has one", () => {+ expect(resolvePetAnimation(ANIMATIONS, "listening")?.row).toBe(1);+ });++ it("walks the fallback chain for a missing state", () => {+ // thinking → listening; talking → listening; sleeping → idle.+ expect(resolvePetAnimation(ANIMATIONS, "thinking")?.row).toBe(1);+ expect(resolvePetAnimation(ANIMATIONS, "talking")?.row).toBe(1);+ expect(resolvePetAnimation(ANIMATIONS, "sleeping")?.row).toBe(0);+ expect(resolvePetAnimation({ idle: ANIMATIONS.idle }, "thinking")?.row).toBe(0);+ });++ it("draws nothing for a manifest without idle", () => {+ expect(resolvePetAnimation({}, "idle")).toBeNull();+ });+});++describe("PetSprite", () => {+ it("cuts one cell at source size and enlarges it by a whole factor", () => {+ render(<PetSprite pet={PET} state="listening" scale={2.6} label="Gigi" />);+ const box = screen.getByRole("img", { name: "Gigi" });+ expect(box.style.width).toBe("144px");+ expect(cell().style.transform).toBe("scale(3)");+ expect(cell().style.backgroundPosition).toBe("0px -48px");+ expect(cell().style.backgroundImage).toContain("/api/pets/gigi/sheet.png");+ });++ it("steps a looping row at the manifest's fps and wraps", () => {+ render(<PetSprite pet={PET} state="idle" scale={1} />);+ expect(cell().style.backgroundPosition).toBe("0px 0px");+ act(() => vi.advanceTimersByTime(250));+ expect(cell().style.backgroundPosition).toBe("-48px 0px");+ act(() => vi.advanceTimersByTime(750));+ expect(cell().style.backgroundPosition).toBe("0px 0px");+ });++ it("holds the last frame of a one-shot row", () => {+ render(<PetSprite pet={PET} state="success" scale={1} />);+ act(() => vi.advanceTimersByTime(1000));+ expect(cell().style.backgroundPosition).toBe("-96px -192px");+ });++ it("shows frame 0 still under reduced motion", () => {+ motion.reduced = true;+ render(<PetSprite pet={PET} state="idle" scale={1} />);+ act(() => vi.advanceTimersByTime(1000));+ expect(cell().style.backgroundPosition).toBe("0px 0px");+ });++ it("is decorative without a label", () => {+ render(<PetSprite pet={PET} state="idle" scale={1} />);+ expect(screen.getByTestId("pet-sprite").getAttribute("aria-hidden")).toBe("true");+ });+});++describe("integerScaleFor", () => {+ it("fits a frame into a box with a whole-number factor", () => {+ expect(integerScaleFor(48, 168)).toBe(3);+ expect(integerScaleFor(32, 96)).toBe(3);+ expect(integerScaleFor(64, 40)).toBe(1);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/pets/PetSprite.tsx b/jarvis/ui/web/frontend/src/components/pets/PetSprite.tsxnew file mode 100644index 0000000000..1a91889965--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/pets/PetSprite.tsx@@ -0,0 +1,130 @@+import { useEffect, useRef, useState } from "react";+import { useReducedMotion } from "framer-motion";++import { resolvePetAnimation, type PetState } from "@/lib/petStates";+import type { Pet } from "@/lib/petsApi";+import { cn } from "@/lib/utils";++/**+ * One pet, one state, drawn straight from its sprite sheet.+ *+ * The frame is a `frame_size` square of the sheet shown as a CSS background,+ * then enlarged by an INTEGER factor with nearest-neighbour sampling, so the+ * pixels stay crisp squares the way the desktop draws them. The sheet's own+ * size is never needed: the cell is cut at source scale and the whole box is+ * scaled with a transform.+ *+ * Frames advance on a small timer that writes the background position+ * directly (no React render per frame), at the manifest's fps. A looping row+ * wraps; a one-shot row holds its last frame. The timer stops while the sprite+ * is off-screen, and under `prefers-reduced-motion` the sprite shows frame 0+ * and never moves.+ */+export function PetSprite({+ pet,+ state,+ scale,+ label,+ className,+}: {+ pet: Pick<Pet, "sheet_url" | "frame_size" | "animations">;+ state: PetState;+ /** Display factor; rounded to a whole number so pixels stay square. */+ scale: number;+ /** Accessible name; the sprite is decorative without one. */+ label?: string;+ className?: string;+}) {+ const boxRef = useRef<HTMLDivElement>(null);+ const cellRef = useRef<HTMLDivElement>(null);+ const reduced = useReducedMotion() ?? false;+ const onScreen = useOnScreen(boxRef);++ const size = pet.frame_size;+ const factor = Math.max(1, Math.round(scale));+ const animation = resolvePetAnimation(pet.animations, state);+ const row = animation?.row ?? 0;+ const frames = animation?.frames ?? 1;+ const fps = animation?.fps ?? 1;+ const loop = animation?.loop ?? true;+ const drawable = animation !== null;++ useEffect(() => {+ const cell = cellRef.current;+ if (!cell || !drawable) return;+ const place = (frame: number) => {+ cell.style.backgroundPosition = `${-frame * size}px ${-row * size}px`;+ };+ place(0);+ if (frames <= 1 || reduced || !onScreen) return;+ let frame = 0;+ const timer = window.setInterval(() => {+ frame += 1;+ if (frame >= frames) {+ if (!loop) {+ window.clearInterval(timer);+ return;+ }+ frame = 0;+ }+ place(frame);+ }, 1000 / Math.max(1, fps));+ return () => window.clearInterval(timer);+ // Primitives only: the animation object is rebuilt on every render, and+ // depending on it would restart the row each time a parent repaints.+ }, [drawable, row, frames, fps, loop, size, reduced, onScreen, pet.sheet_url]);++ return (+ <div+ ref={boxRef}+ role={label ? "img" : undefined}+ aria-label={label}+ aria-hidden={label ? undefined : true}+ data-testid="pet-sprite"+ data-state={state}+ className={cn("relative shrink-0 overflow-hidden", className)}+ style={{ width: size * factor, height: size * factor }}+ >+ {drawable && (+ <div+ ref={cellRef}+ data-testid="pet-sprite-cell"+ className="absolute left-0 top-0 bg-no-repeat [image-rendering:pixelated]"+ style={{+ width: size,+ height: size,+ backgroundImage: `url("${pet.sheet_url.replace(/"/g, "%22")}")`,+ backgroundPosition: `0px ${-row * size}px`,+ transform: `scale(${factor})`,+ transformOrigin: "0 0",+ }}+ />+ )}+ </div>+ );+}++/** The largest whole-number factor that keeps a frame within `maxPx`. */+export function integerScaleFor(frameSize: number, maxPx: number): number {+ if (frameSize <= 0) return 1;+ return Math.max(1, Math.floor(maxPx / frameSize));+}++/**+ * Whether the element is in the viewport. Without IntersectionObserver+ * (jsdom, very old engines) it counts as visible, so the sprite still plays.+ */+function useOnScreen(ref: React.RefObject<HTMLElement>): boolean {+ const [visible, setVisible] = useState(true);+ useEffect(() => {+ const element = ref.current;+ if (!element || typeof IntersectionObserver === "undefined") return;+ const observer = new IntersectionObserver((entries) => {+ const entry = entries[entries.length - 1];+ if (entry) setVisible(entry.isIntersecting);+ });+ observer.observe(element);+ return () => observer.disconnect();+ }, [ref]);+ return visible;+}diff --git a/jarvis/ui/web/frontend/src/hooks/useConversations.ts b/jarvis/ui/web/frontend/src/hooks/useConversations.tsindex 139d97a9fa..ae1ece43be 100644--- a/jarvis/ui/web/frontend/src/hooks/useConversations.ts+++ b/jarvis/ui/web/frontend/src/hooks/useConversations.ts@@ -3,6 +3,7 @@ import { useCallback, useEffect } from "react";import { useEventStore, type ChatMessage, type ConversationKind } from "@/store/events";import { useHomeStore } from "@/store/home";import { requestVoiceHangup } from "@/lib/voiceApi";+import { resetTextConversation } from "@/lib/newChat";import {deleteTextConversation,detailToMessages,@@ -115,11 +116,7 @@ export function useConversations({ poll = false }: { poll?: boolean } = {}) {[seedThinkingTraces, setActiveConversation, setMessages],);- const newChat = useCallback(() => {- setActiveConversation("text", null);- seedThinkingTraces({});- setMessages([]);- }, [seedThinkingTraces, setActiveConversation, setMessages]);+ const newChat = useCallback(() => resetTextConversation(), []);/*** Start a fresh voice run: drop the open voice thread here and tell thediff --git a/jarvis/ui/web/frontend/src/hooks/useHotkey.ts b/jarvis/ui/web/frontend/src/hooks/useHotkey.tsindex 5875742645..995c74f03b 100644--- a/jarvis/ui/web/frontend/src/hooks/useHotkey.ts+++ b/jarvis/ui/web/frontend/src/hooks/useHotkey.ts@@ -496,13 +496,15 @@ export function validateCombo(// Mirrors KEYBIND_ACTIONS in jarvis/core/config_writer.py — keep in sync.// "dictate" is push-to-talk (hold), "dictate_toggle" is hands-free (press once-// to start, again to stop), "paste_last" re-inserts the last transcription.+// to start, again to stop), "paste_last" re-inserts the last transcription,+// "pet_toggle" hides the desktop pet or brings it back (Settings → My Pets).export type KeybindAction =| "call"| "hangup"| "dictate"| "dictate_toggle"- | "paste_last";+ | "paste_last"+ | "pet_toggle";/*** Response of GET /api/settings/keybinds.diff --git a/jarvis/ui/web/frontend/src/hooks/useOverlayStyle.ts b/jarvis/ui/web/frontend/src/hooks/useOverlayStyle.tsindex 9c5a630847..e46379a5ef 100644--- a/jarvis/ui/web/frontend/src/hooks/useOverlayStyle.ts+++ b/jarvis/ui/web/frontend/src/hooks/useOverlayStyle.ts@@ -3,20 +3,22 @@ import { useCallback, useEffect, useState } from "react";/*** On-screen overlay style from GET /api/settings/overlay-style.* "jarvis_bar" = slim default bar, "mascot" = ghost mascot, "voice_orb" = the- * procedural voice orb, "none" = hidden.+ * procedural voice orb, "pet" = an animated pixel-art pet with its control+ * strip (Settings → My Pets), "none" = hidden.** Mirror of the backend's one list (``jarvis/ui/overlay_styles.py``); the two* are pinned together by tests/unit/ui/test_overlay_style_parity.py, which* reads THIS union and the i18n labels. Keep the order identical — it is the* order both pickers render.*/-export type OverlayStyle = "jarvis_bar" | "mascot" | "voice_orb" | "none";+export type OverlayStyle = "jarvis_bar" | "mascot" | "voice_orb" | "pet" | "none";/** Client-side fallback while GET is in flight (same order as the backend). */export const OVERLAY_STYLES: OverlayStyle[] = ["jarvis_bar","mascot","voice_orb",+ "pet","none",];diff --git a/jarvis/ui/web/frontend/src/hooks/usePets.ts b/jarvis/ui/web/frontend/src/hooks/usePets.tsnew file mode 100644index 0000000000..a44b95203e--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/usePets.ts@@ -0,0 +1,85 @@+/**+ * React Query hooks for the desktop pet (Settings → My Pets).+ *+ * One query holds the whole `/api/pets` answer. Every mutation invalidates+ * it, and so does the `PetChanged` bus event (`useWebSocket`), so a change+ * made from another window, the shortcut or the CLI repaints here too. No+ * polling: an idle settings page opens no requests (AP-33).+ */+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import {+ createPet,+ deletePet,+ fetchPets,+ savePetSettings,+ selectPet,+ setPetVisible,+ type CreatePetInput,+ type PetSettingsPatch,+ type PetsState,+} from "@/lib/petsApi";++export const petKeys = {+ all: ["pets"] as const,+};++export function usePets() {+ return useQuery({ queryKey: petKeys.all, queryFn: fetchPets });+}++function useInvalidatePets() {+ const qc = useQueryClient();+ return () => qc.invalidateQueries({ queryKey: petKeys.all });+}++/** Patch the cached answer so a click paints before the refetch lands. */+function usePatchPets() {+ const qc = useQueryClient();+ return (patch: Partial<Omit<PetsState, "pets">>) =>+ qc.setQueryData<PetsState>(petKeys.all, (current) =>+ current ? { ...current, ...patch } : current,+ );+}++export function useSelectPet() {+ const invalidate = useInvalidatePets();+ const patch = usePatchPets();+ return useMutation({+ mutationFn: selectPet,+ onMutate: (petId: string) => patch({ active: petId }),+ onSettled: invalidate,+ });+}++export function useSavePetSettings() {+ const invalidate = useInvalidatePets();+ const patch = usePatchPets();+ return useMutation({+ mutationFn: savePetSettings,+ onMutate: (settings: PetSettingsPatch) => patch(settings),+ onSettled: invalidate,+ });+}++export function useSetPetVisible() {+ const invalidate = useInvalidatePets();+ const patch = usePatchPets();+ return useMutation({+ mutationFn: setPetVisible,+ onMutate: (visible: boolean) => patch({ visible }),+ onSettled: invalidate,+ });+}++export function useCreatePet() {+ const invalidate = useInvalidatePets();+ return useMutation({+ mutationFn: (input: CreatePetInput) => createPet(input),+ onSuccess: invalidate,+ });+}++export function useDeletePet() {+ const invalidate = useInvalidatePets();+ return useMutation({ mutationFn: deletePet, onSettled: invalidate });+}diff --git a/jarvis/ui/web/frontend/src/hooks/useRestartApp.ts b/jarvis/ui/web/frontend/src/hooks/useRestartApp.tsnew file mode 100644index 0000000000..dbd255f7e0--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useRestartApp.ts@@ -0,0 +1,60 @@+import { useCallback, useState } from "react";++import { useT } from "@/i18n";+import { useEventStore } from "@/store/events";++/**+ * The one-click app restart a setting needs when it cannot apply live (a bar+ * <-> orb-window overlay switch, BUG-031). Shared by the display-style picker+ * and the My Pets page so both behave the same.+ *+ * `POST /api/settings/restart-app` answers 409 while missions are running,+ * because a restart would kill them. That arms `forceArmed`; the next call+ * resends with `?force=true`. On success the window goes away, so+ * `restarting` is never cleared there.+ */+export function useRestartApp() {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const [restarting, setRestarting] = useState(false);+ const [forceArmed, setForceArmed] = useState(false);++ const restart = useCallback(async () => {+ if (restarting) return;+ setRestarting(true);+ try {+ const url = forceArmed+ ? "/api/settings/restart-app?force=true"+ : "/api/settings/restart-app";+ const res = await fetch(url, { method: "POST" });+ if (res.status === 409) {+ // Live missions would be killed — surface the count and arm a force+ // restart instead of killing them silently.+ let count = 0;+ try {+ const body = await res.json();+ count = body?.detail?.missions?.length ?? 0;+ } catch {+ /* malformed body — still arm the override */+ }+ setRestarting(false);+ setForceArmed(true);+ pushToast("warning", `${count} ${t("topbar.restart_missions_running")}`);+ return;+ }+ if (!res.ok) throw new Error(`restart-failed:${res.status}`);+ pushToast("info", t("taskbar_view.restarting"));+ } catch (e) {+ setRestarting(false);+ pushToast("error", (e as Error).message);+ }+ }, [forceArmed, pushToast, restarting, t]);++ const buttonLabel = restarting+ ? t("taskbar_view.restarting")+ : forceArmed+ ? t("topbar.restart_force")+ : t("taskbar_view.restart_now");++ return { restart, restarting, forceArmed, buttonLabel };+}diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx b/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsxindex b474f16f9f..3224e580e2 100644--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx@@ -16,6 +16,8 @@ import {voiceInputLevelRef,} from "@/lib/voiceInputLevel";import { useEventStore } from "@/store/events";+import { useHomeStore } from "@/store/home";+import { SPEAKER_MUTE_EVENT } from "@/lib/speakerMute";/** Minimal mock for WebSocket (mirrors __tests__/ws.test.ts). */class MockWebSocket {@@ -379,6 +381,61 @@ describe("useWebSocket VoiceBootStatus handling", () => {invalidate.mockRestore();},);++ it("opens an empty typed chat when the desktop pet's pen asks for one", async () => {+ useEventStore.setState({+ solo: false,+ activeSection: "settings",+ activeKind: "text",+ activeThreadId: "old-thread",+ });+ useHomeStore.setState({ surface: "voice" });+ render(<Harness />);+ await Promise.resolve();++ MockWebSocket.last!.deliver(envelope("ComposeRequested", { source: "pet" }));++ expect(useEventStore.getState().activeSection).toBe("chats");+ expect(useEventStore.getState().activeThreadId).toBeNull();+ expect(useHomeStore.getState().surface).toBe("chat");+ });++ it("keeps a detached window on its section when the pen asks for a chat", async () => {+ useEventStore.setState({ solo: true, activeSection: "visualization" });+ render(<Harness />);+ await Promise.resolve();++ MockWebSocket.last!.deliver(envelope("ComposeRequested", { source: "pet" }));++ expect(useEventStore.getState().activeSection).toBe("visualization");+ });++ it("relays a speaker mute from anywhere to the window", async () => {+ const seen: unknown[] = [];+ const listener = (event: Event) => seen.push((event as CustomEvent).detail);+ window.addEventListener(SPEAKER_MUTE_EVENT, listener);+ render(<Harness />);+ await Promise.resolve();++ MockWebSocket.last!.deliver(envelope("VoiceSpeakerMuteChanged", { muted: true, source: "pet" }));+ MockWebSocket.last!.deliver(envelope("VoiceSpeakerMuteChanged", { source: "garbled" }));++ window.removeEventListener(SPEAKER_MUTE_EVENT, listener);+ expect(seen).toEqual([{ muted: true }]);+ });++ it("re-reads the pets after a PetChanged event", async () => {+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");+ render(<Harness />);+ await Promise.resolve();++ MockWebSocket.last!.deliver(+ envelope("PetChanged", { pet_id: "miso", scale: 1, bubble: true, visible: true, source: "api" }),+ );++ expect(invalidate).toHaveBeenCalledWith({ queryKey: ["pets"] });+ invalidate.mockRestore();+ });});describe("useWebSocket connection state (welcome-gated + warming)", () => {diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.tsindex 5705780dbb..a57857cd8a 100644--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts@@ -31,6 +31,9 @@ import { WSAudioLevel, WSEventEnvelope, WSWelcome } from "@/schema/ws";import { useI18nStore, hydrateUiLanguage, hydrateReplyLanguage, translate } from "@/i18n";import { hydrateUiTheme } from "@/hooks/useTheme";import { announceDictationSettings } from "@/hooks/usePromptMode";+import { petKeys } from "@/hooks/usePets";+import { focusChatComposer, startNewTextChat } from "@/lib/newChat";+import { SPEAKER_MUTE_EVENT } from "@/lib/speakerMute";let singleton: WSClient | null = null;@@ -309,6 +312,31 @@ export function useWebSocket(): void {void queryClient.invalidateQueries({ queryKey: ["society", "roster"] });}+ // The desktop pet's pen: the backend already raised this window; land+ // on an empty typed chat with the caret in the composer. A detached+ // solo window is pinned to its section and stays where it is.+ if (env.event_name === "ComposeRequested" && !useEventStore.getState().solo) {+ startNewTextChat();+ focusChatComposer();+ }++ // The assistant's voice was muted or unmuted somewhere else (the+ // pet's speaker disc, another window); in-app speaker toggles follow.+ if (env.event_name === "VoiceSpeakerMuteChanged") {+ const p = env.payload as { muted?: unknown };+ if (typeof p.muted === "boolean") {+ window.dispatchEvent(+ new CustomEvent(SPEAKER_MUTE_EVENT, { detail: { muted: p.muted } }),+ );+ }+ }++ // The active pet, its look or its visibility changed (this window,+ // another one, the shortcut): the My Pets page re-reads the list.+ if (env.event_name === "PetChanged") {+ void queryClient.invalidateQueries({ queryKey: petKeys.all });+ }+if (env.event_name === "TranscriptionUpdate") {const p = env.payload as { text?: string; is_final?: boolean };if (typeof p.text === "string") {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex f3ce0aaaf9..c877b3b0ff 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -161,6 +161,7 @@"group_system": "System","agent_instructions": "{name}.md","appshots": "Appshots",+ "pets": "Meine Pets","jarvis_actions": "Jarvis-Aktionen","marketplace": "Marketplace","agentic_ide": "Agentic IDE",@@ -2540,7 +2541,7 @@},"overlay_style": {"title": "Anzeige-Stil",- "description": "Wähle, wie {name} bei Sprachaktivität auf dem Bildschirm erscheint. Die Bar ist der schlanke Standard; das Maskottchen ist der klassische Begleiter; der Voice-Orb ist eine leuchtende Kugel; oder ganz ausblenden. Jeder schwebende Stil lässt sich auf jeden Monitor ziehen.",+ "description": "Wähle, wie {name} bei Sprachaktivität auf dem Bildschirm erscheint. Die Bar ist der schlanke Standard; das Maskottchen ist der klassische Begleiter; der Voice-Orb ist eine leuchtende Kugel; das Pet ist ein Pixel-Begleiter, der sichtbar bleibt; oder ganz ausblenden. Jeder schwebende Stil lässt sich auf jeden Monitor ziehen.","label": "Stil","save": "Speichern","saved": "Anzeige-Stil gewechselt.",@@ -2549,6 +2550,7 @@"jarvis_bar": "Bar (Standard)","mascot": "Maskottchen","voice_orb": "Voice-Orb",+ "pet": "Pet","none": "Keins (ausgeblendet)"}},@@ -2586,6 +2588,7 @@"hangup_label": "Auflegen","dictate_label": "Diktat (halten und sprechen, Text landet dort, wo du tippst)","paste_last_label": "Letztes Diktat erneut einfügen",+ "pet_toggle_label": "Pet ein- oder ausblenden","record": "Aufnehmen","stop": "Stopp","recording": "Drücke deine Tasten…",@@ -5797,5 +5800,96 @@"save_error": "Speichern fehlgeschlagen: {0}","toast_refused": "Kein Appshot: {0}","chip_label": "Appshot an deine Nachricht gehängt"+ },+ "pets": {+ "title": "Meine Pets",+ "subtitle": "Ein kleiner Pixel-Begleiter, der auf deinem Desktop schwebt und reagiert, während {name} zuhört, nachdenkt und spricht. Mit {0} blendest du ihn aus oder wieder ein.",+ "subtitle_no_shortcut": "Ein kleiner Pixel-Begleiter, der auf deinem Desktop schwebt und reagiert, während {name} zuhört, nachdenkt und spricht. Unter „Anpassen“ legst du ein Tastenkürzel zum Aus- und Einblenden fest.",+ "hide": "Pet ausblenden",+ "show": "Pet einblenden",+ "open_settings": "Pet auswählen",+ "style_notice_title": "Das Pet ist noch nicht auf deinem Desktop",+ "style_notice_body": "Dein Anzeige-Stil ist „{0}“. Wechsle zum Pet, um es auf deinem Desktop zu sehen. Das Pet, das du unten auswählst, bleibt so oder so gespeichert.",+ "use_pet": "Pet auf dem Desktop nutzen",+ "style_saved": "Das Pet ist jetzt auf deinem Desktop.",+ "restart_hint": "Gespeichert. Starte {name} neu, damit das Pet auf deinem Desktop erscheint.",+ "load_error": "Deine Pets konnten nicht geladen werden: {0}",+ "save_error": "Das wurde nicht gespeichert: {0}",+ "preview_title": "Aktives Pet",+ "customize": "Anpassen",+ "size_label": "Größe",+ "size_hint": "Wie groß das Pet auf deinem Desktop ist.",+ "bubble_label": "Status-Blase",+ "bubble_hint": "Kurze Zeilen unter dem Pet, die zeigen, was {name} gerade tut.",+ "shortcut_hint": "Blendet das Pet aus oder holt es wieder nach vorn.",+ "my_pets": "Meine Pets",+ "create": "Pet erstellen",+ "created": "{0} ist fertig.",+ "none_name": "Keins",+ "none_description": "Nur die Steuerleiste",+ "selected": "Ausgewählt",+ "delete": "Pet löschen",+ "delete_named": "{0} löschen",+ "delete_title": "{0} löschen?",+ "delete_body": "Das Pet und sein Sprite-Sheet werden von diesem Computer entfernt. Das lässt sich nicht rückgängig machen.",+ "deleted": "{0} wurde gelöscht.",+ "states": {+ "idle": "Wartet",+ "listening": "Hört zu",+ "thinking": "Denkt nach",+ "talking": "Spricht",+ "success": "Geschafft",+ "error": "Fehler",+ "sleeping": "Schläft"+ },+ "builtin": {+ "gigi": {+ "description": "Der Geist von {name}, acht Bit groß."+ },+ "miso": {+ "description": "Eine Katze: spitzt beim Zuhören die Ohren und rollt sich zum Schlafen ein."+ },+ "brew": {+ "description": "Eine Teekanne: dampft beim Nachdenken und pfeift beim Sprechen."+ },+ "bolt": {+ "description": "Eine Batterie: lädt beim Nachdenken, sprüht bei Erfolg Funken und ist im Schlaf leer."+ },+ "mochi": {+ "description": "Ein Wackelpudding, der beim Zuhören wabbelt."+ },+ "shelly": {+ "description": "Eine Schnecke: das Haus dreht sich beim Nachdenken, zum Schlafen zieht sie sich zurück."+ }+ },+ "create_dialog": {+ "title": "Pet erstellen",+ "description": "Lade ein Sprite-Sheet hoch, gib deinem Pet einen Namen, und es kommt zu deinen Pets.",+ "name_label": "Name",+ "name_placeholder": "Zum Beispiel: Pixel",+ "description_label": "Beschreibung",+ "description_placeholder": "Ein Satz über dein Pet",+ "sheet_label": "Sprite-Sheet (PNG)",+ "sheet_preview_alt": "Vorschau des gewählten Sprite-Sheets",+ "sheet_hint": "Ein PNG mit transparentem Hintergrund, höchstens 2 MB und 512 × 512 Pixel.",+ "sheet_choose": "PNG auswählen",+ "sheet_change": "Anderes auswählen",+ "frame_size_label": "Bildgröße",+ "frame_size_option": "{0} × {0} px",+ "layout_title": "So ist das Sheet aufgebaut",+ "layout_body": "Das Sheet ist ein Raster aus quadratischen Bildern. Jede Zeile ist ein Zustand, von oben nach unten in dieser Reihenfolge, mit bis zu {0} Bildern von links nach rechts:",+ "template_download": "Vorlage herunterladen",+ "manifest_label": "Manifest (optional)",+ "manifest_hint": "Eine pet.json legt für jede Zeile Bilder, Tempo und Wiederholung fest. Ohne sie werden die Zeilen in der Reihenfolge oben gelesen und die Bilder jeder Zeile gezählt.",+ "manifest_choose": "pet.json hinzufügen",+ "manifest_remove": "Entfernen",+ "error_name": "Gib deinem Pet einen Namen.",+ "error_no_sheet": "Wähle ein Sprite-Sheet aus.",+ "error_not_png": "Wähle ein PNG-Bild aus.",+ "error_too_big": "Dieses Bild ist größer als 2 MB.",+ "error_manifest": "Das Manifest muss eine .json-Datei sein.",+ "create": "Pet erstellen",+ "creating": "Wird erstellt…"+ }}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 61ecf17509..3316e6458e 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -161,6 +161,7 @@"group_system": "System","agent_instructions": "{name}.md","appshots": "Appshots",+ "pets": "My Pets","jarvis_actions": "Jarvis actions","marketplace": "Marketplace","agentic_ide": "Agentic IDE",@@ -2573,7 +2574,7 @@},"overlay_style": {"title": "Display style",- "description": "Choose how {name} appears on screen during voice activity. The bar is the slim default; the mascot is the classic companion; the voice orb is a glowing sphere; or hide it entirely. Every floating style can be dragged to any monitor.",+ "description": "Choose how {name} appears on screen during voice activity. The bar is the slim default; the mascot is the classic companion; the voice orb is a glowing sphere; the pet is a pixel companion that stays on screen; or hide it entirely. Every floating style can be dragged to any monitor.","label": "Style","save": "Save","saved": "Display style switched.",@@ -2582,6 +2583,7 @@"jarvis_bar": "Bar (default)","mascot": "Mascot","voice_orb": "Voice orb",+ "pet": "Pet","none": "None (hidden)"}},@@ -2619,6 +2621,7 @@"hangup_label": "Hangup","dictate_label": "Dictation (hold to speak, text lands where you type)","paste_last_label": "Paste the last dictation again",+ "pet_toggle_label": "Show or hide the pet","record": "Record","stop": "Stop","recording": "Press your keys…",@@ -5830,5 +5833,96 @@"save_error": "Could not save: {0}","toast_refused": "No appshot: {0}","chip_label": "Appshot added to your message"+ },+ "pets": {+ "title": "My Pets",+ "subtitle": "A small pixel companion that floats on your desktop and reacts as {name} listens, thinks and talks. Press {0} to hide or show it.",+ "subtitle_no_shortcut": "A small pixel companion that floats on your desktop and reacts as {name} listens, thinks and talks. Set a shortcut under Customize to hide or show it.",+ "hide": "Hide pet",+ "show": "Show pet",+ "open_settings": "Choose your pet",+ "style_notice_title": "The pet is not on your desktop yet",+ "style_notice_body": "Your display style is “{0}”. Switch to the pet to see it on your desktop. The pet you pick below is kept either way.",+ "use_pet": "Use pet on desktop",+ "style_saved": "The pet is now on your desktop.",+ "restart_hint": "Saved. Restart {name} to bring the pet to your desktop.",+ "load_error": "Your pets could not be loaded: {0}",+ "save_error": "That did not save: {0}",+ "preview_title": "Active pet",+ "customize": "Customize",+ "size_label": "Size",+ "size_hint": "How big the pet is on your desktop.",+ "bubble_label": "Status bubble",+ "bubble_hint": "Short lines under the pet that say what {name} is doing.",+ "shortcut_hint": "Hides the pet, or brings it back to the front.",+ "my_pets": "My pets",+ "create": "Create pet",+ "created": "{0} is ready.",+ "none_name": "None",+ "none_description": "Just the control strip",+ "selected": "Selected",+ "delete": "Delete pet",+ "delete_named": "Delete {0}",+ "delete_title": "Delete {0}?",+ "delete_body": "The pet and its sprite sheet are removed from this computer. This cannot be undone.",+ "deleted": "{0} was deleted.",+ "states": {+ "idle": "Idle",+ "listening": "Listening",+ "thinking": "Thinking",+ "talking": "Talking",+ "success": "Success",+ "error": "Error",+ "sleeping": "Sleeping"+ },+ "builtin": {+ "gigi": {+ "description": "The ghost of {name}, eight bits tall."+ },+ "miso": {+ "description": "A cat: ears up while listening, curls up to sleep."+ },+ "brew": {+ "description": "A teapot: steams while thinking, whistles while talking."+ },+ "bolt": {+ "description": "A battery: charges while thinking, sparks on success, runs flat asleep."+ },+ "mochi": {+ "description": "A jelly blob that wobbles while listening."+ },+ "shelly": {+ "description": "A snail: the shell spins while thinking, it withdraws to sleep."+ }+ },+ "create_dialog": {+ "title": "Create pet",+ "description": "Upload a sprite sheet, give your pet a name, and it joins your pets.",+ "name_label": "Name",+ "name_placeholder": "For example: Pixel",+ "description_label": "Description",+ "description_placeholder": "One sentence about your pet",+ "sheet_label": "Sprite sheet (PNG)",+ "sheet_preview_alt": "Preview of the chosen sprite sheet",+ "sheet_hint": "A PNG with a transparent background, up to 2 MB and 512 × 512 pixels.",+ "sheet_choose": "Choose PNG",+ "sheet_change": "Choose another",+ "frame_size_label": "Frame size",+ "frame_size_option": "{0} × {0} px",+ "layout_title": "How the sheet is laid out",+ "layout_body": "The sheet is a grid of square frames. Each row is one state, top to bottom in this order, with up to {0} frames from left to right:",+ "template_download": "Download template",+ "manifest_label": "Manifest (optional)",+ "manifest_hint": "A pet.json sets each row's frames, speed and looping. Without one, the rows are read in the order above and the frames of each row are counted.",+ "manifest_choose": "Add pet.json",+ "manifest_remove": "Remove",+ "error_name": "Give your pet a name.",+ "error_no_sheet": "Choose a sprite sheet.",+ "error_not_png": "Choose a PNG image.",+ "error_too_big": "This image is larger than 2 MB.",+ "error_manifest": "The manifest must be a .json file.",+ "create": "Create pet",+ "creating": "Creating…"+ }}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 51f4e157fa..2eb92c40f2 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -161,6 +161,7 @@"group_system": "Sistema","agent_instructions": "{name}.md","appshots": "Appshots",+ "pets": "Mis mascotas","jarvis_actions": "Acciones de Jarvis","marketplace": "Marketplace","agentic_ide": "IDE agéntico",@@ -2540,7 +2541,7 @@},"overlay_style": {"title": "Estilo de visualización",- "description": "Elige cómo aparece {name} en pantalla durante la actividad de voz. La barra es el valor predeterminado; la mascota es el acompañante clásico; el orbe de voz es una esfera luminosa; o ocúltalo por completo. Cualquier estilo flotante se puede arrastrar a cualquier monitor.",+ "description": "Elige cómo aparece {name} en pantalla durante la actividad de voz. La barra es el valor predeterminado; la mascota es el acompañante clásico; el orbe de voz es una esfera luminosa; la mascota es un compañero de píxeles que permanece en pantalla; o ocúltalo por completo. Cualquier estilo flotante se puede arrastrar a cualquier monitor.","label": "Estilo","save": "Guardar","saved": "Estilo de visualización cambiado.",@@ -2549,6 +2550,7 @@"jarvis_bar": "Barra (predeterminado)","mascot": "Mascota","voice_orb": "Orbe de voz",+ "pet": "Mascota","none": "Ninguno (oculto)"}},@@ -2586,6 +2588,7 @@"hangup_label": "Colgar","dictate_label": "Dictado (mantén pulsado y habla, el texto va donde escribes)","paste_last_label": "Pegar de nuevo el último dictado",+ "pet_toggle_label": "Mostrar u ocultar la mascota","record": "Grabar","stop": "Detener","recording": "Presiona tus teclas…",@@ -5797,5 +5800,96 @@"save_error": "No se pudo guardar: {0}","toast_refused": "Sin appshot: {0}","chip_label": "Appshot añadido a tu mensaje"+ },+ "pets": {+ "title": "Mis mascotas",+ "subtitle": "Un pequeño compañero de píxeles que flota en tu escritorio y reacciona mientras {name} escucha, piensa y habla. Pulsa {0} para ocultarlo o mostrarlo.",+ "subtitle_no_shortcut": "Un pequeño compañero de píxeles que flota en tu escritorio y reacciona mientras {name} escucha, piensa y habla. Asigna un atajo en Personalizar para ocultarlo o mostrarlo.",+ "hide": "Ocultar mascota",+ "show": "Mostrar mascota",+ "open_settings": "Elegir mascota",+ "style_notice_title": "La mascota aún no está en tu escritorio",+ "style_notice_body": "Tu estilo de visualización es «{0}». Cambia a la mascota para verla en tu escritorio. La mascota que elijas abajo se guarda de todos modos.",+ "use_pet": "Usar mascota en el escritorio",+ "style_saved": "La mascota ya está en tu escritorio.",+ "restart_hint": "Guardado. Reinicia {name} para ver la mascota en tu escritorio.",+ "load_error": "No se pudieron cargar tus mascotas: {0}",+ "save_error": "No se pudo guardar: {0}",+ "preview_title": "Mascota activa",+ "customize": "Personalizar",+ "size_label": "Tamaño",+ "size_hint": "Qué tan grande se ve la mascota en tu escritorio.",+ "bubble_label": "Burbuja de estado",+ "bubble_hint": "Líneas breves bajo la mascota que dicen qué está haciendo {name}.",+ "shortcut_hint": "Oculta la mascota o la trae de nuevo al frente.",+ "my_pets": "Mis mascotas",+ "create": "Crear mascota",+ "created": "{0} está lista.",+ "none_name": "Ninguna",+ "none_description": "Solo la barra de controles",+ "selected": "Seleccionada",+ "delete": "Eliminar mascota",+ "delete_named": "Eliminar {0}",+ "delete_title": "¿Eliminar {0}?",+ "delete_body": "La mascota y su hoja de sprites se eliminan de este ordenador. No se puede deshacer.",+ "deleted": "{0} se eliminó.",+ "states": {+ "idle": "En reposo",+ "listening": "Escuchando",+ "thinking": "Pensando",+ "talking": "Hablando",+ "success": "Éxito",+ "error": "Error",+ "sleeping": "Durmiendo"+ },+ "builtin": {+ "gigi": {+ "description": "El fantasma de {name}, de ocho bits."+ },+ "miso": {+ "description": "Un gato: levanta las orejas al escuchar y se acurruca para dormir."+ },+ "brew": {+ "description": "Una tetera: echa vapor al pensar y silba al hablar."+ },+ "bolt": {+ "description": "Una batería: se carga al pensar, echa chispas al acertar y se agota al dormir."+ },+ "mochi": {+ "description": "Una gelatina que tiembla al escuchar."+ },+ "shelly": {+ "description": "Un caracol: la concha gira al pensar y se esconde para dormir."+ }+ },+ "create_dialog": {+ "title": "Crear mascota",+ "description": "Sube una hoja de sprites, ponle nombre a tu mascota y se unirá a las demás.",+ "name_label": "Nombre",+ "name_placeholder": "Por ejemplo: Pixel",+ "description_label": "Descripción",+ "description_placeholder": "Una frase sobre tu mascota",+ "sheet_label": "Hoja de sprites (PNG)",+ "sheet_preview_alt": "Vista previa de la hoja de sprites elegida",+ "sheet_hint": "Un PNG con fondo transparente, de hasta 2 MB y 512 × 512 píxeles.",+ "sheet_choose": "Elegir PNG",+ "sheet_change": "Elegir otra",+ "frame_size_label": "Tamaño de fotograma",+ "frame_size_option": "{0} × {0} px",+ "layout_title": "Cómo se organiza la hoja",+ "layout_body": "La hoja es una cuadrícula de fotogramas cuadrados. Cada fila es un estado, de arriba abajo en este orden, con hasta {0} fotogramas de izquierda a derecha:",+ "template_download": "Descargar plantilla",+ "manifest_label": "Manifiesto (opcional)",+ "manifest_hint": "Un pet.json fija los fotogramas, la velocidad y la repetición de cada fila. Sin él, las filas se leen en el orden de arriba y se cuentan los fotogramas de cada fila.",+ "manifest_choose": "Añadir pet.json",+ "manifest_remove": "Quitar",+ "error_name": "Ponle un nombre a tu mascota.",+ "error_no_sheet": "Elige una hoja de sprites.",+ "error_not_png": "Elige una imagen PNG.",+ "error_too_big": "Esta imagen ocupa más de 2 MB.",+ "error_manifest": "El manifiesto debe ser un archivo .json.",+ "create": "Crear mascota",+ "creating": "Creando…"+ }}}diff --git a/jarvis/ui/web/frontend/src/lib/newChat.ts b/jarvis/ui/web/frontend/src/lib/newChat.tsnew file mode 100644index 0000000000..bedec516ba--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/newChat.ts@@ -0,0 +1,52 @@+/**+ * Starting a fresh typed chat — ONE definition for every door that opens one:+ * the sidebar's "New chat → Chat", and the desktop pet's pen control, which+ * arrives as the `ComposeRequested` bus event (`useWebSocket`).+ *+ * Store-level on purpose (no hooks), so a socket handler can call it as+ * easily as a click handler.+ */+import { useAgentChatStore } from "@/store/agentChat";+import { useEventStore } from "@/store/events";+import { useHomeStore } from "@/store/home";++/** Drop the open text thread so the history's next message starts a new one. */+export function resetTextConversation(): void {+ const events = useEventStore.getState();+ events.setActiveConversation("text", null);+ events.seedThinkingTraces({});+ events.setMessages([]);+}++/** Land on an empty typed chat on the front page. */+export function startNewTextChat(): void {+ resetTextConversation();+ useAgentChatStore.getState().newChat();+ useHomeStore.getState().setSurface("chat");+ useEventStore.getState().setActiveSection("chats");+}++/** How many frames to wait for the composer to mount after a section switch. */+const FOCUS_ATTEMPTS = 30;++/**+ * Put the caret into the chat composer as soon as it is on screen.+ *+ * The composer mounts a few frames after `startNewTextChat` switches the+ * section (the chat view is code-split), so this retries once per animation+ * frame for about half a second and then gives up quietly: a window that+ * shows no composer has nothing to focus.+ */+export function focusChatComposer(): void {+ let attempts = 0;+ const tryFocus = () => {+ const field = document.querySelector<HTMLElement>("[data-jarvis-chat-input]");+ if (field) {+ field.focus();+ return;+ }+ attempts += 1;+ if (attempts < FOCUS_ATTEMPTS) window.requestAnimationFrame(tryFocus);+ };+ window.requestAnimationFrame(tryFocus);+}diff --git a/jarvis/ui/web/frontend/src/lib/petStates.ts b/jarvis/ui/web/frontend/src/lib/petStates.tsnew file mode 100644index 0000000000..b1043875fc--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/petStates.ts@@ -0,0 +1,72 @@+/**+ * The desktop pet's state vocabulary, mirrored from `jarvis/ui/pets/states.py`.+ *+ * A pet state is one animation row of a sprite sheet. The value crosses+ * Python, the manifest on disk, the REST payload, this file and the+ * `pets.states.*` labels, so `tests/unit/ui/pets/test_pet_state_parity.py`+ * pins the tuple, its ORDER (the sheet's row order) and the fallbacks to the+ * Python module. Change them there first.+ */++/** Every animation state a pet can show, in sprite-sheet row order. */+export const PET_STATES = [+ "idle",+ "listening",+ "thinking",+ "talking",+ "success",+ "error",+ "sleeping",+] as const;++export type PetState = (typeof PET_STATES)[number];++/**+ * Which row to borrow when a manifest has no animation for a state. Every+ * chain ends at `idle`, the one state a manifest must provide.+ */+export const STATE_FALLBACKS: Readonly<Record<Exclude<PetState, "idle">, PetState>> = {+ listening: "idle",+ thinking: "listening",+ talking: "listening",+ success: "idle",+ error: "idle",+ sleeping: "idle",+};++/** The pet id that shows the control strip with no figure ("None" in the UI). */+export const NO_PET_ID = "none";++/** Frame edge lengths a sprite sheet may use, in source pixels. */+export const FRAME_SIZES = [32, 48, 64] as const;++/** Upper bound of frames in one animation row. */+export const MAX_FRAMES_PER_STATE = 8;++/** One animation row as the REST payload describes it. */+export interface PetAnimation {+ row: number;+ frames: number;+ fps: number;+ loop: boolean;+}++/**+ * The animation that plays for `state`: its own row, or the first row found+ * along the fallback chain. `null` only for a manifest without `idle`, which+ * the backend loader rejects, so a caller treats it as "draw nothing".+ */+export function resolvePetAnimation(+ animations: Partial<Record<string, PetAnimation>>,+ state: PetState,+): PetAnimation | null {+ let current: PetState | undefined = state;+ // The chain is at most three hops long; the bound only guards a malformed+ // table from looping forever.+ for (let hop = 0; current && hop <= PET_STATES.length; hop += 1) {+ const animation = animations[current];+ if (animation) return animation;+ current = current === "idle" ? undefined : STATE_FALLBACKS[current];+ }+ return null;+}diff --git a/jarvis/ui/web/frontend/src/lib/petsApi.ts b/jarvis/ui/web/frontend/src/lib/petsApi.tsnew file mode 100644index 0000000000..3b321ca151--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/petsApi.ts@@ -0,0 +1,115 @@+/**+ * Client for `/api/pets` — the desktop pet overlay (`docs/pets.md`).+ *+ * Every write returns once the value is on disk and applied to the desktop;+ * the backend then publishes `PetChanged`, which `useWebSocket` turns into a+ * refetch of the pets query, so a second open window follows along.+ */+import type { PetAnimation } from "@/lib/petStates";++export interface Pet {+ id: string;+ name: string;+ description: string;+ builtin: boolean;+ frame_size: number;+ /** Keyed by pet state; a custom pet may leave states out (see STATE_FALLBACKS). */+ animations: Partial<Record<string, PetAnimation>>;+ sheet_url: string;+}++export interface PetsState {+ /** A pet id, or `NO_PET_ID` for the control strip alone. */+ active: string;+ scale: number;+ bubble: boolean;+ visible: boolean;+ pets: Pet[];+}++export interface PetSettingsPatch {+ scale?: number;+ bubble?: boolean;+}++export interface CreatePetInput {+ sheet: File;+ name: string;+ description: string;+ frameSize?: number;+ /** The text of an optional `pet.json`; sent as a plain form field. */+ manifest?: string | null;+}++/** A refused request, carrying the backend's `detail` when it sent one. */+export class PetsRequestError extends Error {+ readonly status: number;++ constructor(message: string, status: number) {+ super(message);+ this.name = "PetsRequestError";+ this.status = status;+ }+}++async function request<T>(url: string, init?: RequestInit): Promise<T> {+ const response = await fetch(url, init);+ const body = (await response.json().catch(() => null)) as T | { detail?: unknown } | null;+ if (!response.ok) {+ const detail =+ body && typeof body === "object" && "detail" in body && typeof body.detail === "string"+ ? body.detail+ : "";+ throw new PetsRequestError(+ detail || `Pets request failed (${response.status}).`,+ response.status,+ );+ }+ return body as T;+}++function putJson<T>(url: string, payload: unknown): Promise<T> {+ return request<T>(url, {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(payload),+ });+}++/** An empty sheet in the standard layout (48 px cells, rows in PET_STATES order). */+export const PET_TEMPLATE_URL = "/api/pets/template.png";++export function fetchPets(): Promise<PetsState> {+ return request<PetsState>("/api/pets");+}++export function selectPet(petId: string): Promise<unknown> {+ return putJson("/api/pets/active", { pet_id: petId });+}++export function savePetSettings(patch: PetSettingsPatch): Promise<unknown> {+ return putJson("/api/pets/settings", patch);+}++export function setPetVisible(visible: boolean): Promise<unknown> {+ return request("/api/pets/visibility", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ visible }),+ });+}++export function createPet(input: CreatePetInput): Promise<Pet> {+ const form = new FormData();+ form.append("sheet", input.sheet);+ form.append("name", input.name);+ form.append("description", input.description);+ if (input.frameSize) form.append("frame_size", String(input.frameSize));+ if (input.manifest) form.append("manifest", input.manifest);+ // No content-type header: the browser writes the multipart boundary itself.+ return request<Pet>("/api/pets", { method: "POST", body: form });+}++export function deletePet(petId: string): Promise<unknown> {+ return request(`/api/pets/${encodeURIComponent(petId)}`, { method: "DELETE" });+}diff --git a/jarvis/ui/web/frontend/src/lib/speakerMute.ts b/jarvis/ui/web/frontend/src/lib/speakerMute.tsnew file mode 100644index 0000000000..ae111b2465--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/speakerMute.ts@@ -0,0 +1,10 @@+/**+ * Window event fired when the assistant's voice went silent or audible from+ * anywhere (the desktop pet's speaker disc, another window). `detail` is+ * `{ muted: boolean }`. Relayed by `useWebSocket` from the backend's+ * `VoiceSpeakerMuteChanged`, the one authoritative source.+ *+ * Its own module rather than a member of `lib/voiceApi.ts`: tests replace the+ * whole API module with a mock, and an event NAME has nothing to mock.+ */+export const SPEAKER_MUTE_EVENT = "jarvis:speaker-mute-changed";diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.tsindex 8b5f645e66..3814c848a1 100644--- a/jarvis/ui/web/frontend/src/store/events.ts+++ b/jarvis/ui/web/frontend/src/store/events.ts@@ -87,6 +87,9 @@ export type SectionId =// Appshots: the shortcut, destination, sound and flash for showing the// assistant the front window. A Settings-hub page.| "appshots"+ // My Pets: the desktop pet — which one, its size, its bubble, and custom+ // pets from a sprite sheet (docs/pets.md). A Settings-hub page.+ | "pets"// Jarvis actions: every app action Jarvis can run and the person's// allow / ask / block choice for each. A Settings-hub page.| "jarvis-actions"@@ -144,6 +147,7 @@ export const SECTION_IDS = ["feedback","agent-instructions","appshots",+ "pets","jarvis-actions","dictionary","dictation",@@ -239,6 +243,7 @@ export const SECTION_LABELS: Record<SectionId, string> = {feedback: "Feedback","agent-instructions": "Agent Instructions",appshots: "Appshots",+ pets: "My Pets","jarvis-actions": "Jarvis actions",dictionary: "Dictionary",dictation: "Dictation",diff --git a/jarvis/ui/web/frontend/src/views/PetsView.test.tsx b/jarvis/ui/web/frontend/src/views/PetsView.test.tsxnew file mode 100644index 0000000000..415a0b43e0--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/PetsView.test.tsx@@ -0,0 +1,255 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { PetsView } from "@/views/PetsView";+import { useEventStore } from "@/store/events";++const IDLE = { row: 0, frames: 4, fps: 4, loop: true };++function pet(id: string, name: string, builtin: boolean) {+ return {+ id,+ name,+ description: `${name} from the API`,+ builtin,+ frame_size: 48,+ animations: { idle: IDLE },+ sheet_url: `/api/pets/${id}/sheet.png`,+ };+}++interface Call {+ method: string;+ url: string;+ body: unknown;+}++/**+ * A stand-in for the pets, overlay-style and keybind endpoints that keeps+ * state, so a click followed by the refetch it triggers reads back what the+ * click wrote.+ */+function stubServer({ style = "pet" }: { style?: string } = {}) {+ const state = {+ active: "gigi",+ scale: 1,+ bubble: true,+ visible: true,+ style,+ pets: [pet("gigi", "Gigi", true), pet("miso", "Miso", true), pet("u0123456789abcdef", "Pixel", false)],+ };+ const calls: Call[] = [];+ const json = (body: unknown, status = 200) => ({+ ok: status < 400,+ status,+ json: async () => body,+ });++ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: unknown, init?: { method?: string; body?: unknown }) => {+ const url = String(input);+ const method = (init?.method ?? "GET").toUpperCase();+ const body =+ typeof init?.body === "string" ? (JSON.parse(init.body) as Record<string, unknown>) : init?.body;+ calls.push({ method, url, body });++ if (url === "/api/pets" && method === "GET") {+ const { style: _style, ...rest } = state;+ return json(rest);+ }+ if (url === "/api/pets/active") {+ state.active = String((body as { pet_id: string }).pet_id);+ return json({ ok: true });+ }+ if (url === "/api/pets/settings") {+ Object.assign(state, body);+ return json({ ok: true });+ }+ if (url === "/api/pets/visibility") {+ state.visible = Boolean((body as { visible: boolean }).visible);+ return json({ ok: true });+ }+ if (url.startsWith("/api/pets/u") && method === "DELETE") {+ state.pets = state.pets.filter((p) => url !== `/api/pets/${p.id}`);+ return json({ ok: true });+ }+ if (url === "/api/settings/overlay-style" && method === "GET") {+ return json({ style: state.style, options: ["jarvis_bar", "mascot", "voice_orb", "pet", "none"] });+ }+ if (url === "/api/settings/overlay-style" && method === "PUT") {+ state.style = String((body as { style: string }).style);+ return json({+ ok: true,+ style: state.style,+ persisted: true,+ applied_live: false,+ restart_required: true,+ });+ }+ if (url === "/api/settings/keybinds") {+ return json({+ keybinds: { pet_toggle: "alt+win+p" },+ defaults: { pet_toggle: "alt+win+p" },+ suggestions: [],+ restart_required: false,+ });+ }+ return json({}, 404);+ }),+ );+ return { state, calls };+}++function renderView() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>+ <PetsView />+ </QueryClientProvider>,+ );+}++beforeEach(() => {+ useEventStore.setState({ toasts: [], assistantName: "Jarvis" });+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe("PetsView", () => {+ it("lists None first, then every pet, and rings the active one", async () => {+ stubServer();+ renderView();++ const grid = await screen.findByTestId("pets-grid");+ await within(grid).findByText("Miso");+ const tiles = within(grid).getAllByRole("button");+ expect(tiles[0].getAttribute("data-testid")).toBe("pet-tile-none");+ expect(screen.getByTestId("pet-tile-gigi").getAttribute("aria-pressed")).toBe("true");+ expect(screen.getByTestId("pet-tile-miso").getAttribute("aria-pressed")).toBe("false");+ // Built-in copy comes from the locale, a custom pet keeps its own text.+ expect(within(grid).getByText("A cat: ears up while listening, curls up to sleep.")).toBeTruthy();+ expect(within(grid).getByText("Pixel from the API")).toBeTruthy();+ });++ it("names the shortcut in the explanation", async () => {+ stubServer();+ renderView();+ expect(await screen.findByText(/Press Alt \+ Win \+ P to hide or show it\./)).toBeTruthy();+ });++ it("selects a pet with one click", async () => {+ const { calls } = stubServer();+ renderView();++ fireEvent.click(await screen.findByTestId("pet-tile-miso"));++ await waitFor(() =>+ expect(calls).toContainEqual({ method: "PUT", url: "/api/pets/active", body: { pet_id: "miso" } }),+ );+ await waitFor(() =>+ expect(screen.getByTestId("pet-tile-miso").getAttribute("aria-pressed")).toBe("true"),+ );+ });++ it("offers only the control strip for None", async () => {+ const { calls } = stubServer();+ renderView();++ fireEvent.click(await screen.findByTestId("pet-tile-none"));++ await waitFor(() =>+ expect(calls).toContainEqual({ method: "PUT", url: "/api/pets/active", body: { pet_id: "none" } }),+ );+ });++ it("hides the pet from the header button", async () => {+ const { calls } = stubServer();+ renderView();++ const button = await screen.findByTestId("pets-visibility");+ await waitFor(() => expect((button as HTMLButtonElement).disabled).toBe(false));+ expect(button.textContent).toBe("Hide pet");+ fireEvent.click(button);++ await waitFor(() =>+ expect(calls).toContainEqual({ method: "POST", url: "/api/pets/visibility", body: { visible: false } }),+ );+ await waitFor(() => expect(button.textContent).toBe("Show pet"));+ });++ it("switches the display style to the pet and offers the restart", async () => {+ const { calls } = stubServer({ style: "jarvis_bar" });+ renderView();++ fireEvent.click(await screen.findByTestId("pets-use-pet"));++ await waitFor(() =>+ expect(calls).toContainEqual({+ method: "PUT",+ url: "/api/settings/overlay-style",+ body: { style: "pet", persist: true },+ }),+ );+ expect(await screen.findByTestId("pets-restart-notice")).toBeTruthy();+ expect(screen.queryByTestId("pets-style-notice")).toBeNull();+ });++ it("shows no style notice while the pet is already the display style", async () => {+ stubServer();+ renderView();+ await screen.findByTestId("pet-tile-miso");+ expect(screen.queryByTestId("pets-style-notice")).toBeNull();+ });++ it("switches the status bubble off from the customize panel", async () => {+ const { calls } = stubServer();+ renderView();++ const customize = await screen.findByTestId("pets-customize");+ await waitFor(() => expect((customize as HTMLButtonElement).disabled).toBe(false));+ fireEvent.click(customize);+ fireEvent.click(await screen.findByTestId("pets-bubble"));++ await waitFor(() =>+ expect(calls).toContainEqual({ method: "PUT", url: "/api/pets/settings", body: { bubble: false } }),+ );+ });++ it("saves the size when the slider is released", async () => {+ const { calls } = stubServer();+ renderView();++ const customize = await screen.findByTestId("pets-customize");+ await waitFor(() => expect((customize as HTMLButtonElement).disabled).toBe(false));+ fireEvent.click(customize);+ const slider = await screen.findByTestId("pets-size");+ fireEvent.change(slider, { target: { value: "1.5" } });+ fireEvent.mouseUp(slider);++ await waitFor(() =>+ expect(calls).toContainEqual({ method: "PUT", url: "/api/pets/settings", body: { scale: 1.5 } }),+ );+ });++ it("deletes a custom pet after confirming, and never offers it for a built-in", async () => {+ const { calls } = stubServer();+ renderView();++ await screen.findByTestId("pet-tile-miso");+ expect(screen.queryByTestId("pet-delete-miso")).toBeNull();+ fireEvent.click(screen.getByTestId("pet-delete-u0123456789abcdef"));+ fireEvent.click(await screen.findByTestId("delete-pet-confirm"));++ await waitFor(() =>+ expect(calls).toContainEqual({ method: "DELETE", url: "/api/pets/u0123456789abcdef", body: undefined }),+ );+ await waitFor(() => expect(screen.queryByTestId("pet-tile-u0123456789abcdef")).toBeNull());+ });+});diff --git a/jarvis/ui/web/frontend/src/views/PetsView.tsx b/jarvis/ui/web/frontend/src/views/PetsView.tsxnew file mode 100644index 0000000000..4d9aa0ff16--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/PetsView.tsx@@ -0,0 +1,638 @@+import { useEffect, useState } from "react";+import * as Dialog from "@radix-ui/react-dialog";+import { useReducedMotion } from "framer-motion";+import {+ Check,+ Eye,+ EyeOff,+ Loader2,+ PawPrint,+ Plus,+ SlidersHorizontal,+ Trash2,+} from "lucide-react";++import { PageHeader } from "@/components/layout/PageHeader";+import { CreatePetDialog } from "@/components/pets/CreatePetDialog";+import { PetControlStripPreview } from "@/components/pets/PetControlStripPreview";+import { PetSprite, integerScaleFor } from "@/components/pets/PetSprite";+import { Button } from "@/components/ui/button";+import { Switch } from "@/components/ui/switch";+import { useKeybinds } from "@/hooks/useHotkey";+import { useOverlayStyle } from "@/hooks/useOverlayStyle";+import {+ useDeletePet,+ usePets,+ useSavePetSettings,+ useSelectPet,+ useSetPetVisible,+} from "@/hooks/usePets";+import { useRestartApp } from "@/hooks/useRestartApp";+import { useT } from "@/i18n";+import { NO_PET_ID, PET_STATES } from "@/lib/petStates";+import type { Pet } from "@/lib/petsApi";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";+import { KeybindRow, formatCombo } from "@/views/settings/KeybindRow";++/**+ * Settings → My Pets — the desktop pet (`docs/pets.md`).+ *+ * Top to bottom: what a pet is and the shortcut that hides it; a notice when+ * the desktop shows another display style, with the one click that switches+ * it; the active pet playing through all seven states over the strip it+ * carries, with its size, bubble and shortcut behind "Customize"; then every+ * pet as a tile — "None" first — plus "Create pet".+ *+ * Everything reads from one query (`usePets`), which the `PetChanged` event+ * refreshes, so the shortcut or another window moves this page too.+ */++/** How long the big preview holds each state before showing the next. */+const STATE_CYCLE_MS = 2500;+/** Largest edge of the big preview and of a grid tile's sprite, in px. */+const HERO_SPRITE_PX = 168;+const TILE_SPRITE_PX = 96;+const SCALE_MIN = 0.5;+const SCALE_MAX = 2;+const SCALE_STEP = 0.1;++function useStateCycle(enabled: boolean): number {+ const [index, setIndex] = useState(0);+ useEffect(() => {+ if (!enabled) {+ setIndex(0);+ return;+ }+ const timer = window.setInterval(+ () => setIndex((current) => (current + 1) % PET_STATES.length),+ STATE_CYCLE_MS,+ );+ return () => window.clearInterval(timer);+ }, [enabled]);+ return index;+}++export function PetsView() {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const pets = usePets();+ const overlay = useOverlayStyle();+ const keybinds = useKeybinds();+ const select = useSelectPet();+ const setVisible = useSetPetVisible();+ const remove = useDeletePet();+ const restartApp = useRestartApp();++ const [customizeOpen, setCustomizeOpen] = useState(false);+ const [createOpen, setCreateOpen] = useState(false);+ const [pendingDelete, setPendingDelete] = useState<Pet | null>(null);+ const [switchingStyle, setSwitchingStyle] = useState(false);+ const [needsRestart, setNeedsRestart] = useState(false);++ const data = pets.data;+ const activePet =+ data && data.active !== NO_PET_ID+ ? data.pets.find((pet) => pet.id === data.active) ?? null+ : null;+ const styleIsPet = overlay.config?.style === "pet";+ const shortcut = keybinds.config?.keybinds?.pet_toggle ?? "";++ const describe = (pet: Pet) => {+ const key = `pets.builtin.${pet.id}.description`;+ const localized = pet.builtin ? t(key) : key;+ return localized !== key ? localized : pet.description;+ };++ async function switchToPetStyle() {+ setSwitchingStyle(true);+ try {+ const result = await overlay.saveStyle("pet");+ if (result.applied_live) {+ pushToast("success", t("pets.style_saved"));+ } else {+ setNeedsRestart(true);+ }+ } catch (error) {+ pushToast("error", (error as Error).message);+ } finally {+ setSwitchingStyle(false);+ }+ }++ function choose(petId: string) {+ if (!data || data.active === petId || select.isPending) return;+ select.mutate(petId, {+ onError: (error) =>+ pushToast("error", t("pets.save_error").replace("{0}", (error as Error).message)),+ });+ }++ function toggleVisible() {+ if (!data) return;+ setVisible.mutate(!data.visible, {+ onError: (error) =>+ pushToast("error", t("pets.save_error").replace("{0}", (error as Error).message)),+ });+ }++ function confirmDelete() {+ const pet = pendingDelete;+ if (!pet) return;+ remove.mutate(pet.id, {+ onSuccess: () => pushToast("success", t("pets.deleted").replace("{0}", pet.name)),+ onError: (error) =>+ pushToast("error", t("pets.save_error").replace("{0}", (error as Error).message)),+ onSettled: () => setPendingDelete(null),+ });+ }++ return (+ <div+ data-testid="pets-view"+ className="flex h-full flex-col overflow-y-auto bg-background px-8 pb-10 scrollbar-jarvis"+ >+ <div className="w-full max-w-[1400px]">+ <PageHeader+ icon={<PawPrint />}+ title={t("pets.title")}+ description={+ shortcut+ ? t("pets.subtitle").replace("{0}", formatCombo(shortcut))+ : t("pets.subtitle_no_shortcut")+ }+ actions={+ <Button+ type="button"+ variant="outline"+ size="sm"+ data-testid="pets-visibility"+ disabled={!data || !styleIsPet || setVisible.isPending}+ onClick={toggleVisible}+ >+ {data?.visible === false ? <Eye aria-hidden /> : <EyeOff aria-hidden />}+ {data?.visible === false ? t("pets.show") : t("pets.hide")}+ </Button>+ }+ />++ {overlay.config && !styleIsPet && !needsRestart && (+ <div+ data-testid="pets-style-notice"+ className="mb-5 flex flex-wrap items-center gap-4 rounded-xl border border-border bg-card p-5"+ >+ <PawPrint className="h-6 w-6 shrink-0 text-accent" aria-hidden />+ <div className="min-w-0 flex-1">+ <p className="text-base font-medium text-foreground">+ {t("pets.style_notice_title")}+ </p>+ <p className="mt-0.5 text-sm text-muted-foreground">+ {t("pets.style_notice_body").replace(+ "{0}",+ t(`settings_view.overlay_style.options.${overlay.config.style}`),+ )}+ </p>+ </div>+ <Button+ type="button"+ data-testid="pets-use-pet"+ disabled={switchingStyle}+ onClick={() => void switchToPetStyle()}+ >+ {switchingStyle && <Loader2 className="animate-spin" aria-hidden />}+ {t("pets.use_pet")}+ </Button>+ </div>+ )}++ {needsRestart && (+ <div+ data-testid="pets-restart-notice"+ className="mb-5 flex flex-wrap items-center gap-4 rounded-xl border border-border bg-card p-5"+ >+ <p className="min-w-0 flex-1 text-base text-foreground">{t("pets.restart_hint")}</p>+ <Button+ type="button"+ data-testid="pets-restart"+ disabled={restartApp.restarting}+ onClick={() => void restartApp.restart()}+ >+ {restartApp.restarting && <Loader2 className="animate-spin" aria-hidden />}+ {restartApp.buttonLabel}+ </Button>+ </div>+ )}++ {pets.isError ? (+ <div className="rounded-xl border border-border bg-card p-5" role="alert">+ <p className="text-base text-destructive">+ {t("pets.load_error").replace("{0}", (pets.error as Error).message)}+ </p>+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="mt-3"+ onClick={() => void pets.refetch()}+ >+ {t("common.retry")}+ </Button>+ </div>+ ) : (+ <>+ <ActivePetCard+ pet={activePet}+ loading={!data}+ description={activePet ? describe(activePet) : t("pets.none_description")}+ customizeOpen={customizeOpen}+ onToggleCustomize={() => setCustomizeOpen((open) => !open)}+ >+ {customizeOpen && data && (+ <CustomizePanel+ scale={data.scale}+ bubble={data.bubble}+ keybinds={keybinds}+ />+ )}+ </ActivePetCard>++ <div className="mb-3 mt-8 flex items-center justify-between gap-4">+ <h2 className="text-lg font-semibold text-foreground-strong">{t("pets.my_pets")}</h2>+ <Button+ type="button"+ variant="outline"+ size="sm"+ data-testid="pets-create"+ disabled={!data}+ onClick={() => setCreateOpen(true)}+ >+ <Plus aria-hidden />+ {t("pets.create")}+ </Button>+ </div>++ <ul+ data-testid="pets-grid"+ className="grid gap-3 [grid-template-columns:repeat(auto-fill,minmax(200px,1fr))]"+ >+ {!data ? (+ [0, 1, 2, 3].map((index) => (+ <li+ key={index}+ aria-hidden+ className="h-[196px] animate-pulse rounded-xl border border-border bg-foreground/5"+ />+ ))+ ) : (+ <>+ <li>+ <PetTile+ id={NO_PET_ID}+ name={t("pets.none_name")}+ description={t("pets.none_description")}+ selected={data.active === NO_PET_ID}+ disabled={select.isPending}+ onSelect={() => choose(NO_PET_ID)}+ selectedLabel={t("pets.selected")}+ >+ <PetControlStripPreview size="sm" />+ </PetTile>+ </li>+ {data.pets.map((pet) => (+ <li key={pet.id}>+ <PetTile+ id={pet.id}+ name={pet.name}+ description={describe(pet)}+ selected={data.active === pet.id}+ disabled={select.isPending}+ onSelect={() => choose(pet.id)}+ selectedLabel={t("pets.selected")}+ onDelete={pet.builtin ? undefined : () => setPendingDelete(pet)}+ deleteLabel={t("pets.delete_named").replace("{0}", pet.name)}+ >+ <PetSprite+ pet={pet}+ state="idle"+ scale={integerScaleFor(pet.frame_size, TILE_SPRITE_PX)}+ />+ </PetTile>+ </li>+ ))}+ </>+ )}+ </ul>+ </>+ )}+ </div>++ <CreatePetDialog+ open={createOpen}+ onOpenChange={setCreateOpen}+ onCreated={(pet) => {+ pushToast("success", t("pets.created").replace("{0}", pet.name));+ choose(pet.id);+ }}+ />++ <DeletePetDialog+ pet={pendingDelete}+ busy={remove.isPending}+ onCancel={() => setPendingDelete(null)}+ onConfirm={confirmDelete}+ />+ </div>+ );+}++function ActivePetCard({+ pet,+ loading,+ description,+ customizeOpen,+ onToggleCustomize,+ children,+}: {+ pet: Pet | null;+ loading: boolean;+ description: string;+ customizeOpen: boolean;+ onToggleCustomize: () => void;+ children?: React.ReactNode;+}) {+ const t = useT();+ const reduced = useReducedMotion() ?? false;+ const stateIndex = useStateCycle(Boolean(pet) && !reduced);+ const state = PET_STATES[stateIndex];+ const stateLabel = t(`pets.states.${state}`);++ return (+ <section+ data-testid="pets-active-card"+ aria-label={t("pets.preview_title")}+ className="grid gap-5 rounded-xl border border-border bg-card p-5 md:grid-cols-[minmax(0,300px)_minmax(0,1fr)]"+ >+ <div className="flex flex-col items-center gap-3 rounded-lg bg-secondary/60 px-4 py-5">+ <div className="grid h-[180px] w-full place-items-center">+ {loading ? (+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />+ ) : pet ? (+ <PetSprite+ pet={pet}+ state={state}+ scale={integerScaleFor(pet.frame_size, HERO_SPRITE_PX)}+ label={`${pet.name}: ${stateLabel}`}+ />+ ) : (+ <p className="text-sm text-muted-foreground">{t("pets.none_description")}</p>+ )}+ </div>+ {pet && (+ <span+ data-testid="pets-state-label"+ className="rounded-full border border-border bg-background px-2.5 py-0.5 text-xs font-medium text-muted-foreground"+ >+ {stateLabel}+ </span>+ )}+ <PetControlStripPreview />+ </div>++ <div className="flex min-w-0 flex-col">+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <p className="text-sm text-muted-foreground">{t("pets.preview_title")}</p>+ <p className="mt-0.5 truncate text-lg font-semibold text-foreground-strong">+ {loading ? " " : pet ? pet.name : t("pets.none_name")}+ </p>+ <p className="mt-1 text-sm text-muted-foreground">{loading ? "" : description}</p>+ </div>+ <Button+ type="button"+ variant={customizeOpen ? "secondary" : "outline"}+ size="sm"+ data-testid="pets-customize"+ aria-expanded={customizeOpen}+ disabled={loading}+ onClick={onToggleCustomize}+ >+ <SlidersHorizontal aria-hidden />+ {t("pets.customize")}+ </Button>+ </div>+ {children}+ </div>+ </section>+ );+}++function CustomizePanel({+ scale,+ bubble,+ keybinds,+}: {+ scale: number;+ bubble: boolean;+ keybinds: ReturnType<typeof useKeybinds>;+}) {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const save = useSavePetSettings();+ const [size, setSize] = useState(scale);++ // Follow the server (another window, a failed save) whenever it moves.+ useEffect(() => setSize(scale), [scale]);++ function commitSize(next: number) {+ const rounded = Math.round(next * 10) / 10;+ if (rounded === scale) return;+ save.mutate(+ { scale: rounded },+ {+ onError: (error) => {+ setSize(scale);+ pushToast("error", t("pets.save_error").replace("{0}", (error as Error).message));+ },+ },+ );+ }++ return (+ <div+ data-testid="pets-customize-panel"+ className="mt-4 divide-y divide-border rounded-lg border border-border bg-background"+ >+ <div className="px-4 py-3">+ <div className="flex items-center justify-between gap-4">+ <label htmlFor="pets-size" className="text-sm font-medium text-foreground">+ {t("pets.size_label")}+ </label>+ <span className="font-mono text-sm text-foreground-strong">{`${Math.round(size * 100)}%`}</span>+ </div>+ <p className="mt-0.5 text-xs text-muted-foreground">{t("pets.size_hint")}</p>+ <input+ id="pets-size"+ type="range"+ data-testid="pets-size"+ min={SCALE_MIN}+ max={SCALE_MAX}+ step={SCALE_STEP}+ value={size}+ disabled={save.isPending}+ onChange={(event) => setSize(Number(event.target.value))}+ onMouseUp={() => commitSize(size)}+ onKeyUp={() => commitSize(size)}+ onTouchEnd={() => commitSize(size)}+ className="mt-3 w-full accent-primary disabled:opacity-50"+ />+ </div>+ <div className="flex items-center justify-between gap-4 px-4 py-3">+ <div className="min-w-0">+ <p className="text-sm font-medium text-foreground">{t("pets.bubble_label")}</p>+ <p className="mt-0.5 text-xs text-muted-foreground">{t("pets.bubble_hint")}</p>+ </div>+ <Switch+ checked={bubble}+ disabled={save.isPending}+ aria-label={t("pets.bubble_label")}+ data-testid="pets-bubble"+ onCheckedChange={(next) =>+ save.mutate(+ { bubble: next },+ {+ onError: (error) =>+ pushToast("error", t("pets.save_error").replace("{0}", (error as Error).message)),+ },+ )+ }+ />+ </div>+ <div className="px-4 py-3">+ <KeybindRow+ action="pet_toggle"+ label={t("settings_view.keybinds.pet_toggle_label")}+ config={keybinds.config}+ loading={keybinds.loading}+ onSave={keybinds.saveKeybind}+ />+ <p className="mt-1.5 text-xs text-muted-foreground">{t("pets.shortcut_hint")}</p>+ </div>+ </div>+ );+}++function PetTile({+ id,+ name,+ description,+ selected,+ disabled,+ selectedLabel,+ onSelect,+ onDelete,+ deleteLabel,+ children,+}: {+ id: string;+ name: string;+ description: string;+ selected: boolean;+ disabled: boolean;+ selectedLabel: string;+ onSelect: () => void;+ onDelete?: () => void;+ deleteLabel?: string;+ children: React.ReactNode;+}) {+ return (+ <div className="group relative h-full">+ <button+ type="button"+ data-testid={`pet-tile-${id}`}+ aria-pressed={selected}+ disabled={disabled && !selected}+ onClick={onSelect}+ className={cn(+ "flex h-full w-full flex-col rounded-xl border bg-card p-3 text-left transition-colors",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ selected+ ? "border-accent ring-1 ring-accent"+ : "border-border hover:border-border-strong",+ )}+ >+ <div className="grid h-28 w-full place-items-center overflow-hidden rounded-lg bg-secondary/60">+ {children}+ </div>+ <div className="mt-3 flex min-w-0 items-center gap-2 pr-6">+ <span className="truncate text-base font-medium text-foreground">{name}</span>+ {selected && (+ <span className="inline-flex shrink-0 items-center gap-1 text-xs font-medium text-accent">+ <Check className="h-3.5 w-3.5" aria-hidden />+ {selectedLabel}+ </span>+ )}+ </div>+ <p className="mt-0.5 line-clamp-2 text-sm text-muted-foreground">{description}</p>+ </button>+ {onDelete && (+ <button+ type="button"+ data-testid={`pet-delete-${id}`}+ aria-label={deleteLabel}+ title={deleteLabel}+ onClick={onDelete}+ className="absolute bottom-3 right-3 grid h-7 w-7 place-items-center rounded-md text-muted-foreground opacity-70 transition-colors hover:bg-secondary hover:text-destructive hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <Trash2 className="h-4 w-4" aria-hidden />+ </button>+ )}+ </div>+ );+}++function DeletePetDialog({+ pet,+ busy,+ onCancel,+ onConfirm,+}: {+ pet: Pet | null;+ busy: boolean;+ onCancel: () => void;+ onConfirm: () => void;+}) {+ const t = useT();+ return (+ <Dialog.Root open={pet !== null} onOpenChange={(open) => !open && !busy && onCancel()}>+ <Dialog.Portal>+ <Dialog.Overlay className="fixed inset-0 z-[80] bg-scrim/75 backdrop-blur-sm data-[state=open]:animate-in data-[state=open]:fade-in-0 motion-reduce:animate-none" />+ <Dialog.Content+ data-testid="delete-pet-dialog"+ className="fixed inset-0 z-[80] m-auto h-fit w-[min(400px,calc(100vw-32px))] rounded-2xl border border-border bg-popover p-6 text-popover-foreground shadow-float outline-none data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 motion-reduce:animate-none"+ >+ <Dialog.Title className="text-base font-semibold text-foreground-strong">+ {t("pets.delete_title").replace("{0}", pet?.name ?? "")}+ </Dialog.Title>+ <Dialog.Description className="mt-1.5 text-sm text-muted-foreground">+ {t("pets.delete_body")}+ </Dialog.Description>+ <div className="mt-6 flex justify-end gap-2">+ <Button type="button" variant="ghost" disabled={busy} onClick={onCancel}>+ {t("common.cancel")}+ </Button>+ <Button+ type="button"+ variant="destructive"+ data-testid="delete-pet-confirm"+ disabled={busy}+ onClick={onConfirm}+ >+ {busy && <Loader2 className="animate-spin" aria-hidden />}+ {t("pets.delete")}+ </Button>+ </div>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/SettingsHubView.test.tsx b/jarvis/ui/web/frontend/src/views/SettingsHubView.test.tsxindex fa974612b8..37ecbfee6c 100644--- a/jarvis/ui/web/frontend/src/views/SettingsHubView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/SettingsHubView.test.tsx@@ -83,6 +83,7 @@ vi.mock("@/views/TelephonyView", () => ({vi.mock("@/views/LocalModelsView", () => ({LocalModelsView: stub("TAB_LOCAL_MODELS"),}));+vi.mock("@/views/PetsView", () => ({ PetsView: stub("TAB_PETS") }));vi.mock("@/views/CostsView", () => ({ CostsView: stub("TAB_COSTS") }));vi.mock("@/views/feedback/FeedbackView", () => ({FeedbackView: stub("TAB_FEEDBACK"),@@ -95,6 +96,7 @@ const SettingsHubView = () => <HubView onClose={noop} />;const NAV_IDS = ["settings",+ "pets","profile","agent-instructions","contacts",@@ -150,7 +152,7 @@ describe("SettingsHubView header and navigation", () => {expect(onClose).not.toHaveBeenCalled();});- it("lists all ten entries in the left navigation", async () => {+ it("lists every mocked entry in the left navigation", async () => {render(<SettingsHubView />);for (const id of NAV_IDS) {@@ -191,6 +193,7 @@ describe("SettingsHubView tab resolution", () => {["socials", "TAB_SOCIALS"],["apikeys", "TAB_APIKEYS"],["local-models", "TAB_LOCAL_MODELS"],+ ["pets", "TAB_PETS"],["costs", "TAB_COSTS"],["feedback", "TAB_FEEDBACK"],// Merged-in ids land on the tab hosting their content.diff --git a/jarvis/ui/web/frontend/src/views/SettingsHubView.tsx b/jarvis/ui/web/frontend/src/views/SettingsHubView.tsxindex b55de0d8e3..d3bb24f4e9 100644--- a/jarvis/ui/web/frontend/src/views/SettingsHubView.tsx+++ b/jarvis/ui/web/frontend/src/views/SettingsHubView.tsx@@ -22,7 +22,7 @@ import { cn } from "@/lib/utils";* floats over the user's current section, with a searchable left navigation* (General · System · Activity) and the selected section on the right:*- * General: Settings, Appshots, Profile, {name}.md, Contacts, Socials+ * General: Settings, Appshots, My Pets, Profile, {name}.md, Contacts, Socials* System: Computers, API Keys, Local models, Jarvis actions* Activity: Spend, Feedback*@@ -84,6 +84,9 @@ const JarvisActionsTab = lazy(() =>const AppshotsTab = lazy(() =>import("@/views/AppshotsView").then((m) => ({ default: m.AppshotsView })),);+const PetsTab = lazy(() =>+ import("@/views/PetsView").then((m) => ({ default: m.PetsView })),+);const CostsTab = lazy(() =>import("@/views/CostsView").then((m) => ({ default: m.CostsView })),);@@ -93,10 +96,11 @@ const FeedbackTab = lazy(() =>})),);-/** The twelve entries of the left navigation, in display order. */+/** The entries of the left navigation, in display order. */type HubNavId =| "settings"| "appshots"+ | "pets"| "profile"| "agent-instructions"| "contacts"@@ -111,7 +115,7 @@ type HubNavId =const HUB_NAV_GROUPS: readonly { labelKey: string; ids: readonly HubNavId[] }[] = [{labelKey: "settings_hub.group_general",- ids: ["settings", "appshots", "profile", "agent-instructions", "contacts", "socials"],+ ids: ["settings", "appshots", "pets", "profile", "agent-instructions", "contacts", "socials"],},{labelKey: "settings_hub.group_system",@@ -134,6 +138,7 @@ const TAB_CONTENT: Record<HubNavId | "telephony-setup", LazyExoticComponent<Comp"local-models": LocalModelsTab,computers: ComputersTab,appshots: AppshotsTab,+ pets: PetsTab,"jarvis-actions": JarvisActionsTab,costs: CostsTab,feedback: FeedbackTab,@@ -165,6 +170,8 @@ function resolveHubTab(active: string): { content: HubNavId | "telephony-setup";return { content: "computers", highlight: "computers" };case "appshots":return { content: "appshots", highlight: "appshots" };+ case "pets":+ return { content: "pets", highlight: "pets" };case "jarvis-actions":return { content: "jarvis-actions", highlight: "jarvis-actions" };case "costs":diff --git a/jarvis/ui/web/frontend/src/views/settings/KeybindRow.tsx b/jarvis/ui/web/frontend/src/views/settings/KeybindRow.tsxindex 530dcbe52f..d5b8eb328d 100644--- a/jarvis/ui/web/frontend/src/views/settings/KeybindRow.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/KeybindRow.tsx@@ -145,6 +145,7 @@ export const ACTION_LABEL_KEY: Record<KeybindAction, string> = {dictate: "settings_view.keybinds.dictate_label",dictate_toggle: "settings_view.keybinds.dictate_toggle_label",paste_last: "settings_view.keybinds.paste_last_label",+ pet_toggle: "settings_view.keybinds.pet_toggle_label",};/**diff --git a/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.tsxindex edc3026725..e84666d8e9 100644--- a/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.tsx@@ -1,5 +1,5 @@import { useEffect, useState } from "react";-import { Monitor, Eye, Volume2, Bell, MousePointer } from "lucide-react";+import { Monitor, Eye, Volume2, Bell, MousePointer, PawPrint } from "lucide-react";import { Switch } from "@/components/ui/switch";import {useOverlayStyle,@@ -12,13 +12,14 @@ import { useBarFollowCursor } from "@/hooks/useBarFollowCursor";import { BarSizeGroup } from "@/views/settings/BarSizeGroup";import { useMuteMusic } from "@/hooks/useMuteMusic";import { useSoundEffects } from "@/hooks/useSoundEffects";+import { useRestartApp } from "@/hooks/useRestartApp";import { useEventStore } from "@/store/events";import { useT } from "@/i18n";import { cn } from "@/lib/utils";/*** "Bar & Overlay" group inside the Settings view — the on-screen overlay- * appearance (Bar / Mascot / None) and two dictation behaviours: show the bar at+ * appearance (Bar / Mascot / Voice orb / Pet / None) and two dictation behaviours: show the bar at* all times, and mute music while a voice session is active. Moved here from the* former standalone Taskbar section; the controls, hooks, and i18n keys* (``taskbar_view.*`` + ``settings_view.overlay_style.*``) are unchanged.@@ -232,58 +233,25 @@ function SoundEffectsRow() {}/**- * On-screen overlay style selector (Bar / Mascot / None). Reuses the- * settings_view.overlay_style.* i18n. A bar <-> mascot switch cannot apply live- * (BUG-031: Tcl cross-thread abort), so the app self-restarts to deliver it.+ * On-screen overlay style selector (Bar / Mascot / Voice orb / Pet / None).+ * Reuses the settings_view.overlay_style.* i18n. A switch between the bar and+ * an orb-window style cannot apply live (BUG-031: Tcl cross-thread abort), so+ * the app self-restarts to deliver it (`useRestartApp`).*/function OverlayStylePanel() {const t = useT();const { config, loading, error, saveStyle } = useOverlayStyle();const pushToast = useEventStore((s) => s.pushToast);+ const setActiveSection = useEventStore((s) => s.setActiveSection);const [style, setStyle] = useState<OverlayStyle>("jarvis_bar");const [saving, setSaving] = useState(false);const [needsRestart, setNeedsRestart] = useState(false);- const [restarting, setRestarting] = useState(false);- // Armed after the backend refuses the restart (HTTP 409) because missions are- // running; the next click resends with ``force=true``.- const [forceArmed, setForceArmed] = useState(false);+ const { restart, restarting, buttonLabel: restartLabel } = useRestartApp();useEffect(() => {if (config) setStyle(config.style);}, [config]);- // The window goes away on success, so we never clear ``restarting`` there.- async function onRestartNow(force: boolean) {- if (restarting) return;- setRestarting(true);- try {- const url = force- ? "/api/settings/restart-app?force=true"- : "/api/settings/restart-app";- const res = await fetch(url, { method: "POST" });- if (res.status === 409) {- // Live missions would be killed — surface the count and arm a force- // restart instead of killing them silently.- let count = 0;- try {- const body = await res.json();- count = body?.detail?.missions?.length ?? 0;- } catch {- /* malformed body — still arm the override */- }- setRestarting(false);- setForceArmed(true);- pushToast("warning", `${count} ${t("topbar.restart_missions_running")}`);- return;- }- if (!res.ok) throw new Error(`restart-failed:${res.status}`);- pushToast("info", t("taskbar_view.restarting"));- } catch (e) {- setRestarting(false);- pushToast("error", (e as Error).message);- }- }-const options = config?.options ?? OVERLAY_STYLES;async function onPick(opt: OverlayStyle) {@@ -319,9 +287,9 @@ function OverlayStylePanel() {</p>{/* Visual preview cards — click to apply (no dropdown). Two columns- on a narrow window so a fourth style never squeezes the previews+ on a narrow window so a fifth style never squeezes the previewsinto unreadable slivers. */}- <div className="mt-4 grid grid-cols-2 gap-3 sm:grid-cols-4">+ <div className="mt-4 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">{options.map((opt) => (<buttonkey={opt}@@ -351,6 +319,19 @@ function OverlayStylePanel() {))}</div>+ {/* Which pet, its size and its bubble live on their own page. */}+ {style === "pet" && (+ <button+ type="button"+ data-testid="overlay-style-open-pets"+ onClick={() => setActiveSection("pets")}+ className="mt-3 inline-flex items-center gap-1.5 text-xs font-medium text-accent hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <PawPrint className="h-3.5 w-3.5" aria-hidden />+ {t("pets.open_settings")}+ </button>+ )}+{needsRestart && (<div className="mt-3 flex flex-wrap items-center gap-3"><p className="text-xs text-foreground">@@ -358,15 +339,11 @@ function OverlayStylePanel() {</p><buttontype="button"- onClick={() => onRestartNow(forceArmed)}+ onClick={() => void restart()}disabled={restarting}className="rounded-md bg-secondary px-3 py-1.5 text-xs font-medium text-foreground-strong transition-colors hover:bg-popover disabled:opacity-60">- {restarting- ? t("taskbar_view.restarting")- : forceArmed- ? t("topbar.restart_force")- : t("taskbar_view.restart_now")}+ {restartLabel}</button></div>)}diff --git a/jarvis/ui/web/frontend/src/views/settings/settingsSearch.ts b/jarvis/ui/web/frontend/src/views/settings/settingsSearch.tsindex 8c154282b4..931055da00 100644--- a/jarvis/ui/web/frontend/src/views/settings/settingsSearch.ts+++ b/jarvis/ui/web/frontend/src/views/settings/settingsSearch.ts@@ -31,6 +31,7 @@ const SEARCH_PAGES = [{ id: "socials", keys: ["socials"] },{ id: "apikeys", keys: ["apikeys_view", "apikeys_voice", "apikeys_model", "apikeys_cu_model"] },{ id: "appshots", keys: ["appshots"] },+ { id: "pets", keys: ["pets"] },{ id: "jarvis-actions", keys: ["jarvis_actions"] },{ id: "costs", keys: ["costs_view"] },{ id: "feedback", keys: ["feedback"] },diff --git a/tests/unit/ui/pets/test_pet_state_parity.py b/tests/unit/ui/pets/test_pet_state_parity.pynew file mode 100644index 0000000000..1cd3045b10--- /dev/null+++ b/tests/unit/ui/pets/test_pet_state_parity.py@@ -0,0 +1,92 @@+"""The pet state vocabulary must mean the same thing in every layer.++A pet state is one animation row of a sprite sheet. It crosses Python+(``jarvis.ui.pets.states``), the manifest on disk, the REST payload, the+TypeScript mirror and the ``pets.states.*`` labels — the five-layer enum this+repo has been bitten by four times (AP-4 / BUG-008). The classic symptom here+is a preview that cycles through a state the backend never sends, or a state+label that renders its raw key on the settings page.++So this pins the layers to the Python module:++* the TS ``PET_STATES`` tuple, in the SAME order (it is the sheet's row order),+* the TS ``STATE_FALLBACKS`` table and the "none" pet id,+* the frame-size and frames-per-row limits the create dialog checks against,+* a ``pets.states.<state>`` label in every locale.++Every parsed set is asserted non-empty first, so a reformat that breaks a+regex fails loudly instead of passing against nothing.+"""+from __future__ import annotations++import json+import re+from pathlib import Path++import pytest++from jarvis.ui.pets.states import (+ FRAME_SIZES,+ MAX_FRAMES_PER_STATE,+ NO_PET_ID,+ PET_STATES,+ STATE_FALLBACKS,+)++_FRONTEND = Path(__file__).resolve().parents[4] / "jarvis/ui/web/frontend/src"+_TS_FILE = _FRONTEND / "lib/petStates.ts"+_LOCALES = _FRONTEND / "i18n/locales"+++def _ts() -> str:+ assert _TS_FILE.exists(), f"TS mirror missing: {_TS_FILE}"+ return _TS_FILE.read_text(encoding="utf-8")+++def _locale_names() -> list[str]:+ return sorted(path.stem for path in _LOCALES.glob("*.json"))+++def test_typescript_states_match_python_in_order() -> None:+ match = re.search(r"export const PET_STATES = \[([^\]]*)\] as const;", _ts())+ assert match, "PET_STATES const tuple not found in petStates.ts"+ states = re.findall(r'"([a-z_]+)"', match.group(1))+ assert states, "parsed no states from petStates.ts"+ assert states == list(PET_STATES)+++def test_typescript_fallbacks_match_python() -> None:+ match = re.search(r"export const STATE_FALLBACKS[^=]*=\s*\{([^}]*)\};", _ts())+ assert match, "STATE_FALLBACKS table not found in petStates.ts"+ pairs = dict(re.findall(r'([a-z_]+):\s*"([a-z_]+)"', match.group(1)))+ assert pairs, "parsed no fallbacks from petStates.ts"+ assert pairs == STATE_FALLBACKS+++def test_typescript_constants_match_python() -> None:+ source = _ts()+ none_id = re.search(r'export const NO_PET_ID = "([^"]+)";', source)+ assert none_id and none_id.group(1) == NO_PET_ID+ sizes = re.search(r"export const FRAME_SIZES = \[([^\]]*)\] as const;", source)+ assert sizes, "FRAME_SIZES not found in petStates.ts"+ assert tuple(int(n) for n in re.findall(r"\d+", sizes.group(1))) == FRAME_SIZES+ max_frames = re.search(r"export const MAX_FRAMES_PER_STATE = (\d+);", source)+ assert max_frames and int(max_frames.group(1)) == MAX_FRAMES_PER_STATE+++def test_every_fallback_chain_ends_at_idle() -> None:+ for state in PET_STATES:+ seen: set[str] = set()+ current = state+ while current != "idle":+ assert current not in seen, f"fallback loop at {current}"+ seen.add(current)+ current = STATE_FALLBACKS[current]++[email protected]("locale", _locale_names())+def test_every_state_is_labelled_in_every_locale(locale: str) -> None:+ data = json.loads((_LOCALES / f"{locale}.json").read_text(encoding="utf-8"))+ labels = data["pets"]["states"]+ assert sorted(labels) == sorted(PET_STATES)+ assert all(str(label).strip() for label in labels.values())