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(wallpaper): bring your own picture into the wallpaper section
rubenluetke10-beepc245f6989ae8
diff --git a/jarvis/agentic_ide/deck_voice.py b/jarvis/agentic_ide/deck_voice.pydeleted file mode 100644index 1ac2ec098a..0000000000--- a/jarvis/agentic_ide/deck_voice.py+++ /dev/null@@ -1,176 +0,0 @@-"""Give the Command Deck's report queue a voice — EventBus <-> :mod:`.standup`.--:mod:`.standup` decides what should be said and when. It deliberately knows-nothing about how speech works: it runs inside the pane sweep, which has to keep-working in a headless install, in the tests, and on a machine with no audio at-all. This module is the one place the two meet.--Modelled on :class:`jarvis.missions.voice.announcer.MissionAnnouncer`, and for-the same reasons it exists: an ``AnnouncementRequested`` on the speech bus gets-``scrub_for_voice``, the barge-in rules, the transcript's spoken track and the-TTS provider for free, and it is the path every other unprompted line in this-app already takes. A second, private TTS route would be a second set of edge-cases to get wrong.--Three things travel the other way, and all three are READ rather than derived:--* **The language.** One resolver decides a turn's output language for every- layer (CLAUDE.md §1, ``core/turn_language.py``). This module never calls it —- it caches what the turn already resolved to, off ``ResponseGenerated`` and- ``VoiceSessionStarted``. Re-deriving it here is exactly the divergence the- doctrine exists to stop.-* **Whether a conversation is open.** The deck talks to a person who is- listening. Outside a session the queue fills and says nothing, and the next- session opens with one "while you were away" line.-* **Hanging up.** ``VoiceSessionEnded`` ends the conversation here too. Speech- itself is already dead by then — the killswitch is the pipeline's contract,- not ours — but the queue must stop offering, or it would greet the next- session with a report from an hour ago as though it were news.--Everything is best-effort. A bus subscriber that raises would take a voice turn-down with it (AP-18), and none of this is worth that: the worst honest outcome-is a deck whose lane fills up silently, which is exactly what an install with no-speech stack gets anyway (§3).-"""--from __future__ import annotations--import logging-from typing import TYPE_CHECKING, Any--from jarvis.core.events import (- AnnouncementRequested,- ResponseGenerated,- VoiceSessionEnded,- VoiceSessionStarted,-)--from . import standup--if TYPE_CHECKING: # pragma: no cover - typing only- from jarvis.core.bus import EventBus--logger = logging.getLogger(__name__)--#: What the pipeline is told this line is. ``info`` rather than ``completion``:-#: a completion is the answer to something the user asked for in this turn, and-#: a deck report is news arriving on its own. The distinction drives the-#: pipeline's own idle-window and barge-in handling.-ANNOUNCEMENT_KIND = "info"--#: Fallback when nothing has been spoken yet in this process. Only reachable-#: for a report that lands before the user's first answer, which is a very-#: short window and not worth guessing about.-DEFAULT_LANGUAGE = "en"---class DeckVoice:- """Subscribes on ``start()``, publishes announcements, remembers nothing else."""-- def __init__(self, bus: EventBus, *, composer: Any = None) -> None:- self._bus = bus- self._composer = composer- self._language = DEFAULT_LANGUAGE- # (event type, handler) pairs rather than unsubscribe callables: this- # bus's `subscribe` returns None and `unsubscribe` takes both halves- # back. Kept so `stop()` is a real detach — a bridge that only stopped- # publishing would still be holding a dead handler on a live bus.- self._bound: list[tuple[type[Any], Any]] = []- self._started = False-- # ------------------------------------------------------------- lifecycle-- def start(self) -> None:- """Wire the queue to this bus. Idempotent."""- if self._started:- return- try:- for event_type, handler in (- (VoiceSessionStarted, self._on_started),- (VoiceSessionEnded, self._on_ended),- (ResponseGenerated, self._on_response),- ):- self._bus.subscribe(event_type, handler)- self._bound.append((event_type, handler))- except Exception as exc: # noqa: BLE001 - an optional surface never breaks boot- logger.warning("Command Deck voice not subscribed: %s", exc)- self._unsubscribe()- return- standup.wire(- speak=self._speak,- language=lambda: self._language,- composer=self._composer,- )- self._started = True-- def stop(self) -> None:- """Unsubscribe and take the queue's voice away. Idempotent."""- self._unsubscribe()- standup.unwire()- self._started = False-- def _unsubscribe(self) -> None:- for event_type, handler in self._bound:- try:- self._bus.unsubscribe(event_type, handler)- except Exception: # noqa: BLE001 - shutdown must not raise- logger.debug("Command Deck voice: unsubscribe failed", exc_info=True)- self._bound.clear()-- # ---------------------------------------------------------------- events-- async def _on_started(self, event: VoiceSessionStarted) -> None:- self._remember_language(getattr(event, "language", ""))- standup.queue().conversation_started()-- async def _on_ended(self, event: VoiceSessionEnded) -> None:- _ = event- standup.queue().conversation_ended()-- async def _on_response(self, event: ResponseGenerated) -> None:- """Cache the language the turn resolved to, and wake the queue.-- Both halves matter. The language is read here rather than resolved- because one resolver owns that decision. And an answer means the user- is engaged with the deck right now, which is precisely when a queue- that went quiet after an unanswered line should be allowed to speak- again (``standup`` rule 8).- """- self._remember_language(getattr(event, "language", ""))- queue = standup.queue()- if queue.in_conversation():- queue.wake()-- def _remember_language(self, language: object) -> None:- text = str(language or "").strip().lower()[:2]- if text:- self._language = text-- # ----------------------------------------------------------------- speak-- async def _speak(self, text: str, language: str) -> None:- """Publish one report. Never ``interrupt`` — see ``standup`` rule 5."""- line = (text or "").strip()- if not line:- return- try:- await self._bus.publish(- AnnouncementRequested(- text=line,- priority="normal",- language=language or self._language,- kind=ANNOUNCEMENT_KIND,- )- )- except Exception as exc: # noqa: BLE001 - a mute deck beats a dead sweep- logger.warning("Command Deck report not announced: %s", exc)---def attach(bus: EventBus, *, composer: Any = None) -> DeckVoice:- """Build and start the bridge — the one call a host needs."""- voice = DeckVoice(bus, composer=composer)- voice.start()- return voice---__all__ = ["ANNOUNCEMENT_KIND", "DEFAULT_LANGUAGE", "DeckVoice", "attach"]diff --git a/jarvis/agentic_ide/standup.py b/jarvis/agentic_ide/standup.pydeleted file mode 100644index f7254a8ba0..0000000000--- a/jarvis/agentic_ide/standup.py+++ /dev/null@@ -1,821 +0,0 @@-"""One agent reports at a time — the Command Deck's way back to the user.--## The gap this closes--:mod:`.notifications` already knows the moment a pane stops working, and the-header bell already carries the count. What nobody ever does is SAY it. In the-grid and in chat that is the right behaviour: the user is looking at the panes,-and a wall of terminals that talks would be unbearable. In the Command Deck it-is the whole point — the user is a team lead who handed out work by voice and-then looked away, and the work coming back is the half that was missing.--## Why a queue rather than "announce each one"--Eight agents can stop inside the same ten seconds. Spoken naively that is eight-announcements stacked on each other, or — with the speech pipeline's own-queueing — one long recital nobody asked for, delivered while the user is-mid-sentence about something else.--So nothing is announced directly. Reports land here, and this module answers-one question per sweep: *is there something to say right now, and what is the-one thing it is?* The rules, in the order they were argued out with the-maintainer:--1. **One speaker.** Exactly one report is on air. Everything else waits.-2. **Headline before detail.** Several landing in the same silence produce ONE- line — "three are done: Mika, Nova and Kai" — not three reports. That is the- sentence a team lead would actually get, and it clears the pile-up in one- breath instead of spending a minute on it.-3. **The user's answer advances the queue.** Asking for one by name puts that- report on air; "later" puts the queue to sleep.-4. **A blocker cuts the line.** ``needs_input`` outranks ``completed``: a pane- holding a question has work STOPPED on it, a finished pane has work merely- waiting to be read.-5. **Never interrupt.** Everything leaves here as ``priority="normal"``, which- the speech pipeline queues behind whatever is being said. Nothing this- module produces is ever worth cutting the user off for.-6. **Read means silent.** A pane the user opened and read in the deck drops out- of the queue without ever being spoken — they already know.-7. **Hanging up is still the killswitch.** Speech stops instantly, because that- is the pipeline's contract, not ours. The queue SURVIVES and is offered once- at the start of the next conversation. It is never shouted after the user- (see ``auflegen`` mandate + the no-nagging one).-8. **Said once.** An unanswered headline is not repeated, and a report that has- been spoken is not spoken again. After an unanswered line the queue goes- quiet until the user does something — with one exception, which is rule 4:- a pane that is BLOCKED wakes it, because there the work has stopped.-9. **Bounded.** :data:`MAX_PENDING` reports; past that the oldest ``completed``- ones collapse into the count instead of growing a backlog nobody will hear.--## What it will not claim--Nothing here reads the agent's prose to decide whether the work went well. A-"finished" report means the pane went quiet, exactly as the bell's entry does-(:mod:`.notifications`) — the wording says so, and the deck's card says so.-Promising the other thing would be the one lie this whole surface cannot-afford, because the user asked for it precisely so they could stop looking.--## Cost--Zero polling of its own: the sweep in :mod:`.notifications` already looks at-every pane every couple of seconds, and hands its findings here. Announcing is-one bounded flash call through :func:`jarvis.voice.contextual_readback.render_readback`-with a deterministic multilingual fallback, so an install with no provider at-all still gets a spoken line (§3).-"""--from __future__ import annotations--import logging-import time-from dataclasses import dataclass-from itertools import count-from typing import TYPE_CHECKING, Any, Literal--if TYPE_CHECKING: # pragma: no cover - typing only- from collections.abc import Callable, Iterable, Sequence-- from .notifications import Notification--logger = logging.getLogger(__name__)--#: What one report is about — the same four kinds the bell files.-Kind = Literal["completed", "needs_input", "exited", "failed"]--#: Where a report is in its life.-#:-#: ``pending`` waiting · ``on_air`` the one being reported right now · ``reported``-#: delivered · ``dropped`` taken out without being said (the user read the pane,-#: or asked for it to go away).-#:-#: ``reported`` rather than "answered" on purpose: what the deck knows is that-#: it said the line, never that the user took it in. Naming the state after the-#: stronger claim is how the first version ended up treating an ignored report-#: as a closed one.-ReportState = Literal["pending", "on_air", "reported", "dropped"]--#: What the user can do about a report.-Action = Literal["next", "later", "drop"]--#: How many reports wait at once. A dozen is already more than anyone will sit-#: through; past it the oldest finished ones are folded into the headline count,-#: which is the honest way to lose them — they are still on their cards.-MAX_PENDING = 12--#: Kinds that may wake a settled queue, because work has STOPPED rather than-#: finished. Rule 4 and rule 8's one exception.-BLOCKING_KINDS: frozenset[str] = frozenset({"needs_input"})--#: Reporting order. A blocked pane first, then a crashed one (it is not coming-#: back on its own either), then the ordinary finishes.-_PRIORITY: dict[str, int] = {"needs_input": 0, "failed": 1, "exited": 2, "completed": 3}--_ids = count(1)---@dataclass(slots=True)-class Report:- """One pane's news, waiting for its turn to be said."""-- id: str- workspace_id: str- pane_key: str- pane: str- agent: str- kind: Kind- #: One clause: what happened. Taken from the bell's entry so the spoken- #: line, the deck card and the notification panel cannot disagree.- headline: str- #: What the pane was working on, from its own recap. May be empty.- detail: str- at: float- state: ReportState = "pending"- #: Has this report itself been spoken? Distinct from having been counted in- #: a headline — "three are done" names the panes without reporting them.- spoken: bool = False- #: Was this one of the panes a headline counted? Stops a second headline- #: from being produced for a set the user has already been told about.- in_headline: bool = False-- def to_dict(self) -> dict[str, Any]:- return {- "id": self.id,- "workspace_id": self.workspace_id,- "pane_key": self.pane_key,- "pane": self.pane,- "agent": self.agent,- "kind": self.kind,- "headline": self.headline,- "detail": self.detail,- "at": self.at,- "state": self.state,- "spoken": self.spoken,- }---@dataclass(frozen=True, slots=True)-class Utterance:- """What should be said right now, and what saying it covers.-- ``form`` is the shape rather than the wording: ``report`` is one pane's- news, ``headline`` is the "three are done" line that stands in for several,- and ``resumed`` is the once-only "while you were away" opening. The words- themselves are composed later — this is the decision, not the sentence.- """-- form: Literal["report", "headline", "resumed"]- reports: tuple[Report, ...]-- @property- def panes(self) -> tuple[str, ...]:- return tuple(report.pane for report in self.reports)---class StandupQueue:- """The per-process queue, and every rule about when it may speak.-- Deliberately synchronous and loop-free: the whole decision is a function of- (reports, clock, what the user last did), so it can be tested without a- PTY, a voice session or a wait — which is what the four failure modes in- the module docstring all needed and none of them got.-- Not thread-safe, by the same reasoning as :class:`.notifications.NotificationCenter`:- the sweep that fills it and the routes that read it are all on the event- loop.- """-- def __init__(self, limit: int = MAX_PENDING) -> None:- self._reports: list[Report] = []- self._limit = limit- #: True once a line has gone out that nobody answered. Rule 8: the- #: queue then holds its tongue until the user does something. Blocking- #: news clears it — see :meth:`offer`.- self._settled = False- #: True while the user is away (they hung up) and reports arrived. The- #: next conversation opens with one "while you were away" line.- self._missed = False- #: Is a conversation happening at all? Nothing is spoken outside one:- #: the deck talks to a person who is listening, not to an empty room.- self._in_conversation = False-- # ------------------------------------------------------------------ fill-- def offer(self, entries: Iterable[Notification], *, now: float | None = None) -> list[Report]:- """Take what the sweep just found. Returns the reports actually filed.-- Duplicates are dropped rather than stacked: the same pane finishing the- same episode twice is one piece of news, and the bell's own- ``announced`` latch already means a second entry is a new episode — but- a pane that finishes, is asked something, and finishes again inside one- silence must not produce three lines about the same work.- """- moment = time.time() if now is None else now- filed: list[Report] = []- for entry in entries:- report = self._file(entry, moment)- if report is None:- continue- filed.append(report)- # Rule 4 / rule 8's exception: a pane waiting on the user is not- # news that can sit. It wakes a queue that had gone quiet.- if report.kind in BLOCKING_KINDS:- self._settled = False- if filed and not self._in_conversation:- self._missed = True- self._trim()- return filed-- def _file(self, entry: Notification, now: float) -> Report | None:- ident = (entry.workspace_id, entry.pane_key)- for existing in self._reports:- if (existing.workspace_id, existing.pane_key) != ident:- continue- if existing.state not in ("pending", "on_air"):- continue- if existing.kind == entry.kind:- # Same news about the same pane, still unsaid. Refresh what it- # says (a recap can improve between sweeps) and keep its place.- existing.headline = entry.title- existing.detail = entry.detail- return None- if _PRIORITY.get(entry.kind, 9) < _PRIORITY.get(existing.kind, 9):- # It finished, and now it is asking. The question is the news;- # the finish is what led to it.- existing.kind = entry.kind # type: ignore[assignment]- existing.headline = entry.title- existing.detail = entry.detail- existing.at = now- existing.in_headline = False- return None- return None- report = Report(- id=f"sr{next(_ids)}",- workspace_id=entry.workspace_id,- pane_key=entry.pane_key,- pane=entry.pane,- agent=entry.agent,- kind=entry.kind,- headline=entry.title,- detail=entry.detail,- at=now,- )- self._reports.append(report)- return report-- def _trim(self) -> None:- """Rule 9 — keep the waiting list bounded, losing the least useful end.-- Only ``completed`` reports are ever dropped, and only the oldest. A- blocked or crashed pane is never quietly forgotten: those are the two- the user most needs to hear about, and a queue that silently loses them- is worse than one that says nothing at all.- """- waiting = [r for r in self._reports if r.state == "pending"]- excess = len(waiting) - self._limit- if excess <= 0:- return- droppable = [r for r in waiting if r.kind == "completed"]- for report in droppable[:excess]:- report.state = "dropped"-- # ------------------------------------------------------------------ read-- def pending(self) -> list[Report]:- """Everything still waiting, blockers first, then oldest first."""- return sorted(- (r for r in self._reports if r.state == "pending"),- key=lambda r: (_PRIORITY.get(r.kind, 9), r.at),- )-- def on_air(self) -> Report | None:- return next((r for r in self._reports if r.state == "on_air"), None)-- def find(self, report_id: str) -> Report | None:- return next((r for r in self._reports if r.id == report_id), None)-- def sleeping(self) -> bool:- """Has a line gone unanswered, so the queue is holding its tongue?"""- return self._settled-- # --------------------------------------------------------------- speaking-- def take_due(self, *, now: float | None = None) -> Utterance | None:- """The one thing to say right now, marked as said. ``None`` for silence.-- Marking happens HERE rather than after the sentence is spoken, and that- is deliberate: composing a line is an awaited call, the sweep runs- every couple of seconds, and a second sweep arriving mid-compose would- otherwise decide the same report is still due and say it twice.- """- _ = now- if not self._in_conversation:- return None- # A report the user asked for BY NAME jumps every rule below it: they- # said "tell me about Nova", and anything else answering that is the- # deck deciding it knows better.- requested = next((r for r in self._reports if r.state == "on_air" and not r.spoken), None)- if requested is not None:- requested.spoken = True- self._settled = True- return Utterance(form="report", reports=(requested,))- waiting = self.pending()- if not waiting:- return None- if self._missed:- # Rule 7: one opening line for everything that happened while the- # user was away. It is a headline even for a single report — the- # point is the handover, not the count.- self._missed = False- self._settled = True- for report in waiting:- report.in_headline = True- return Utterance(form="resumed", reports=tuple(waiting))- if self._settled:- return None # rule 8- unheralded = [r for r in waiting if not r.in_headline]- if not unheralded:- return None- if len(unheralded) == 1:- # One piece of news is simply said. A "one agent is done, shall I- # tell you?" would be a question with one possible answer, which- # costs the user a turn and tells them nothing.- report = unheralded[0]- self._retire_on_air()- report.state = "on_air"- report.spoken = True- self._settled = True- return Utterance(form="report", reports=(report,))- for report in unheralded:- report.in_headline = True- self._settled = True- return Utterance(form="headline", reports=tuple(unheralded))-- # ------------------------------------------------------------- user input-- def acknowledge(self, report_id: str, action: Action) -> Report | None:- """What the user said about a report. Returns it, or ``None`` if gone.-- ``next`` is the interesting one: it is both "I heard that" for whatever- was on air and "tell me this one" for the report named. One call rather- than two because that is one utterance — "yes, and what about Nova?".- """- report = self.find(report_id)- if report is None:- return None- if action == "drop":- report.state = "dropped"- self._settled = False- return report- if action == "later":- # The queue sleeps, but nothing is thrown away: the deck keeps- # showing the lane, and the next thing the user says wakes it.- self._retire_on_air()- self._settled = True- return report- self._retire_on_air()- # Put ON AIR but not yet spoken: the sentence is composed on the next- # beat, and marking it said here would mean a compose that fails leaves- # the user having asked for a report they never get.- report.state = "on_air"- report.spoken = False- self._settled = False- return report-- def _retire_on_air(self) -> None:- """Whatever was being reported is finished with.-- Deliberately not a state called "answered": the user may well have said- nothing at all. What is true is that the report was DELIVERED, and a- delivered report must not sit on air blocking the queue behind it —- which is exactly what it did in the first version, where one unanswered- line silenced the deck permanently.- """- current = self.on_air()- if current is not None:- current.state = "reported" if current.spoken else "pending"-- def wake(self) -> None:- """The user did something — the queue may speak again.-- Called when a turn is taken in the deck. Rule 8 stops the queue from- repeating itself into silence; it must not stop it from answering a- person who has just come back to it.- """- self._settled = False- self._retire_on_air()-- def conversation_started(self) -> None:- self._in_conversation = True- self._settled = False-- def conversation_ended(self) -> None:- """Hung up. Speech is already dead; the queue simply stops offering.-- Whatever is on air is retired rather than left mid-report: the user did- not answer it, and it must not be waiting on air for a conversation- that may be an hour away.- """- self._in_conversation = False- self._retire_on_air()- if self.pending():- self._missed = True-- def in_conversation(self) -> bool:- return self._in_conversation-- # ------------------------------------------------------------- housekeeping-- def drop_pane(self, workspace_id: str, pane_key: str) -> int:- """Rule 6 — the user read this pane, so there is nothing to tell them."""- dropped = 0- for report in self._reports:- if report.state not in ("pending", "on_air"):- continue- if report.workspace_id != workspace_id or report.pane_key != pane_key:- continue- report.state = "dropped"- dropped += 1- return dropped-- def forget_workspace(self, workspace_id: str) -> int:- before = len(self._reports)- self._reports = [r for r in self._reports if r.workspace_id != workspace_id]- return before - len(self._reports)-- def retain(self, live: Sequence[tuple[str, str]]) -> int:- """Drop reports whose pane is gone — nothing to jump to, nothing to say."""- alive = set(live)- before = len(self._reports)- self._reports = [r for r in self._reports if (r.workspace_id, r.pane_key) in alive]- return before - len(self._reports)-- def clear(self) -> None:- self._reports.clear()- self._settled = False- self._missed = False- self._in_conversation = False-- def state(self) -> dict[str, Any]:- """Everything the deck's lane needs in one response."""- on_air = self.on_air()- return {- "sleeping": self._settled,- "in_conversation": self._in_conversation,- "on_air": None if on_air is None else on_air.to_dict(),- "pending": [r.to_dict() for r in self.pending()],- "reports": [r.to_dict() for r in self._reports if r.state in ("pending", "on_air")],- }---# --------------------------------------------------------------------- wording---def spoken_facts(utterance: Utterance) -> dict[str, object]:- """The ground truth a composed sentence may rephrase and nothing else.-- Handed to :func:`~jarvis.voice.contextual_readback.render_readback`, whose- honesty guard rejects anything the model adds on top. Kept small on- purpose: the pane names and what happened to them is the whole message, and- every extra field is another thing a rephrasing can get subtly wrong.- """- if utterance.form == "report":- report = utterance.reports[0]- return {- "agent": report.pane,- "what_happened": report.headline,- "was_working_on": report.detail,- }- return {- "agents": list(utterance.panes),- "count": len(utterance.reports),- "what_happened": [r.headline for r in utterance.reports],- }---def canned_line(utterance: Utterance, language: str) -> str:- """The deterministic sentence, in the three languages the pipeline speaks.-- This is what an install with no provider — or a provider that timed out —- actually says, so it has to stand on its own rather than read as a- placeholder. It is also the honesty floor the composed version is checked- against.-- Product surface, so German and Spanish are allowed here (CLAUDE.md §1,- closed-list item: runtime voice output).- """- lang = (language or "en").lower()[:2]- names = _spoken_list(utterance.panes, lang)- count_ = len(utterance.reports)- if utterance.form == "report":- report = utterance.reports[0]- if report.kind in BLOCKING_KINDS:- if lang == "de":- return f"{report.pane} wartet auf dich." # i18n-allow: voice output- if lang == "es":- return f"{report.pane} está esperando tu respuesta." # i18n-allow: voice output- return f"{report.pane} is waiting on you."- if lang == "de":- return f"{report.pane} ist durch." # i18n-allow: voice output- if lang == "es":- return f"{report.pane} ha terminado." # i18n-allow: voice output- return f"{report.pane} is done."- if utterance.form == "resumed":- if lang == "de":- return f"Während du weg warst: {names}." # i18n-allow: voice output- if lang == "es":- return f"Mientras no estabas: {names}." # i18n-allow: voice output- return f"While you were away: {names}."- if lang == "de":- return f"{count_} sind durch: {names}. Womit fange ich an?" # i18n-allow: voice output- if lang == "es":- return f"{count_} han terminado: {names}. ¿Por cuál empiezo?" # i18n-allow: voice output- return f"{count_} are done: {names}. Which one first?"---def _spoken_list(names: Sequence[str], language: str) -> str:- """ "Mika, Nova and Kai" — a list said the way a person says one."""- items = [n for n in names if n]- if not items:- return ""- if len(items) == 1:- return items[0]- joiner = {"de": "und", "es": "y"}.get(language, "and") # i18n-allow: voice output- return f"{', '.join(items[:-1])} {joiner} {items[-1]}"---# ----------------------------------------------------------------------- store-_QUEUE = StandupQueue()---def queue() -> StandupQueue:- """The process-wide queue the sweep fills and the routes read."""- return _QUEUE---def reset() -> None:- """Drop everything — for tests, and for a registry that was torn down."""- _QUEUE.clear()- reset_switch_cache()---@dataclass(slots=True)-class _Wiring:- """How this module reaches the voice, injected rather than imported.-- Nothing here imports the speech pipeline, and that is not tidiness: this- runs inside the pane sweep, which must keep working in a headless install,- in the tests, and on a machine with no audio at all. Unwired, the queue- still fills and the deck still shows the lane — it simply says nothing,- which is the honest degradation (§3).- """-- #: Publish an announcement. Given the text and the language.- speak: Callable[[str, str], Any] | None = None- #: The language this turn should be spoken in. ONE resolver decides that- #: for every layer (CLAUDE.md §1); this asks it rather than guessing.- language: Callable[[], str] | None = None- #: The flash composer that turns facts into a sentence. ``None`` keeps the- #: deterministic line, which is a complete answer rather than a fallback.- composer: Any = None---_wiring = _Wiring()---def wire(- *,- speak: Callable[[str, str], Any] | None = None,- language: Callable[[], str] | None = None,- composer: Any = None,-) -> None:- """Give the queue a voice. Called once, where the speech stack is built."""- _wiring.speak = speak- _wiring.language = language- _wiring.composer = composer---def unwire() -> None:- """Take the voice away again — shutdown, and tests that assert silence."""- _wiring.speak = None- _wiring.language = None- _wiring.composer = None---#: How long the config switch is trusted before it is read again. Same reason-#: and same number as :data:`.notifications.SWITCH_TTL_S`: ``load_config``-#: parses the TOML on every call and this runs beside a two-second sweep.-SWITCH_TTL_S = 15.0--_switch: tuple[float, bool] = (0.0, True)---def enabled() -> bool:- """Is the deck allowed to speak on this install?-- A config that cannot be read answers "on", matching the bell: failing- closed here would make a broken config look like a broken feature, and the- surface is opt-in already — you have to be in the deck for any of it.- """- global _switch- cached_at, value = _switch- now = time.monotonic()- if now - cached_at < SWITCH_TTL_S:- return value- try:- from jarvis.core.config import load_config-- value = bool(getattr(load_config().agentic_ide, "deck_reports", True))- except Exception: # noqa: BLE001 - never let a config read stop the sweep- value = True- _switch = (now, value)- return value---def reset_switch_cache() -> None:- """Forget the cached switch — for tests, and for a live config change."""- global _switch- _switch = (0.0, True)---def deck_workspaces(registry: Any) -> set[str]:- """Which open workspaces are being READ as a Command Deck right now.-- The deck is the only surface that speaks, and "is it on screen" is the- frontend's answer, reported through ``set_surface_context``. Asking per- sweep rather than remembering it means navigating away goes quiet on the- next beat instead of whenever something else happens to notice.- """- from .workspace_view import VIEW_DECK-- found: set[str] = set()- try:- for session in registry.sessions:- if getattr(session, "surface_view", "") == VIEW_DECK:- found.add(str(session.id))- except Exception: # noqa: BLE001 - a registry read must not end the sweep- return set()- return found---def held_panes(registry: Any) -> set[tuple[str, str]]:- """Panes the user has taken over — the deck reports none of them.-- The other half of ``deck_hold`` (see ``session.Terminal``). Somebody who is- sitting in front of a pane answering its question does not need to be told- it stopped: they are watching it stop.- """- held: set[tuple[str, str]] = set()- try:- for session in registry.sessions:- for term in getattr(session, "terminals", []):- if bool(getattr(term, "deck_hold", False)):- held.add((str(session.id), str(getattr(term, "key", "") or "")))- except Exception: # noqa: BLE001 - a registry read must not end the sweep- return set()- return held---async def pump(registry: Any, entries: Sequence[Notification]) -> str:- """The sweep's one call into this module: take the news, say what is due.-- Everything is filtered to workspaces currently being read as a deck. A- finished pane in a workspace the user is watching as a grid is not news- they need told — they are looking at it.-- Never raises. It runs inside the pane sweep, which also files the bell's- entries and the resume checkpoints, and none of those may die because the- deck could not think of a sentence.- """- try:- if not enabled():- return ""- decks = deck_workspaces(registry)- if not decks:- # Nothing is being read as a deck. The queue keeps whatever it- # holds — the user may come back to it — but takes nothing new.- return ""- held = held_panes(registry)- fresh = [- entry- for entry in entries- if entry.workspace_id in decks- and (entry.workspace_id, entry.pane_key) not in held- ]- if fresh:- _QUEUE.offer(fresh)- # A pane taken over AFTER its report was filed drops out too. The user- # is in front of it now, which is the same reason reading one silences- # it (rule 6) — and without this the deck would announce a pane the- # user is currently typing into.- for workspace_id, pane_key in held:- _QUEUE.drop_pane(workspace_id, pane_key)- return await announce_due()- except Exception as exc: # noqa: BLE001 - a mute deck beats a dead sweep- logger.warning("Agentic IDE: standup pump failed: %s", exc)- return ""---async def announce_due() -> str:- """Say the one thing that is due, if anything is. Returns what was said.-- Never raises: this is called from the pane sweep, and a failure to speak- must not take down the loop that also files the bell's entries and the- resume checkpoints.- """- if _wiring.speak is None:- return ""- try:- utterance = _QUEUE.take_due()- if utterance is None:- return ""- language = _resolve_language()- text = await _compose(utterance, language)- if not text:- return ""- await _deliver(text, language)- return text- except Exception as exc: # noqa: BLE001 - a mute deck beats a dead sweep- logger.warning("Agentic IDE: standup announcement failed: %s", exc)- return ""---def _resolve_language() -> str:- if _wiring.language is None:- return "en"- try:- return str(_wiring.language() or "en")- except Exception: # noqa: BLE001 - a language lookup must not silence the deck- return "en"---async def _compose(utterance: Utterance, language: str) -> str:- from jarvis.voice.contextual_readback import render_readback-- return await render_readback(- _wiring.composer,- instruction=_INSTRUCTION[utterance.form],- language=language,- canned=lambda: canned_line(utterance, language),- facts=spoken_facts(utterance),- # The report IS the fact. A rephrasing that adds an outcome ("Mika- # fixed the tests") would be inventing the one thing this surface- # promised not to claim — see "What it will not claim" above.- honesty_bound=True,- )---async def _deliver(text: str, language: str) -> None:- speak = _wiring.speak- if speak is None:- return- result = speak(text, language)- if hasattr(result, "__await__"):- await result---#: What the composer is asked to write, per shape. Instructions rather than-#: templates: the maintainer's standing rule is that Jarvis must not read fixed-#: sentences out of a table, and these say what the line is FOR while leaving-#: the wording to the moment.-_INSTRUCTION: dict[str, str] = {- "report": (- "Tell the user, in one short spoken sentence, that this coding agent "- "has stopped working. Do not claim the work succeeded — only that the "- "agent is done and waiting. Do not offer to summarise."- ),- "headline": (- "Several coding agents finished at once. Say so in ONE short spoken "- "sentence naming them, and ask which one to start with. Do not report "- "any of them yet."- ),- "resumed": (- "The user has just come back to the conversation. In one short spoken "- "sentence, tell them which coding agents finished while they were "- "away. Do not report any of them in detail yet."- ),-}---__all__ = [- "BLOCKING_KINDS",- "MAX_PENDING",- "SWITCH_TTL_S",- "Action",- "Kind",- "Report",- "ReportState",- "StandupQueue",- "Utterance",- "announce_due",- "canned_line",- "deck_workspaces",- "enabled",- "held_panes",- "pump",- "queue",- "reset",- "reset_switch_cache",- "spoken_facts",- "unwire",- "wire",-]diff --git a/jarvis/ui/web/frontend/src/hooks/useWallpaperCatalog.ts b/jarvis/ui/web/frontend/src/hooks/useWallpaperCatalog.tsindex 6654e22e65..1f231df1a1 100644--- a/jarvis/ui/web/frontend/src/hooks/useWallpaperCatalog.ts+++ b/jarvis/ui/web/frontend/src/hooks/useWallpaperCatalog.ts@@ -18,6 +18,11 @@ export interface WallpaperEntry {* come from the bundle, not from `/api/wallpapers`.*/isDefault?: boolean;+ /**+ * True for a picture the owner uploaded. Those are the only wallpapers that+ * can be removed or re-themed, so the preview needs to know which it has.+ */+ isUpload?: boolean;}export interface WallpaperStyle {diff --git a/jarvis/ui/web/frontend/src/hooks/useWallpaperUploads.ts b/jarvis/ui/web/frontend/src/hooks/useWallpaperUploads.tsnew file mode 100644index 0000000000..3516fd3926--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useWallpaperUploads.ts@@ -0,0 +1,125 @@+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";++import type { Theme } from "@/hooks/useTheme";+import type { WallpaperEntry } from "@/hooks/useWallpaperCatalog";++/** One wallpaper the owner brought themselves, as the server reports it. */+export interface WallpaperUpload {+ id: string;+ title: string;+ theme: Theme;+ createdAt: number;+}++/** The filter slug and chip label the owner's own pictures live under. */+export const UPLOAD_WALLPAPER_STYLE = "yours";++const UPLOADS_URL = "/api/wallpapers/uploads";+const UPLOADS_KEY = ["wallpapers", "uploads"] as const;++/** Read the sentence the server sent, or fall back to a plain one. */+async function detail(response: Response, fallback: string): Promise<string> {+ try {+ const body = (await response.json()) as { detail?: unknown };+ if (typeof body?.detail === "string" && body.detail.trim()) return body.detail;+ } catch {+ /* a body that is not JSON tells us nothing useful */+ }+ return fallback;+}++/** Present an upload the way the browse grid knows every other wallpaper. */+export function uploadAsEntry(upload: WallpaperUpload): WallpaperEntry {+ return {+ id: upload.id,+ title: upload.title,+ style: UPLOAD_WALLPAPER_STYLE,+ styleLabel: "Yours",+ theme: upload.theme,+ isUpload: true,+ };+}++/**+ * The owner's own wallpapers.+ *+ * A query of its own rather than part of the catalog: the generated library is+ * five hundred fixed entries fetched once and kept forever, while this list+ * changes every time someone adds or removes a picture. Keeping them apart lets+ * one be refetched without discarding the other.+ */+export function useWallpaperUploads() {+ return useQuery<WallpaperUpload[]>({+ queryKey: UPLOADS_KEY,+ queryFn: async () => {+ // A backend that is mid-restart means "no uploads to show right now",+ // not a broken section — the library and the bundled original still are.+ const data = await fetch(UPLOADS_URL)+ .then((response) => (response.ok ? response.json() : null))+ .catch(() => null);+ const items = (data as { items?: unknown } | null)?.items;+ if (!Array.isArray(items)) return [];+ return items.filter(+ (item): item is WallpaperUpload =>+ typeof item?.id === "string" &&+ typeof item?.title === "string" &&+ (item?.theme === "light" || item?.theme === "dark"),+ );+ },+ });+}++/**+ * Add, retheme, and remove the owner's own wallpapers.+ *+ * Every mutation refetches the list rather than patching it in place: the store+ * is a directory on disk that another window may also be writing to, and a+ * refetch is a few hundred bytes.+ */+export function useUploadMutations() {+ const client = useQueryClient();+ const refresh = () => client.invalidateQueries({ queryKey: UPLOADS_KEY });++ const add = useMutation<WallpaperUpload, Error, File>({+ mutationFn: async (file) => {+ const body = new FormData();+ body.append("file", file);+ const response = await fetch(UPLOADS_URL, { method: "POST", body });+ if (!response.ok) {+ throw new Error(await detail(response, "That image could not be added."));+ }+ return (await response.json()) as WallpaperUpload;+ },+ onSuccess: refresh,+ });++ const setTheme = useMutation<WallpaperUpload, Error, { id: string; theme: Theme }>({+ mutationFn: async ({ id, theme }) => {+ const response = await fetch(`${UPLOADS_URL}/${encodeURIComponent(id)}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ theme }),+ });+ if (!response.ok) {+ throw new Error(await detail(response, "That change could not be saved."));+ }+ return (await response.json()) as WallpaperUpload;+ },+ onSuccess: refresh,+ });++ const remove = useMutation<string, Error, string>({+ mutationFn: async (id) => {+ const response = await fetch(`${UPLOADS_URL}/${encodeURIComponent(id)}`, {+ method: "DELETE",+ });+ if (!response.ok) {+ throw new Error(await detail(response, "That wallpaper could not be removed."));+ }+ return id;+ },+ onSuccess: refresh,+ });++ return { add, setTheme, remove };+}diff --git a/jarvis/ui/web/frontend/src/store/wallpaper.ts b/jarvis/ui/web/frontend/src/store/wallpaper.tsindex 4d66dcdab2..e03d0af719 100644--- a/jarvis/ui/web/frontend/src/store/wallpaper.ts+++ b/jarvis/ui/web/frontend/src/store/wallpaper.ts@@ -42,14 +42,35 @@ const LEGACY_KEY = "jarvis.wallpaper.v1";*/const FAVORITES_KEY = "jarvis.wallpaper.favorites.v1";+/**+ * An id minted by the upload store (`u` + 16 hex), as opposed to one written by+ * the library's manifest builder (`03-anime-neon-07`).+ *+ * The two stores are served from different paths, and the id is what tells them+ * apart — deliberately, so that everything holding only an id (the shell that+ * paints the background, a per-theme selection restored from storage) resolves+ * to the right picture without carrying a flag alongside it.+ */+const UPLOAD_ID_PATTERN = /^u[0-9a-f]{16}$/;++export function isUploadId(id: string): boolean {+ return UPLOAD_ID_PATTERN.test(id);+}+/** Where a chosen wallpaper's full-size file is served from. */export function wallpaperFullUrl(id: string): string {- return `/api/wallpapers/${encodeURIComponent(id)}/full`;+ const safe = encodeURIComponent(id);+ return isUploadId(id)+ ? `/api/wallpapers/uploads/${safe}/full`+ : `/api/wallpapers/${safe}/full`;}/** Where a chosen wallpaper's grid thumbnail is served from. */export function wallpaperThumbUrl(id: string): string {- return `/api/wallpapers/${encodeURIComponent(id)}/thumb`;+ const safe = encodeURIComponent(id);+ return isUploadId(id)+ ? `/api/wallpapers/uploads/${safe}/thumb`+ : `/api/wallpapers/${safe}/thumb`;}function readStoredId(theme: Theme): string | null {@@ -100,6 +121,12 @@ interface WallpaperStore {favorites: string[];/** Persist a choice for one theme. Pass null to go back to the default. */select: (id: string | null, theme: Theme) => void;+ /**+ * Drop one wallpaper everywhere it is remembered — every theme slot and the+ * favourites. For a picture that no longer exists: an id kept for a deleted+ * upload would resolve to a 404 and silently fall back forever.+ */+ forget: (id: string) => void;/** Star or un-star one wallpaper. */toggleFavorite: (id: string) => void;/** Adopt choices made in another window. Does not write back. */@@ -122,6 +149,28 @@ export const useWallpaperStore = create<WallpaperStore>((set, get) => ({}set({ selections: readSelections() });},+ forget: (id) => {+ if (!id) return;+ try {+ for (const theme of ["light", "dark"] as Theme[]) {+ if (window.localStorage.getItem(THEME_KEYS[theme]) === id) {+ window.localStorage.removeItem(THEME_KEYS[theme]);+ }+ }+ if (window.localStorage.getItem(LEGACY_KEY) === id) {+ window.localStorage.removeItem(LEGACY_KEY);+ }+ const favorites = readFavorites().filter((entry) => entry !== id);+ if (favorites.length) {+ window.localStorage.setItem(FAVORITES_KEY, JSON.stringify(favorites));+ } else {+ window.localStorage.removeItem(FAVORITES_KEY);+ }+ } catch {+ /* nothing to clean up if storage is unavailable */+ }+ set({ selections: readSelections(), favorites: readFavorites() });+ },toggleFavorite: (id) => {if (!id) return;// Computed from the store rather than re-read from storage, so a rapiddiff --git a/jarvis/ui/web/frontend/src/views/WallpaperView.test.tsx b/jarvis/ui/web/frontend/src/views/WallpaperView.test.tsxindex cd3d472cfe..68ec59d8a1 100644--- a/jarvis/ui/web/frontend/src/views/WallpaperView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/WallpaperView.test.tsx@@ -46,11 +46,80 @@ const CATALOG = {],};-function renderView(catalog: unknown = CATALOG) {+interface Upload {+ id: string;+ title: string;+ theme: "light" | "dark";+ createdAt: number;+}++/**+ * A stand-in for the two wallpaper endpoints, holding the uploads in memory.+ *+ * A fake rather than a per-call mock: the section adds, re-themes and removes+ * pictures and then re-reads the list, and only something that actually keeps+ * state can tell whether those round trips agree with each other.+ */+function stubServer(catalog: unknown = CATALOG, uploads: Upload[] = []) {+ const state = { uploads: [...uploads], rejectUpload: null as string | null };+ const json = (body: unknown, ok = true, status = 200) => ({+ ok,+ status,+ json: async () => body,+ });+vi.stubGlobal("fetch",- vi.fn().mockResolvedValue({ ok: true, json: async () => catalog }),+ vi.fn(async (input: unknown, init?: { method?: string; body?: unknown }) => {+ const url = String(input);+ const method = (init?.method ?? "GET").toUpperCase();++ if (url === "/api/wallpapers/uploads") {+ if (method === "POST") {+ if (state.rejectUpload) {+ return json({ detail: state.rejectUpload }, false, 400);+ }+ const added: Upload = {+ id: `u${String(state.uploads.length).padStart(16, "0")}`,+ title: "Harbour At Dawn",+ theme: "light",+ createdAt: 1_700_000_000 + state.uploads.length,+ };+ state.uploads = [added, ...state.uploads];+ return json(added);+ }+ return json({ items: state.uploads });+ }++ const own = url.match(/^\/api\/wallpapers\/uploads\/([^/]+)$/);+ if (own) {+ const id = own[1];+ if (method === "DELETE") {+ state.uploads = state.uploads.filter((item) => item.id !== id);+ return json({ removed: id });+ }+ const theme = JSON.parse(String(init?.body ?? "{}")).theme as Upload["theme"];+ state.uploads = state.uploads.map((item) =>+ item.id === id ? { ...item, theme } : item,+ );+ const updated = state.uploads.find((item) => item.id === id);+ return updated ? json(updated) : json({ detail: "Not Found" }, false, 404);+ }++ if (url === "/api/wallpapers") return json(catalog);+ // Everything else the shell asks for while mounted (the appearance+ // endpoint, say) is none of this section's business.+ return json({});+ }),);+ return state;+}++/** The fake behind the current render, for tests that need to poke at it. */+let server: ReturnType<typeof stubServer>;++function renderView(catalog: unknown = CATALOG, uploads: Upload[] = []) {+ server = stubServer(catalog, uploads);const client = new QueryClient({defaultOptions: { queries: { retry: false } },});@@ -371,6 +440,183 @@ describe("WallpaperView", () => {});});+ // ------------------------------------------------------------------+ // The owner's own pictures.+ // ------------------------------------------------------------------++ const OWN: Upload = {+ id: "u000000000000000a",+ title: "Kitchen Window",+ theme: "light",+ createdAt: 1_700_000_000,+ };++ /** Hand a file to the hidden picker the way the OS dialog would. */+ function pickFile(name = "harbour at dawn.png") {+ const input = screen.getByTestId("wallpaper-file-input") as HTMLInputElement;+ const file = new File([new Uint8Array([1, 2, 3])], name, { type: "image/png" });+ fireEvent.change(input, { target: { files: [file] } });+ }++ it("lists an uploaded picture right after the original", async () => {+ renderView(CATALOG, [OWN]);++ await screen.findByAltText("Kitchen Window");+ const tiles = [...document.querySelectorAll('[data-testid="wallpaper-grid"] img')];++ expect(tiles.slice(0, 2).map((tile) => tile.getAttribute("alt"))).toEqual([+ "The Original",+ "Kitchen Window",+ ]);+ });++ it("serves an upload's thumbnail from the uploads endpoint", async () => {+ renderView(CATALOG, [OWN]);++ const tile = await screen.findByAltText("Kitchen Window");++ expect(tile.getAttribute("src")).toBe("/api/wallpapers/uploads/u000000000000000a/thumb");+ });++ it("gathers uploads under a style chip of their own", async () => {+ renderView(CATALOG, [OWN]);++ fireEvent.click(await screen.findByRole("button", { name: "Yours" }));++ await waitFor(() => {+ const tiles = [...document.querySelectorAll('[data-testid="wallpaper-grid"] img')];+ expect(tiles.map((tile) => tile.getAttribute("alt"))).toEqual(["Kitchen Window"]);+ });+ });++ it("offers no Yours chip while nothing has been uploaded", async () => {+ renderView();++ await screen.findByAltText("Flooded Observatory");++ expect(screen.queryByRole("button", { name: "Yours" })).toBeNull();+ });++ it("adds a picked file and opens its preview", async () => {+ renderView();+ await screen.findByAltText("Flooded Observatory");++ pickFile();++ const preview = await screen.findByTestId("wallpaper-preview");+ expect(within(preview).getByText("Harbour At Dawn")).toBeTruthy();+ expect(server.uploads).toHaveLength(1);+ });++ it("does not apply an upload behind the owner's back", async () => {+ renderView();+ await screen.findByAltText("Flooded Observatory");++ pickFile();+ await screen.findByTestId("wallpaper-preview");++ expect(useWallpaperStore.getState().selections).toEqual({+ light: null,+ dark: null,+ });+ });++ it("shows the server's reason when an upload is refused", async () => {+ renderView();+ await screen.findByAltText("Flooded Observatory");+ server.rejectUpload = "That file is not an image the app can read.";++ pickFile("notes.txt");++ expect(+ await screen.findByText("That file is not an image the app can read."),+ ).toBeTruthy();+ });++ it("removes an upload and forgets it everywhere", async () => {+ renderView(CATALOG, [OWN]);+ act(() => {+ useWallpaperStore.getState().select(OWN.id, "light");+ useWallpaperStore.getState().toggleFavorite(OWN.id);+ });++ fireEvent.click(await screen.findByAltText("Kitchen Window"));+ const preview = await screen.findByTestId("wallpaper-preview");+ fireEvent.click(within(preview).getByRole("button", { name: "Remove Kitchen Window" }));++ await waitFor(() => {+ expect(useWallpaperStore.getState().selections.light).toBeNull();+ });+ expect(useWallpaperStore.getState().favorites).toEqual([]);+ expect(server.uploads).toEqual([]);+ await waitFor(() => {+ expect(screen.queryByAltText("Kitchen Window")).toBeNull();+ });+ });++ it("corrects the light/dark guess on an upload", async () => {+ renderView(CATALOG, [OWN]);++ fireEvent.click(await screen.findByAltText("Kitchen Window"));+ const preview = await screen.findByTestId("wallpaper-preview");+ fireEvent.click(within(preview).getByRole("button", { name: /Dark/ }));++ await waitFor(() => {+ expect(server.uploads[0].theme).toBe("dark");+ });+ });++ it("moves an applied upload into the mode it was re-themed to", async () => {+ renderView(CATALOG, [OWN]);++ fireEvent.click(await screen.findByAltText("Kitchen Window"));+ const preview = await screen.findByTestId("wallpaper-preview");+ fireEvent.click(within(preview).getByRole("button", { name: "Use this wallpaper" }));+ await waitFor(() => {+ expect(useWallpaperStore.getState().selections.light).toBe(OWN.id);+ });++ fireEvent.click(within(preview).getByRole("button", { name: /Dark/ }));++ await waitFor(() => {+ expect(useWallpaperStore.getState().selections.dark).toBe(OWN.id);+ });+ // The old slot must not keep a copy, or toggling back would restore a+ // picture that is no longer authored for that mode.+ expect(useWallpaperStore.getState().selections.light).toBeNull();+ });++ it("offers no remove or re-theme controls on a library wallpaper", async () => {+ renderView();++ fireEvent.click(await screen.findByAltText("Neon Crossing"));+ const preview = await screen.findByTestId("wallpaper-preview");++ expect(within(preview).queryByRole("button", { name: /^Remove Neon/ })).toBeNull();+ expect(within(preview).queryByRole("button", { name: /^Dark$/ })).toBeNull();+ });++ it("keeps working when the uploads endpoint is unavailable", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: unknown) =>+ String(input) === "/api/wallpapers"+ ? { ok: true, status: 200, json: async () => CATALOG }+ : { ok: false, status: 500, json: async () => ({}) },+ ),+ );+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(+ <QueryClientProvider client={client}>+ <ThemeProvider>+ <WallpaperView />+ </ThemeProvider>+ </QueryClientProvider>,+ );++ expect(await screen.findByAltText("Flooded Observatory")).toBeTruthy();+ });+it("still offers the original when the library is absent", async () => {renderView({ available: false, count: 0, styles: [], items: [] });diff --git a/jarvis/ui/web/frontend/src/views/WallpaperView.tsx b/jarvis/ui/web/frontend/src/views/WallpaperView.tsxindex 59d3557bf8..2c4e5bd34f 100644--- a/jarvis/ui/web/frontend/src/views/WallpaperView.tsx+++ b/jarvis/ui/web/frontend/src/views/WallpaperView.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {Check,ChevronLeft,@@ -9,6 +9,8 @@ import {Moon,RotateCcw,Sun,+ Trash2,+ Upload,X,} from "lucide-react";@@ -21,8 +23,14 @@ import {useWallpaperCatalog,type WallpaperEntry,} from "@/hooks/useWallpaperCatalog";+import {+ uploadAsEntry,+ useUploadMutations,+ useWallpaperUploads,+ UPLOAD_WALLPAPER_STYLE,+} from "@/hooks/useWallpaperUploads";import { useApplyWallpaper } from "@/hooks/useApplyWallpaper";-import { useThemeValue } from "@/hooks/useTheme";+import { useThemeValue, type Theme } from "@/hooks/useTheme";import { useWallpaperStore } from "@/store/wallpaper";import { cn } from "@/lib/utils";@@ -48,6 +56,13 @@ function shuffleRank(id: string): number {return hash;}+/** Where a wallpaper came from, as the grid orders it: bundled, own, library. */+function originRank(item: WallpaperEntry): number {+ if (item.isDefault) return 0;+ if (item.isUpload) return 1;+ return 2;+}+/** The segmented filter/ordering controls share one look. */function SegmentButton({active,@@ -221,16 +236,22 @@ function WallpaperPreview({item,applied,favorite,+ busy,onApply,onToggleFavorite,+ onSetTheme,+ onRemove,onClose,onStep,}: {item: WallpaperEntry;applied: boolean;favorite: boolean;+ busy: boolean;onApply: () => void;onToggleFavorite: () => void;+ onSetTheme: (theme: Theme) => void;+ onRemove: () => void;onClose: () => void;onStep: (delta: number) => void;}) {@@ -265,6 +286,37 @@ function WallpaperPreview({{item.styleLabel} · {item.theme === "dark" ? "Dark" : "Light"}</p></div>+ {/* Only an upload can be re-themed: the library's own light/dark comes+ from the prompt each picture was painted to, and the bundled+ original is a night scene by definition. */}+ {item.isUpload && (+ <div className="flex items-center gap-1 rounded-lg border border-border p-0.5">+ <SegmentButton+ active={item.theme === "light"}+ onClick={() => onSetTheme("light")}+ >+ <Sun className="h-3 w-3" /> Light+ </SegmentButton>+ <SegmentButton+ active={item.theme === "dark"}+ onClick={() => onSetTheme("dark")}+ >+ <Moon className="h-3 w-3" /> Dark+ </SegmentButton>+ </div>+ )}+ {item.isUpload && (+ <Button+ size="sm"+ variant="ghost"+ onClick={onRemove}+ disabled={busy}+ aria-label={`Remove ${item.title}`}+ className="text-muted-foreground hover:text-destructive"+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ )}<FavoriteButtonitem={item}favorite={favorite}@@ -336,6 +388,8 @@ function WallpaperPreview({*/export function WallpaperView() {const { data, isLoading } = useWallpaperCatalog();+ const { data: uploads } = useWallpaperUploads();+ const { add, setTheme: retheme, remove } = useUploadMutations();// Each theme keeps its own pick; the grid marks the one worn by the mode// the app is in right now (adopting a tile switches mode WITH the picture,// so the check mark always lands on what is actually on screen).@@ -343,6 +397,7 @@ export function WallpaperView() {const selectedId = useWallpaperStore((state) => state.selections[activeTheme]);const favorites = useWallpaperStore((state) => state.favorites);const toggleFavorite = useWallpaperStore((state) => state.toggleFavorite);+ const forget = useWallpaperStore((state) => state.forget);const apply = useApplyWallpaper();const [theme, setTheme] = useState<ThemeFilter>("all");@@ -350,9 +405,33 @@ export function WallpaperView() {const [style, setStyle] = useState<string | null>(null);const [favoritesOnly, setFavoritesOnly] = useState(false);const [previewId, setPreviewId] = useState<string | null>(null);+ const fileInput = useRef<HTMLInputElement | null>(null);- const items = data?.items ?? [];- const styles = data?.styles ?? [];+ const ownEntries = useMemo(+ () => (uploads ?? []).map(uploadAsEntry),+ [uploads],+ );++ // The owner's own pictures sit between the bundled original and the generated+ // library — brought here on purpose, so they are found without scrolling.+ const items = useMemo(() => {+ const catalog = data?.items ?? [];+ if (!ownEntries.length) return catalog;+ const [bundled, ...rest] = catalog;+ return bundled ? [bundled, ...ownEntries, ...rest] : [...ownEntries, ...catalog];+ }, [data?.items, ownEntries]);++ const styles = useMemo(() => {+ const known = data?.styles ?? [];+ if (!ownEntries.length) return known;+ const chip = {+ slug: UPLOAD_WALLPAPER_STYLE,+ label: "Yours",+ count: ownEntries.length,+ };+ const [bundled, ...rest] = known;+ return bundled ? [bundled, chip, ...rest] : [chip, ...known];+ }, [data?.styles, ownEntries.length]);const favoriteIds = useMemo(() => new Set(favorites), [favorites]);// Counted against the catalog, not against the stored list: an id left over@@ -375,7 +454,9 @@ export function WallpaperView() {return filtered.sort((left, right) => {// The bundled original outranks every ordering and every shuffle: it is// the first wallpaper this app ever had, and it stays the first tile.- if (left.isDefault !== right.isDefault) return left.isDefault ? -1 : 1;+ // The owner's own pictures come next, ahead of the generated five hundred.+ const byOrigin = originRank(left) - originRank(right);+ if (byOrigin !== 0) return byOrigin;if (ordering === "style") {const byStyle = left.style.localeCompare(right.style);if (byStyle !== 0) return byStyle;@@ -418,6 +499,49 @@ export function WallpaperView() {[previewIndex, visible],);+ // Adding one opens its preview rather than applying it: the picture arrives+ // re-encoded and auto-themed, and seeing it full size before adopting it is+ // the difference between a choice and a surprise.+ const onFilePicked = (event: React.ChangeEvent<HTMLInputElement>) => {+ const file = event.target.files?.[0];+ // Clear the input first, so picking the same file twice in a row still+ // fires a change event.+ event.target.value = "";+ if (!file) return;+ add.mutate(file, { onSuccess: (upload) => setPreviewId(upload.id) });+ };++ const onRemoveUpload = (item: WallpaperEntry) => {+ remove.mutate(item.id, {+ onSuccess: () => {+ // Everything that remembered it goes too, or the shell would keep+ // asking for a picture that is no longer on disk.+ forget(item.id);+ setPreviewId(null);+ },+ });+ };++ const onRethemeUpload = (item: WallpaperEntry, next: Theme) => {+ if (item.theme === next) return;+ retheme.mutate(+ { id: item.id, theme: next },+ {+ onSuccess: (updated) => {+ // A wallpaper in use is filed under the mode it belongs to. Moving it+ // to the other mode has to move that filing with it, or the picture+ // would come back under a theme it is no longer authored for.+ if (isApplied(item)) {+ forget(item.id);+ apply(uploadAsEntry(updated));+ }+ },+ },+ );+ };++ const uploadError = add.error?.message ?? remove.error?.message ?? retheme.error?.message;+const header = (<ViewHeadericon={<ImageIcon className="h-4 w-4 text-primary" />}@@ -428,12 +552,35 @@ export function WallpaperView() {: "The app's desktop background"}right={- selectedId ? (- <Button size="sm" variant="outline" onClick={() => apply(null)}>- <RotateCcw className="mr-1.5 h-3.5 w-3.5" />- Default+ <div className="flex items-center gap-2">+ <input+ ref={fileInput}+ type="file"+ accept="image/png,image/jpeg,image/webp,image/gif,image/bmp"+ onChange={onFilePicked}+ className="hidden"+ data-testid="wallpaper-file-input"+ />+ <Button+ size="sm"+ variant="outline"+ onClick={() => fileInput.current?.click()}+ disabled={add.isPending}+ >+ {add.isPending ? (+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />+ ) : (+ <Upload className="mr-1.5 h-3.5 w-3.5" />+ )}+ Add your own</Button>- ) : undefined+ {selectedId && (+ <Button size="sm" variant="outline" onClick={() => apply(null)}>+ <RotateCcw className="mr-1.5 h-3.5 w-3.5" />+ Default+ </Button>+ )}+ </div>}/>);@@ -453,6 +600,15 @@ export function WallpaperView() {<div className="flex h-full flex-col">{header}+ {uploadError && (+ <p+ role="alert"+ className="border-b border-border bg-destructive/10 px-6 py-2.5 text-xs text-destructive"+ >+ {uploadError}+ </p>+ )}+{!data?.libraryAvailable && (<p className="border-b border-border px-6 py-2.5 text-xs text-muted-foreground"><span className="font-medium text-foreground">@@ -562,8 +718,11 @@ export function WallpaperView() {item={previewItem}applied={isApplied(previewItem)}favorite={favoriteIds.has(previewItem.id)}+ busy={remove.isPending || retheme.isPending}onApply={() => apply(previewItem)}onToggleFavorite={() => toggleFavorite(previewItem.id)}+ onSetTheme={(next) => onRethemeUpload(previewItem, next)}+ onRemove={() => onRemoveUpload(previewItem)}onClose={() => setPreviewId(null)}onStep={step}/>diff --git a/jarvis/ui/web/wallpapers.py b/jarvis/ui/web/wallpapers.pyindex 4c792d9297..acf23f9714 100644--- a/jarvis/ui/web/wallpapers.py+++ b/jarvis/ui/web/wallpapers.py@@ -1,11 +1,19 @@-"""The desktop-wallpaper library: catalog, thumbnails, and full-size delivery.+"""The desktop wallpapers: the generated library, plus the owner's own uploads.-The 500 generated wallpapers are *content*, not source. They live under-``data/jarvis-wallpaper-gallery`` — a git-ignored directory — and are served-from there instead of being copied into the frontend's ``public/`` folder:-147 MB of artwork in the repository would be paid for by every clone, every-build, and every packaged desktop app, including the ones whose owner never-opens the picker.+Two stores live here, deliberately kept apart on disk:++* The generated library — five hundred pieces of *content* under+ ``data/jarvis-wallpaper-gallery`` (see below).+* Uploads — the pictures the owner brought themselves, under+ ``data/jarvis-wallpaper-uploads``. Regenerating or deleting the library must+ never touch somebody's own photograph, which is the one thing here that+ cannot be produced again.++The 500 generated wallpapers are *content*, not source. They live in a+git-ignored directory and are served from there instead of being copied into+the frontend's ``public/`` folder: 147 MB of artwork in the repository would be+paid for by every clone, every build, and every packaged desktop app, including+the ones whose owner never opens the picker.Two consequences shape this module:@@ -20,14 +28,19 @@ Two consequences shape this module:from __future__ import annotations+import ioimport json+import osimport re+import secrets+import tempfileimport threading+import timefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any-from fastapi import FastAPI+from fastapi import FastAPI, File, UploadFilefrom fastapi.responses import FileResponse, JSONResponsefrom loguru import logger@@ -36,6 +49,10 @@ from jarvis.core.config import DATA_DIR#: Where the generated library lives, relative to the project data directory.LIBRARY_DIRNAME = "jarvis-wallpaper-gallery"+#: Where the owner's own wallpapers live. A sibling of the library, never a+#: child of it: the library is regenerable content, these are not.+UPLOADS_DIRNAME = "jarvis-wallpaper-uploads"+#: Derived thumbnails are cached beside the originals. The leading dot keeps#: them out of the manifest builder's ``images/`` scan.THUMBS_DIRNAME = ".thumbs"@@ -53,6 +70,27 @@ THUMB_QUALITY = 72#: loaded catalog is what keeps a request from reaching outside the library._ID_PATTERN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*-\d{2}$")+#: An upload id. Random rather than derived from the file name: two photographs+#: called ``IMG_0042.jpg`` are two wallpapers, and a name is not a key.+_UPLOAD_ID_PATTERN = re.compile(r"^u[0-9a-f]{16}$")++#: Ceiling for an accepted upload. Generous enough for a phone photograph or a+#: 4K screenshot, low enough that a mis-drop of a video file fails fast.+MAX_UPLOAD_BYTES = 40 * 1024 * 1024++#: Uploads are re-encoded to at most this width. A wallpaper never needs more+#: pixels than the largest desktop, and a 12-megapixel original would otherwise+#: be decoded on every repaint of the app's background.+UPLOAD_MAX_WIDTH = 3840++#: Quality of the re-encoded upload. Visually indistinguishable at wallpaper+#: distance, and a fraction of the size of the incoming PNG.+UPLOAD_QUALITY = 82++#: Mean luminance (0-255) at or above which an upload is treated as a light+#: picture. The midpoint is the honest guess; the owner can correct it.+_LIGHT_THEME_LUMA = 128+#: Immutable content: the files are generated once and never edited in place._CACHE_HEADERS = {"Cache-Control": "public, max-age=31536000, immutable"}@@ -198,42 +236,327 @@ class WallpaperLibrary:}def thumbnail(self, item: Wallpaper) -> Path:- """Return a cached grid thumbnail, deriving it on first request.-- Falls back to the original file when Pillow is unavailable or the- resize fails: a heavier grid is a far better outcome than an empty one.- """+ """Return a cached grid thumbnail, deriving it on first request."""target = self._root / THUMBS_DIRNAME / item.style / f"{item.id}.webp"+ return _derive_thumbnail(item.path, target, item.id)+++class UploadRejected(Exception):+ """An upload the store refuses, with a sentence meant for the owner."""++ def __init__(self, message: str, status_code: int = 400) -> None:+ super().__init__(message)+ self.message = message+ self.status_code = status_code+++@dataclass(frozen=True)+class UploadedWallpaper:+ """One wallpaper the owner brought themselves."""++ id: str+ title: str+ theme: str+ created_at: float+ path: Path++ def to_json(self) -> dict[str, Any]:+ return {+ "id": self.id,+ "title": self.title,+ "theme": self.theme,+ "createdAt": self.created_at,+ }+++def _clean_title(filename: str) -> str:+ """A display title from an upload's file name.++ The file name is decoration, never a path: only the stem survives, the+ separators become spaces, and the result is capped. What lands on disk is+ the random id, so a hostile name has nothing to reach.+ """+ stem = Path(filename or "").stem.strip()+ words = re.split(r"[\s._-]+", stem)+ title = " ".join(word for word in words if word).strip()+ return title[:60] or "Your wallpaper"+++class WallpaperUploads:+ """The owner's own wallpapers: add, list, retheme, remove.++ Each upload is two files under one directory — ``<id>.webp`` for the+ picture and ``<id>.json`` beside it for title and theme. A shared index+ file would be a single point of corruption for a store whose whole job is+ holding on to something irreplaceable; a sidecar can only ever lose its own+ entry, and the directory listing stays the source of truth.++ Nothing is cached in memory: a handful of uploads is a cheap directory+ scan, and re-reading means a second window's upload is visible here without+ any invalidation protocol between them.+ """++ def __init__(self, root: Path | None = None) -> None:+ self._root = root or (DATA_DIR / UPLOADS_DIRNAME)+ self._lock = threading.Lock()++ @property+ def root(self) -> Path:+ return self._root++ def _meta_path(self, upload_id: str) -> Path:+ return self._root / f"{upload_id}.json"++ def _image_path(self, upload_id: str) -> Path:+ return self._root / f"{upload_id}.webp"++ def _read(self, upload_id: str) -> UploadedWallpaper | None:+ image = self._image_path(upload_id)+ if not image.is_file():+ return None+ theme = "dark"+ title = "Your wallpaper"+ created = 0.0try:- if target.is_file() and target.stat().st_mtime >= item.path.stat().st_mtime:- return target- except OSError:- return item.path+ meta = json.loads(self._meta_path(upload_id).read_text(encoding="utf-8"))+ except (OSError, ValueError):+ # A lost sidecar costs the title, not the picture: the image is the+ # part that cannot be reconstructed, so it still gets listed.+ meta = {}+ if isinstance(meta, dict):+ if str(meta.get("theme")) in {"light", "dark"}:+ theme = str(meta["theme"])+ if str(meta.get("title", "")).strip():+ title = str(meta["title"]).strip()[:60]+ try:+ created = float(meta.get("createdAt", 0.0))+ except (TypeError, ValueError):+ created = 0.0+ if not created:+ try:+ created = image.stat().st_mtime+ except OSError:+ created = 0.0+ return UploadedWallpaper(+ id=upload_id, title=title, theme=theme, created_at=created, path=image+ )++ def _write_meta(self, item: UploadedWallpaper) -> None:+ _atomic_write(+ self._meta_path(item.id),+ json.dumps(item.to_json(), ensure_ascii=False, indent=2).encode("utf-8"),+ prefix=".meta.",+ suffix=".json",+ )++ def list(self) -> list[UploadedWallpaper]:+ """Every upload, newest first — the one just added is the first tile."""+ if not self._root.is_dir():+ return []+ items: list[UploadedWallpaper] = []+ for image in self._root.glob("u*.webp"):+ if not _UPLOAD_ID_PATTERN.match(image.stem):+ continue+ item = self._read(image.stem)+ if item is not None:+ items.append(item)+ return sorted(items, key=lambda item: (-item.created_at, item.id))++ def get(self, upload_id: str) -> UploadedWallpaper | None:+ if not _UPLOAD_ID_PATTERN.match(upload_id):+ return None+ return self._read(upload_id)++ def add(self, data: bytes, filename: str = "") -> UploadedWallpaper:+ """Validate, re-encode, and store one uploaded picture.++ The incoming bytes are decoded by Pillow rather than trusted by their+ declared type, and what is written is the *re-encoded* image — so+ whatever else the upload carried (a forged header, an appended+ payload, EXIF) does not survive the round trip onto disk.+ """+ if not data:+ raise UploadRejected("That file is empty.")+ if len(data) > MAX_UPLOAD_BYTES:+ raise UploadRejected(+ f"That image is larger than {MAX_UPLOAD_BYTES // (1024 * 1024)} MB.",+ status_code=413,+ )try:from PIL import Image- except ImportError:- return item.path+ except ImportError as exc: # pragma: no cover - Pillow is a hard dependency+ raise UploadRejected(+ "Image support is unavailable on this install.", status_code=503+ ) from exctry:- target.parent.mkdir(parents=True, exist_ok=True)- with Image.open(item.path) as source:+ with Image.open(io.BytesIO(data)) as probe:+ probe.verify()+ with Image.open(io.BytesIO(data)) as source:source.load()- thumb = source.convert("RGB")- height = max(1, round(thumb.height * THUMB_WIDTH / thumb.width))- thumb = thumb.resize((THUMB_WIDTH, height), Image.Resampling.LANCZOS)- # Write via a per-item temporary name: two browsers scrolling- # the same row must not read a half-written file.- staging = target.with_suffix(".webp.part")- thumb.save(staging, "WEBP", quality=THUMB_QUALITY, method=4)- staging.replace(target)- return target- except (OSError, ValueError) as exc:- logger.warning("Could not derive wallpaper thumbnail for {}: {}", item.id, exc)- return item.path+ prepared = source.convert("RGB")+ except Exception as exc: # noqa: BLE001 — any decode failure = not an image+ raise UploadRejected(+ "That file is not an image the app can read (PNG, JPEG, WebP, GIF or BMP)."+ ) from exc++ if prepared.width > UPLOAD_MAX_WIDTH:+ height = max(1, round(prepared.height * UPLOAD_MAX_WIDTH / prepared.width))+ prepared = prepared.resize((UPLOAD_MAX_WIDTH, height), Image.Resampling.LANCZOS)+ theme = _detect_theme(prepared)+ buffer = io.BytesIO()+ prepared.save(buffer, "WEBP", quality=UPLOAD_QUALITY, method=4)+ prepared.close()-def register_wallpaper_routes(app: FastAPI, library: WallpaperLibrary | None = None) -> None:+ with self._lock:+ try:+ self._root.mkdir(parents=True, exist_ok=True)+ except OSError as exc:+ raise UploadRejected(+ "The app could not write to its data directory.", status_code=500+ ) from exc+ upload_id = f"u{secrets.token_hex(8)}"+ item = UploadedWallpaper(+ id=upload_id,+ title=_clean_title(filename),+ theme=theme,+ created_at=time.time(),+ path=self._image_path(upload_id),+ )+ try:+ _atomic_write(item.path, buffer.getvalue(), prefix=".upload.", suffix=".webp")+ self._write_meta(item)+ except OSError as exc:+ raise UploadRejected(+ "The app could not store that image.", status_code=500+ ) from exc+ logger.info("Wallpaper upload stored: {} ({})", item.id, item.title)+ return item++ def set_theme(self, upload_id: str, theme: str) -> UploadedWallpaper | None:+ """Correct the light/dark guess made at upload time."""+ if theme not in {"light", "dark"}:+ raise UploadRejected("Theme must be 'light' or 'dark'.")+ with self._lock:+ item = self.get(upload_id)+ if item is None:+ return None+ updated = UploadedWallpaper(+ id=item.id,+ title=item.title,+ theme=theme,+ created_at=item.created_at,+ path=item.path,+ )+ try:+ self._write_meta(updated)+ except OSError as exc:+ raise UploadRejected(+ "The app could not save that change.", status_code=500+ ) from exc+ return updated++ def remove(self, upload_id: str) -> bool:+ """Delete one upload, picture and sidecar and thumbnail."""+ if not _UPLOAD_ID_PATTERN.match(upload_id):+ return False+ with self._lock:+ image = self._image_path(upload_id)+ existed = image.is_file()+ for path in (+ image,+ self._meta_path(upload_id),+ self._root / THUMBS_DIRNAME / f"{upload_id}.webp",+ ):+ try:+ path.unlink()+ except OSError:+ # Already gone, or held open by a reader on Windows. The+ # entry disappears from the listing either way.+ pass+ return existed++ def thumbnail(self, item: UploadedWallpaper) -> Path:+ """A grid thumbnail for an upload, derived and cached like the library's."""+ target = self._root / THUMBS_DIRNAME / f"{item.id}.webp"+ return _derive_thumbnail(item.path, target, item.id)+++def _detect_theme(image: Any) -> str:+ """Guess whether a picture belongs to light or dark mode.++ Mean luminance of a thumbnail-sized copy: bright artwork under dark chrome+ (or the reverse) is the thing that reads as a bug, and mean brightness is+ what that judgement actually turns on. A wrong guess is one click to fix,+ so this stays a cheap heuristic rather than a saliency model.+ """+ try:+ from PIL import ImageStat++ small = image.convert("L").resize((32, 32))+ mean = ImageStat.Stat(small).mean[0]+ except Exception: # noqa: BLE001 — a guess is never worth failing an upload+ return "dark"+ return "light" if mean >= _LIGHT_THEME_LUMA else "dark"+++def _atomic_write(target: Path, payload: bytes, *, prefix: str, suffix: str) -> None:+ """Write bytes so a reader sees either the old file or the whole new one."""+ target.parent.mkdir(parents=True, exist_ok=True)+ fd, tmp_path = tempfile.mkstemp(prefix=prefix, suffix=suffix, dir=str(target.parent))+ try:+ with os.fdopen(fd, "wb") as handle:+ handle.write(payload)+ os.replace(tmp_path, target)+ except Exception:+ try:+ os.unlink(tmp_path)+ except OSError:+ pass+ raise+++def _derive_thumbnail(source_path: Path, target: Path, label: str) -> Path:+ """Shared thumbnail derivation for both stores.++ Falls back to the original file when Pillow is unavailable or the resize+ fails: a heavier grid is a far better outcome than an empty one.+ """+ try:+ if target.is_file() and target.stat().st_mtime >= source_path.stat().st_mtime:+ return target+ except OSError:+ return source_path++ try:+ from PIL import Image+ except ImportError:+ return source_path++ try:+ with Image.open(source_path) as source:+ source.load()+ thumb = source.convert("RGB")+ height = max(1, round(thumb.height * THUMB_WIDTH / thumb.width))+ thumb = thumb.resize((THUMB_WIDTH, height), Image.Resampling.LANCZOS)+ buffer = io.BytesIO()+ thumb.save(buffer, "WEBP", quality=THUMB_QUALITY, method=4)+ # Staged through a temporary name: two browsers scrolling the same row+ # must not read a half-written file.+ _atomic_write(target, buffer.getvalue(), prefix=".thumb.", suffix=".webp")+ return target+ except (OSError, ValueError) as exc:+ logger.warning("Could not derive wallpaper thumbnail for {}: {}", label, exc)+ return source_path+++def register_wallpaper_routes(+ app: FastAPI,+ library: WallpaperLibrary | None = None,+ uploads: WallpaperUploads | None = None,+) -> None:"""Mount the wallpaper endpoints under ``/api``.Deliberately under ``/api`` rather than a static mount of its own: that@@ -241,11 +564,71 @@ def register_wallpaper_routes(app: FastAPI, library: WallpaperLibrary | None = Nidentically in development and in the packaged app."""lib = library or WallpaperLibrary()+ own = uploads or WallpaperUploads()@app.get("/api/wallpapers")async def list_wallpapers() -> dict[str, Any]:return lib.catalog()+ # The upload routes are declared before the ``{item_id}`` ones purely for+ # reading order — they never collide, because every upload path carries the+ # literal ``uploads`` segment at a depth the catalog routes do not use.++ @app.get("/api/wallpapers/uploads")+ async def list_uploads() -> dict[str, Any]:+ return {"items": [item.to_json() for item in own.list()]}++ @app.post("/api/wallpapers/uploads", response_model=None)+ async def upload_wallpaper(+ file: UploadFile = File(...), # noqa: B008 — FastAPI dependency default+ ) -> dict[str, Any] | JSONResponse:+ # Read with a ceiling rather than whole: UploadFile spools to disk, so+ # an oversized upload must be refused before it is fully absorbed.+ data = await file.read(MAX_UPLOAD_BYTES + 1)+ try:+ item = own.add(data, file.filename or "")+ except UploadRejected as exc:+ return JSONResponse({"detail": exc.message}, status_code=exc.status_code)+ return item.to_json()++ @app.patch("/api/wallpapers/uploads/{upload_id}", response_model=None)+ async def retheme_upload(upload_id: str, body: dict[str, Any]) -> dict[str, Any] | JSONResponse:+ try:+ item = own.set_theme(upload_id, str(body.get("theme", "")))+ except UploadRejected as exc:+ return JSONResponse({"detail": exc.message}, status_code=exc.status_code)+ if item is None:+ return JSONResponse({"detail": "Not Found"}, status_code=404)+ return item.to_json()++ @app.delete("/api/wallpapers/uploads/{upload_id}", response_model=None)+ async def delete_upload(upload_id: str) -> dict[str, Any] | JSONResponse:+ if not own.remove(upload_id):+ return JSONResponse({"detail": "Not Found"}, status_code=404)+ return {"removed": upload_id}++ @app.get("/api/wallpapers/uploads/{upload_id}/thumb", response_model=None)+ async def upload_thumb(upload_id: str) -> FileResponse | JSONResponse:+ item = own.get(upload_id)+ if item is None:+ return JSONResponse({"detail": "Not Found"}, status_code=404)+ return FileResponse(+ str(own.thumbnail(item)),+ media_type="image/webp",+ headers=_CACHE_HEADERS,+ )++ @app.get("/api/wallpapers/uploads/{upload_id}/full", response_model=None)+ async def upload_full(upload_id: str) -> FileResponse | JSONResponse:+ item = own.get(upload_id)+ if item is None:+ return JSONResponse({"detail": "Not Found"}, status_code=404)+ return FileResponse(+ str(item.path),+ media_type="image/webp",+ headers=_CACHE_HEADERS,+ )+@app.get("/api/wallpapers/{item_id}/thumb", response_model=None)async def wallpaper_thumb(item_id: str) -> FileResponse | JSONResponse:item = lib.get(item_id)diff --git a/tests/unit/agentic_ide/test_deck_delegation.py b/tests/unit/agentic_ide/test_deck_delegation.pydeleted file mode 100644index 4bc6d2d8a9..0000000000--- a/tests/unit/agentic_ide/test_deck_delegation.py+++ /dev/null@@ -1,185 +0,0 @@-"""Work with nobody's name on it still reaches an agent — in the deck only.--Two halves, and the second one is the dangerous half. Getting "somebody fix the-wake path" to a free agent is the feature; NOT getting "what time is it" typed-into a coding agent as a task is what makes the feature safe to ship.-"""--from __future__ import annotations--import time-from typing import Any--import pytest--from jarvis.agentic_ide import intent, standup-from jarvis.agentic_ide.fleet_actions import free_agents--from .test_standup import entry---class FakeTerminal:- """Enough of a pane for the free-agent scan and the hold."""-- def __init__(- self,- name: str,- *,- agent: str = "claude",- activity: str = "waiting",- status: str = "live",- index: int = 0,- since: float = 0.0,- deck_hold: bool = False,- ) -> None:- self.key = name.lower()- self.name = name- self.agent = agent- self.status = status- self.index = index- self.deck_hold = deck_hold- # Stamped as the sweep would, so `observed` reads it rather than- # falling back to a single look at a screen this fake does not have.- self.activity = activity- self.activity_at = time.time()- self.activity_since = since---class FakeSession:- def __init__(self, *terminals: FakeTerminal, view: str = "deck") -> None:- self.id = "ide_test"- self.terminals = list(terminals)- self.surface_view = view---class TestWhoTakesIt:- def test_an_idle_agent_is_offered(self) -> None:- session = FakeSession(FakeTerminal("Mika"))-- assert [t.name for t in free_agents(session)] == ["Mika"]-- def test_a_working_agent_is_not(self) -> None:- # Typing a second job into a busy CLI does not queue it — it lands as- # an interruption of the first.- session = FakeSession(FakeTerminal("Mika", activity="working"))-- assert free_agents(session) == []-- def test_a_plain_shell_is_never_offered(self) -> None:- # It would RUN the sentence as a command.- session = FakeSession(FakeTerminal("Sh", agent="shell"))-- assert free_agents(session) == []-- def test_a_dead_pane_is_not_offered(self) -> None:- session = FakeSession(FakeTerminal("Mika", status="exited"))-- assert free_agents(session) == []-- def test_a_pane_the_user_took_over_is_not_offered(self) -> None:- session = FakeSession(FakeTerminal("Mika", deck_hold=True), FakeTerminal("Nova"))-- assert [t.name for t in free_agents(session)] == ["Nova"]-- def test_the_longest_idle_agent_goes_first(self) -> None:- # Otherwise the same pane takes every order while the rest sit there.- session = FakeSession(- FakeTerminal("Mika", since=500.0, index=0),- FakeTerminal("Nova", since=100.0, index=1),- )-- assert [t.name for t in free_agents(session)] == ["Nova", "Mika"]-- def test_an_untouched_fleet_answers_in_pane_order(self) -> None:- # Nothing has run, so every `since` is 0 — the answer still has to be- # stable, or two consecutive orders would scatter at random.- session = FakeSession(- FakeTerminal("Kai", index=2),- FakeTerminal("Mika", index=0),- FakeTerminal("Nova", index=1),- )-- assert [t.name for t in free_agents(session)] == ["Mika", "Nova", "Kai"]---class TestWhatCountsAsWork:- @pytest.mark.parametrize(- "utterance",- [- "get the wake-path tests green",- "fix the failing build",- "refactor the audio provider",- "mach mal einen Deep Dive über den Wake-Pfad", # i18n-allow: spoken input- "schreib Tests für die Recap-Engine", # i18n-allow: spoken input- "revisa el módulo de audio", # i18n-allow: spoken input- ],- )- def test_an_order_with_no_name_on_it_is_work(self, utterance: str) -> None:- assert intent.unaddressed_work(utterance) == utterance-- @pytest.mark.parametrize(- "utterance",- [- # Questions are ANSWERED, never delegated. Each of these carries a- # perfectly good instruction verb and is not an instruction.- "what time is it?",- "how do I fix the wake path",- "can you explain what a PTY is",- "was machen die gerade", # i18n-allow: spoken input- "wie läuft der Build", # i18n-allow: spoken input- "¿qué está haciendo?", # i18n-allow: spoken input- # A status question without a question mark.- "status on the tests",- # No instruction shape at all.- "okay",- "danke, super", # i18n-allow: spoken input- "",- ],- )- def test_everything_else_is_not(self, utterance: str) -> None:- assert intent.unaddressed_work(utterance) is None-- def test_a_named_pane_is_left_to_the_addressing_detector(self) -> None:- # The detector above stood down for a reason. Re-routing the order to- # whichever agent happens to be free would send it to the wrong one —- # with the right one's name still in the sentence.- assert intent.unaddressed_work("Mika die Tests", names=["Mika", "Nova"]) is None---class TestHoldSilencesReports:- @pytest.fixture(autouse=True)- def _fresh(self) -> Any:- standup.reset()- standup.unwire()- yield- standup.reset()- standup.unwire()-- class Registry:- def __init__(self, session: FakeSession) -> None:- self.sessions = [session]-- async def test_a_held_pane_is_not_reported(self) -> None:- said: list[str] = []- standup.wire(speak=lambda text, _lang: said.append(text), language=lambda: "en")- standup.queue().conversation_started()- session = FakeSession(FakeTerminal("Mika", deck_hold=True))-- await standup.pump(self.Registry(session), [entry("Mika")])-- assert said == []- assert standup.queue().pending() == []-- async def test_taking_a_pane_over_drops_a_report_already_waiting(self) -> None:- # The user is typing into it right now. Announcing it would be the deck- # talking over somebody who is already there.- standup.queue().conversation_started()- session = FakeSession(FakeTerminal("Mika"), FakeTerminal("Nova"))- registry = self.Registry(session)- await standup.pump(registry, [entry("Mika"), entry("Nova")])- assert len(standup.queue().pending()) >= 1-- session.terminals[0].deck_hold = True- await standup.pump(registry, [])-- assert "Mika" not in [r.pane for r in standup.queue().pending()]diff --git a/tests/unit/agentic_ide/test_deck_routes.py b/tests/unit/agentic_ide/test_deck_routes.pydeleted file mode 100644index d177ca1570..0000000000--- a/tests/unit/agentic_ide/test_deck_routes.py+++ /dev/null@@ -1,128 +0,0 @@-"""The report lane the Command Deck renders, and answering from it.--Voice and click go through the same two routes on purpose: "tell me about Nova"-and pressing Nova's card are the same instruction, and a second path for the-second one is a second thing to keep in step.-"""--from __future__ import annotations--from typing import Any--import pytest-from fastapi import FastAPI-from fastapi.testclient import TestClient--from jarvis.agentic_ide import standup-from jarvis.ui.web import agentic_ide_routes--from .test_standup import entry--[email protected](autouse=True)-def _fresh() -> Any:- standup.reset()- standup.unwire()- yield- standup.reset()- standup.unwire()---def client() -> TestClient:- app = FastAPI()- app.include_router(agentic_ide_routes.router)- return TestClient(app)---def filled(*panes: str, kind: str = "completed") -> standup.StandupQueue:- queue = standup.queue()- queue.conversation_started()- queue.offer([entry(pane, kind) for pane in panes])- return queue---def test_an_empty_lane_reads_as_empty_rather_than_missing(client: TestClient) -> None:- body = client.get("/api/agentic-ide/deck/queue").json()-- assert body["pending"] == []- assert body["on_air"] is None- assert body["sleeping"] is False---def test_the_lane_lists_what_is_waiting_blockers_first(client: TestClient) -> None:- filled("Mika")- standup.queue().offer([entry("Nova", "needs_input")])-- body = client.get("/api/agentic-ide/deck/queue").json()-- assert [r["pane"] for r in body["pending"]] == ["Nova", "Mika"]---def test_asking_for_one_report_puts_it_on_air(client: TestClient) -> None:- queue = filled("Mika", "Nova")- queue.take_due()- nova = next(r for r in queue.pending() if r.pane == "Nova")-- body = client.post(- "/api/agentic-ide/deck/ack", json={"id": nova.id, "action": "next"}- ).json()-- assert body["found"] is True- assert body["on_air"]["pane"] == "Nova"---def test_later_puts_the_lane_to_sleep_without_losing_anything(client: TestClient) -> None:- queue = filled("Mika", "Nova")- queue.take_due()- first = queue.pending()[0]-- body = client.post(- "/api/agentic-ide/deck/ack", json={"id": first.id, "action": "later"}- ).json()-- assert body["sleeping"] is True- assert len(body["pending"]) == 2---def test_dropping_one_takes_it_out_of_the_lane(client: TestClient) -> None:- queue = filled("Mika", "Nova")- mika = next(r for r in queue.pending() if r.pane == "Mika")-- body = client.post(- "/api/agentic-ide/deck/ack", json={"id": mika.id, "action": "drop"}- ).json()-- assert [r["pane"] for r in body["pending"]] == ["Nova"]---def test_answering_a_report_that_is_already_gone_is_not_an_error(- client: TestClient,-) -> None:- # A report goes away when its pane does, and a click that lands a moment- # later got the outcome it wanted. A 404 here would put an error toast in- # front of a user who did nothing wrong.- response = client.post(- "/api/agentic-ide/deck/ack", json={"id": "sr-gone", "action": "next"}- )-- assert response.status_code == 200- assert response.json()["found"] is False---def test_an_action_nobody_defined_is_refused_at_the_door(client: TestClient) -> None:- queue = filled("Mika")- mika = queue.pending()[0]-- response = client.post(- "/api/agentic-ide/deck/ack", json={"id": mika.id, "action": "snooze"}- )-- assert response.status_code == 422---def test_the_route_literal_still_matches_the_source_of_truth() -> None:- """Layer 3 against layer 0, same guard as the workspace-view enum."""- from typing import get_args-- assert set(get_args(agentic_ide_routes.DeckAction)) == set(get_args(standup.Action))diff --git a/tests/unit/agentic_ide/test_deck_voice.py b/tests/unit/agentic_ide/test_deck_voice.pydeleted file mode 100644index 647678dc1c..0000000000--- a/tests/unit/agentic_ide/test_deck_voice.py+++ /dev/null@@ -1,169 +0,0 @@-"""The Command Deck's report queue reaches the user through the speech bus.--The bridge itself is thin on purpose — what these tests pin is the three things-it must not get wrong: never interrupting, never re-deriving the turn language,-and going quiet the moment the user hangs up.-"""--from __future__ import annotations--from typing import Any--import pytest--from jarvis.agentic_ide import deck_voice, standup-from jarvis.core.bus import EventBus-from jarvis.core.events import (- AnnouncementRequested,- ResponseGenerated,- VoiceSessionEnded,- VoiceSessionStarted,-)--from .test_standup import entry--[email protected](autouse=True)-def _fresh() -> Any:- standup.reset()- standup.unwire()- yield- standup.reset()- standup.unwire()---class Recorder:- """Collects what would have been spoken."""-- def __init__(self, bus: EventBus) -> None:- self.said: list[AnnouncementRequested] = []- bus.subscribe(AnnouncementRequested, self._on)-- async def _on(self, event: AnnouncementRequested) -> None:- self.said.append(event)---class FakeSession:- def __init__(self, ident: str = "ide_test", view: str = "deck") -> None:- self.id = ident- self.surface_view = view---class FakeRegistry:- def __init__(self, *sessions: Any) -> None:- self.sessions = list(sessions or [FakeSession()])---async def test_a_finished_pane_is_announced_once_a_session_is_open() -> None:- bus = EventBus()- heard = Recorder(bus)- deck_voice.attach(bus)-- await bus.publish(VoiceSessionStarted(session_id="s1", language="en"))- await standup.pump(FakeRegistry(), [entry("Mika")])-- assert len(heard.said) == 1- assert "Mika" in heard.said[0].text---async def test_it_never_interrupts() -> None:- # Rule 5. Nothing the deck has to say is worth cutting the user off for —- # `interrupt` stops playback mid-word, and this is news, not an emergency.- bus = EventBus()- heard = Recorder(bus)- deck_voice.attach(bus)- await bus.publish(VoiceSessionStarted(session_id="s1", language="en"))-- await standup.pump(FakeRegistry(), [entry("Mika")])-- assert heard.said[0].priority == "normal"---async def test_nothing_is_said_before_a_session_starts() -> None:- bus = EventBus()- heard = Recorder(bus)- deck_voice.attach(bus)-- await standup.pump(FakeRegistry(), [entry("Mika")])-- assert heard.said == []- # Kept, not lost — it is offered when the user comes back.- assert [r.pane for r in standup.queue().pending()] == ["Mika"]---async def test_hanging_up_stops_the_deck_talking() -> None:- bus = EventBus()- heard = Recorder(bus)- deck_voice.attach(bus)- await bus.publish(VoiceSessionStarted(session_id="s1", language="en"))- await bus.publish(VoiceSessionEnded(session_id="s1"))-- await standup.pump(FakeRegistry(), [entry("Mika")])-- assert heard.said == []---async def test_and_the_next_session_gets_it_once() -> None:- bus = EventBus()- heard = Recorder(bus)- deck_voice.attach(bus)- await bus.publish(VoiceSessionStarted(session_id="s1", language="en"))- await bus.publish(VoiceSessionEnded(session_id="s1"))- await standup.pump(FakeRegistry(), [entry("Mika"), entry("Nova")])-- await bus.publish(VoiceSessionStarted(session_id="s2", language="en"))- await standup.pump(FakeRegistry(), [])-- assert len(heard.said) == 1- assert "While you were away" in heard.said[0].text- # Once. Coming back to the deck a third time is not a reason to hear it- # again — the reports are on their cards and in the lane.- await standup.pump(FakeRegistry(), [])- assert len(heard.said) == 1---async def test_the_line_is_spoken_in_the_language_the_turn_resolved_to() -> None:- # Read, never re-derived: one resolver owns the output language for every- # layer, and a second opinion here is exactly the divergence it prevents.- bus = EventBus()- heard = Recorder(bus)- deck_voice.attach(bus)- await bus.publish(VoiceSessionStarted(session_id="s1", language="en"))- await bus.publish(ResponseGenerated(text="Alles klar.", language="de"))-- await standup.pump(FakeRegistry(), [entry("Mika")])-- assert heard.said[0].language == "de"- assert "durch" in heard.said[0].text # i18n-allow: asserting voice output---async def test_an_answer_wakes_a_queue_that_had_gone_quiet() -> None:- bus = EventBus()- heard = Recorder(bus)- deck_voice.attach(bus)- await bus.publish(VoiceSessionStarted(session_id="s1", language="en"))- await standup.pump(FakeRegistry(), [entry("Mika")])- assert len(heard.said) == 1-- # Unanswered, so the queue settles (rule 8) — until the user says something.- await standup.pump(FakeRegistry(), [entry("Nova")])- assert len(heard.said) == 1-- await bus.publish(ResponseGenerated(text="Go on.", language="en"))- await standup.pump(FakeRegistry(), [])-- assert len(heard.said) == 2- assert "Nova" in heard.said[1].text---async def test_stopping_the_bridge_leaves_the_queue_mute_but_working() -> None:- bus = EventBus()- heard = Recorder(bus)- voice = deck_voice.attach(bus)- await bus.publish(VoiceSessionStarted(session_id="s1", language="en"))-- voice.stop()- await standup.pump(FakeRegistry(), [entry("Mika")])-- assert heard.said == []- assert [r.pane for r in standup.queue().pending()] == ["Mika"]diff --git a/tests/unit/agentic_ide/test_standup.py b/tests/unit/agentic_ide/test_standup.pydeleted file mode 100644index 95ea63d128..0000000000--- a/tests/unit/agentic_ide/test_standup.py+++ /dev/null@@ -1,454 +0,0 @@-"""The Command Deck reports one agent at a time.--What is pinned here is the behaviour the maintainer asked for by describing the-failure: eight agents finishing inside ten seconds must not produce eight-announcements, and the queue must never turn into something that talks at-somebody who has stopped listening.-"""--from __future__ import annotations--from typing import Any--import pytest--from jarvis.agentic_ide import standup-from jarvis.agentic_ide.notifications import Notification--[email protected](autouse=True)-def _fresh() -> Any:- standup.reset()- standup.unwire()- yield- standup.reset()- standup.unwire()---def entry(- pane: str,- kind: str = "completed",- *,- workspace: str = "ide_test",- title: str = "Finished and waiting at its prompt",- detail: str = "",-) -> Notification:- """One bell entry, as the sweep files it."""- return Notification(- id=f"n-{workspace}-{pane}-{kind}",- kind=kind, # type: ignore[arg-type]- workspace_id=workspace,- workspace="project",- pane_key=pane.lower(),- pane=pane,- agent="claude",- display_name="Claude Code",- title=title,- detail=detail,- created_at=0.0,- )---def open_queue() -> standup.StandupQueue:- """A queue with a conversation open — nothing is ever said without one."""- queue = standup.StandupQueue()- queue.conversation_started()- return queue---class TestSeveralAtOnce:- """The pile-up this whole module exists for."""-- def test_three_finishing_together_produce_one_headline(self) -> None:- queue = open_queue()- queue.offer([entry("Mika"), entry("Nova"), entry("Kai")])-- utterance = queue.take_due()-- assert utterance is not None- assert utterance.form == "headline"- assert set(utterance.panes) == {"Mika", "Nova", "Kai"}- # And nothing follows it on its own — the user answers first.- assert queue.take_due() is None-- def test_the_headline_names_them_rather_than_counting_them(self) -> None:- # "Three are done" without names is a notification, not a handover:- # the next thing the user has to say is "which three?".- queue = open_queue()- queue.offer([entry("Mika"), entry("Nova")])-- line = standup.canned_line(queue.take_due(), "en") # type: ignore[arg-type]-- assert "Mika" in line- assert "Nova" in line-- def test_one_piece_of_news_is_simply_said(self) -> None:- # A "one agent is done, shall I tell you?" is a question with one- # possible answer. It costs the user a turn and tells them nothing.- queue = open_queue()- queue.offer([entry("Mika")])-- utterance = queue.take_due()-- assert utterance is not None- assert utterance.form == "report"- assert utterance.panes == ("Mika",)-- def test_asking_for_one_by_name_puts_that_report_on_air(self) -> None:- queue = open_queue()- queue.offer([entry("Mika"), entry("Nova"), entry("Kai")])- queue.take_due()- nova = next(r for r in queue.pending() if r.pane == "Nova")-- queue.acknowledge(nova.id, "next")-- assert queue.on_air() is not None- assert queue.on_air().pane == "Nova" # type: ignore[union-attr]-- def test_a_report_nobody_answered_does_not_silence_the_deck_forever(self) -> None:- """The first version's real bug, found by the blocker test below it.-- A report went ON AIR when it was spoken and stayed there until the user- acknowledged it — and "one report on air" was also the gate on saying- anything at all. So a single unanswered line, which is the ordinary- case for somebody who is reading code, muted the deck permanently.- """- queue = open_queue()- queue.offer([entry("Mika")])- queue.take_due() # spoken, never acknowledged-- queue.offer([entry("Nova")])- queue.wake()-- utterance = queue.take_due()- assert utterance is not None- assert utterance.panes == ("Nova",)-- def test_a_report_asked_for_by_name_is_spoken_on_the_next_beat(self) -> None:- # `acknowledge` only decides WHAT is next; the sentence is composed a- # beat later. Marking it said at the moment of asking would mean a- # failed compose leaves the user waiting for a report that never comes.- queue = open_queue()- queue.offer([entry("Mika"), entry("Nova")])- queue.take_due()- nova = next(r for r in queue.pending() if r.pane == "Nova")- queue.acknowledge(nova.id, "next")-- utterance = queue.take_due()-- assert utterance is not None- assert utterance.form == "report"- assert utterance.panes == ("Nova",)- # ...and it is not said a second time on the beat after that.- assert queue.take_due() is None-- def test_only_one_report_is_ever_on_air(self) -> None:- queue = open_queue()- queue.offer([entry("Mika"), entry("Nova")])- queue.take_due()- first, second = queue.pending()[0], queue.pending()[1]-- queue.acknowledge(first.id, "next")- queue.acknowledge(second.id, "next")-- on_air = [r for r in queue.state()["reports"] if r["state"] == "on_air"]- assert len(on_air) == 1- assert on_air[0]["pane"] == second.pane---class TestPriority:- def test_a_blocked_pane_outranks_a_finished_one(self) -> None:- # Work has STOPPED on a pane holding a question; a finished pane is- # merely waiting to be read.- queue = open_queue()- queue.offer([entry("Mika"), entry("Nova", "needs_input")])-- assert queue.pending()[0].pane == "Nova"-- def test_a_blocker_wakes_a_queue_that_had_gone_quiet(self) -> None:- queue = open_queue()- queue.offer([entry("Mika")])- queue.take_due()- assert queue.sleeping()-- queue.offer([entry("Nova", "needs_input")])-- utterance = queue.take_due()- assert utterance is not None- assert utterance.panes == ("Nova",)-- def test_another_ordinary_finish_does_not(self) -> None:- # Rule 8. Somebody who did not answer the first line is not helped by- # a second one, and this is the difference between a deck and a nag.- queue = open_queue()- queue.offer([entry("Mika")])- queue.take_due()-- queue.offer([entry("Nova")])-- assert queue.take_due() is None- # Still there, still listed — it is on the card and in the lane.- assert [r.pane for r in queue.pending()] == ["Nova"]-- def test_the_user_saying_something_brings_it_back(self) -> None:- queue = open_queue()- queue.offer([entry("Mika")])- queue.take_due()- queue.offer([entry("Nova")])-- queue.wake()-- utterance = queue.take_due()- assert utterance is not None- assert utterance.panes == ("Nova",)---class TestNothingIsSaidIntoAnEmptyRoom:- def test_no_conversation_means_no_announcement(self) -> None:- queue = standup.StandupQueue() # never started a conversation- queue.offer([entry("Mika")])-- assert queue.take_due() is None- assert queue.pending() # kept, not thrown away-- def test_hanging_up_keeps_the_queue_and_offers_it_once_on_return(self) -> None:- # The killswitch mandate cuts speech dead. It does not cancel the work- # that came back while the user was away — that is theirs to hear.- queue = open_queue()- queue.conversation_ended()- queue.offer([entry("Mika"), entry("Nova")])-- queue.conversation_started()- first = queue.take_due()-- assert first is not None- assert first.form == "resumed"- assert set(first.panes) == {"Mika", "Nova"}- # Once. It is a handover, not a thing that repeats every time the user- # comes back to the deck.- assert queue.take_due() is None-- def test_a_report_on_air_at_hangup_is_not_left_hanging(self) -> None:- queue = open_queue()- queue.offer([entry("Mika"), entry("Nova")])- queue.take_due()- queue.acknowledge(queue.pending()[0].id, "next")- assert queue.on_air() is not None-- queue.conversation_ended()-- # Otherwise it would still be "being reported" an hour later, and- # rule 1 would keep the whole queue silent behind it.- assert queue.on_air() is None---class TestReadMeansSilent:- def test_a_pane_the_user_read_drops_out_unspoken(self) -> None:- queue = open_queue()- queue.offer([entry("Mika"), entry("Nova")])-- queue.drop_pane("ide_test", "mika")-- assert [r.pane for r in queue.pending()] == ["Nova"]-- def test_later_puts_the_queue_to_sleep_without_losing_anything(self) -> None:- queue = open_queue()- queue.offer([entry("Mika"), entry("Nova")])- queue.take_due()-- queue.acknowledge(queue.pending()[0].id, "later")-- assert queue.sleeping()- assert len(queue.pending()) == 2---class TestOnePieceOfNewsPerPane:- def test_the_same_finish_twice_is_reported_once(self) -> None:- queue = open_queue()- queue.offer([entry("Mika")])- queue.offer([entry("Mika")])-- assert len(queue.pending()) == 1-- def test_a_finish_that_becomes_a_question_is_upgraded_in_place(self) -> None:- # The agent stopped, then put a permission prompt on screen. The- # question is the news; two entries about one pane would have the user- # hear "Mika is done" and then "Mika needs you" about the same moment.- queue = open_queue()- queue.offer([entry("Mika")])- queue.offer([entry("Mika", "needs_input", title="Waiting for your answer")])-- pending = queue.pending()- assert len(pending) == 1- assert pending[0].kind == "needs_input"-- def test_a_later_finish_does_not_downgrade_a_pending_question(self) -> None:- queue = open_queue()- queue.offer([entry("Mika", "needs_input")])- queue.offer([entry("Mika")])-- assert queue.pending()[0].kind == "needs_input"---class TestBounded:- def test_past_the_limit_the_oldest_finishes_fall_away(self) -> None:- queue = standup.StandupQueue(limit=3)- queue.conversation_started()-- queue.offer([entry(f"T{i}") for i in range(6)])-- assert len(queue.pending()) == 3-- def test_but_never_a_blocked_or_crashed_pane(self) -> None:- # Those are the two the user most needs to hear about. A queue that- # silently loses them is worse than one that says nothing.- queue = standup.StandupQueue(limit=2)- queue.conversation_started()-- queue.offer(- [- entry("Blocked", "needs_input"),- entry("Dead", "exited"),- *[entry(f"T{i}") for i in range(5)],- ]- )-- kinds = {r.pane for r in queue.pending()}- assert "Blocked" in kinds- assert "Dead" in kinds---class TestWording:- """The deterministic floor — what an install with no provider says."""-- @pytest.mark.parametrize(- ("language", "must_contain"),- [("en", "are done"), ("de", "sind durch"), ("es", "han terminado")],- )- def test_a_headline_reads_as_a_sentence_in_every_language(- self, language: str, must_contain: str- ) -> None:- queue = open_queue()- queue.offer([entry("Mika"), entry("Nova")])- utterance = queue.take_due()-- line = standup.canned_line(utterance, language) # type: ignore[arg-type]-- assert must_contain in line- assert "Mika" in line and "Nova" in line-- def test_a_list_is_said_the_way_a_person_says_one(self) -> None:- queue = open_queue()- queue.offer([entry("Mika"), entry("Nova"), entry("Kai")])-- line = standup.canned_line(queue.take_due(), "en") # type: ignore[arg-type]-- assert "Mika, Nova and Kai" in line-- def test_a_blocked_pane_is_not_described_as_finished(self) -> None:- queue = open_queue()- queue.offer([entry("Mika", "needs_input")])-- line = standup.canned_line(queue.take_due(), "en") # type: ignore[arg-type]-- assert "waiting on you" in line- assert "done" not in line-- def test_the_facts_handed_to_the_composer_carry_no_verdict(self) -> None:- # The honesty guard can only reject what it was not given. "Finished"- # is the whole claim; whether the work is any good is not knowable from- # a pane going quiet, and must not be inventable from these fields.- queue = open_queue()- queue.offer([entry("Mika", detail="Fixing the wake-path tests")])-- facts = standup.spoken_facts(queue.take_due()) # type: ignore[arg-type]-- assert facts["agent"] == "Mika"- assert "succeeded" not in str(facts).lower()- assert "fixed" not in str(facts).lower()---class TestPump:- """The sweep's one call in, and the surface gate on it."""-- class FakeSession:- def __init__(self, ident: str, view: str) -> None:- self.id = ident- self.surface_view = view-- class FakeRegistry:- def __init__(self, *sessions: Any) -> None:- self.sessions = list(sessions)-- async def test_a_workspace_read_as_a_grid_is_never_spoken(self) -> None:- said: list[str] = []- standup.wire(speak=lambda text, _lang: said.append(text), language=lambda: "en")- registry = self.FakeRegistry(self.FakeSession("ide_test", "grid"))-- await standup.pump(registry, [entry("Mika")])-- assert said == []- assert standup.queue().pending() == []-- async def test_a_deck_workspace_is(self) -> None:- said: list[str] = []- standup.wire(speak=lambda text, _lang: said.append(text), language=lambda: "en")- standup.queue().conversation_started()- registry = self.FakeRegistry(self.FakeSession("ide_test", "deck"))-- await standup.pump(registry, [entry("Mika")])-- assert said and "Mika" in said[0]-- async def test_only_that_workspace_s_news(self) -> None:- # Call-signs repeat between workspaces, and a deck must not report a- # pane from the grid the user has open in the next tab.- said: list[str] = []- standup.wire(speak=lambda text, _lang: said.append(text), language=lambda: "en")- standup.queue().conversation_started()- registry = self.FakeRegistry(- self.FakeSession("ide_deck", "deck"),- self.FakeSession("ide_grid", "grid"),- )-- await standup.pump(- registry,- [entry("Mika", workspace="ide_grid"), entry("Nova", workspace="ide_deck")],- )-- assert said and "Nova" in said[0]- assert "Mika" not in said[0]-- async def test_an_unwired_deck_fills_the_lane_and_stays_silent(self) -> None:- # No speech stack (headless, tests, a machine with no audio). The queue- # still works and the deck still shows it — honest degradation, not a- # broken feature.- standup.queue().conversation_started()- registry = self.FakeRegistry(self.FakeSession("ide_test", "deck"))-- spoken = await standup.pump(registry, [entry("Mika")])-- assert spoken == ""-- async def test_a_broken_speaker_does_not_take_the_sweep_down(self) -> None:- def explode(_text: str, _lang: str) -> None:- raise RuntimeError("no audio device")-- standup.wire(speak=explode, language=lambda: "en")- standup.queue().conversation_started()- registry = self.FakeRegistry(self.FakeSession("ide_test", "deck"))-- assert await standup.pump(registry, [entry("Mika")]) == ""-- async def test_the_switch_being_off_means_nothing_is_collected(- self, monkeypatch: pytest.MonkeyPatch- ) -> None:- monkeypatch.setattr(standup, "enabled", lambda: False)- said: list[str] = []- standup.wire(speak=lambda text, _lang: said.append(text), language=lambda: "en")- standup.queue().conversation_started()- registry = self.FakeRegistry(self.FakeSession("ide_test", "deck"))-- await standup.pump(registry, [entry("Mika")])-- assert said == []diff --git a/tests/unit/brain/test_command_deck_delegation.py b/tests/unit/brain/test_command_deck_delegation.pydeleted file mode 100644index 41ece54ec7..0000000000--- a/tests/unit/brain/test_command_deck_delegation.py+++ /dev/null@@ -1,217 +0,0 @@-"""In the Command Deck, an order with nobody's name on it still reaches an agent.--Everywhere else that sentence keeps meaning what it always did. That boundary is-the whole safety story of this feature: a workspace open in the grid must not-start swallowing ordinary conversation, and the deck must not need a call-sign-per order from a user who is running the room by voice.-"""--from __future__ import annotations--import time-from pathlib import Path--import pytest--from jarvis.agentic_ide import prompt_composer-from jarvis.agentic_ide import session as session_mod-from jarvis.agentic_ide.prompt_composer import ComposedPrompt-from jarvis.agentic_ide.session import Registry-from jarvis.brain.manager import BrainManager-from jarvis.core.bus import EventBus-from jarvis.core.config import JarvisConfig-from tests.fakes.fake_pty_manager import FakePtyManager--[email protected](autouse=True)-def _isolated_recents(- tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch-) -> None:- from jarvis.agentic_ide import recents-- store = tmp_path_factory.mktemp("recents") / "recents.json"- monkeypatch.setattr(recents, "_store_path", lambda: store)---def registry(monkeypatch: pytest.MonkeyPatch) -> Registry:- monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))- reg = Registry(pty_manager=FakePtyManager())- monkeypatch.setattr(session_mod, "get_registry", lambda: reg)- return reg---def manager() -> BrainManager:- cfg = JarvisConfig()- cfg.brain.primary = "fake"- mgr = BrainManager(config=cfg, bus=EventBus(), tools={})- # Pinned so the wording assertions do not depend on the host's locale- # (AP-23: never test against the maintainer's own configuration).- mgr._reply_language = "en"- return mgr--[email protected](autouse=True)-def _fake_composer(monkeypatch: pytest.MonkeyPatch) -> None:- async def fake_compose(utterance: str, **kwargs: object) -> ComposedPrompt:- name = kwargs["terminal_name"]- instruction = kwargs.get("instruction") or utterance- return ComposedPrompt(- text=f"## Task for {name}\n{instruction}", files=[], composed_by="llm"- )-- monkeypatch.setattr(prompt_composer, "compose", fake_compose)---async def _noop(_text: str) -> None:- return None---async def _noop_exit(_code: int) -> None:- return None---async def _open(registry: Registry, folder: Path, count: int, *, view: str) -> None:- """Open ``count`` live panes and report the workspace as read in ``view``."""- await registry.start(str(folder), [{"agent": "claude"} for _ in range(count)])- assert registry.session is not None- for term in list(registry.session.terminals):- await registry.attach(term.name, 100, 30, _noop, _noop_exit)- registry.set_surface_context(- workspace_id=registry.session.id,- view=view,- on_screen=True,- terminal=None,- )---def _typed(registry: Registry) -> dict[str, str]:- """What actually reached each pane, by call-sign."""- assert registry.session is not None- return {- term.name: str(getattr(term, "last_prompt", "") or "")- for term in registry.session.terminals- }---async def test_the_deck_gives_an_unaddressed_order_to_a_free_agent(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- await _open(registry, tmp_path, 2, view="deck")-- reply = await manager._run_agentic_ide_fast_path("get the wake-path tests green")-- assert reply is not None- delivered = [name for name, prompt in _typed(registry).items() if prompt]- assert len(delivered) == 1---async def test_the_grid_does_not(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- # The boundary. An unaddressed instruction in the grid is a sentence for- # Jarvis, and a workspace that quietly typed it into an agent would make- # every open workspace a hazard to ordinary conversation.- await _open(registry, tmp_path, 2, view="grid")-- await manager._run_agentic_ide_fast_path("get the wake-path tests green")-- assert not any(_typed(registry).values())---async def test_a_question_is_never_delegated(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- # It contains an instruction verb and is not an instruction. Typing it into- # a coding agent as a task is the worst thing this path could do.- await _open(registry, tmp_path, 2, view="deck")-- await manager._run_agentic_ide_fast_path("how do I fix the wake path?")-- assert not any(_typed(registry).values())---async def test_a_busy_fleet_is_told_rather_than_queued(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- # A silently held order is how somebody ends up waiting an hour on work- # that was never started.- await _open(registry, tmp_path, 1, view="deck")- assert registry.session is not None- for term in registry.session.terminals:- # Stamped as the sweep would, NOW. A timestamp in the future is not- # "very fresh" to `activity.observed` — it is outside the window in the- # other direction, and the reading falls back to a single look.- term.activity = "working"- term.activity_at = time.time()- term.activity_since = time.time()-- reply = await manager._run_agentic_ide_fast_path("get the wake-path tests green")-- assert reply is not None- assert "free" in reply.lower() or "working" in reply.lower()- assert not any(_typed(registry).values())---async def test_a_workspace_with_no_agent_says_that_instead(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- # Telling somebody their agents are busy when they have none is the kind of- # small lie that makes a surface untrustworthy.- await registry.start(str(tmp_path), [{"agent": "shell"}])- assert registry.session is not None- registry.set_surface_context(- workspace_id=registry.session.id, view="deck", on_screen=True, terminal=None- )-- reply = await manager._run_agentic_ide_fast_path("get the wake-path tests green")-- assert reply is not None- assert "no agent" in reply.lower()---async def test_a_pane_the_user_took_over_is_skipped(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- await _open(registry, tmp_path, 2, view="deck")- assert registry.session is not None- first, second = registry.session.terminals- registry.set_deck_hold(first.name, True)-- await manager._run_agentic_ide_fast_path("get the wake-path tests green")-- typed = _typed(registry)- assert not typed[first.name]- assert typed[second.name]---async def test_naming_a_pane_still_wins(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- # Delegation is the fallback for an order with no name on it, never a- # replacement for the addressing path.- await _open(registry, tmp_path, 3, view="deck")- assert registry.session is not None- wanted = registry.session.terminals[2].name-- await manager._run_agentic_ide_fast_path(f"tell {wanted} to fix the wake path")-- typed = _typed(registry)- assert typed[wanted]- assert [name for name, prompt in typed.items() if prompt] == [wanted]---async def test_asking_for_a_background_agent_still_spawns_one(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- # Precedence rule 1 of `intent`: naming the spawn vehicle outranks the- # workspace. The deck must not swallow it just because a pane is free.- await _open(registry, tmp_path, 2, view="deck")-- reply = await manager._run_agentic_ide_fast_path(- "spawn a background agent to review the wake path"- )-- assert reply is None- assert not any(_typed(registry).values())diff --git a/tests/unit/ui/test_wallpaper_routes.py b/tests/unit/ui/test_wallpaper_routes.pyindex f464c5bf4e..655cbcef17 100644--- a/tests/unit/ui/test_wallpaper_routes.py+++ b/tests/unit/ui/test_wallpaper_routes.py@@ -11,6 +11,9 @@ Contract (see jarvis/ui/web/wallpapers.py):- GET /api/wallpapers/{id}/full -> the original 1920x1080 artwork.- Unknown or malformed ids -> 404, including ids that try to walk outof the library directory.+- POST /api/wallpapers/uploads -> store one of the owner's own pictures,+ re-encoded, with a guessed light/dark.+- GET/PATCH/DELETE .../uploads[/{id}] -> list them, correct the guess, remove one.The library itself is content living under a git-ignored ``data/`` directory,so these tests build a miniature one in a tmp_path rather than depending on the@@ -19,6 +22,7 @@ five hundred generated files being present.from __future__ import annotations+import ioimport jsonfrom pathlib import Path@@ -27,8 +31,11 @@ from fastapi import FastAPIfrom fastapi.testclient import TestClientfrom jarvis.ui.web.wallpapers import (+ MAX_UPLOAD_BYTES,THUMB_WIDTH,+ UPLOAD_MAX_WIDTH,WallpaperLibrary,+ WallpaperUploads,register_wallpaper_routes,)@@ -85,12 +92,39 @@ def library(tmp_path: Path) -> WallpaperLibrary:@pytest.fixture()-def client(library: WallpaperLibrary) -> TestClient:+def uploads(tmp_path: Path) -> WallpaperUploads:+ """An empty upload store, well away from the maintainer's real one."""+ return WallpaperUploads(tmp_path / "jarvis-wallpaper-uploads")+++def client(library: WallpaperLibrary, uploads: WallpaperUploads) -> TestClient:app = FastAPI()- register_wallpaper_routes(app, library)+ register_wallpaper_routes(app, library, uploads)return TestClient(app)+def _image_bytes(+ color: tuple[int, int, int],+ size: tuple[int, int] = (1920, 1080),+ fmt: str = "PNG",+) -> bytes:+ from PIL import Image++ buffer = io.BytesIO()+ Image.new("RGB", size, color).save(buffer, fmt)+ return buffer.getvalue()+++def _upload(client: TestClient, data: bytes, name: str = "my holiday_photo.png") -> dict:+ response = client.post(+ "/api/wallpapers/uploads",+ files={"file": (name, data, "image/png")},+ )+ assert response.status_code == 200, response.text+ return response.json()++def test_catalog_lists_every_entry(client: TestClient) -> None:payload = client.get("/api/wallpapers").json()@@ -142,8 +176,6 @@ def test_thumbnail_is_far_smaller_than_the_original(assert original is not Noneassert len(response.content) < original.path.stat().st_size- import io-with Image.open(io.BytesIO(response.content)) as thumb:assert thumb.width == THUMB_WIDTH@@ -179,6 +211,187 @@ def test_unknown_ids_are_refused(client: TestClient, item_id: str) -> None:assert client.get(f"/api/wallpapers/{item_id}/full").status_code == 404+# ----------------------------------------------------------------------+# Uploads — the owner's own pictures.+# ----------------------------------------------------------------------+++def test_upload_is_listed_and_served(client: TestClient) -> None:+ item = _upload(client, _image_bytes((10, 12, 20)))++ listed = client.get("/api/wallpapers/uploads").json()["items"]+ assert [entry["id"] for entry in listed] == [item["id"]]++ full = client.get(f"/api/wallpapers/uploads/{item['id']}/full")+ assert full.status_code == 200+ assert full.headers["content-type"] == "image/webp"+++def test_upload_keeps_the_library_catalog_untouched(client: TestClient) -> None:+ """Two stores, two endpoints: an upload is not a library entry."""+ _upload(client, _image_bytes((10, 12, 20)))++ catalog = client.get("/api/wallpapers").json()++ assert catalog["count"] == 2+ assert all(not item["id"].startswith("u") for item in catalog["items"])+++def test_upload_title_comes_from_the_file_name(client: TestClient) -> None:+ item = _upload(client, _image_bytes((10, 12, 20)), name="sunset_over-the_bay.jpg")++ assert item["title"] == "sunset over the bay"+++def test_upload_without_a_usable_name_still_gets_a_title(client: TestClient) -> None:+ item = _upload(client, _image_bytes((10, 12, 20)), name="___.png")++ assert item["title"] == "Your wallpaper"+++def test_dark_and_light_pictures_are_told_apart(client: TestClient) -> None:+ """The guess is what decides which mode the app switches into."""+ night = _upload(client, _image_bytes((8, 10, 24)))+ noon = _upload(client, _image_bytes((238, 236, 228)))++ assert night["theme"] == "dark"+ assert noon["theme"] == "light"+++def test_the_guess_can_be_corrected(client: TestClient) -> None:+ item = _upload(client, _image_bytes((8, 10, 24)))++ response = client.patch(f"/api/wallpapers/uploads/{item['id']}", json={"theme": "light"})++ assert response.status_code == 200+ assert response.json()["theme"] == "light"+ listed = client.get("/api/wallpapers/uploads").json()["items"]+ assert listed[0]["theme"] == "light"+++def test_a_nonsense_theme_is_refused(client: TestClient) -> None:+ item = _upload(client, _image_bytes((8, 10, 24)))++ response = client.patch(f"/api/wallpapers/uploads/{item['id']}", json={"theme": "sepia"})++ assert response.status_code == 400+++def test_oversized_pictures_are_scaled_down_on_the_way_in(client: TestClient) -> None:+ """A wallpaper never needs more pixels than the largest desktop."""+ from PIL import Image++ item = _upload(client, _image_bytes((30, 40, 50), size=(6000, 3000)))++ full = client.get(f"/api/wallpapers/uploads/{item['id']}/full")+ with Image.open(io.BytesIO(full.content)) as stored:+ assert stored.width == UPLOAD_MAX_WIDTH+++def test_upload_thumbnail_is_derived_and_cached(+ client: TestClient, uploads: WallpaperUploads+) -> None:+ from PIL import Image++ item = _upload(client, _image_bytes((30, 40, 50)))++ response = client.get(f"/api/wallpapers/uploads/{item['id']}/thumb")++ assert response.status_code == 200+ with Image.open(io.BytesIO(response.content)) as thumb:+ assert thumb.width == THUMB_WIDTH+ assert (uploads.root / ".thumbs" / f"{item['id']}.webp").is_file()+++def test_a_file_that_is_not_an_image_is_refused(client: TestClient) -> None:+ """A forged content type must not put arbitrary bytes on disk."""+ response = client.post(+ "/api/wallpapers/uploads",+ files={"file": ("payload.png", b"MZ\x90\x00 not a picture", "image/png")},+ )++ assert response.status_code == 400+ assert client.get("/api/wallpapers/uploads").json()["items"] == []+++def test_an_empty_file_is_refused(client: TestClient) -> None:+ response = client.post(+ "/api/wallpapers/uploads", files={"file": ("empty.png", b"", "image/png")}+ )++ assert response.status_code == 400+++def test_an_oversized_file_is_refused_rather_than_absorbed(client: TestClient) -> None:+ response = client.post(+ "/api/wallpapers/uploads",+ files={"file": ("huge.png", b"\x00" * (MAX_UPLOAD_BYTES + 1), "image/png")},+ )++ assert response.status_code == 413+++def test_deleting_an_upload_removes_every_trace(+ client: TestClient, uploads: WallpaperUploads+) -> None:+ item = _upload(client, _image_bytes((30, 40, 50)))+ client.get(f"/api/wallpapers/uploads/{item['id']}/thumb")++ assert client.delete(f"/api/wallpapers/uploads/{item['id']}").status_code == 200++ assert client.get("/api/wallpapers/uploads").json()["items"] == []+ assert client.get(f"/api/wallpapers/uploads/{item['id']}/full").status_code == 404+ assert list(uploads.root.glob(f"{item['id']}*")) == []+ assert not (uploads.root / ".thumbs" / f"{item['id']}.webp").exists()+++def test_deleting_something_that_is_not_there_is_a_404(client: TestClient) -> None:+ assert client.delete("/api/wallpapers/uploads/u0123456789abcdef").status_code == 404+++ "upload_id",+ ["../../../etc/passwd", "01-cinematic-photoreal-01", "u00", "uZZZZZZZZZZZZZZZZ"],+)+def test_malformed_upload_ids_are_refused(client: TestClient, upload_id: str) -> None:+ assert client.get(f"/api/wallpapers/uploads/{upload_id}/full").status_code == 404+ assert client.delete(f"/api/wallpapers/uploads/{upload_id}").status_code == 404+++def test_uploads_are_listed_newest_first(client: TestClient) -> None:+ """The picture just added is the one being looked for."""+ first = _upload(client, _image_bytes((10, 10, 10)), name="one.png")+ second = _upload(client, _image_bytes((20, 20, 20)), name="two.png")++ listed = client.get("/api/wallpapers/uploads").json()["items"]++ assert [entry["id"] for entry in listed] == [second["id"], first["id"]]+++def test_an_upload_survives_a_lost_sidecar(client: TestClient, uploads: WallpaperUploads) -> None:+ """The picture is the irreplaceable half; a missing title must not hide it."""+ item = _upload(client, _image_bytes((10, 10, 10)))+ (uploads.root / f"{item['id']}.json").unlink()++ listed = client.get("/api/wallpapers/uploads").json()["items"]++ assert [entry["id"] for entry in listed] == [item["id"]]+ assert listed[0]["title"] == "Your wallpaper"+++def test_a_missing_upload_directory_is_an_empty_list_not_an_error(+ tmp_path: Path,+) -> None:+ app = FastAPI()+ register_wallpaper_routes(+ app,+ WallpaperLibrary(tmp_path / "nothing-here"),+ WallpaperUploads(tmp_path / "no-uploads-either"),+ )++ assert TestClient(app).get("/api/wallpapers/uploads").json() == {"items": []}++def test_manifest_paths_pointing_outside_the_library_are_dropped(tmp_path: Path,) -> None: