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
chore(repo): restore the files 44f43df8e committed from a stale index
rubenluetke10-beep8b504fc388c3
diff --git a/docs/architecture-overview.md b/docs/architecture-overview.mdindex fb807012a9..24d7127ed5 100644--- a/docs/architecture-overview.md+++ b/docs/architecture-overview.md@@ -120,7 +120,7 @@ Ack-Brain (`jarvis/brain/ack_brain/`) emits a sub-second butler-style preamble b**Persona / custom system prompt:** the live persona comes from `jarvis/brain/persona_loader.py`. `base_persona_prompt()` returns an editable override (`data/custom_system_prompt.md`, written atomically via the Settings UI / `settings_routes.py`) when present, else the packaged `JARVIS_PERSONA.md`. `load_effective_persona_prompt()` is what the brains call: the base **plus the active mode's character block**. Edits apply on the **next turn** (no restart); `invalidate_cache()` clears the in-process cache. Never hardcode the persona string elsewhere.-### The typed chat: two surfaces, three runners (2026-08-25)+### The typed chat: two surfaces, three runners (2026-08-26)`jarvis/agent_chat/` serves two chats that look the same and mean differentthings — every session carries a `surface` (`store.SURFACES`, mirrored in@@ -128,9 +128,21 @@ Pydantic and TypeScript, parity-tested):| Surface | What a typed turn is | Runner per seat | Permission ladder ||---|---|---|---|-| `"jarvis"` — the front page's Chat section | **Jarvis with a keyboard**: the same assistant the microphone talks to (soul, persona, profile, identity card, memory, wiki, skills, ALL tools through the risk tiers) on the model the composer picked for THIS chat | API-key / local rows → `runner_brain` (`BrainManager.generate` + a `TurnOverride`); subscription CLIs → `runner_cli` with the Jarvis identity | ONE ladder in Claude Code's words — `ask` / `accept-edits` / `bypass` + `plan` — folded onto each CLI's own spelling |+| `"jarvis"` — the front page's Chat section | **Jarvis with a keyboard**: the same assistant the microphone talks to (soul, persona, profile, identity card, memory, wiki, skills, ALL tools through the risk tiers) on the model the composer picked for THIS chat | EVERY seat → `runner_brain` (`BrainManager.generate` + a `TurnOverride`). No CLI seats at all (`SurfaceKit.cli_seats = False`) | ONE ladder in Claude Code's words — `ask` / `accept-edits` / `bypass` + `plan` || `"agent"` — the Agentic IDE's chat mode | a plain coding-agent session in a folder | `runner_api` (tool loop) or a plain `runner_cli` | the vendor's own ladder |+**Which providers a surface may be seated on** is `catalog.rows_for(surface)`,+and it gates on the capability, never on a name (AP-21): a surface with CLI+seats gets every row; one without gets only the rows a brain plugin drives+(`runner_api.BRAIN_BY_PROVIDER`). The front page is the second case+(maintainer, 2026-08-26) — one pipeline, one place the model is picked, one+usage ledger, and a model change is a `TurnOverride` rather than a different+vendor process. Its `claude-api` row therefore always resolves to the+Anthropic endpoint, Claude Code installed or not. Chats seated on a CLI+before the change move to the API row of the same brand once per database+(`service._retire_cli_seats`, marked by SQLite's `user_version`), keeping+their transcript and dropping only a model id the endpoint cannot take.+**The per-turn override contract (binding).** A chat's pick of provider /model / effort NEVER moves the live brain: `BrainManager.generate(turn_override=…)`carries it in a ContextVar (`jarvis/brain/turn_override.py`), read in exactly@@ -159,9 +171,14 @@ handler) turns the stance into a decision: `ask` cards everything consequential,gate itself; `plan` offers reading hands only. The blacklist is never reachedfrom here in any stance.-**A CLI seat as Jarvis.** A subscription CLI keeps its own loop (that is what-the subscription pays for; only the vendor's official binary spends it) but-runs with Jarvis' head: `BrainManager.render_surface_prompt` renders the+**A CLI seat as Jarvis** (built, currently unreachable). No surface seats a+CLI as Jarvis any more — the front page dropped its CLI seats on 2026-08-26+and the IDE's chat runs a plain coding agent — so `run_cli_turn(identity=…)`+is False on every turn today. The machinery stays wired to the kit+(`kit.brain_runner and kit.cli_seats`) rather than to a surface name, so a+surface that wants both works without a rebuild. How it works, when reached:+a subscription CLI keeps its own loop (that is what the subscription pays+for; only the vendor's official binary spends it) but runs with Jarvis' head: `BrainManager.render_surface_prompt` renders thevoice turn's prompt layers read-only, `jarvis_harness.build_identity` adds thechat's transcript on a fresh conversation and the surface addendum, and eachCLI takes it the way it can (Claude Code: `--append-system-prompt-file`; Codexdiff --git a/jarvis/agent_chat/attachments.py b/jarvis/agent_chat/attachments.pynew file mode 100644index 0000000000..bc84f8a635--- /dev/null+++ b/jarvis/agent_chat/attachments.py@@ -0,0 +1,221 @@+"""Files dropped, pasted or picked into a chat composer.++The typed chats — the front page and the Agentic IDE's chat mode — take a+sentence and nothing else. Someone with a screenshot of a broken layout has to+describe it in words, which is the one thing a screenshot exists to avoid. The+IDE's TERMINAL panes have taken dropped files since 2026-08 (``drops`` ++``drop_analysis``); the chats were never wired to any of it, so a drop landed+on a bare ``<textarea>`` and the browser navigated away to the file.++This module is that wiring, and it is deliberately thin: everything hard was+already solved one layer down and is reused rather than rewritten.++* :mod:`jarvis.agentic_ide.drops` writes the bytes into the chat's own working+ directory (``.jarvis/drops``, self-ignoring) and hands back a reference the+ agent can open.+* :mod:`jarvis.agentic_ide.drop_analysis` has a vision-capable model describe+ an image and extracts a document's text.+* :func:`jarvis.agentic_ide.prompt_blueprint.attachment_block` lays the result+ out for whatever answers the turn.++Why the description travels with the message rather than the file alone: a+chat can be answered by a coding CLI, by a provider's own API loop, or by+Jarvis' brain, and several of those cannot open an image at all. Sending only+a path means the person drops a picture, types "what is wrong here", and the+model receives a filename and a pronoun. The description is what makes the+gesture work on every seat instead of the maintainer's.++Import-light on purpose (AP-26): the heavy halves are imported inside the+functions, so a boot that never sees an attachment pays nothing for this.+"""++from __future__ import annotations++import asyncio+import logging+from pathlib import Path+from typing import Any++log = logging.getLogger(__name__)++__all__ = [+ "MAX_TOTAL_BYTES",+ "AttachmentError",+ "compose",+ "ingest",+ "to_analysis",+]++#: Total cap for one attach gesture, shared with the terminal drop path so the+#: two surfaces cannot disagree about what is too large.+MAX_TOTAL_BYTES = 100 * 1024 * 1024+++class AttachmentError(RuntimeError):+ """The attach carried nothing usable, or the copies could not be written."""+++async def ingest(+ cwd: str | Path,+ *,+ paths: list[str] | None = None,+ uploads: list[tuple[str, bytes]] | None = None,+ provider: str = "",+) -> list[Any]:+ """Store what was dropped in ``cwd`` and read what is in it.++ ``paths`` are real locations the browser managed to hand over (an Explorer+ or Finder drag usually carries them, and inside the desktop shell the host+ resolves them for every drop). ``uploads`` are ``(name, bytes)`` for+ everything with no path at all — a pasted screenshot, an image dragged off+ a web page.++ A path already inside ``cwd`` is referenced where it lies; anything else is+ copied in, because an agent's reach outside its working directory is+ neither guaranteed nor silent.++ Returns ``drop_analysis.DropAnalysis`` entries — one per file, in the order+ they arrived. Raises :class:`AttachmentError` when nothing usable was+ carried; an analysis that fails costs the description and nothing else, so+ the file still travels.+ """+ from jarvis.agentic_ide import drops++ folder = Path(cwd).expanduser() # noqa: ASYNC240 — string work; the stat below is threaded+ if not await asyncio.to_thread(folder.is_dir):+ raise AttachmentError(f"Not a folder: {folder}")++ references: list[str] = []+ # (name, bytes, reference) for everything attached — the reference travels+ # with the bytes so a description can never drift onto another file.+ readable: list[tuple[str, bytes, str]] = []+ to_copy: list[tuple[str, bytes]] = []++ for raw in paths or []:+ candidate = (raw or "").strip()+ if not candidate:+ continue+ inside = drops.within_workspace(candidate, folder)+ if inside is not None:+ reference = drops.reference(inside, agent=provider)+ references.append(reference)+ try:+ body = await asyncio.to_thread((folder / inside).read_bytes)+ except OSError as exc:+ # The reference still ships; the file simply goes undescribed.+ log.info("chat attach: %r not readable for analysis (%s)", inside, exc)+ else:+ readable.append((Path(inside).name, body, reference))+ continue+ # expanduser() is string work; the read itself goes to a worker thread+ # (a dropped file may live on a slow network share).+ resolved = Path(candidate).expanduser() # noqa: ASYNC240+ try:+ data = await asyncio.to_thread(resolved.read_bytes)+ except OSError as exc:+ log.info("chat attach: unreadable dropped path %r (%s)", candidate, exc)+ continue+ to_copy.append((resolved.name, data))++ total = sum(len(data) for _name, data in to_copy)+ for name, data in uploads or []:+ total += len(data)+ if total > MAX_TOTAL_BYTES:+ megabytes = MAX_TOTAL_BYTES // (1024 * 1024)+ raise AttachmentError(f"That attachment is too large (max {megabytes} MB in total).")+ if data:+ to_copy.append((name or "file", data))++ # ``store`` skips empty entries silently, so they are dropped HERE instead —+ # that keeps ``stored[i]`` paired with ``to_copy[i]`` positionally.+ to_copy = [(name, data) for name, data in to_copy if data]++ if to_copy:+ try:+ stored = await asyncio.to_thread(drops.store, folder, to_copy)+ except drops.DropError as exc:+ raise AttachmentError(str(exc)) from exc+ for item, (_original, data) in zip(stored, to_copy, strict=True):+ reference = drops.reference(item.relative_path, agent=provider)+ references.append(reference)+ readable.append((item.name, data, reference))++ if not references:+ raise AttachmentError("That attachment carried nothing this chat could use.")++ return await _analyze(readable)+++async def _analyze(readable: list[tuple[str, bytes, str]]) -> list[Any]:+ """Describe images and extract documents. Never raises — this is a bonus.++ The files are already stored and referenced by the time this runs, so a+ provider outage here must cost the description and nothing more.+ """+ import mimetypes++ from jarvis.agentic_ide import drop_analysis+ from jarvis.brain.drop_context import DroppedItem++ if not readable:+ return []+ items = [+ (+ DroppedItem(+ name=name,+ mime=mimetypes.guess_type(name)[0] or "application/octet-stream",+ data=data,+ ),+ reference,+ )+ for name, data, reference in readable+ ]+ try:+ return await drop_analysis.analyze(items)+ except Exception as exc: # noqa: BLE001 — the attach itself already succeeded+ log.info("chat attach: analysis failed (%s)", exc)+ return []+++def to_analysis(raw: list[dict[str, Any]] | None) -> list[Any]:+ """Rebuild the analyses a composer hands back on the wire.++ The client holds what :func:`ingest` returned while the person finishes+ typing, then posts it with the message. It is request data, so nothing here+ may assume a shape: a malformed entry becomes an empty-detail attachment+ rather than a 500 on a message somebody is waiting to send.+ """+ from jarvis.agentic_ide import drop_analysis++ out: list[Any] = []+ for entry in raw or []:+ if not isinstance(entry, dict):+ continue+ item = drop_analysis.DropAnalysis.from_dict(entry)+ if item.name:+ out.append(item)+ return out+++def compose(text: str, attachments: list[Any] | None) -> str:+ """The message as the turn will actually receive it.++ The person's sentence first, then what was attached — the sentence is the+ task, the files are context for it, and a model reads the instruction+ better when it is not buried under a page of extracted PDF.++ Returns ``text`` unchanged when nothing is attached, so an ordinary message+ is never reshaped by a feature it did not use.+ """+ from jarvis.agentic_ide.prompt_blueprint import attachment_block++ said = (text or "").strip()+ block = attachment_block(list(attachments or []))+ if not block:+ return said+ lead = (+ "Files the user attached to this message are below. Their contents are "+ "given in full because the file itself may not be openable from here — "+ "read them as part of the message."+ )+ return "\n\n".join(part for part in (said, lead, block) if part)diff --git a/jarvis/agent_chat/jarvis_harness.py b/jarvis/agent_chat/jarvis_harness.pyindex cf1a9da8fc..6d23827012 100644--- a/jarvis/agent_chat/jarvis_harness.py+++ b/jarvis/agent_chat/jarvis_harness.py@@ -25,6 +25,12 @@ official binary ever spends the subscription (maintainer, 2026-08-25).This surface is deliberately additive: a CLI that cannot mount MCP servers, anapp whose tool gateway is not up yet, or a brain that has not finished buildingsimply runs with less. Nothing here is allowed to make a turn fail.++Currently unreachable, on purpose. No surface seats a CLI as Jarvis since the+front page's chat went API-only (2026-08-26, ``SurfaceKit.cli_seats``), so+``run_cli_turn(identity=…)`` is False on every turn today. The service asks the+kit — ``brain_runner and cli_seats`` — rather than a surface name, so a surface+that wants both picks this up without a change here. Keep it working."""from __future__ import annotationsdiff --git a/jarvis/agent_chat/runner_brain.py b/jarvis/agent_chat/runner_brain.pyindex 39c7adbabc..482ac4403c 100644--- a/jarvis/agent_chat/runner_brain.py+++ b/jarvis/agent_chat/runner_brain.py@@ -1,11 +1,12 @@"""The Jarvis surface's runner: Jarvis' own brain, driven by text.-This is what the front page's chat runs on for an API-key or local seat. A-typed turn is the same turn a spoken one is — ``BrainManager.generate`` with-its router, its tools, its memory, its wiki and its safety tiers — with the-keyboard in place of the microphone. Nothing here spawns a coding CLI or a-second agent loop; there is one assistant in this app and this is how you-type at it (maintainer, 2026-08-25).+This is what the front page's chat runs on — every seat of it, since that+surface gave up its CLI seats (2026-08-26): a provider API behind a key, or+a server on this machine. A typed turn is the same turn a spoken one is —+``BrainManager.generate`` with its router, its tools, its memory, its wiki+and its safety tiers — with the keyboard in place of the microphone. Nothing+here spawns a coding CLI or a second agent loop; there is one assistant in+this app and this is how you type at it (maintainer, 2026-08-25).What the composer's pick changes is which model Jarvis thinks with FOR THISCHAT, and how hard: provider, model and effort travel as adiff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.pyindex 273a039657..e2c53689fa 100644--- a/jarvis/agent_chat/service.py+++ b/jarvis/agent_chat/service.py@@ -25,17 +25,23 @@ import shutilimport uuidfrom collections.abc import Callablefrom pathlib import Path-from typing import Any+from typing import Any, Final+from jarvis.agent_chat import attachments as chat_attachmentsfrom jarvis.agent_chat.approval_bridge import ChatApprovalBridge-from jarvis.agent_chat.catalog import provider_row+from jarvis.agent_chat.catalog import PROVIDER_ROWS, api_seat, offers, provider_rowfrom jarvis.agent_chat.effort import normalize_effortfrom jarvis.agent_chat.events import make_eventfrom jarvis.agent_chat.permissions import ladder_key, normalize_permissionfrom jarvis.agent_chat.runner_api import TurnHandle, run_api_turn, supports_api_runnerfrom jarvis.agent_chat.runner_brain import run_brain_turnfrom jarvis.agent_chat.runner_cli import run_cli_turn, supports_cli_runner-from jarvis.agent_chat.store import DEFAULT_SURFACE, AgentChatSession, AgentChatStore+from jarvis.agent_chat.store import (+ DEFAULT_SURFACE,+ SURFACES,+ AgentChatSession,+ AgentChatStore,+)from jarvis.agent_chat.surface_kits import kit_forlog = logging.getLogger(__name__)@@ -65,20 +71,21 @@ def resolve_runner(provider: str, *, surface: str = "agent") -> str:On the Jarvis surface the API path is Jarvis' own brain (``brain``): thesame set of providers, driven by ``BrainManager.generate`` instead of the- coding agent's tool loop. The CLI seats keep their CLI runner there — a- subscription only pays for the vendor's own loop — and run as Jarvis- (see :mod:`jarvis.agent_chat.jarvis_harness`).+ coding agent's tool loop. That surface has no CLI seats at all+ (``SurfaceKit.cli_seats``, maintainer 2026-08-26), so a vendor CLI never+ answers there — not even the dual Claude row, which runs on the Anthropic+ API behind its key like every other seat."""kit = kit_for(surface)api_runner = "brain" if kit.brain_runner else "api"row = provider_row(provider)- if kit.brain_only:- # The surface's tools only exist inside the brain loop: a CLI seat- # (agy-cli, codex-cli, claude-cli) would run the vendor's coding agent- # without them, so any provider the brain knows is driven by the brain.- return "brain" if row is not None or supports_api_runner(provider) else "unknown"if row is None:return api_runner if supports_api_runner(provider) else "unknown"+ if not kit.cli_seats:+ # No vendor process here: the provider's own API answers, or nothing+ # does. ``rows_for`` keeps the picker to the same set, so "unknown"+ # is only reachable through a stale session or a hand-made request.+ return api_runner if supports_api_runner(row.id) else "unknown"if row.id == "claude-api":return "claude-cli" if _claude_cli_installed() else api_runnerif row.runner == "api":@@ -86,6 +93,13 @@ def resolve_runner(provider: str, *, surface: str = "agent") -> str:return row.runner+#: ``AgentChatStore.data_version`` after the front page's chat gave up its+#: CLI seats (2026-08-26) and its sessions moved to the API row of the same+#: brand. Bump — and add a branch in ``_retire_cli_seats``' caller — only for+#: another migration that rewrites what a person picked.+_CLI_SEATS_RETIRED: Final[int] = 1++class _Running:__slots__ = ("task", "cancel", "turn_id")@@ -128,11 +142,71 @@ class AgentChatService:# no word for "auto" and flipping to bypass would silence every later# card, a mail send included.self._always_allowed: dict[str, set[str]] = {}+ self._retire_cli_seats()++ def _retire_cli_seats(self) -> None:+ """Move chats off a CLI seat their surface no longer offers.++ The front page's chat runs on provider APIs only (``cli_seats``).+ A session opened before that — a Codex or Antigravity seat, or a+ Claude one carrying a Claude Code model id — would otherwise show a+ provider its own picker does not list, or send the endpoint a model+ name only the CLI understands. It moves to the API row of the same+ brand instead (``catalog.api_seat``), keeping its title, its folder,+ its permission mode and its whole transcript.++ Once per database, not once per boot (``data_version``): it rewrites+ a pick, and a pick made afterwards — a live model id the curated+ list does not carry — must survive every later start untouched.+ """+ if self.store.data_version() >= _CLI_SEATS_RETIRED:+ return+ for surface in SURFACES:+ if kit_for(surface).cli_seats:+ continue+ for row in PROVIDER_ROWS:+ # Rows that were always an API seat have nothing to migrate.+ if row.runner == "api":+ continue+ for session in self.store.sessions_on(surface, row.id):+ provider, model = api_seat(session.provider, session.model)+ if (provider, model) == (session.provider, session.model):+ continue+ self.store.reseat_session(session.session_id, provider=provider, model=model)+ log.info(+ "agent chat: %s left the %s CLI seat for %s %s",+ session.session_id,+ row.id,+ provider,+ f"({model})" if model else "(its default model)",+ )+ self.store.set_data_version(_CLI_SEATS_RETIRED)# ------------------------------------------------------------ sessions- def default_cwd(self) -> str:- return self._default_cwd()+ def default_cwd(self, surface: str = DEFAULT_SURFACE) -> str:+ """Where a new ``surface`` session starts when nobody picked a folder.++ A surface that brings its own workspace (the Jarvis chat) gets that+ directory, created on first use. One that cannot be created — a+ read-only install, no writable app data — falls back to the service+ default rather than handing a chat a folder it cannot work in.+ """+ workspace = kit_for(surface).workspace_dir+ if workspace is None:+ return self._default_cwd()+ folder = workspace()+ try:+ folder.mkdir(parents=True, exist_ok=True)+ except OSError as exc:+ log.warning(+ "chat workspace %s could not be created (%s) — starting in the "+ "fallback folder instead",+ folder,+ exc,+ )+ return self._default_cwd()+ return str(folder)def _bridge_for(self, bus: Any | None) -> ChatApprovalBridge | None:"""The approval bridge, built on the first Jarvis turn that has a bus."""@@ -156,6 +230,11 @@ class AgentChatService:row = provider_row(provider)if row is None and not supports_api_runner(provider):raise ValueError(f"Unknown agent-chat provider: {provider!r}")+ if row is not None and not offers(surface, provider):+ raise ValueError(+ f"Provider {provider!r} is not offered on the {surface!r} chat. "+ "That chat runs on a provider API behind a key, not on a vendor CLI."+ )ladder = ladder_key(surface, resolve_runner(provider, surface=surface))permission_mode = normalize_permission(ladder, permission_mode)eff = normalize_effort(provider, effort) if effort is not None else ""@@ -167,7 +246,7 @@ class AgentChatService:provider=provider,model=model or (row.default_model if row else ""),effort=eff,- cwd=cwd or self.default_cwd(),+ cwd=cwd or self.default_cwd(surface),permission_mode=permission_mode,title=title,surface=surface,@@ -208,16 +287,37 @@ class AgentChatService:# ---------------------------------------------------------------- turns- async def send(self, session_id: str, text: str) -> str:- """Persist the person's message and start the turn. Returns turn_id."""+ async def send(+ self,+ session_id: str,+ text: str,+ attachments: list[dict[str, Any]] | None = None,+ ) -> str:+ """Persist the person's message and start the turn. Returns turn_id.++ ``attachments`` are what the composer already had read for this message+ (``jarvis.agent_chat.attachments``): a described screenshot, an+ extracted document. Their contents go INTO the message the turn+ receives, because a chat may be answered by a coding CLI or a+ text-only model that cannot open the file itself.++ A message with attachments may carry no sentence at all — dropping a+ picture and pressing Enter is a complete gesture — but an empty message+ with nothing attached is still refused.+ """session = self.store.get_session(session_id)if session is None:raise NoSuchSession(session_id)if self.is_running(session_id):raise SessionBusy(session_id)+ kit = kit_for(session.surface)text = text.strip()- if not text:+ attached = chat_attachments.to_analysis(attachments)+ if not text and not attached:raise ValueError("empty message")+ # What the turn receives; ``text`` stays what the person typed so the+ # timeline shows their sentence rather than a page of extracted PDF.+ prompt = chat_attachments.compose(text, attached)turn_id = uuid.uuid4().hexcancel = asyncio.Event()@@ -225,7 +325,37 @@ class AgentChatService:self._running[session_id] = runhistory = self.store.list_events(session_id)- await self._emit(session_id, make_event("user_message", {"text": text}))+ await self._emit(+ session_id,+ make_event(+ "user_message",+ {+ # The full prompt: this is what was actually sent, and the+ # API runner rebuilds the conversation from these events —+ # storing only the sentence would lose the picture on the+ # NEXT turn (runner_api.messages_from_events).+ "text": prompt,+ # What the person typed, when it differs from the prompt.+ # Absent on an ordinary message, so nothing changes there.+ **({"typed": text} if attached else {}),+ **(+ {+ "attachments": [+ {+ "name": item.name,+ "kind": item.kind,+ "described_by": item.described_by,+ "note": item.note,+ }+ for item in attached+ ]+ }+ if attached+ else {}+ ),+ },+ ),+ )runner = resolve_runner(session.provider, surface=session.surface)await self._emit(session_id,@@ -235,13 +365,12 @@ class AgentChatService:"turn_id": turn_id,"provider": session.provider,"model": session.model,- # The effort the turn RUNS with: a surface may ask for more- # than the session's own pick (the setup helper does), and- # the timeline must not report the stale one.- "effort": normalize_effort(- session.provider,- kit_for(session.surface).effort or session.effort,- ),+ # The effort the turn RUNS with. It is the session's own+ # pick: no surface overrides it any more (the kit's+ # `effort` went with the setup helper), so reading one off+ # the kit would only be a way to raise an AttributeError+ # on every turn.+ "effort": normalize_effort(session.provider, session.effort),"runner": runner,"surface": session.surface,},@@ -261,7 +390,7 @@ class AgentChatService:assistant_name=self._assistant_name(),bus=bus,surface=session.surface,- stance=session.permission_mode if kit_for(session.surface).uses_stance else "",+ stance=session.permission_mode if kit.uses_stance else "",)async def _body() -> None:@@ -275,12 +404,20 @@ class AgentChatService:always_allowed=self.always_allowed(session_id),)elif supports_cli_runner(runner):+ # A CLI runs AS Jarvis — its own tools over MCP, its calls+ # answered by the chat's approval card — only where the+ # surface both is Jarvis and seats a CLI at all. The front+ # page is the first and the second is now false there, so+ # today this is every CLI turn running as a plain coding+ # agent. Asked of the kit rather than the surface name, so+ # a surface that combines the two keeps working.+ as_jarvis = kit.brain_runner and kit.cli_seatsvendor = await run_cli_turn(handle,text,runner,- identity=(session.surface == "jarvis"),- bridge=self._bridge_for(bus) if session.surface == "jarvis" else None,+ identity=as_jarvis,+ bridge=self._bridge_for(bus) if as_jarvis else None,always_allowed=self.always_allowed(session_id),)if vendor and vendor != session.vendor_session:diff --git a/jarvis/agentic_ide/folders.py b/jarvis/agentic_ide/folders.pyindex ab93404f0e..67b7a8ebc9 100644--- a/jarvis/agentic_ide/folders.py+++ b/jarvis/agentic_ide/folders.py@@ -429,7 +429,14 @@ def search_folders(if budget <= 0:breakname = item.name- if name in _SKIP_DIRS or _is_hidden(name):+ if name in _SKIP_DIRS:+ continue+ # Hidden folders are matched only when the query itself+ # starts with a dot (".claude", ".config") — that is the+ # one time a person means one — and are never walked into:+ # ".cache" alone can hold more entries than the budget.+ hidden = _is_hidden(name)+ if hidden and not needle.startswith("."):continuetry:if not item.is_dir(follow_symlinks=False):@@ -455,7 +462,7 @@ def search_folders(),))- if depth < max_depth:+ if depth < max_depth and not hidden:queue.append((child, depth + 1))except (PermissionError, OSError):continue@@ -464,6 +471,50 @@ def search_folders(return [entry for _t, _k, _n, entry in hits[:limit]]+def create_folder(parent: str | Path | None, name: str) -> tuple[FolderEntry | None, str | None]:+ """Make one new folder called ``name`` inside ``parent``.++ Returns ``(entry, error_message)``. Without a parent the folder goes into+ the home directory — the one place that exists on every machine.++ One segment only: a name carrying a separator would silently create a tree+ the person never saw, so it is refused rather than honoured. The parent must+ already exist for the same reason. A folder that is already there is handed+ back as it is — the person wanted that folder, and it now exists; whether+ it was made just now is not something they need to be told twice.+ """+ cleaned = name.strip()+ if not cleaned or cleaned in {".", ".."}:+ return None, "Give the new folder a name first."+ if any(sep in cleaned for sep in ("/", "\\", "\x00")):+ return None, "A folder name cannot contain slashes. Type just the name."++ base = Path(parent).expanduser() if parent else Path.home()+ try:+ if not base.is_dir():+ return None, (f"There is no folder called {base}, so nothing can be created inside it.")+ except OSError as exc:+ return None, f"Could not open {base}: {exc}"++ target = base / cleaned+ try:+ if target.is_dir():+ is_project, is_repo = _looks_like_project(target)+ return (+ FolderEntry(name=cleaned, path=str(target), is_project=is_project, is_repo=is_repo),+ None,+ )+ if target.exists():+ return None, f"{target} already exists and is a file, not a folder."+ target.mkdir()+ except PermissionError:+ return None, f"Jarvis is not allowed to create folders inside {base}."+ except OSError as exc:+ return None, f"Could not create {target}: {exc}"++ return FolderEntry(name=cleaned, path=str(target), is_project=False, is_repo=False), None++def _git_branch(root: Path) -> str | None:"""Current branch from ``.git/HEAD`` — no subprocess, no git required."""head = root / ".git" / "HEAD"@@ -585,6 +636,7 @@ __all__ = ["ProjectProfile","WorkspaceEntry","WorkspaceListing",+ "create_folder","list_dir","list_workspace_dir","probe_project",diff --git a/jarvis/brain/turn_override.py b/jarvis/brain/turn_override.pyindex ca281de54d..ad7811a3e0 100644--- a/jarvis/brain/turn_override.py+++ b/jarvis/brain/turn_override.py@@ -103,8 +103,8 @@ class TurnOverride:``system_extra``A per-turn addendum to the system prompt, appended after themanager's own ``_system_prompt_extra``. Empty leaves the prompt- byte-identical; a surface with its own briefing (the local-models- setup assistant) sets it for its turns only.+ byte-identical; a surface with its own briefing sets it for its+ turns only."""provider: strdiff --git a/jarvis/local_models/__init__.py b/jarvis/local_models/__init__.pyindex 5755fb6826..f93de01baa 100644--- a/jarvis/local_models/__init__.py+++ b/jarvis/local_models/__init__.py@@ -1,10 +1,9 @@-"""The local-models setup assistant: test runner, benchmarks, tools and prompt.+"""The local-models self-check: the health monitor behind the section badge.-Everything the "Help me set up" panel of the Local models section runs on,-kept apart from :mod:`jarvis.brain.ollama_*` (which own the server, the-inventory and the roles) and from :mod:`jarvis.agent_chat` (which owns the-chat surface). Nothing here runs at import time (AP-26); every module-imports its heavy neighbours lazily inside the function that needs them.+Kept apart from :mod:`jarvis.brain.ollama_*` (which own the server, the+inventory and the roles). Nothing here runs at import time (AP-26); the+module imports its heavy neighbours lazily inside the function that needs+them."""from __future__ import annotationsdiff --git a/jarvis/mcp/adapter.py b/jarvis/mcp/adapter.pyindex 688f6f4399..48171346e4 100644--- a/jarvis/mcp/adapter.py+++ b/jarvis/mcp/adapter.py@@ -237,6 +237,10 @@ class MCPToolAdapter:)# Flag for the tool-use-loop guard: MCP tools are always action-centric.self.is_action_tool: bool = True+ # Flag for the context-window fit (BrainManager._fit_tools_to_brain):+ # a connected server's tools are the first to leave a surface that+ # does not fit a small local model's window.+ self.is_mcp_tool: bool = Trueself.risk_tier: RiskTier = risk_tier# Register with the global CapabilityRegistry so the voice pathdiff --git a/jarvis/plugins/tool/youtube_music_rest.py b/jarvis/plugins/tool/youtube_music_rest.pyindex da8b60ccb8..575f42692d 100644--- a/jarvis/plugins/tool/youtube_music_rest.py+++ b/jarvis/plugins/tool/youtube_music_rest.py@@ -404,6 +404,10 @@ class YouTubeMusicRestTool:self._player = playerself._playback_mode = playback_mode or _default_playback_modeself._player_confirm_timeout_s = player_confirm_timeout_s+ # Whether the last blind media key this tool sent was a pause — the+ # only state in which a blind "play" is a resume rather than a guess+ # (``_control_blind``).+ self._blind_pause_sent = Falseself._pool = HttpClientPool(transport=transport)# search.list is the rationed call (100/day). Same words → same answer# within a session, so a repeat costs nothing.@@ -558,7 +562,12 @@ class YouTubeMusicRestTool:ok, why = False, str(exc)if ok:try:- return await self._play_in_player(url, started)+ out = await self._play_in_player(url, started)+ # Only a player that reported "playing" counts as done;+ # a cookie wall, a paused page or a page still loading+ # is an attempt the voice must not sell as a result.+ out["verified"] = bool(out.get("playback_confirmed"))+ return outexcept Exception as exc: # noqa: BLE001 — player unusable → browser, and say solog.info("background player unusable, opening the browser: %s", exc)why = f"The background player could not start ({exc})."@@ -823,7 +832,12 @@ class YouTubeMusicRestTool:return {"error": f"The background player did not accept '{verb}': {exc}"}if not ok:return {"error": f"The background player did not accept '{verb}'."}- via_player: dict[str, Any] = {"ok": True, "action": verb, "app": _PLAYER_APP}+ via_player: dict[str, Any] = {+ "ok": True,+ "action": verb,+ "app": _PLAYER_APP,+ "verified": True,+ }if verb in ("next", "previous"):await asyncio.sleep(1.2)after = await self._player_state()@@ -837,27 +851,62 @@ class YouTubeMusicRestTool:cap = await media.capability()if not cap.can_control:return {"error": "This machine cannot control playback. " + (cap.note or "")}- before = await media.now_playing() if cap.can_read else None- if cap.can_read and before is None:+ if not cap.can_read:+ return await self._control_blind(media, verb, cap.note)+ before = await media.now_playing()+ if before is None:return {"error": _NO_SESSION_READ}ok = bool(await getattr(media, verb)())if not ok:return {"error": f"The player did not accept '{verb}'."}- out: dict[str, Any] = {"ok": True, "action": verb}- if before is not None:- out["app"] = before.app- if verb in ("next", "previous"):- await asyncio.sleep(0.8)- after = await media.now_playing()- if after is not None:- out["now"] = after.as_dict()- else:- out["track"] = before.title- out["artist"] = before.artist- elif cap.backend == "media-keys":- out["note"] = "Sent as a media key: this toggles play/pause blindly."+ out: dict[str, Any] = {"ok": True, "action": verb, "verified": True, "app": before.app}+ if verb in ("next", "previous"):+ await asyncio.sleep(0.8)+ after = await media.now_playing()+ if after is not None:+ out["now"] = after.as_dict()+ else:+ out["track"] = before.title+ out["artist"] = before.artistreturn out+ async def _control_blind(self, media: Any, verb: str, note: str | None) -> dict[str, Any]:+ """Steer through media keys on a machine that cannot read its media+ session (Windows without the ``winrt`` extras).++ A media key reaches whatever player the OS considers current and+ reports nothing back, so the result is an ATTEMPT and says so+ (``verified: false``): the realtime bridge turns that into a spoken+ caveat, never a completion. ``play`` is the one verb refused outright+ unless this tool itself paused something the same way — the key is+ the play/pause TOGGLE, so with nothing known to be paused it starts a+ random tab or stops a running one. Live 2026-08-26 19:50: "play some+ cool music" arrived without a title, this path pressed the toggle,+ answered ``ok: true, resumed: true``, and the voice said "I've just+ started some cool music on YouTube Music" over a silent machine.+ """+ if verb == "play" and not self._blind_pause_sent:+ return {+ "error": (+ "Nothing is known to be paused, and this machine cannot see "+ "what is playing, so play was not pressed."+ )+ }+ ok = bool(await getattr(media, verb)())+ if not ok:+ return {"error": f"The player did not accept '{verb}'."}+ self._blind_pause_sent = verb == "pause"+ return {+ "ok": True,+ "action": verb,+ "verified": False,+ "note": (+ "Sent as a media key to whichever player is current; this machine "+ "cannot confirm that anything changed. "+ + (note or "")+ ).strip(),+ }+async def pause(self) -> dict[str, Any]:return await self._control("pause")@@ -927,12 +976,23 @@ class YouTubeMusicRestTool:confirmed = Truebreakout["playback_confirmed"] = confirmed+ out["verified"] = confirmedif not confirmed:out["note"] = ("YouTube Music opened, but the browser has not reported playback ""yet — if it stays silent, press play once (browsers block ""autoplay on a site until it has been used there).")+ else:+ # The page opened; whether it plays is beyond what this machine+ # can see, so the result is an attempt (``verified: false``),+ # never "it is playing".+ out["playback_confirmed"] = False+ out["verified"] = False+ out["note"] = (+ "YouTube Music opened in the browser; this machine cannot confirm "+ "that playback started. " + (cap.note or "")+ ).strip()return outasync def play(diff --git a/jarvis/ui/web/frontend/src/components/LiveCore.tsx b/jarvis/ui/web/frontend/src/components/LiveCore.tsxnew file mode 100644index 0000000000..e947202038--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/LiveCore.tsx@@ -0,0 +1,27 @@+import { cn } from "@/lib/utils";++/**+ * The mark that says work is happening right now: an accent core inside two+ * rings that expand and fade away.+ *+ * It is the ONE live mark the product owns. The agent chat used to spin a+ * borrowed CLI asterisk instead (maintainer, 2026-08-25: "dieses komische+ * Denksymbol"), which read as a foreign glyph next to the home chat's core —+ * two answers to the same question on two screens of the same app.+ *+ * Under reduced motion the rings stand still behind the core, which still+ * reads as "in progress" beside the ticking clock (index.css).+ */+export function LiveCore({ className }: { className?: string }) {+ return (+ <span+ className={cn("relative flex h-2.5 w-2.5 shrink-0", className)}+ aria-hidden+ data-testid="live-core"+ >+ <span className="thinking-ring absolute inline-flex h-full w-full rounded-full bg-primary/50" />+ <span className="thinking-ring absolute inline-flex h-full w-full rounded-full bg-primary/50 [animation-delay:0.9s]" />+ <span className="thinking-core relative inline-flex h-2.5 w-2.5 rounded-full bg-primary" />+ </span>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/ThinkingTrace.tsx b/jarvis/ui/web/frontend/src/components/ThinkingTrace.tsxindex f9aec8b3b7..658a1e65b7 100644--- a/jarvis/ui/web/frontend/src/components/ThinkingTrace.tsx+++ b/jarvis/ui/web/frontend/src/components/ThinkingTrace.tsx@@ -31,6 +31,7 @@ import type {} from "@/lib/thinkingSteps";import { cn } from "@/lib/utils";import { useT } from "@/i18n";+import { LiveCore } from "@/components/LiveCore";/** Rows visible in the live card — older ones collapse into a "+N" row. */const VISIBLE_STEPS = 5;@@ -165,17 +166,6 @@ function StepRail({);}-/** Pulsing gold core in the card header — two expanding rings + glow dot. */-function CoreOrb() {- return (- <span className="relative flex h-2.5 w-2.5 shrink-0" aria-hidden>- <span className="thinking-ring absolute inline-flex h-full w-full rounded-full bg-primary/50" />- <span className="thinking-ring absolute inline-flex h-full w-full rounded-full bg-primary/50 [animation-delay:0.9s]" />- <span className="thinking-core relative inline-flex h-2.5 w-2.5 rounded-full bg-primary" />- </span>- );-}-/** The live card rendered in the transcript while `chatThinking` is true. */export function ThinkingTrace() {const t = useT();@@ -202,7 +192,7 @@ export function ThinkingTrace() {/><div className="relative flex items-center gap-2">- <CoreOrb />+ <LiveCore /><span className="font-mono text-[10px] uppercase tracking-[0.14em] text-primary">{assistantName}</span>diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsxnew file mode 100644index 0000000000..28cd05cc03--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsx@@ -0,0 +1,92 @@+import { FileText, ImageIcon, Loader2, X } from "lucide-react";++import type { ChatAttachment } from "@/lib/agentChatApi";+import { fill, useT } from "@/i18n";++/**+ * The files waiting to go in with the next message.+ *+ * Each chip says what was actually LEARNED from the file, not merely that one+ * is attached. That distinction is the whole feature: "screenshot.png" tells+ * the person nothing about whether the model will be able to see it, while+ * "described" and "not described" are the two outcomes they need to tell apart+ * BEFORE pressing Send — and the second happens for real, on any install whose+ * providers cannot see images.+ *+ * A near-twin of the Agentic IDE's terminal strip+ * (components/agentic/PromptAttachments) and deliberately not shared with it:+ * that one is hardcoded English, which is right inside a terminal composer+ * whose every other label is too, and wrong in a chat that speaks the app's+ * language everywhere else.+ */+export function ChatAttachmentStrip({+ attachments,+ analyzing,+ onRemove,+}: {+ attachments: ChatAttachment[];+ analyzing: number;+ onRemove: (name: string) => void;+}) {+ const t = useT();+ if (attachments.length === 0 && analyzing === 0) return null;+ return (+ <div+ data-testid="chat-attachments"+ className="flex max-h-20 shrink-0 flex-wrap items-center gap-1.5 overflow-y-auto px-1 scrollbar-jarvis"+ >+ {attachments.map((item) => {+ const read = item.described_by !== "none" && item.detail.length > 0;+ return (+ <span+ key={item.name}+ data-testid={`chat-attachment-${item.name}`}+ title={+ read+ ? `${item.detail.slice(0, 400)}${item.detail.length > 400 ? "…" : ""}`+ : item.note || item.name+ }+ className={+ "flex items-center gap-1.5 rounded-md border px-2 py-1 text-[11px] " ++ (read+ ? "border-primary/40 bg-primary/10 text-foreground"+ : "border-border text-muted-foreground")+ }+ >+ {item.kind === "image" ? (+ <ImageIcon className="h-3 w-3 shrink-0" aria-hidden />+ ) : (+ <FileText className="h-3 w-3 shrink-0" aria-hidden />+ )}+ <span className="max-w-[12rem] truncate font-mono">{item.name}</span>+ <span className="shrink-0 text-[10px] text-muted-foreground">+ {read+ ? item.described_by === "vision"+ ? t("agent_chat.attach_described")+ : t("agent_chat.attach_text_read")+ : t("agent_chat.attach_not_described")}+ </span>+ <button+ type="button"+ aria-label={fill(t("agent_chat.attach_remove"), { name: item.name })}+ data-testid={`chat-attachment-remove-${item.name}`}+ onClick={() => onRemove(item.name)}+ className="shrink-0 rounded text-muted-foreground transition-colors hover:text-destructive"+ >+ <X className="h-3 w-3" />+ </button>+ </span>+ );+ })}+ {analyzing > 0 && (+ <span+ data-testid="chat-attachment-working"+ className="flex items-center gap-1.5 rounded-md border border-dashed border-border px-2 py-1 text-[11px] text-muted-foreground"+ >+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden />+ {t("agent_chat.attach_working")}+ </span>+ )}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsxnew file mode 100644index 0000000000..c34c6d8132--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx@@ -0,0 +1,302 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { AgentComposer } from "@/components/agentchat/AgentComposer";+import { AgentChatStoreProvider } from "@/components/agentchat/AgentChatStoreContext";+import { EMPTY_TIMELINE, reduceEvent } from "@/components/agentchat/reduce";+import { useFileDropGuard } from "@/hooks/useFileDropGuard";+import { useAgentChatStore } from "@/store/agentChat";+import { useEventStore } from "@/store/events";+import type { AgentChatCatalog } from "@/lib/agentChatApi";++/**+ * Files in the chat composer — the drop, the paste, and what travels with the+ * message.+ *+ * The two chats (the front page and the Agentic IDE's chat mode) share this+ * one composer, so everything asserted here holds for both. What is under test+ * is that a file reaches the backend at all and that its CONTENTS ride along+ * with the sentence: a chat can be answered by a coding CLI or a text-only+ * model, and a bare path leaves those with a filename and a pronoun.+ */++const CATALOG: AgentChatCatalog = {+ default_cwd: "C:\\work",+ shell: "pwsh",+ providers: [+ {+ id: "claude-api",+ label: "Anthropic Claude",+ family: "claude",+ runner: "claude-cli",+ models_source: "curated",+ curated_models: [{ id: "claude-opus-5", label: "Claude Opus 5" }],+ default_model: "",+ keyless: false,+ native_resume: true,+ effort_levels: ["low", "high"],+ default_effort: "high",+ permission_modes: [{ id: "default", label: "Ask before acting", description: "" }],+ default_permission_mode: "default",+ cli_installed: true,+ },+ ],+};++const ATTACHMENT = {+ name: "shot.png",+ reference: '".jarvis/drops/shot.png"',+ kind: "image" as const,+ detail: "A composer with no attach button.",+ described_by: "vision" as const,+ note: "",+};++function seed(overrides: Record<string, unknown> = {}) {+ useAgentChatStore.setState({+ catalog: CATALOG,+ connections: [{ jarvis: "claude-api", key_set: true, is_active_brain: true }],+ catalogError: null,+ backendOutdated: false,+ liveModels: {},+ sessions: [],+ activeSessionId: "s-1",+ activeSession: null,+ timeline: EMPTY_TIMELINE,+ draft: {+ provider: "claude-api",+ model: "",+ effort: "high",+ permissionMode: "default",+ buildMode: "default",+ cwd: "C:\\work",+ },+ busy: false,+ lastError: null,+ loadCatalog: async () => {},+ loadSessions: async () => {},+ loadModels: async () => {},+ ...overrides,+ });+}++function composer() {+ return render(+ <AgentChatStoreProvider store={useAgentChatStore}>+ <AgentComposer />+ </AgentChatStoreProvider>,+ );+}++/** A DataTransfer stand-in: jsdom's own carries neither files nor types. */+function transfer(files: File[]) {+ return {+ files,+ items: files.map((file) => ({ kind: "file", type: file.type, getAsFile: () => file })),+ types: files.length ? ["Files"] : [],+ getData: () => "",+ dropEffect: "none",+ };+}++describe("chat composer attachments", () => {+ let fetchMock: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ window.localStorage.clear();+ useEventStore.setState({ connected: true, wsWarming: false, assistantName: "Jarvis" });+ seed();+ fetchMock = vi.fn(async (url: string) => {+ if (String(url).includes("/api/agent-chat/attachments")) {+ return {+ ok: true,+ status: 200,+ json: async () => ({ attachments: [ATTACHMENT], cwd: "C:\\work" }),+ } as Response;+ }+ return { ok: true, status: 200, json: async () => ({ turn_id: "t-1" }) } as Response;+ });+ vi.stubGlobal("fetch", fetchMock);+ });++ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ it("takes a pasted image and shows what was read from it", async () => {+ composer();+ const box = document.querySelector("textarea[data-jarvis-chat-input]") as HTMLTextAreaElement;+ const png = new File([new Uint8Array([1, 2, 3])], "image.png", { type: "image/png" });++ await act(async () => {+ fireEvent.paste(box, { clipboardData: transfer([png]) });+ });++ await waitFor(() => expect(screen.getByTestId("chat-attachment-shot.png")).toBeDefined());+ // The chip says the model could SEE it — that is the outcome a person has+ // to be able to read before pressing Send.+ expect(screen.getByTestId("chat-attachment-shot.png").textContent).toContain("described");++ const [url, init] = fetchMock.mock.calls.find(([u]) =>+ String(u).includes("/attachments"),+ ) as [string, RequestInit];+ expect(url).toContain("/api/agent-chat/attachments");+ expect((init.body as FormData).get("session_id")).toBe("s-1");+ });++ it("leaves a pasted TEXT alone so ordinary copy-paste keeps working", async () => {+ composer();+ const box = document.querySelector("textarea[data-jarvis-chat-input]") as HTMLTextAreaElement;++ const event = new Event("paste", { bubbles: true, cancelable: true });+ Object.defineProperty(event, "clipboardData", { value: transfer([]) });+ await act(async () => {+ box.dispatchEvent(event);+ });++ // Not claimed, not prevented: the browser inserts the text itself.+ expect(event.defaultPrevented).toBe(false);+ expect(fetchMock.mock.calls.some(([u]) => String(u).includes("/attachments"))).toBe(false);+ });++ it("takes a dropped file and arms the drop overlay while the drag is over", async () => {+ composer();+ const card = screen.getByTestId("agent-composer");+ const png = new File([new Uint8Array([1])], "shot.png", { type: "image/png" });++ fireEvent.dragEnter(card, { dataTransfer: transfer([png]) });+ expect(screen.getByTestId("composer-drop-overlay")).toBeDefined();++ await act(async () => {+ fireEvent.drop(card, { dataTransfer: transfer([png]) });+ });++ await waitFor(() => expect(screen.getByTestId("chat-attachment-shot.png")).toBeDefined());+ expect(screen.queryByTestId("composer-drop-overlay")).toBeNull();+ });++ it("sends the attachments with the sentence and then holds none", async () => {+ const send = vi.fn(async () => {});+ seed({ send });+ composer();+ const box = document.querySelector("textarea[data-jarvis-chat-input]") as HTMLTextAreaElement;+ const png = new File([new Uint8Array([1])], "image.png", { type: "image/png" });++ await act(async () => {+ fireEvent.paste(box, { clipboardData: transfer([png]) });+ });+ await waitFor(() => expect(screen.getByTestId("chat-attachment-shot.png")).toBeDefined());++ fireEvent.change(box, { target: { value: "what is wrong here" } });+ await act(async () => {+ fireEvent.click(screen.getByTestId("composer-send"));+ });++ expect(send).toHaveBeenCalledWith("what is wrong here", [ATTACHMENT]);+ // Cleared on send: the next message must not silently re-send the picture.+ expect(screen.queryByTestId("chat-attachment-shot.png")).toBeNull();+ });++ it("lets a picture alone be the whole message", async () => {+ const send = vi.fn(async () => {});+ seed({ send });+ composer();+ const box = document.querySelector("textarea[data-jarvis-chat-input]") as HTMLTextAreaElement;+ const png = new File([new Uint8Array([1])], "image.png", { type: "image/png" });++ await act(async () => {+ fireEvent.paste(box, { clipboardData: transfer([png]) });+ });+ await waitFor(() => expect(screen.getByTestId("chat-attachment-shot.png")).toBeDefined());++ await act(async () => {+ fireEvent.click(screen.getByTestId("composer-send"));+ });+ expect(send).toHaveBeenCalledWith("", [ATTACHMENT]);+ });+});++describe("the timeline's receipt for a message that carried files", () => {+ it("shows the sentence that was typed, not the composed prompt", () => {+ const tl = reduceEvent(EMPTY_TIMELINE, {+ seq: 1,+ ts_ms: 10,+ kind: "user_message",+ payload: {+ text: "what is wrong here\n\n<attachment name=\"shot.png\">…</attachment>",+ typed: "what is wrong here",+ attachments: [{ name: "shot.png", kind: "image", described_by: "vision" }],+ },+ });+ const item = tl.items[0];+ expect(item.type).toBe("user");+ if (item.type !== "user") return;+ expect(item.text).toBe("what is wrong here");+ expect(item.attachments).toEqual([+ { name: "shot.png", kind: "image", describedBy: "vision" },+ ]);+ });++ it("leaves an ordinary message exactly as it was", () => {+ const tl = reduceEvent(EMPTY_TIMELINE, {+ seq: 1,+ ts_ms: 10,+ kind: "user_message",+ payload: { text: "hello" },+ });+ const item = tl.items[0];+ if (item.type !== "user") throw new Error("expected a user item");+ expect(item.text).toBe("hello");+ expect(item.attachments).toEqual([]);+ });+});++describe("the app-wide file drop guard", () => {+ function Guarded() {+ useFileDropGuard();+ return <div data-testid="page">nothing here takes files</div>;+ }++ afterEach(cleanup);++ /** A drop event carrying `types`, with `preventDefault` observable. */+ function dropEvent(types: string[]) {+ const event = new Event("drop", { bubbles: true, cancelable: true });+ Object.defineProperty(event, "dataTransfer", {+ value: { ...transfer([]), types },+ });+ const prevent = vi.spyOn(event, "preventDefault");+ return { event, prevent };+ }++ it("swallows a file dropped on chrome that has no drop target", () => {+ render(<Guarded />);+ const { event, prevent } = dropEvent(["Files"]);+ window.dispatchEvent(event);+ // Prevented = the browser will NOT navigate away to the file, which inside+ // the desktop shell would take the whole app with it.+ expect(prevent).toHaveBeenCalled();+ expect(event.defaultPrevented).toBe(true);+ });++ it("keeps its hands off a drop a real target already claimed", () => {+ render(<Guarded />);+ const { event, prevent } = dropEvent(["Files"]);+ event.preventDefault(); // what a drop zone does, below window+ prevent.mockClear();+ window.dispatchEvent(event);+ // The guard saw `defaultPrevented` and stood down — it never touches an+ // event a target is already handling.+ expect(prevent).not.toHaveBeenCalled();+ });++ it("leaves dragged text and links to the browser", () => {+ render(<Guarded />);+ const { event, prevent } = dropEvent(["text/plain"]);+ window.dispatchEvent(event);+ expect(prevent).not.toHaveBeenCalled();+ expect(event.defaultPrevented).toBe(false);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.ts b/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.tsnew file mode 100644index 0000000000..822455c7be--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.ts@@ -0,0 +1,166 @@+/**+ * Files waiting to go in with the next chat message — the drop, the paste and+ * the paperclip.+ *+ * The Agentic IDE's terminal composer has taken files since 2026-08+ * (components/agentic/PromptAttachments). The two CHATS — the front page and+ * the IDE's chat mode, which share one composer — never did: a dropped+ * screenshot landed on a bare `<textarea>`, where the browser's own default is+ * to NAVIGATE to the file, replacing the whole app with the picture. A gesture+ * that works one click away and destroys the view here reads as the app being+ * broken, not as two surfaces with different features (maintainer, 2026-08-24).+ *+ * The pieces are deliberately the terminal path's own — the same drag tracking+ * (`usePaneFileDrag`), the same payload extraction (`paneDrop`), the same+ * desktop-shell path resolution (`waitForNativeDrop`) — so the two surfaces+ * cannot drift into disagreeing about what a drop is. Only the endpoint+ * differs: a chat has no pane to type a path into, so the files are HELD here+ * and travel with the sentence when it is sent.+ */+import { useCallback, useState } from "react";++import {+ extractPaneDrop,+ extractPasteFiles,+ isEmptyPayload,+ nameClipboardFile,+ type PaneDropPayload,+} from "@/components/agentic/paneDrop";+import { usePaneFileDrag } from "@/components/agentic/paneFileDrag";+import { waitForNativeDrop } from "@/lib/nativeDrop";+import { attachChatFiles, type AgentChatSurface, type ChatAttachment } from "@/lib/agentChatApi";++export interface ChatAttachments {+ /** What will travel with the next message. */+ attachments: ChatAttachment[];+ /** How many files are being read right now — 0 when nothing is in flight. */+ analyzing: number;+ /** True while a file drag hovers the composer; drives the drop styling. */+ dragging: boolean;+ /** Spread onto the element that should accept drops. */+ dragHandlers: ReturnType<typeof usePaneFileDrag>["handlers"];+ /** Attach files chosen by hand (the paperclip) or read off the clipboard. */+ attachFiles: (files: File[]) => void;+ /** Put on the text box: claims a pasted IMAGE, never a pasted text. */+ onPaste: (event: React.ClipboardEvent) => void;+ remove: (name: string) => void;+ clear: () => void;+}++/**+ * Hold files for one chat's next message.+ *+ * `onProblem` is where the caller puts its own error line — this hook does not+ * decide how a surface reports things. It DOES decide how bad the news is: a+ * drop that carried nothing usable is a warning about what was dragged, while+ * an attach that threw is an error about the app, and collapsing the two+ * buries the second.+ */+export function useChatAttachments(+ target: {+ sessionId: string | null;+ cwd: string;+ provider: string;+ surface: AgentChatSurface;+ },+ onProblem: (message: string, severity: "warning" | "error") => void,+): ChatAttachments {+ const [attachments, setAttachments] = useState<ChatAttachment[]>([]);+ const [analyzing, setAnalyzing] = useState(0);+ const { sessionId, cwd, provider, surface } = target;++ const attach = useCallback(+ async (payload: PaneDropPayload) => {+ if (isEmptyPayload(payload)) return;+ setAnalyzing((n) => n + 1);+ try {+ const found = await attachChatFiles({+ files: payload.files,+ paths: payload.paths,+ sessionId,+ cwd,+ provider,+ surface,+ });+ if (found.length === 0) {+ onProblem("That drop carried nothing this chat could use.", "warning");+ return;+ }+ // Keyed by name so the same file attached twice is held once — a+ // repeated reference has the model read it again for nothing.+ setAttachments((prev) => [+ ...prev,+ ...found.filter((item) => !prev.some((held) => held.name === item.name)),+ ]);+ } catch (e) {+ onProblem((e as Error).message, "error");+ } finally {+ setAnalyzing((n) => Math.max(0, n - 1));+ }+ },+ [sessionId, cwd, provider, surface, onProblem],+ );++ const { dragging, handlers: dragHandlers } = usePaneFileDrag(+ useCallback(+ (dt: DataTransfer) => {+ // Both reads happen BEFORE any await, and they have to: a DataTransfer+ // empties the moment this handler returns, and the desktop shell only+ // answers a listener that was already in place when the drop happened.+ const payload = extractPaneDrop(dt);+ void waitForNativeDrop().then((detail) => {+ if (!detail?.paths.length) return void attach(payload);+ // Inside the desktop shell the host knows where the file really+ // lies. Prefer that over uploading its bytes — same file, no copy —+ // and drop the byte copies the shell just accounted for so nothing+ // is attached twice.+ const named = new Set(detail.names.map((n) => n.toLowerCase()));+ return void attach({+ paths: Array.from(new Set([...payload.paths, ...detail.paths])),+ files: payload.files.filter((f) => !named.has(f.name.toLowerCase())),+ });+ });+ },+ [attach],+ ),+ );++ const attachFiles = useCallback(+ (files: File[]) => {+ if (files.length > 0) void attach({ paths: [], files });+ },+ [attach],+ );++ const onPaste = useCallback(+ (event: React.ClipboardEvent) => {+ // Text paste belongs to the browser and must keep working — this only+ // claims what a text box would otherwise DISCARD: an image on the+ // clipboard, which is what PrintScreen and Ctrl+V produce.+ const files = extractPasteFiles(event.clipboardData).map((f) =>+ nameClipboardFile(f, "chat"),+ );+ if (files.length === 0) return;+ event.preventDefault();+ void attach({ paths: [], files });+ },+ [attach],+ );++ const remove = useCallback((name: string) => {+ setAttachments((prev) => prev.filter((a) => a.name !== name));+ }, []);++ const clear = useCallback(() => setAttachments([]), []);++ return {+ attachments,+ analyzing,+ dragging,+ dragHandlers,+ attachFiles,+ onPaste,+ remove,+ clear,+ };+}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.test.tsxnew file mode 100644index 0000000000..a016ae70c3--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.test.tsx@@ -0,0 +1,112 @@+import { act, cleanup, fireEvent, render } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { usePasteRescue } from "@/components/agentchat/usePasteRescue";++/**+ * Ctrl+V where the embedded browser never sends a `paste` event.+ *+ * The behaviour that matters is the NEGATIVE one: in a browser that pastes+ * normally this hook must do nothing at all, or every paste lands twice. So+ * both halves are pinned — the rescue fires when the event is missing, and+ * stays out of the way when it is not.+ */++function Field({ onRescued }: { onRescued?: () => void }) {+ const rescue = usePasteRescue();+ return (+ <textarea+ data-testid="field"+ defaultValue=""+ onKeyDown={(e) => rescue.onKeyDown(e)}+ onPaste={() => {+ rescue.onPaste();+ onRescued?.();+ }}+ />+ );+}++describe("usePasteRescue", () => {+ let fetchMock: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ vi.useFakeTimers();+ fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ if (String(url).includes("/api/clipboard/text") && (init?.method ?? "GET") === "GET") {+ return { ok: true, status: 200, json: async () => ({ text: "from the clipboard" }) } as Response;+ }+ return { ok: false, status: 404, json: async () => ({}) } as Response;+ });+ vi.stubGlobal("fetch", fetchMock);+ });++ afterEach(() => {+ cleanup();+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ it("puts the clipboard text in when no paste event follows the keystroke", async () => {+ const { getByTestId } = render(<Field />);+ const field = getByTestId("field") as HTMLTextAreaElement;+ field.focus();++ fireEvent.keyDown(field, { key: "v", ctrlKey: true });+ // No `paste` event — this is the embedded browser that swallows it.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(300);+ });++ expect(fetchMock).toHaveBeenCalled();+ expect(field.value).toBe("from the clipboard");+ });++ it("does nothing at all when the browser delivers the paste itself", async () => {+ const { getByTestId } = render(<Field />);+ const field = getByTestId("field") as HTMLTextAreaElement;+ field.focus();++ fireEvent.keyDown(field, { key: "v", ctrlKey: true });+ fireEvent.paste(field, { clipboardData: { items: [], files: [], types: [] } });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(300);+ });++ // Never read the clipboard, never inserted: a second insertion here is+ // exactly the double paste this timing exists to avoid.+ expect(fetchMock).not.toHaveBeenCalled();+ expect(field.value).toBe("");+ });++ it("ignores every keystroke that is not Ctrl/Cmd+V", async () => {+ const { getByTestId } = render(<Field />);+ const field = getByTestId("field") as HTMLTextAreaElement;++ fireEvent.keyDown(field, { key: "v" });+ fireEvent.keyDown(field, { key: "c", ctrlKey: true });+ fireEvent.keyDown(field, { key: "v", ctrlKey: true, altKey: true });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(300);+ });++ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("leaves an empty clipboard alone rather than reporting a failure", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => ({ ok: true, status: 200, json: async () => ({ text: "" }) }) as Response),+ );+ const { getByTestId } = render(<Field />);+ const field = getByTestId("field") as HTMLTextAreaElement;+ field.focus();++ fireEvent.keyDown(field, { key: "v", ctrlKey: true });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(300);+ });+ expect(field.value).toBe("");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.ts b/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.tsnew file mode 100644index 0000000000..7675cf2089--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.ts@@ -0,0 +1,85 @@+import { useCallback, useEffect, useRef } from "react";++import { robustPaste } from "@/lib/clipboard";+import { captureEditSnapshot, pasteInto } from "@/lib/editActions";++/**+ * Make Ctrl+V put text in the box even where the embedded browser never sends+ * a `paste` event.+ *+ * In a real browser this hook does nothing at all, and that is the design. A+ * `<textarea>` pastes on its own; nothing here competes with it.+ *+ * The desktop shell is the reason it exists. Its WebView already withholds+ * `clipboard-read` — measured in 2026-07, `navigator.clipboard.readText()`+ * inside it never settles, resolved or rejected, which is why the right-click+ * menu reads the clipboard through the host process instead (lib/clipboard).+ * A build that also declines to deliver the `paste` event leaves Ctrl+V doing+ * nothing whatsoever in a text box, with no error anywhere to explain it.+ *+ * ## How it can tell the difference+ *+ * A real paste delivers its event in the SAME task as the keystroke. So the+ * keystroke arms a one-shot timer and the `paste` event disarms it; if the+ * timer still fires, no paste was delivered and the text is fetched through+ * the host route and inserted at the caret that was saved when the key went+ * down. The window is deliberately short — long enough to outlast a busy main+ * thread, far shorter than a person's next keystroke — because the failure+ * mode to avoid is pasting twice.+ *+ * `pasteInto` goes through `insertText`, so the caret, the undo history and+ * React's controlled value all survive (lib/editActions).+ */++/**+ * How long a real `paste` has to arrive before the keystroke counts as+ * unanswered. Browsers deliver it synchronously; this allows for a main thread+ * busy with a streaming turn.+ */+const RESCUE_AFTER_MS = 150;++export interface PasteRescue {+ /** Call from the field's `onKeyDown`, before anything else. */+ onKeyDown: (event: React.KeyboardEvent<HTMLElement>) => void;+ /** Call from the field's `onPaste` — this is what proves the event arrives. */+ onPaste: () => void;+}++export function usePasteRescue(): PasteRescue {+ const timerRef = useRef<number | undefined>(undefined);++ const disarm = useCallback(() => {+ if (timerRef.current !== undefined) {+ window.clearTimeout(timerRef.current);+ timerRef.current = undefined;+ }+ }, []);++ // A component unmounting mid-window must not paste into a field that is gone.+ useEffect(() => disarm, [disarm]);++ const onKeyDown = useCallback(+ (event: React.KeyboardEvent<HTMLElement>) => {+ const key = event.key.toLowerCase();+ if (key !== "v" || !(event.ctrlKey || event.metaKey) || event.altKey) return;+ // Captured now: by the time the timer fires the caret may have moved,+ // and the position the text belongs at is this one.+ const snapshot = captureEditSnapshot(event.currentTarget);+ if (!snapshot.editable) return;+ disarm();+ timerRef.current = window.setTimeout(() => {+ timerRef.current = undefined;+ void (async () => {+ const text = await robustPaste();+ // Null = no route could read the clipboard; empty = nothing on it.+ // Neither is an error worth a message: the person pressed a key and+ // the box stayed as it was, which is what an empty clipboard means.+ if (text) pasteInto(snapshot, text);+ })();+ }, RESCUE_AFTER_MS);+ },+ [disarm],+ );++ return { onKeyDown, onPaste: disarm };+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsxindex ba157e61e3..18f63a83cb 100644--- a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx@@ -9,6 +9,7 @@ vi.mock("@/lib/agenticIdeApi", () => ({resolveDroppedFolder: vi.fn(),fetchNativePickerSupport: vi.fn(),openNativePicker: vi.fn(),+ createFolder: vi.fn(),}));import {@@ -16,6 +17,7 @@ import {extractDropPayload,isAbsolutePath,joinPath,+ looksLikePath,normalizeTypedPath,resolveTypedPath,separatorOf,@@ -300,7 +302,7 @@ describe("the system folder window", () => {await waitFor(() => expect(onSelect).toHaveBeenCalledWith("C:\\work\\shop"));// And the in-page browser follows it there, so both views agree.- expect(api.fetchFolders).toHaveBeenCalledWith("C:\\work\\shop");+ expect(api.fetchFolders).toHaveBeenCalledWith("C:\\work\\shop", false);});it("says a window is waiting, because it can open behind the app", async () => {@@ -498,3 +500,143 @@ describe("typing a path", () => {expect(onSelect).not.toHaveBeenCalled();});});++describe("a path in the search field", () => {+ it("opens that folder instead of searching the machine for its name", async () => {+ // Reported: `C:\Users\me\.claude` typed into the search found nothing —+ // no folder is CALLED that — and the wizard looked broken.+ vi.mocked(api.fetchFolders).mockImplementation(async (target) =>+ target === "C:\\Users\\me\\.claude"+ ? {+ path: "C:\\Users\\me\\.claude",+ parent: "C:\\Users\\me",+ entries: [+ {+ name: "skills",+ path: "C:\\Users\\me\\.claude\\skills",+ is_project: false,+ is_repo: false,+ },+ ],+ device_name: "Box",+ }+ : LISTING,+ );+ const onSelect = vi.fn();+ render(<FolderPicker selected={null} onSelect={onSelect} />);+ await screen.findByText("webshop");++ fireEvent.change(screen.getByTestId("folder-search"), {+ target: { value: "C:\\Users\\me\\.claude" },+ });++ await waitFor(() => expect(onSelect).toHaveBeenCalledWith("C:\\Users\\me\\.claude"), {+ timeout: 2000,+ });+ expect(api.searchFolders).not.toHaveBeenCalled();+ // A dot-name asks for hidden folders by itself; nobody has to find the switch.+ expect(api.fetchFolders).toHaveBeenCalledWith("C:\\Users\\me\\.claude", true);+ expect(await screen.findByText("skills")).toBeTruthy();+ });++ it("reads a pasted prompt as the path inside it", () => {+ expect(normalizeTypedPath("PS C:\\Users\\me\\.claude>")).toBe("C:\\Users\\me\\.claude");+ expect(normalizeTypedPath("C:\\Users\\me\\.claude> ")).toBe("C:\\Users\\me\\.claude");+ expect(looksLikePath("C:\\Users\\me")).toBe(true);+ expect(looksLikePath("Desktop/shop")).toBe(true);+ expect(looksLikePath("~")).toBe(true);+ expect(looksLikePath("shop")).toBe(false);+ });++ it("offers to create the folder when the last segment does not exist yet", async () => {+ vi.mocked(api.fetchFolders).mockImplementation(async (target) =>+ target === "/home/ruben/newshop"+ ? {+ path: "/home/ruben/newshop",+ parent: "/home/ruben",+ entries: [],+ error: "There is no folder called /home/ruben/newshop.",+ device_name: "Box",+ }+ : { ...LISTING, path: "/home/ruben", parent: "/home" },+ );+ vi.mocked(api.createFolder).mockResolvedValue({+ folder: { name: "newshop", path: "/home/ruben/newshop", is_project: false, is_repo: false },+ error: null,+ });+ const onSelect = vi.fn();+ render(<FolderPicker selected={null} onSelect={onSelect} />);+ await screen.findByText("webshop");++ fireEvent.change(screen.getByTestId("folder-search"), {+ target: { value: "/home/ruben/newshop" },+ });++ const offer = await screen.findByTestId("create-offer", {}, { timeout: 2000 });+ expect(offer.textContent).toContain("newshop");+ // Nothing is chosen until the folder exists.+ expect(onSelect).not.toHaveBeenCalled();++ fireEvent.click(offer);+ await waitFor(() =>+ expect(api.createFolder).toHaveBeenCalledWith({ parent: "/home/ruben", name: "newshop" }),+ );+ await waitFor(() => expect(onSelect).toHaveBeenCalledWith("/home/ruben/newshop"));+ });+});++describe("a new folder", () => {+ it("is made in the folder on screen and becomes the selection", async () => {+ vi.mocked(api.fetchFolders).mockResolvedValue({+ ...LISTING,+ path: "/home/ruben",+ parent: "/home",+ });+ vi.mocked(api.createFolder).mockResolvedValue({+ folder: { name: "shop2", path: "/home/ruben/shop2", is_project: false, is_repo: false },+ error: null,+ });+ const onSelect = vi.fn();+ render(<FolderPicker selected={null} onSelect={onSelect} />);+ await screen.findByText("webshop");++ fireEvent.click(screen.getByTestId("new-folder"));+ fireEvent.change(screen.getByTestId("new-folder-name"), { target: { value: "shop2" } });+ fireEvent.submit(screen.getByTestId("new-folder-form"));++ await waitFor(() =>+ expect(api.createFolder).toHaveBeenCalledWith({ parent: "/home/ruben", name: "shop2" }),+ );+ await waitFor(() => expect(onSelect).toHaveBeenCalledWith("/home/ruben/shop2"));+ });++ it("shows why it could not be made and keeps the name for correcting", async () => {+ vi.mocked(api.createFolder).mockResolvedValue({+ folder: null,+ error: "A folder name cannot contain slashes. Type just the name.",+ });+ const onSelect = vi.fn();+ render(<FolderPicker selected={null} onSelect={onSelect} />);+ await screen.findByText("webshop");++ fireEvent.click(screen.getByTestId("new-folder"));+ fireEvent.change(screen.getByTestId("new-folder-name"), { target: { value: "a/b" } });+ fireEvent.submit(screen.getByTestId("new-folder-form"));++ expect(await screen.findByText(/cannot contain slashes/)).toBeTruthy();+ expect((screen.getByTestId("new-folder-name") as HTMLInputElement).value).toBe("a/b");+ expect(onSelect).not.toHaveBeenCalled();+ });+});++describe("hidden folders", () => {+ it("are listed only once the switch is on", async () => {+ render(<FolderPicker selected={null} onSelect={vi.fn()} />);+ await screen.findByText("webshop");+ expect(api.fetchFolders).toHaveBeenLastCalledWith(null, false);++ fireEvent.click(screen.getByTestId("toggle-hidden"));++ await waitFor(() => expect(api.fetchFolders).toHaveBeenLastCalledWith(null, true));+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneActivityPill.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneActivityPill.test.tsxindex aafe513ec9..6e1f344499 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PaneActivityPill.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneActivityPill.test.tsx@@ -30,10 +30,13 @@ describe("what the badge shows", () => {expect(badge.getAttribute("data-icon")).toBe("spinner");});- it("shows a still amber dot for a pane that was given a job and has stopped", () => {+ it("shows an amber check mark for a pane that was given a job and has finished", () => {+ // A check, not a still dot: beside a row of spinners a dot read as "also+ // busy, just not animated", and the maintainer asked for an indicator+ // that says working or done (2026-08-27).const badge = pill({ status: "live", activity: "waiting", worked: true });expect(badge.textContent).toBe("");- expect(badge.getAttribute("data-icon")).toBe("dot");+ expect(badge.getAttribute("data-icon")).toBe("check");expect(badge.className).toContain("text-amber-400");});diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneActivityPill.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneActivityPill.tsxindex e5b027dfd8..a36a86f9f9 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PaneActivityPill.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneActivityPill.tsx@@ -1,4 +1,4 @@-import { AlertCircle, Loader2 } from "lucide-react";+import { AlertCircle, Check, Loader2 } from "lucide-react";import { cn } from "@/lib/utils";import type { PaneActivity } from "@/lib/agenticIdeApi";@@ -49,18 +49,25 @@ import type { PaneActivity } from "@/lib/agenticIdeApi";** The two states a person scans this list for — still grinding vs. finished —* are told apart by SHAPE first, not by hue: a pane that is working shows a- * turning spinner, and a pane that has stopped shows a still dot. That reads at- * a glance, survives every colour-blindness, and it is why the working state is- * no longer a pulsing dot: a slow throb and a steady dot are the same silhouette- * at 8 pixels, so the difference lived entirely in a colour the eye had to- * compare against its neighbours to judge.+ * turning spinner, and a pane that has finished shows a check mark. That reads+ * at a glance, survives every colour-blindness, and it is why the working state+ * is no longer a pulsing dot: a slow throb and a steady dot are the same+ * silhouette at 8 pixels, so the difference lived entirely in a colour the eye+ * had to compare against its neighbours to judge.+ *+ * The finished state is a CHECK and not a still dot for the same reason. A dot+ * is what every list uses for "online", and beside a row of amber spinners an+ * amber dot read as "also busy, just not animated right now" — the maintainer+ * asked for an indicator that says working or done, looking at a list that+ * already had one (2026-08-27). A check says finished the way a spinner says+ * busy: on its own, without a neighbour to compare against.** Colour then carries the second question — is this pane's stillness news? Amber- * is the app's own accent and marks a pane holding something for you: filled for- * a finished job, hollow for one that is merely ready and has done nothing yet.- * Blue is spent on the one state that wants an action from you right now, a pane- * stopped on a question. Grey is for a pane with nothing to report, red for a- * broken one.+ * is the app's own accent and marks a pane holding something for you: a check+ * for a finished job, a hollow ring for one that is merely ready and has done+ * nothing yet. Blue is spent on the one state that wants an action from you+ * right now, a pane stopped on a question. Grey is for a pane with nothing to+ * report, red for a broken one.*//**@@ -87,9 +94,9 @@ type Look = {state: PaneActivityState;label: string;className: string;- icon: "spinner" | "dot" | "ring" | "alert" | "beacon";+ icon: "spinner" | "dot" | "ring" | "alert" | "beacon" | "check";/**- * A soft halo of the dot's own colour. Spent on exactly one state — a+ * A soft halo of the mark's own colour. Spent on exactly one state — a* finished job — so the one row holding something for you glows and the* grey ones (exited, a plain shell) stay matte.*/@@ -156,18 +163,19 @@ const DONE: Look = {state: "done",label: "done",className: "text-amber-400",- icon: "dot",+ icon: "check",glow: true,hint: "Finished and waiting at its prompt. That it stopped, not that the work is right.",};/**- * Ready, but holding nothing — the same amber, drawn hollow.+ * Ready, but holding nothing — the same amber, drawn as an empty ring.** A ring rather than a second colour because this is the SAME piece of news as* `done` with one part missing: the pane is quiet and yours to talk to, it just- * has no finished job behind it. Reading "empty" out of an unfilled shape is- * what a fuel gauge does, and it keeps the accent colour meaning one thing.+ * has no finished job behind it. Reading "nothing here yet" out of an unfilled+ * shape is what a fuel gauge does, and it keeps the accent colour meaning one+ * thing.*/const IDLE: Look = {state: "idle",@@ -286,12 +294,22 @@ export function durationLabel(since: number, now: number): string {return hours === 1 ? "1 hour" : `${hours} hours`;}-/** The soft self-coloured halo a dot that holds something for you wears. */+/** The soft self-coloured halo a mark that holds something for you wears. */const GLOW = "shadow-[0_0_5px_currentColor]";+/** The same halo for a stroked icon, where a box shadow would draw a square. */+const GLOW_STROKE = "drop-shadow-[0_0_3px_currentColor]";function Icon({ look }: { look: Look }) {if (look.icon === "spinner")return <Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" />;+ if (look.icon === "check")+ return (+ <Check+ className={cn("h-3.5 w-3.5", look.glow && GLOW_STROKE)}+ strokeWidth={3}+ aria-hidden="true"+ />+ );if (look.icon === "dot")return (<spandiff --git a/jarvis/ui/web/frontend/src/hooks/useFileDropGuard.ts b/jarvis/ui/web/frontend/src/hooks/useFileDropGuard.tsnew file mode 100644index 0000000000..4ba0c51d9e--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useFileDropGuard.ts@@ -0,0 +1,51 @@+import { useEffect } from "react";++/**+ * Stop a missed file drop from replacing the app with the file.+ *+ * A browser's default action for a file dropped anywhere in a page is to+ * NAVIGATE to it. Inside the desktop shell there is no address bar and no Back+ * button, so a screenshot dropped two centimetres beside the composer does not+ * merely fail — it takes the whole window: every open chat, every terminal in+ * the grid, gone until the app is restarted. The person who did it has no way+ * to read that as "you missed", because nothing about a picture filling the+ * window says a drop was refused.+ *+ * So every drop that no drop zone claimed is swallowed here, and nothing else+ * happens: no toast, no highlight. A drop on empty chrome SHOULD do nothing —+ * this only makes "nothing" true.+ *+ * ## Why this cannot break a real drop target+ *+ * The listeners run in the BUBBLE phase on `window`, which is after React has+ * delivered the event to its own tree (React 18 attaches at the root+ * container, below `window`). A target that took the drop has already called+ * `preventDefault()` by then, and `defaultPrevented` is how this tells the two+ * apart. A handler that did NOT call it was not going to receive the file+ * anyway — that is what the default action being navigation means.+ *+ * `dragover` needs the same treatment: without a `preventDefault()` there the+ * browser refuses the drop before `drop` ever fires, so guarding only `drop`+ * would leave the cursor showing 🚫 over the whole app. Guarding both keeps+ * the page's own targets in charge of the cursor — they preventDefault first,+ * and this one only claims what they left.+ */+export function useFileDropGuard(): void {+ useEffect(() => {+ const carriesFiles = (event: DragEvent): boolean => {+ const types = event.dataTransfer?.types;+ return types ? Array.from(types).includes("Files") : false;+ };+ const swallow = (event: DragEvent) => {+ if (event.defaultPrevented) return; // a real target took it+ if (!carriesFiles(event)) return; // dragged text/links are the browser's+ event.preventDefault();+ };+ window.addEventListener("dragover", swallow);+ window.addEventListener("drop", swallow);+ return () => {+ window.removeEventListener("dragover", swallow);+ window.removeEventListener("drop", swallow);+ };+ }, []);+}diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx b/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsxindex 7fbbe269ac..1f54f341d2 100644--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx@@ -204,6 +204,43 @@ describe("useWebSocket VoiceBootStatus handling", () => {expect(toasts[2].message).toContain("never showed it arriving");});+ it("hands a pane's activity change to the window, payload intact and without a toast", async () => {+ render(<Harness />);+ await Promise.resolve();+ const seen: unknown[] = [];+ const onActivity = (event: Event) => seen.push((event as CustomEvent).detail);+ window.addEventListener("jarvis:agentic-ide-activity", onActivity);+ try {+ MockWebSocket.last!.deliver(+ envelope("AgenticIdePaneActivity", {+ session_id: "ide_1",+ key: "t3",+ name: "T3",+ status: "live",+ activity: "waiting",+ activity_since: 1787823736,+ worked: true,+ }),+ );+ } finally {+ window.removeEventListener("jarvis:agentic-ide-activity", onActivity);+ }++ expect(seen).toEqual([+ {+ session_id: "ide_1",+ key: "t3",+ name: "T3",+ status: "live",+ activity: "waiting",+ activity_since: 1787823736,+ worked: true,+ },+ ]);+ // The bell is the surface for "it finished"; the badge just keeps up.+ expect(useEventStore.getState().toasts).toEqual([]);+ });+it("routes native microphone levels outside React state and clears them after listening", async () => {render(<Harness />);await Promise.resolve();diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.tsindex 1b9d8ea503..4957d4777e 100644--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts@@ -25,6 +25,7 @@ import {} from "@/store/commandActivity";import { useDeckStore } from "@/store/deck";import { useHomeStore } from "@/store/home";+import { PANE_ACTIVITY_EVENT } from "@/store/workspacePanes";import { WSAudioLevel, WSEventEnvelope, WSWelcome } from "@/schema/ws";import { useI18nStore, hydrateUiLanguage, hydrateReplyLanguage, translate } from "@/i18n";import { hydrateUiTheme } from "@/hooks/useTheme";@@ -520,6 +521,19 @@ export function useWebSocket(): void {}}+ if (env.event_name === "AgenticIdePaneActivity") {+ // One pane's agent changed state — started, stopped, asked, died.+ // The payload is the activity half of a `/panes` row, so the session+ // list and the grid patch their row in place the moment the sweep+ // decides, instead of showing a spinner over a finished session+ // until their next poll (up to four seconds in the sidebar). No+ // toast: the bell is the surface for "it finished", this is the+ // badge keeping up with the pane.+ window.dispatchEvent(+ new CustomEvent(PANE_ACTIVITY_EVENT, { detail: env.payload }),+ );+ }+if (env.event_name === "AgenticIdeComposeProgress") {// One beat of a brief being written for a pane — the prompt bar// shows it as a live status line. Deliberately no toast: a singlediff --git a/jarvis/ui/web/frontend/src/i18n/local-models-i18n-parity.test.ts b/jarvis/ui/web/frontend/src/i18n/local-models-i18n-parity.test.tsindex a71f9901ff..26a1573a59 100644--- a/jarvis/ui/web/frontend/src/i18n/local-models-i18n-parity.test.ts+++ b/jarvis/ui/web/frontend/src/i18n/local-models-i18n-parity.test.ts@@ -29,7 +29,6 @@ const keysFor = (loc: Record<string, unknown>): Set<string> =>const SRC = join(__dirname, "..");const PANEL_DIR = join(SRC, "views", "local-models");-const ASSISTANT_DIR = join(SRC, "components", "local-models");const sources = (dir: string) =>readdirSync(dir).filter((f) => f.endsWith(".tsx") && !f.endsWith(".test.tsx"))@@ -37,7 +36,6 @@ const sources = (dir: string) =>const SOURCE_FILES = [join(SRC, "views", "LocalModelsView.tsx"),...sources(PANEL_DIR),- ...sources(ASSISTANT_DIR),];/** Literal keys only; template keys (`local_models.tune.${key}`) are covereddiff --git a/jarvis/workspace/agents.py b/jarvis/workspace/agents.pyindex 5068060b44..db3d6b1b25 100644--- a/jarvis/workspace/agents.py+++ b/jarvis/workspace/agents.py@@ -40,6 +40,8 @@ from typing import Any, Literalfrom jarvis.clis.prober import CliStatusProberfrom jarvis.clis.spec import AuthConfig, CliSpec, InstallMethods, RiskConfigfrom jarvis.terminal.shells import default_shell+from jarvis.workspace.launch_picks import VALUE as picks_value+from jarvis.workspace.launch_picks import LaunchPicks, flag_modeslog = logging.getLogger(__name__)@@ -226,6 +228,14 @@ class WorkspaceAgent:#: under one binary name. ``None`` when there is only ever one.generation_probe: Callable[[], str | None] | None = None+ #: How this CLI takes a model / effort / permission pick on its launch argv+ #: (:mod:`jarvis.workspace.launch_picks`). ``None`` means "offers no picks":+ #: a pane of it opens on whatever the binary itself defaults to, and every+ #: picker upstream shows nothing to choose rather than a control that does+ #: nothing. Declaring it is what makes those three picks work for an entry —+ #: no layer above knows any CLI's flag spelling (AP-21).+ launch_picks: LaunchPicks | None = None+# --- How it behaves once it is running ----------------------------------trust: TrustSpec | None = Noneaccount: AccountSpec | None = None@@ -585,10 +595,108 @@ def glm_spawn_env() -> dict[str, str] | None:return env+# ---------------------------------------------------------------- launch picks+#+# What each CLI accepts as "run on THIS model, think THIS hard, ask THIS often"+# when a pane opens. Every flag below was read off the installed binary's own+# ``--help`` and its rejected-value message, which is the only source that can+# be trusted here: a wrong word is not a warning but a pane that dies on the+# command line. The mode NAMES stay the agent chat's ladder vocabulary+# (jarvis/agent_chat/permissions.py) even where the binary spells one+# differently, so one word means one stance across the whole app.++_CLAUDE_PICKS = LaunchPicks(+ provider="claude-api",+ model_args=("--model", picks_value),+ effort_args=("--effort", picks_value),+ # ``default`` is this CLI's ask-first mode. Recent builds call the same+ # stance ``manual`` in their help text and still accept ``default``+ # (verified on 2.1.247), so the older word is the one that runs on both.+ permission_args=flag_modes(+ "--permission-mode",+ "default",+ "acceptEdits",+ "plan",+ "auto",+ "dontAsk",+ "bypassPermissions",+ ),+)++#: GLM drives the Claude Code binary, so it takes the same permission words —+#: but its models are Z.ai's own and this app ships no list of them, and the+#: effort flag belongs to Anthropic's endpoint rather than Z.ai's. Offering+#: neither is what keeps a picker from listing choices the endpoint refuses.+_GLM_PICKS = LaunchPicks(provider="claude-api", permission_args=_CLAUDE_PICKS.permission_args)++_CODEX_PICKS = LaunchPicks(+ provider="openai-codex",+ model_args=("--model", picks_value),+ # A ``-c`` override, not a flag of its own. The value is parsed as TOML and+ # falls back to the literal string, so the level goes in bare — quoting it+ # here would put the quote characters themselves into the setting.+ effort_args=("-c", f"model_reasoning_effort={picks_value}"),+ permission_args=(+ ("read-only", ("--sandbox", "read-only")),+ ("approve-for-me", ("--approve-for-me",)),+ ("auto", ("--sandbox", "workspace-write")),+ ("full-access", ("--dangerously-bypass-approvals-and-sandbox",)),+ ),+)++_AGY_PICKS = LaunchPicks(+ provider="antigravity",+ model_args=("--model", picks_value),+ effort_args=("--effort", picks_value),+ permission_args=(+ ("accept-edits", ("--mode", "accept-edits")),+ ("plan", ("--mode", "plan")),+ ("skip-permissions", ("--dangerously-skip-permissions",)),+ ),+ # A base Gemini id is an error without a level beside it.+ effort_required=True,+)++_GROK_PICKS = LaunchPicks(+ provider="grok-build",+ model_args=("--model", picks_value),+ effort_args=("--reasoning-effort", picks_value),+ # The binary also takes ``auto`` and ``dontAsk``; they are left out because+ # this app has no sentence describing what they mean for Grok Build, and a+ # picker entry nobody can explain is worse than one fewer choice.+ permission_args=flag_modes(+ "--permission-mode",+ "default",+ "acceptEdits",+ "plan",+ "bypassPermissions",+ ),+)++#: OpenCode and Kimi bring their own accounts and their own model aliases, so+#: neither publishes a list this app could offer — the pick is whatever the+#: person has configured, and the shape check in ``launch_picks`` is what+#: stands in for a list. Their one permission flag is described by the shared+#: API ladder, which has the right sentence for "everything runs without+#: asking" already.+_OPENCODE_PICKS = LaunchPicks(+ model_args=("--model", picks_value),+ permission_args=(("auto", ("--auto",)),),+ ladder="api",+)++_KIMI_PICKS = LaunchPicks(+ model_args=("--model", picks_value),+ permission_args=(("auto", ("--auto",)),),+ ladder="api",+)++_AGENTS: dict[str, WorkspaceAgent] = {"claude": make_cli_agent("claude","Claude Code",+ launch_picks=_CLAUDE_PICKS,binary="claude",npm_package="@anthropic-ai/claude-code",homepage="https://claude.com/claude-code",@@ -622,6 +730,7 @@ _AGENTS: dict[str, WorkspaceAgent] = {"codex": make_cli_agent("codex","Codex",+ launch_picks=_CODEX_PICKS,binary="codex",npm_package="@openai/codex",homepage="https://github.com/openai/codex",@@ -644,6 +753,7 @@ _AGENTS: dict[str, WorkspaceAgent] = {"opencode": make_cli_agent("opencode","OpenCode",+ launch_picks=_OPENCODE_PICKS,binary="opencode",homepage="https://opencode.ai",description="Open-source terminal coding agent — bring your own model.",@@ -678,6 +788,7 @@ _AGENTS: dict[str, WorkspaceAgent] = {"kimi": make_cli_agent("kimi","Kimi Code",+ launch_picks=_KIMI_PICKS,binary="kimi",npm_package="@moonshot-ai/kimi-code",homepage="https://moonshotai.github.io/kimi-code/en/",@@ -728,6 +839,7 @@ _AGENTS: dict[str, WorkspaceAgent] = {"glm": make_cli_agent("glm","GLM Coding Plan",+ launch_picks=_GLM_PICKS,# The whole design of this entry: the binary IS Claude Code. Z.ai ships# no CLI of its own — its own documentation says to run Anthropic's# binary against a different endpoint — so detection, the install@@ -749,6 +861,7 @@ _AGENTS: dict[str, WorkspaceAgent] = {"grok-build": make_cli_agent("grok-build","Grok Build",+ launch_picks=_GROK_PICKS,binary="grok",homepage="https://x.ai/cli",description="xAI's terminal coding agent — SuperGrok or X Premium+.",@@ -775,6 +888,7 @@ _AGENTS: dict[str, WorkspaceAgent] = {"antigravity": make_cli_agent("antigravity","Antigravity",+ launch_picks=_AGY_PICKS,binary="agy",homepage="https://antigravity.google",description="Google's terminal coding agent — billed against the Google subscription.",diff --git a/tests/fixtures/brain/fake_brain.py b/tests/fixtures/brain/fake_brain.pyindex b1d893e802..ee715b36d5 100644--- a/tests/fixtures/brain/fake_brain.py+++ b/tests/fixtures/brain/fake_brain.py@@ -19,7 +19,10 @@ class FakeBrain:"""Fake brain provider for tests."""name: str = "fake-brain"- context_window: int = 8192+ # A hosted-provider window. The manager sizes the tool surface to this+ # (BUG-187); a test that wants the small-local-model behaviour sets a+ # small window explicitly on its own fake.+ context_window: int = 200_000supports_tools: bool = Truesupports_vision: bool = Falsediff --git a/tests/unit/agent_chat/test_agent_chat_core.py b/tests/unit/agent_chat/test_agent_chat_core.pyindex 134bd8edb4..3a808caac7 100644--- a/tests/unit/agent_chat/test_agent_chat_core.py+++ b/tests/unit/agent_chat/test_agent_chat_core.py@@ -477,18 +477,93 @@ def test_codex_reasoning_start_is_announced():def test_resolve_runner_per_surface(monkeypatch):- """The Jarvis surface runs API-key and local rows on the brain; CLI seats stay CLIs."""+ """The Jarvis surface is API endpoints only; the agent surface keeps its CLIs."""from jarvis.agent_chat import service as svc_modmonkeypatch.setattr(svc_mod, "_claude_cli_installed", lambda: False)assert svc_mod.resolve_runner("openai") == "api"assert svc_mod.resolve_runner("openai", surface="jarvis") == "brain"assert svc_mod.resolve_runner("ollama", surface="jarvis") == "brain"- assert svc_mod.resolve_runner("openai-codex", surface="jarvis") == "codex-cli"- assert svc_mod.resolve_runner("antigravity", surface="jarvis") == "agy-cli"assert svc_mod.resolve_runner("claude-api") == "api"assert svc_mod.resolve_runner("claude-api", surface="jarvis") == "brain"+ # A CLI-only row has no API path, so the surface that dropped its CLI+ # seats has no runner for it at all — and never offers it (see+ # test_the_jarvis_surface_offers_api_seats_only).+ assert svc_mod.resolve_runner("openai-codex", surface="jarvis") == "unknown"+ assert svc_mod.resolve_runner("antigravity", surface="jarvis") == "unknown"+ assert svc_mod.resolve_runner("openai-codex", surface="agent") == "codex-cli"+ assert svc_mod.resolve_runner("antigravity", surface="agent") == "agy-cli"monkeypatch.setattr(svc_mod, "_claude_cli_installed", lambda: True)assert svc_mod.resolve_runner("claude-api") == "claude-cli"- assert svc_mod.resolve_runner("claude-api", surface="jarvis") == "claude-cli"+ # Even with Claude Code installed: the front page's chat runs the+ # Anthropic endpoint, not the subscription seat (maintainer 2026-08-26).+ assert svc_mod.resolve_runner("claude-api", surface="jarvis") == "brain"assert svc_mod.resolve_runner("no-such-provider", surface="jarvis") == "unknown"+++def test_the_jarvis_surface_offers_api_seats_only():+ """Every row the front page's chat lists has a brain plugin behind it."""+ from jarvis.agent_chat.catalog import PROVIDER_ROWS, offers, rows_for+ from jarvis.agent_chat.runner_api import supports_api_runner++ jarvis_ids = [row.id for row in rows_for("jarvis")]+ assert jarvis_ids and all(supports_api_runner(pid) for pid in jarvis_ids)+ # The CLI-only rows are gone from it and still there for the IDE's chat.+ for cli_row in ("openai-codex", "antigravity", "grok-build"):+ assert not offers("jarvis", cli_row)+ assert offers("agent", cli_row)+ assert [row.id for row in rows_for("agent")] == [row.id for row in PROVIDER_ROWS]+++def test_a_cli_seat_cannot_be_created_or_patched_onto_the_jarvis_chat(tmp_path):+ """The picker does not list them, and the routes refuse them either way."""+ import pytest++ from jarvis.agent_chat.service import AgentChatService+ from jarvis.agent_chat.store import AgentChatStore++ svc = AgentChatService(AgentChatStore(":memory:"), default_cwd=lambda: str(tmp_path))+ with pytest.raises(ValueError, match="not offered"):+ svc.create_session(provider="openai-codex", surface="jarvis")+ # The same row is fine on the surface that has CLI seats.+ assert svc.create_session(provider="openai-codex", surface="agent").provider == "openai-codex"+++def test_an_old_cli_seated_jarvis_chat_moves_to_its_api_twin(tmp_path):+ """A chat from before the change keeps its history and gains a working seat."""+ from jarvis.agent_chat.service import AgentChatService+ from jarvis.agent_chat.store import AgentChatStore++ store = AgentChatStore(":memory:")+ # ``gpt-5.2`` is in Codex's own catalog and not in OpenAI's, so it goes.+ codex = store.create_session(+ provider="openai-codex", model="gpt-5.2", effort="high", cwd=".", surface="jarvis"+ )+ # One the API does know rides along rather than resetting for nothing.+ shared = store.create_session(+ provider="openai-codex", model="gpt-5.5", effort="high", cwd=".", surface="jarvis"+ )+ claude = store.create_session(+ provider="claude-api", model="opusplan", effort="high", cwd=".", surface="jarvis"+ )+ kept = store.create_session(+ provider="claude-api", model="claude-opus-5", effort="high", cwd=".", surface="agent"+ )+ before = store.get_session(codex.session_id).updated_ms++ AgentChatService(store, default_cwd=lambda: str(tmp_path))++ moved = store.get_session(codex.session_id)+ assert (moved.provider, moved.model) == ("openai", "")+ assert (store.get_session(shared.session_id).provider, store.get_session(shared.session_id).model) == (+ "openai",+ "gpt-5.5",+ )+ # The list order is by updated_ms; a migration must not reshuffle it.+ assert moved.updated_ms == before+ # Claude keeps its row and loses only the model id the API cannot take.+ assert store.get_session(claude.session_id).provider == "claude-api"+ assert store.get_session(claude.session_id).model == ""+ # The IDE's chat is untouched.+ assert store.get_session(kept.session_id).provider == "claude-api"+ assert store.get_session(kept.session_id).model == "claude-opus-5"diff --git a/tests/unit/agent_chat/test_agent_chat_surface_parity.py b/tests/unit/agent_chat/test_agent_chat_surface_parity.pyindex 73b2fd9570..f882c7360a 100644--- a/tests/unit/agent_chat/test_agent_chat_surface_parity.py+++ b/tests/unit/agent_chat/test_agent_chat_surface_parity.py@@ -1,8 +1,7 @@"""The session's ``surface`` — one enum in three languages, and the migration.``"jarvis"`` is the front page's chat (Jarvis with a keyboard), ``"agent"`` a-plain coding-agent session (the Agentic IDE's chat mode), ``"local-models"``-the Local models section's setup assistant. The value crosses+plain coding-agent session (the Agentic IDE's chat mode). The value crossesPython -> SQLite -> Pydantic -> TypeScript, so the four spellings are pinnedagainst each other here (AP-4) instead of trusted to stay in step by hand."""@@ -39,13 +38,6 @@ def test_typescript_spells_the_surface_the_same():match = re.search(r"export type AgentChatSurface\s*=\s*([^;]+);", text)assert match, "agentChatApi.ts must export `AgentChatSurface`"members = set(re.findall(r'"([a-z-]+)"', match.group(1)))- if "local-models" in SURFACES and "local-models" not in members:- import pytest-- pytest.xfail(- "frontend has not added 'local-models' to AgentChatSurface yet "- "(owned by the assistant-ui chunk, D8)"- )assert members == set(SURFACES)diff --git a/tests/unit/agent_chat/test_chat_attachments.py b/tests/unit/agent_chat/test_chat_attachments.pynew file mode 100644index 0000000000..a910f5a59b--- /dev/null+++ b/tests/unit/agent_chat/test_chat_attachments.py@@ -0,0 +1,257 @@+"""Files dropped, pasted or picked into a chat composer.++Covers the whole path the composer uses: the attach route stores the bytes and+returns what was read from them, and the message that follows carries those+contents into the turn while the timeline still shows the person's own+sentence.++The vision layer is faked throughout. What is under test is the wiring — that a+chat can take a file at all, which is what it could not do — not whether a+model describes a picture well.+"""++from __future__ import annotations++import asyncio+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.agent_chat import attachments as chat_attachments+from jarvis.agent_chat.service import AgentChatService+from jarvis.agent_chat.store import AgentChatStore+from jarvis.agentic_ide import drop_analysis+from jarvis.ui.web.agent_chat_routes import router++# A one-pixel PNG — real bytes, so the store and the mime guess behave.+PNG = bytes.fromhex(+ "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4"+ "890000000a49444154789c6360000002000100" + "05fe02fe" + "0000000049454e44ae426082"+)+++def _app(tmp_path: Path) -> FastAPI:+ app = FastAPI()+ app.include_router(router)+ app.state.agent_chat = None+ app.state.agent_chat_factory = lambda: AgentChatService(+ AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(tmp_path)+ )+ return app+++def described(monkeypatch: pytest.MonkeyPatch) -> None:+ """Every image comes back described, without a provider being involved."""++ async def fake_analyze(items, **_kwargs): # noqa: ANN001, ANN202+ return [+ drop_analysis.DropAnalysis(+ name=item.name,+ reference=reference,+ kind="image",+ detail="A screenshot of a chat composer with no attach button.",+ described_by=drop_analysis.BY_VISION,+ )+ for item, reference in items+ ]++ monkeypatch.setattr(drop_analysis, "analyze", fake_analyze)+++# ---------------------------------------------------------------- the route+++def test_attach_stores_the_bytes_and_returns_what_was_read(tmp_path: Path, described) -> None:+ with TestClient(_app(tmp_path)) as client:+ res = client.post(+ "/api/agent-chat/attachments",+ files=[("files", ("shot.png", PNG, "image/png"))],+ data={"cwd": str(tmp_path), "surface": "jarvis"},+ )+ assert res.status_code == 200, res.text+ body = res.json()++ (row,) = body["attachments"]+ assert row["name"].endswith(".png")+ assert row["described_by"] == "vision"+ assert "composer" in row["detail"]+ # The copy landed in the chat's own folder, where the agent can open it.+ copies = list((tmp_path / ".jarvis" / "drops").glob("*.png"))+ assert len(copies) == 1+ assert copies[0].read_bytes() == PNG+++def test_attach_falls_back_to_the_surface_folder_when_the_cwd_is_gone(+ tmp_path: Path, described+) -> None:+ """A remembered folder that no longer exists must not refuse the file."""+ with TestClient(_app(tmp_path)) as client:+ res = client.post(+ "/api/agent-chat/attachments",+ files=[("files", ("shot.png", PNG, "image/png"))],+ data={"cwd": str(tmp_path / "moved-away"), "surface": "agent"},+ )+ assert res.status_code == 200, res.text+ assert res.json()["cwd"] == str(tmp_path)+++def test_attach_refuses_an_empty_drop(tmp_path: Path) -> None:+ with TestClient(_app(tmp_path)) as client:+ res = client.post(+ "/api/agent-chat/attachments",+ data={"cwd": str(tmp_path), "paths": " \n "},+ )+ assert res.status_code == 422+ assert "nothing" in res.json()["detail"].lower()+++def test_a_path_inside_the_folder_is_referenced_where_it_lies(+ tmp_path: Path, described+) -> None:+ """Nothing is copied for a file the agent can already open."""+ existing = tmp_path / "notes.png"+ existing.write_bytes(PNG)++ with TestClient(_app(tmp_path)) as client:+ res = client.post(+ "/api/agent-chat/attachments",+ data={"cwd": str(tmp_path), "paths": str(existing)},+ )+ assert res.status_code == 200, res.text+ (row,) = res.json()["attachments"]+ assert "notes.png" in row["reference"]+ assert not (tmp_path / ".jarvis" / "drops").exists()+++# ------------------------------------------------------------- composition+++def test_compose_leaves_an_ordinary_message_alone() -> None:+ assert chat_attachments.compose("what is this", []) == "what is this"+ assert chat_attachments.compose(" spaced ", None) == "spaced"+++def test_compose_carries_the_contents_into_the_message() -> None:+ item = drop_analysis.DropAnalysis(+ name="shot.png",+ reference='"shot.png"',+ kind="image",+ detail="A red error banner over the login form.",+ described_by=drop_analysis.BY_VISION,+ )+ out = chat_attachments.compose("fix this", [item])++ assert out.startswith("fix this")+ # The description is what makes the drop useful to a model that cannot open+ # the file, so it must be IN the message, not merely referenced.+ assert "A red error banner over the login form." in out+ assert "shot.png" in out+++def test_to_analysis_survives_a_malformed_row() -> None:+ """The rows come back from a browser, so no shape may be assumed.++ A message somebody is waiting to send must not 500 over a stray field:+ anything that is not an object is dropped, and a row with a missing or+ mistyped field degrades to a named, empty-detail attachment.+ """+ rows = [+ {"name": "ok.png", "kind": "image", "detail": "d", "described_by": "vision"},+ {"kind": "image"}, # no name — kept under a placeholder, not dropped+ "not a dict", # not an object at all — dropped+ {"name": "odd.txt", "detail": 42}, # wrong type — degrades to empty+ ]+ out = chat_attachments.to_analysis(rows) # type: ignore[arg-type]+ assert [item.name for item in out] == ["ok.png", "file", "odd.txt"]+ assert out[2].detail == ""+++# ------------------------------------------------------ the message it rides+++def test_a_message_with_files_shows_the_sentence_and_sends_the_contents(+ tmp_path: Path,+) -> None:+ """The event log holds both halves, and each is used for its own job."""+ svc = AgentChatService(+ AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(tmp_path)+ )+ session = svc.store.create_session(+ provider="fakeprov", model="", effort="", cwd=str(tmp_path)+ )++ async def run() -> None:+ # No runner is reachable for "fakeprov" here, so the turn fails after+ # the user message is persisted — which is the part under test.+ await svc.send(+ session.session_id,+ "what is wrong here",+ [+ {+ "name": "shot.png",+ "reference": '"shot.png"',+ "kind": "image",+ "detail": "A red error banner.",+ "described_by": "vision",+ "note": "",+ }+ ],+ )+ await svc.cancel(session.session_id)++ asyncio.run(run())++ events = svc.store.list_events(session.session_id)+ user = next(e for e in events if e["kind"] == "user_message")+ payload = user["payload"]+ # What the person typed — the timeline shows this.+ assert payload["typed"] == "what is wrong here"+ # What the turn received — history rebuilds from this.+ assert "A red error banner." in payload["text"]+ assert payload["text"].startswith("what is wrong here")+ # The receipt the timeline draws under the message.+ assert payload["attachments"] == [+ {"name": "shot.png", "kind": "image", "described_by": "vision", "note": ""}+ ]+++def test_files_alone_are_a_complete_message(tmp_path: Path) -> None:+ """Dropping a picture and pressing Enter says enough."""+ svc = AgentChatService(+ AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(tmp_path)+ )+ session = svc.store.create_session(+ provider="fakeprov", model="", effort="", cwd=str(tmp_path)+ )++ async def run() -> None:+ await svc.send(+ session.session_id,+ "",+ [{"name": "shot.png", "reference": "x", "kind": "image", "detail": "A chart."}],+ )+ await svc.cancel(session.session_id)++ asyncio.run(run())+ user = next(+ e for e in svc.store.list_events(session.session_id) if e["kind"] == "user_message"+ )+ assert "A chart." in user["payload"]["text"]+++def test_an_empty_message_with_nothing_attached_is_still_refused(tmp_path: Path) -> None:+ svc = AgentChatService(+ AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(tmp_path)+ )+ session = svc.store.create_session(+ provider="fakeprov", model="", effort="", cwd=str(tmp_path)+ )++ async def run() -> None:+ with pytest.raises(ValueError):+ await svc.send(session.session_id, " ", [])++ asyncio.run(run())diff --git a/tests/unit/agent_chat/test_surface_kits.py b/tests/unit/agent_chat/test_surface_kits.pyindex 3a53ee22c8..8a2ae4b611 100644--- a/tests/unit/agent_chat/test_surface_kits.py+++ b/tests/unit/agent_chat/test_surface_kits.py@@ -1,18 +1,19 @@-"""Surface kits: one lookup per call site, and the local-models surface's recipe."""+"""Surface kits: one lookup per call site, and what a kit hands a turn."""from __future__ import annotationsfrom pathlib import Pathfrom typing import Any+import pytest+from jarvis.agent_chat import surface_kitsfrom jarvis.agent_chat.permissions import JARVIS_LADDER, ladder_keyfrom jarvis.agent_chat.runner_brain import build_override, kit_payloadfrom jarvis.agent_chat.service import resolve_runnerfrom jarvis.agent_chat.store import SURFACES, AgentChatSession-from jarvis.agent_chat.surface_kits import LOCAL_MODELS_SURFACE, kit_for-from jarvis.core.config import BrainProviderConfig, JarvisConfig-from jarvis.core.protocols import ExecutionContext, ToolResult+from jarvis.agent_chat.surface_kits import SurfaceKit, kit_for+from jarvis.core.protocols import Tooldef _session(surface: str) -> AgentChatSession:@@ -33,49 +34,53 @@ def _session(surface: str) -> AgentChatSession:)-class _SearchWeb:- name = "search_web"-+class _Brain:def __init__(self) -> None:- self.queries: list[str] = []+ self._config = object()- async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:- self.queries.append(str(args["query"]))- return ToolResult(- success=True,- output={"results": [{"title": "t", "url": "u", "snippet": "s"}, "junk"]},- )+def _probe_kit(monkeypatch: pytest.MonkeyPatch) -> SurfaceKit:+ """A throwaway surface with its own hands and briefing, registered for one test."""-class _Brain:- def __init__(self, cfg: JarvisConfig, tools: dict[str, Any]) -> None:- self._config = cfg- self._tools = tools+ def _tools(cfg: Any, brain: Any) -> dict[str, Tool]:+ return {"probe_read": object()} # type: ignore[dict-item]+ async def _extra(cfg: Any, brain: Any) -> str:+ return "BRIEFING"-def _cfg() -> JarvisConfig:- cfg = JarvisConfig()- cfg.brain.providers["ollama"] = BrainProviderConfig(model="qwen3.5:4b")- return cfg+ kit = SurfaceKit(+ surface="probe",+ brain_runner=True,+ ladder=JARVIS_LADDER,+ uses_stance=True,+ tools=_tools,+ system_extra=_extra,+ tool_origin="probe-origin",+ tool_filter=lambda tools: {n: t for n, t in tools.items() if n.startswith("probe_")},+ max_turns=7,+ )+ monkeypatch.setitem(surface_kits._KITS, "probe", kit)+ return kitdef test_every_surface_has_a_kit_and_the_table_matches_the_store() -> None:assert set(surface_kits._KITS) == set(SURFACES)assert kit_for("nope").surface == "agent"- assert kit_for("jarvis").brain_runner and kit_for(LOCAL_MODELS_SURFACE).brain_runner+ assert kit_for("jarvis").brain_runnerassert not kit_for("agent").brain_runnerdef test_the_four_call_sites_read_the_kit() -> None:- assert resolve_runner("openai", surface=LOCAL_MODELS_SURFACE) == "brain"+ assert resolve_runner("openai", surface="jarvis") == "brain"assert resolve_runner("openai", surface="agent") == "api"- assert ladder_key(LOCAL_MODELS_SURFACE, "brain") == JARVIS_LADDER+ assert ladder_key("jarvis", "brain") == JARVIS_LADDERassert ladder_key("agent", "api") == "api"-def test_build_override_uses_the_kit_tools_and_briefing() -> None:- session = _session(LOCAL_MODELS_SURFACE)- tools = {"lm_inventory": object()}+def test_build_override_uses_the_kit_tools_and_briefing(monkeypatch: pytest.MonkeyPatch) -> None:+ _probe_kit(monkeypatch)+ session = _session("probe")+ tools = {"probe_read": object()}override = build_override(session,brain=None,@@ -85,61 +90,37 @@ def test_build_override_uses_the_kit_tools_and_briefing() -> None:kit_tools=tools, # type: ignore[arg-type]system_extra="BRIEFING",)- assert set(override.tools_extra) == {"lm_inventory"}+ assert set(override.tools_extra) == {"probe_read"}assert override.system_extra == "BRIEFING"- assert override.tool_context["tool_origin"] == "local-models-assistant"+ assert override.tool_context["tool_origin"] == "probe-origin"assert override.tool_context["approval_surface"] == "interactive"- assert override.max_turns == 40+ assert override.max_turns == 7plain = build_override(_session("jarvis"), brain=None, stance="ask", cwd=Path("."), ref="r")assert "Read" in plain.tools_extra and plain.system_extra == ""assert plain.tool_context["tool_origin"] == "agent-chat"-async def test_kit_payload_builds_lm_tools_and_the_briefing() -> None:- search = _SearchWeb()- brain = _Brain(_cfg(), {"search_web": search})- tools, extra = await kit_payload(_session(LOCAL_MODELS_SURFACE), brain)- assert tools is not None and "lm_test_plan" in tools and "lm_pull" in tools- assert all(name.startswith("lm_") for name in tools)- assert "LOCAL MODELS SETUP ASSISTANT" in extra- assert "```jarvis-proposal" in extra+async def test_kit_payload_builds_the_kit_tools_and_the_briefing(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _probe_kit(monkeypatch)+ tools, extra = await kit_payload(_session("probe"), _Brain())+ assert tools is not None and set(tools) == {"probe_read"}+ assert extra == "BRIEFING"- none_tools, none_extra = await kit_payload(_session("jarvis"), brain)+ none_tools, none_extra = await kit_payload(_session("jarvis"), _Brain())assert none_tools is None and none_extra == ""-async def test_search_fn_wraps_the_brains_search_web_tool() -> None:- search = _SearchWeb()- fn = surface_kits.local_models_search_fn(_Brain(_cfg(), {"search_web": search}))- assert fn is not None- rows = await fn("qwen3.5 LMArena")- assert rows == [{"title": "t", "url": "u", "snippet": "s"}]- assert search.queries == ["qwen3.5 LMArena"]- assert surface_kits.local_models_search_fn(_Brain(_cfg(), {})) is None---def test_local_models_surface_drives_cli_seats_through_the_brain() -> None:- """A coding agent's loop has none of the lm_* tools, so a seat whose- provider also ships a brain plugin runs through Jarvis' brain here."""- from jarvis.agent_chat.service import resolve_runner-- assert resolve_runner("antigravity", surface="local-models") == "brain"- assert resolve_runner("gemini", surface="local-models") == "brain"- # The Jarvis surface keeps the vendor CLI for a subscription seat.- assert resolve_runner("antigravity", surface="jarvis") != "brain"---def test_local_models_surface_keeps_only_its_own_hands_and_web_search() -> None:- """The router's 100+ declarations (some with schemas Gemini refuses) never- reach this surface: only lm_* and web search survive the kit filter."""- from jarvis.agent_chat.surface_kits import kit_for+def test_a_kit_filter_keeps_only_its_own_hands(monkeypatch: pytest.MonkeyPatch) -> None:+ kit = _probe_kit(monkeypatch)class _T:def __init__(self, name: str) -> None:self.name = name- tools = {n: _T(n) for n in ("lm_hardware", "search_web", "patch", "spawn-worker", "lm_pull")}- kept = kit_for("local-models").tool_filter(tools) # type: ignore[misc]- assert sorted(kept) == ["lm_hardware", "lm_pull", "search_web"]+ tools = {n: _T(n) for n in ("probe_read", "search_web", "patch", "spawn-worker")}+ assert kit.tool_filter is not None+ assert sorted(kit.tool_filter(tools)) == ["probe_read"] # type: ignore[arg-type]assert kit_for("jarvis").tool_filter is Nonediff --git a/tests/unit/agentic_ide/test_folders_create.py b/tests/unit/agentic_ide/test_folders_create.pynew file mode 100644index 0000000000..77663fa2cf--- /dev/null+++ b/tests/unit/agentic_ide/test_folders_create.py@@ -0,0 +1,104 @@+"""Making a folder from the picker, and finding a hidden one by name.++A new project has no folder to pick; a `.claude` folder is hidden from the+search. Both left the wizard with "go make it in Explorer first", which is the+detour the picker exists to remove.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from jarvis.agentic_ide.folders import create_folder, search_folders+++# ------------------------------------------------------------------- create+def test_creates_one_folder_inside_an_existing_one(tmp_path: Path) -> None:+ entry, error = create_folder(tmp_path, "shop")++ assert error is None+ assert entry is not None+ assert entry.name == "shop"+ assert Path(entry.path) == tmp_path / "shop"+ assert (tmp_path / "shop").is_dir()+ assert entry.is_project is False+++def test_surrounding_whitespace_is_not_part_of_the_name(tmp_path: Path) -> None:+ entry, error = create_folder(tmp_path, " shop ")++ assert error is None+ assert entry is not None and entry.name == "shop"+++def test_a_folder_already_there_is_handed_back_not_refused(tmp_path: Path) -> None:+ (tmp_path / "shop").mkdir()+ (tmp_path / "shop" / ".git").mkdir()++ entry, error = create_folder(tmp_path, "shop")++ assert error is None+ assert entry is not None+ assert entry.is_repo is True+++def test_a_file_of_that_name_is_an_error(tmp_path: Path) -> None:+ (tmp_path / "shop").write_text("", encoding="utf-8")++ entry, error = create_folder(tmp_path, "shop")++ assert entry is None+ assert error is not None and "file" in error++[email protected]("name", ["", " ", ".", "..", "a/b", "a\\b"])+def test_refuses_names_that_are_not_one_plain_segment(tmp_path: Path, name: str) -> None:+ entry, error = create_folder(tmp_path, name)++ assert entry is None+ assert error+ assert not any(p.is_dir() for p in tmp_path.iterdir())+++def test_a_missing_parent_is_reported_not_created(tmp_path: Path) -> None:+ entry, error = create_folder(tmp_path / "nowhere", "shop")++ assert entry is None+ assert error is not None and "nowhere" in error+ assert not (tmp_path / "nowhere").exists()+++def test_no_parent_means_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))++ entry, error = create_folder(None, "shop")++ assert error is None+ assert entry is not None and Path(entry.path) == tmp_path / "shop"+++# ------------------------------------------------------------------- hidden+def test_search_finds_a_hidden_folder_when_asked_for_by_its_dot_name(tmp_path: Path) -> None:+ (tmp_path / ".claude").mkdir()+ (tmp_path / "claude-notes").mkdir()++ names = [e.name for e in search_folders(".claude", roots=[tmp_path])]++ assert names == [".claude"]+++def test_search_still_hides_dot_folders_for_an_ordinary_query(tmp_path: Path) -> None:+ (tmp_path / ".claude").mkdir()+ (tmp_path / "claude-notes").mkdir()++ names = [e.name for e in search_folders("claude", roots=[tmp_path])]++ assert names == ["claude-notes"]+++def test_search_never_walks_into_a_hidden_folder(tmp_path: Path) -> None:+ (tmp_path / ".cache" / ".claude").mkdir(parents=True)++ assert search_folders(".claude", roots=[tmp_path]) == []diff --git a/tests/unit/agentic_ide/test_pane_notifications.py b/tests/unit/agentic_ide/test_pane_notifications.pyindex 5221275c08..7d111ebbff 100644--- a/tests/unit/agentic_ide/test_pane_notifications.py+++ b/tests/unit/agentic_ide/test_pane_notifications.py@@ -18,11 +18,13 @@ and is unusable in a grid of twelve.from __future__ import annotations+import timefrom pathlib import Pathfrom typing import Anyimport pytest+from jarvis.agentic_ide import activity as activity_modfrom jarvis.agentic_ide import notificationsfrom jarvis.agentic_ide import session as session_modfrom jarvis.agentic_ide.activity import STILL_S, read_activity@@ -723,19 +725,186 @@ async def test_a_tool_step_gap_does_not_demand_reconfirmation(watcher.poll(registry, now=at)assert term.activity == "working", "sustained movement confirms"- # A quiet tool step: the screen stands still past its freshness tail.+ # A quiet tool step: the screen stands still past its freshness tail. The+ # RAW reading says waiting; the badge holds (see the next test).watcher.poll(registry, now=1008.0 + STILL_S + 1)+ assert watcher._panes[(_session.id, term.key)].activity == "waiting" # noqa: SLF001+ assert term.activity == "working"++ # The pause outlasts the hold: now it is a stop, dated from the last paint.+ watcher.poll(registry, now=1008.0 + notifications.WORK_HOLD_S + 1)assert term.activity == "waiting"# Work resumes. The badge must follow on the SAME sweep, not five later.term.transcript.clear()_draw(term, "\r\n· working again after the tool call\r\n")- term.last_output_at = 1015.0- watcher.poll(registry, now=1015.0)+ term.last_output_at = 1020.0+ watcher.poll(registry, now=1020.0)assert term.activity == "working", "a resuming job needs no re-confirmation"+async def test_a_short_pause_is_not_published_as_done(registry: Registry, tmp_path: Path) -> None:+ """The dip itself. A working pane that stands still for a beat — a slow+ tool call, the redraw shadow of a resize — used to flip the badge to a+ finished dot for a sweep and restart its clock: a pane whose own spinner+ read "11m 00s" wore "Working for 7s" (maintainer, 2026-08-27). The badge+ now holds "working" for WORK_HOLD_S past the raw flip, and the episode's+ start survives the pause."""+ watcher = notifications.watcher()+ _session, term = await _pane(registry, tmp_path)+ term.last_submit_at = 500.0+ term.submit_generation = term.process_generation+ _quiet_since(term, 999.0)+ _draw(term, IDLE_SCREEN)+ watcher.poll(registry, now=996.0)++ for step, at in enumerate((1000.0, 1002.0, 1004.0, 1006.0, 1008.0)):+ term.transcript.clear()+ _draw(term, f"\r\n· working, frame {step}\r\n")+ term.last_output_at = at+ watcher.poll(registry, now=at)+ assert (term.activity, term.activity_since) == ("working", 1000.0)++ # Still past STILL_S — the raw reading has flipped — but inside the hold.+ for at in (1008.0 + STILL_S + 1, 1008.0 + notifications.WORK_HOLD_S):+ watcher.poll(registry, now=at)+ assert term.activity == "working", f"a pause of {at - 1008.0:.0f}s is not a stop"+ assert term.activity_since == 1000.0, "the clock counts the whole episode"++ # Work resumes: same episode, same clock.+ term.transcript.clear()+ _draw(term, "\r\n· working again\r\n")+ term.last_output_at = 1014.0+ watcher.poll(registry, now=1014.0)+ assert (term.activity, term.activity_since) == ("working", 1000.0)+++async def test_a_stop_is_dated_from_the_last_paint(registry: Registry, tmp_path: Path) -> None:+ """When the hold runs out the badge says "done" — and says since WHEN it+ has been done: the moment the screen last moved, not the sweep that+ finally admitted it. "Done for 0s" about a pane quiet for nine seconds is+ the clock lying the other way."""+ watcher = notifications.watcher()+ _session, term = await _pane(registry, tmp_path)+ term.last_submit_at = 500.0+ term.submit_generation = term.process_generation+ _quiet_since(term, 999.0)+ _draw(term, IDLE_SCREEN)+ watcher.poll(registry, now=996.0)+ for step, at in enumerate((1000.0, 1002.0, 1004.0, 1006.0, 1008.0)):+ term.transcript.clear()+ _draw(term, f"\r\n· working, frame {step}\r\n")+ term.last_output_at = at+ watcher.poll(registry, now=at)++ watcher.poll(registry, now=1008.0 + STILL_S + 1)+ watcher.poll(registry, now=1008.0 + notifications.WORK_HOLD_S + 1)++ assert term.activity == "waiting"+ assert term.activity_since == 1008.0, "quiet since the last paint, not since the sweep"+++async def test_a_question_is_not_held_back_by_the_hold(registry: Registry, tmp_path: Path) -> None:+ """A working pane that stops on a permission prompt has stopped FOR THE+ USER. The hold covers a plain pause only; a question on screen takes the+ badge over the moment the raw reading sees it."""+ watcher = notifications.watcher()+ _session, term = await _pane(registry, tmp_path)+ term.last_submit_at = 500.0+ term.submit_generation = term.process_generation+ _quiet_since(term, 999.0)+ _draw(term, IDLE_SCREEN)+ watcher.poll(registry, now=996.0)+ for step, at in enumerate((1000.0, 1002.0, 1004.0, 1006.0, 1008.0)):+ term.transcript.clear()+ _draw(term, f"\r\n· working, frame {step}\r\n")+ term.last_output_at = at+ watcher.poll(registry, now=at)++ term.transcript.clear()+ _draw(term, QUESTION_SCREEN)+ term.last_output_at = 1009.0+ watcher.poll(registry, now=1009.0)+ watcher.poll(registry, now=1009.0 + STILL_S + 1)++ assert term.activity == "asking"+++# ------------------------------------------------------------ the live feed+#+# The sweep is the one thing that knows the MOMENT a pane's word changes; the+# feed turns that into one event per change for every client on the app+# socket, so a finished session shows as finished without waiting for a poll.+++async def test_the_feed_reports_a_pane_once_per_change(registry: Registry, tmp_path: Path) -> None:+ feed = notifications.ActivityFeed()+ session, term = await _pane(registry, tmp_path)++ first = feed.changes(registry)+ assert [(row["session_id"], row["key"], row["name"]) for row in first] == [+ (session.id, term.key, "Alex")+ ]+ assert feed.changes(registry) == [], "nothing changed, nothing to say"++ # The sweep stamps a new word (on the wall clock: `reading()` trusts a+ # stamp only while it is fresh against the real time).+ now = time.time()+ activity_mod.stamp(term, "working", now=now)+ term.last_submit_at = now+ term.submit_generation = term.process_generation+ rows = feed.changes(registry)+ assert [(row["activity"], row["activity_since"], row["worked"]) for row in rows] == [+ ("working", now, True)+ ]+ assert feed.changes(registry) == []++ # A pane that is gone is forgotten, not carried as a ghost.+ await registry.close_terminal(term.name)+ assert feed.changes(registry) == []+ assert feed._last == {} # noqa: SLF001 - the leak this guards against is invisible otherwise+++async def test_changes_go_to_the_bus_as_pane_activity_events(+ registry: Registry, tmp_path: Path+) -> None:+ """What a client receives: the activity half of a `/panes` row, verbatim,+ under the workspace id and the pane's stable key — enough to patch the+ row in place without a second request."""+ from jarvis.core.events import AgenticIdePaneActivity++ published: list[Any] = []++ async def publish(event: Any) -> None:+ published.append(event)++ notifications.set_publisher(publish)+ session, term = await _pane(registry, tmp_path)++ await notifications._publish_changes(registry) # noqa: SLF001 - the sweep's own step+ await notifications._publish_changes(registry) # noqa: SLF001++ assert len(published) == 1+ event = published[0]+ assert isinstance(event, AgenticIdePaneActivity)+ assert (event.session_id, event.key, event.name) == (session.id, term.key, "Alex")+ assert event.status == "live"+ assert event.activity == term.reading().activity+ assert event.worked is False+ assert event.source_layer == "agentic_ide.notifications"+++async def test_a_deaf_bus_does_not_end_the_sweep(registry: Registry, tmp_path: Path) -> None:+ async def publish(_event: Any) -> None:+ raise RuntimeError("bus closed")++ notifications.set_publisher(publish)+ await _pane(registry, tmp_path)++ await notifications._publish_changes(registry) # noqa: SLF001 - must not raise++async def test_a_question_is_reported_even_though_it_never_worked(registry: Registry, tmp_path: Path) -> None:diff --git a/tests/unit/brain/test_context_window_fit.py b/tests/unit/brain/test_context_window_fit.pynew file mode 100644index 0000000000..21f56a9556--- /dev/null+++ b/tests/unit/brain/test_context_window_fit.py@@ -0,0 +1,250 @@+"""The tool surface fits the answering brain's context window (BUG-187).++Live 2026-08-27 10:11 (and 2026-08-26 20:32, 20:58): the front page's chat+ran on a local 32k model, the registry held 221 tools (78 built-in, 131 from+three connected MCP servers, 12 CLIs) and a plain "Hallo" went out as 67,852+tokens. The server refused it with a 400 that named the cause, the+one-provider chain was exhausted, and the user read "I can't reach my provider+— check the network". Two defects, two guards:++1. Nothing read ``Brain.context_window`` — ``_fit_tools_to_context_window``+ now sizes the surface: connected-server tools leave first, then the largest+ remaining ones, mandated tools never.+2. The 400 was classified as a generic call failure —+ ``_classify_provider_error`` now returns ``context_overflow`` and the cause+ phrase / diagnostic name the size, not the network.+"""+from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any++import pytest++from jarvis.brain.manager import (+ _DEAD_LIST_KINDS,+ _PROVIDER_DOWN_CAUSE_PHRASES,+ BrainManager,+ _classify_provider_error,+ _fit_tools_to_context_window,+ _format_provider_chain_error,+ _primary_provider_down_cause,+ _provider_down_phrase,+ _tool_surface_tokens,+)++# The exact server refusal from the live log (Ollama over the OpenAI route).+_LIVE_OLLAMA_400 = (+ "Error code: 400 - {'error': {'message': '{\"error\":{\"code\":400,"+ "\"message\":\"request (67852 tokens) exceeds the available context size "+ "(32768 tokens), try increasing it\",\"type\":\"exceed_context_size_error\","+ "\"n_prompt_tokens\":67852,\"n_ctx\":32768}}', 'type': 'invalid_request_error'}}"+)+++@dataclass+class _FakeTool:+ name: str+ description: str = "does a thing"+ schema: dict[str, Any] = field(default_factory=lambda: {"type": "object", "properties": {}})+ is_mcp_tool: bool = False+++def _tool(name: str, *, size: int = 1, mcp: bool = False) -> _FakeTool:+ """A tool whose wire size scales with ``size`` (schema padding)."""+ props = {f"arg{i}": {"type": "string", "description": "x" * 40} for i in range(size)}+ return _FakeTool(+ name=name,+ schema={"type": "object", "properties": props},+ is_mcp_tool=mcp,+ )+++class _FakeBrain:+ name = "fake"+ context_window = 0+ supports_vision = False++ def __init__(self, window: int) -> None:+ self.context_window = window+++# --------------------------------------------------------------- the fit+++class TestFitToolsToContextWindow:+ def test_no_declared_window_leaves_the_surface_alone(self) -> None:+ tools = {"a": _tool("a", size=50), "b": _tool("b", size=50)}+ fitted, dropped = _fit_tools_to_context_window(+ tools, context_window=0, used_tokens=1_000_000+ )+ assert fitted is tools+ assert dropped == []++ def test_a_surface_that_fits_is_untouched(self) -> None:+ tools = {"a": _tool("a"), "b": _tool("b", mcp=True)}+ fitted, dropped = _fit_tools_to_context_window(+ tools, context_window=100_000, used_tokens=10_000+ )+ assert fitted is tools+ assert dropped == []++ def test_connected_server_tools_leave_before_built_in_ones(self) -> None:+ # Two small built-ins and two LARGE MCP tools; the budget holds only+ # the built-ins. Size alone would keep nothing built-in either way —+ # the group order is what protects Jarvis's own hands.+ tools = {+ "run_shell": _tool("run_shell", size=2),+ "search_web": _tool("search_web", size=2),+ "github/create_issue": _tool("github/create_issue", size=20, mcp=True),+ "linear/list_issues": _tool("linear/list_issues", size=20, mcp=True),+ }+ built_in_cost = sum(+ _tool_surface_tokens(n, t) for n, t in tools.items() if not t.is_mcp_tool+ )+ fitted, dropped = _fit_tools_to_context_window(+ tools, context_window=built_in_cost + 100, used_tokens=100+ )+ assert set(fitted) == {"run_shell", "search_web"}+ assert dropped == ["linear/list_issues", "github/create_issue"] or dropped == [+ "github/create_issue",+ "linear/list_issues",+ ]++ def test_then_the_largest_remaining_tools_go_first(self) -> None:+ tools = {+ "tiny": _tool("tiny", size=1),+ "huge": _tool("huge", size=40),+ "medium": _tool("medium", size=5),+ }+ budget = _tool_surface_tokens("tiny", tools["tiny"]) + _tool_surface_tokens(+ "medium", tools["medium"]+ )+ fitted, dropped = _fit_tools_to_context_window(+ tools, context_window=budget, used_tokens=0+ )+ assert dropped == ["huge"]+ assert list(fitted) == ["tiny", "medium"] # registry order preserved++ def test_kept_names_are_never_dropped(self) -> None:+ tools = {+ "mandated": _tool("mandated", size=40),+ "other": _tool("other", size=1),+ }+ fitted, dropped = _fit_tools_to_context_window(+ tools, context_window=10, used_tokens=0, keep={"mandated"}+ )+ assert "mandated" in fitted+ assert dropped == ["other"]++ def test_prompt_larger_than_window_drops_every_droppable_tool(self) -> None:+ tools = {"a": _tool("a"), "b": _tool("b", mcp=True)}+ fitted, dropped = _fit_tools_to_context_window(+ tools, context_window=1_000, used_tokens=5_000+ )+ assert fitted == {}+ assert set(dropped) == {"a", "b"}+++class TestFitOnTheManager:+ def _mgr(self) -> BrainManager:+ m = BrainManager.__new__(BrainManager) # bypass heavy __init__+ m._tools = {}+ m._evidence_required_tool = None+ m._skill_turn_match = None+ return m++ def test_cloud_sized_window_keeps_the_whole_surface(self) -> None:+ m = self._mgr()+ tools = {f"t{i}": _tool(f"t{i}", size=10, mcp=i % 2 == 0) for i in range(221)}+ fitted = m._fit_tools_to_brain(+ tools, _FakeBrain(1_048_576), system_prompt="x" * 40_000, history=None+ )+ assert fitted is tools++ def test_local_window_trims_the_live_shape(self) -> None:+ # 221 tools, a long system prompt, a 32k window: the surface shrinks+ # and the connected-server tools are the ones that went.+ m = self._mgr()+ tools = {f"t{i}": _tool(f"t{i}", size=10, mcp=i % 2 == 0) for i in range(221)}+ fitted = m._fit_tools_to_brain(+ tools, _FakeBrain(32_768), system_prompt="x" * 30_000, history=None+ )+ assert 0 < len(fitted) < 221+ assert not any(t.is_mcp_tool for t in fitted.values())++ def test_mandated_tool_survives_a_local_window(self) -> None:+ m = self._mgr()+ m._evidence_required_tool = "search_web"+ m._skill_turn_match = object()+ tools = {+ "search_web": _tool("search_web", size=60),+ "run-skill": _tool("run-skill", size=60),+ "github/x": _tool("github/x", size=60, mcp=True),+ }+ fitted = m._fit_tools_to_brain(+ tools, _FakeBrain(4_200), system_prompt="", history=None+ )+ assert {"search_web", "run-skill"} <= set(fitted)+ assert "github/x" not in fitted++ def test_undeclared_window_is_left_alone(self) -> None:+ m = self._mgr()++ class _Windowless:+ name = "w"++ tools = {"a": _tool("a", size=60)}+ assert m._fit_tools_to_brain(tools, _Windowless(), system_prompt="", history=None) is tools+++# ---------------------------------------------------------- the cause+++class TestContextOverflowCause:+ @pytest.mark.parametrize(+ "msg",+ [+ _LIVE_OLLAMA_400,+ "Error code: 400 - This model's maximum context length is 128000 tokens.",+ "Error code: 400 - context_length_exceeded",+ "prompt is too long: 213462 tokens > 200000 maximum",+ "400 INVALID_ARGUMENT. The input token count (2000000) exceeds the "+ "maximum number of tokens allowed (1048576).",+ ],+ )+ def test_size_refusals_classify_as_context_overflow(self, msg: str) -> None:+ assert _classify_provider_error(msg, default="call_fail") == "context_overflow"++ def test_overflow_never_dead_lists_the_provider(self) -> None:+ assert "context_overflow" not in _DEAD_LIST_KINDS++ def test_a_plain_400_still_falls_through(self) -> None:+ kind = _classify_provider_error("Error code: 400 - bad request", default="call_fail")+ assert kind == "call_fail"++ def test_spoken_cause_names_the_size_not_the_network(self) -> None:+ errors = [("ollama", "qwen3.8-16gb:latest", "context_overflow", _LIVE_OLLAMA_400)]+ cause = _primary_provider_down_cause(errors)+ assert cause == "context_overflow"+ for lang in ("de", "en", "es"):+ phrase = _provider_down_phrase(lang, 0, cause)+ assert phrase == _PROVIDER_DOWN_CAUSE_PHRASES["context_overflow"][lang]+ low = phrase.lower()+ assert "netzwerk" not in low and "network" not in low and "red" != low+ assert "ollama" not in low # voice-safe: no provider names++ def test_missing_key_still_outranks_an_overflow(self) -> None:+ errors = [+ ("ollama", "m", "context_overflow", "…"),+ ("gemini", "g", "missing_key", "…"),+ ]+ assert _primary_provider_down_cause(errors) == "missing_key"++ def test_developer_diagnostic_stops_blaming_the_network(self) -> None:+ text = _format_provider_chain_error(+ [("ollama", "qwen3.8-16gb:latest", "context_overflow", _LIVE_OLLAMA_400)]+ )+ assert "Kontextfenster" in text # i18n-allow: the diagnostic is German+ assert "ollama" in text+ assert "Netzwerk" not in text # i18n-allowdiff --git a/tests/unit/brain/test_gemini_schema_sanitize.py b/tests/unit/brain/test_gemini_schema_sanitize.pyindex f169d408f7..9ed1d07064 100644--- a/tests/unit/brain/test_gemini_schema_sanitize.py+++ b/tests/unit/brain/test_gemini_schema_sanitize.py@@ -12,7 +12,9 @@ Drive question got no real answer for reasons unrelated to Drive.import json-from jarvis.plugins.brain.gemini import _sanitize_for_gemini+import pytest++from jarvis.plugins.brain.gemini import _gemini_schema_keys, _sanitize_for_geminidef _flatten(schema: dict) -> str:@@ -73,3 +75,86 @@ def test_sanitizer_recurses_into_nested_and_lists():assert "propertyNames" not in _flatten(clean)# Structure preserved.assert clean["properties"]["outer"]["items"]["type"] == "object"+++def test_an_unknown_extension_key_is_dropped_whatever_it_is_called():+ """The 2026-08-26 outage: the GitHub MCP server tags parameters with+ ``x-mcp-header``. It was on no block-list, so 81 validation errors killed+ the whole request and the front page's chat answered "I can't reach my+ provider". An allow-list does not need to have heard of it."""+ bad = {+ "type": "object",+ "properties": {+ "owner": {"type": "string", "description": "Repo owner", "x-mcp-header": "owner"},+ "repo": {"type": "string", "x-mcp-header": "repo"},+ },+ "required": ["owner", "repo"],+ }+ clean = _sanitize_for_gemini(bad)+ assert "x-mcp-header" not in _flatten(clean)+ # A stripped tool is not a fix: the parameters and their prose survive.+ assert set(clean["properties"]) == {"owner", "repo"}+ assert clean["properties"]["owner"]["description"] == "Repo owner"+ assert clean["required"] == ["owner", "repo"]+ # And an invented key nobody has seen yet goes the same way.+ invented = _sanitize_for_gemini({"type": "string", "x-vendor-someday": {"a": 1}})+ assert invented == {"type": "string"}+++def test_a_property_named_like_a_schema_keyword_survives():+ """Under ``properties`` the keys are names a tool author chose. Judging+ those against the allow-list would delete the parameters themselves — the+ one way an allow-list can be worse than the block-list it replaces."""+ schema = {+ "type": "object",+ "properties": {+ "strict": {"type": "boolean"},+ "propertyNames": {"type": "string"},+ "x-mcp-header": {"type": "string"},+ },+ }+ clean = _sanitize_for_gemini(schema)+ assert set(clean["properties"]) == {"strict", "propertyNames", "x-mcp-header"}+ assert clean["properties"]["strict"]["type"] == "boolean"+++def test_a_data_value_is_not_walked_as_a_schema():+ """``example``/``default`` carry the tool author's DATA. A dict in there+ that happens to look like a schema must come back byte-identical."""+ schema = {+ "type": "object",+ "properties": {+ "cfg": {"type": "object", "default": {"strict": True, "propertyNames": "x"}},+ },+ }+ clean = _sanitize_for_gemini(schema)+ assert clean["properties"]["cfg"]["default"] == {"strict": True, "propertyNames": "x"}+++def test_the_allow_list_comes_from_the_installed_library():+ """The model that rejects the request is the only honest source for what+ it accepts — so the list is read off it, not spelled out beside it."""+ keys = _gemini_schema_keys()+ assert {"type", "properties", "items", "required", "description"} <= keys+ assert "x-mcp-header" not in keys and "strict" not in keys+++def test_the_sanitized_schema_passes_googles_own_validator():+ """The end-to-end claim: what we send validates where it is validated."""+ types = pytest.importorskip("google.genai.types")+ dirty = {+ "type": "object",+ "properties": {+ "owner": {"type": "string", "x-mcp-header": "owner"},+ "page": {"type": "integer", "exclusiveMinimum": 0},+ "anchor": {"type": "string", "propertyNames": {"type": "string"}},+ "opts": {"type": "object", "strict": True, "additionalProperties": False},+ },+ "required": ["owner"],+ }+ with pytest.raises(Exception):+ types.Schema.model_validate(dirty)+ clean = _sanitize_for_gemini(dirty)+ types.Schema.model_validate(clean) # must not raise+ # The exclusive bound was converted, not merely dropped.+ assert clean["properties"]["page"]["minimum"] == 0diff --git a/tests/unit/plugins/tool/test_youtube_music_rest.py b/tests/unit/plugins/tool/test_youtube_music_rest.pyindex 951c9208b1..55d8b697c8 100644--- a/tests/unit/plugins/tool/test_youtube_music_rest.py+++ b/tests/unit/plugins/tool/test_youtube_music_rest.py@@ -447,6 +447,61 @@ async def test_control_with_nothing_registered_is_an_error():assert "Nothing is registered" in out["error"]+# -- blind media keys (a machine that cannot read its media session) ---------+#+# Live 2026-08-26 19:50: "play some cool music" arrived as play without a+# title, the machine had no winrt, the tool pressed the play/pause toggle+# blindly and answered ``ok: true, resumed: true`` — the voice said "I've+# just started some cool music on YouTube Music" over a silent machine.+++def _blind() -> FakeMedia:+ return FakeMedia(now=None, can_read=False, backend="media-keys", note="install X")+++async def test_blind_play_with_nothing_known_paused_presses_nothing_and_says_so():+ media = _blind()+ out = await _tool(_search_handler, media=media).play(query="")+ assert media.calls == []+ assert "say what to play" in out["error"]+++async def test_blind_pause_is_an_attempt_not_a_result():+ media = _blind()+ out = await _tool(_search_handler, media=media).pause()+ assert media.calls == ["pause"]+ assert out["ok"] is True and out["verified"] is False+ assert "cannot confirm" in out["note"] and "install X" in out["note"]+ assert "track" not in out+++async def test_blind_play_after_a_blind_pause_is_a_resume_attempt():+ media = _blind()+ tool = _tool(_search_handler, media=media)+ await tool.pause()+ out = await tool.play(query="")+ assert media.calls == ["pause", "play"]+ assert out["ok"] is True and out["resumed"] is True and out["verified"] is False+ # The resume spent the pause: a second bare play is a guess again.+ out = await tool.play(query="")+ assert media.calls == ["pause", "play"] and "say what to play" in out["error"]+++async def test_readable_session_control_is_verified():+ media = FakeMedia(now=_playing())+ out = await _tool(_search_handler, media=media).pause()+ assert out["ok"] is True and out["verified"] is True and out["track"] == "Karma Police"+++async def test_blind_play_of_a_song_opens_the_link_but_never_claims_playback():+ media = _blind()+ opener = Opener(media=media)+ out = await _tool(_search_handler, media=media, opener=opener).play(query="Karma Police")+ assert opener.urls == [song_url("vid123")]+ assert out["ok"] is True and out["playback_confirmed"] is False+ assert out["verified"] is False and "cannot confirm" in out["note"]++# -- library writes -----------------------------------------------------------diff --git a/tests/unit/realtime/test_tools.py b/tests/unit/realtime/test_tools.pyindex b1dd705747..1c016e74ec 100644--- a/tests/unit/realtime/test_tools.py+++ b/tests/unit/realtime/test_tools.py@@ -28,8 +28,9 @@ class FakeTool:class FakeExecutor:- def __init__(self, *, confirmation_required: bool = False) -> None:+ def __init__(self, *, confirmation_required: bool = False, output="opened") -> None:self.confirmation_required = confirmation_required+ self.output = outputself.execute_calls = []self.confirmed_calls = []self.cancelled = []@@ -43,7 +44,7 @@ class FakeExecutor:output={"tool_name": tool.name},error=VOICE_CONFIRM_SENTINEL,)- return SimpleNamespace(success=True, output="opened", error=None)+ return SimpleNamespace(success=True, output=self.output, error=None)async def execute_confirmed(self, trace_id, **kwargs):self.confirmed_calls.append((trace_id, kwargs))@@ -121,6 +122,41 @@ async def test_available_tool_runs_only_through_tool_executor():assert executor.execute_calls[0][2]["config_snapshot"]["voice_confirm"] is True+async def test_unverified_outcome_carries_the_attempt_not_outcome_instruction():+ """A tool that acted blind (``verified: false``) must reach the model as+ an attempt: live 2026-08-26 19:50 a media-key "play" came back ok and+ the voice announced music that never started."""+ tool = FakeTool("youtube_music")+ executor = FakeExecutor(output={"ok": True, "action": "play", "verified": False})+ bridge = RealtimeToolBridge(tools={"youtube_music": tool}, executor=executor, language="en")++ _name, result = await bridge.execute(+ wire_name="youtube_music", arguments={"app_name": "x"}+ )++ assert result["success"] is True and result["unverified"] is True+ assert "not a confirmed outcome" in result["instruction"]+ assert "never say it is done" in result["instruction"]+++async def test_verified_outcome_carries_no_instruction():+ tool = FakeTool("youtube_music")+ executor = FakeExecutor(output={"ok": True, "action": "play", "verified": True})+ bridge = RealtimeToolBridge(tools={"youtube_music": tool}, executor=executor, language="en")++ _name, result = await bridge.execute(+ wire_name="youtube_music", arguments={"app_name": "x"}+ )++ assert result == {+ "success": True,+ "output": {"ok": True, "action": "play", "verified": True},+ "error": None,+ }++@pytest.mark.asyncioasync def test_vertex_toolset_prefix_resolves_to_the_declared_tool():"""Vertex Live prefixes user-declared functions with the tool-set name.diff --git a/tests/unit/web/test_agentic_ide_create_folder.py b/tests/unit/web/test_agentic_ide_create_folder.pynew file mode 100644index 0000000000..bb99752b93--- /dev/null+++ b/tests/unit/web/test_agentic_ide_create_folder.py@@ -0,0 +1,34 @@+"""``POST /folders/create`` — a refusal is an answer, not a status code.++The picker shows the reason next to the name field, the same way it shows a+typed path that does not exist, so the route reports through ``error`` and+never raises for an ordinary "no".+"""++from __future__ import annotations++from pathlib import Path++from jarvis.ui.web import agentic_ide_routes as routes+++async def test_makes_the_folder_and_describes_it(tmp_path: Path) -> None:+ res = await routes.create_new_folder(+ routes.CreateFolderRequest(parent=str(tmp_path), name="shop")+ )++ assert res.error is None+ assert res.folder is not None+ assert res.folder.name == "shop"+ assert Path(res.folder.path) == tmp_path / "shop"+ assert (tmp_path / "shop").is_dir()+++async def test_a_bad_name_comes_back_as_a_reason(tmp_path: Path) -> None:+ res = await routes.create_new_folder(+ routes.CreateFolderRequest(parent=str(tmp_path), name="a/b")+ )++ assert res.folder is None+ assert res.error is not None and "slashes" in res.error+ assert list(tmp_path.iterdir()) == [] # noqa: ASYNC240