Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat: add voice orb prompt context
Ruben Lütkeb30d6ac94e35
diff --git a/jarvis/agentic_ide/fanout.py b/jarvis/agentic_ide/fanout.pyindex 15ac5c2f3e..3a83172d9a 100644--- a/jarvis/agentic_ide/fanout.py+++ b/jarvis/agentic_ide/fanout.py@@ -130,6 +130,59 @@ def _unique(terminals: Sequence[str]) -> list[str]:return out+async def _reserve_prompt_attachments(term: Any) -> tuple[tuple[Any, ...], tuple[Any, ...]]:+ """Reserve unclaimed batches and return both batches and flat analyses."""+ lock = term.pending_prompt_attachment_lock+ async with lock:+ batches = tuple(+ batch+ for batch in term.pending_prompt_attachment_batches+ if batch.batch_id not in term.pending_prompt_attachment_reservations+ )+ term.pending_prompt_attachment_reservations.update(+ batch.batch_id for batch in batches+ )+ attachments = tuple(+ attachment for batch in batches for attachment in batch.attachments+ )+ return batches, attachments+++async def _finish_prompt_attachments(+ term: Any, batches: Sequence[Any], *, consume: bool+) -> None:+ """Commit or release reservations without touching later drops."""+ if not batches:+ return+ batch_ids = {batch.batch_id for batch in batches}+ async with term.pending_prompt_attachment_lock:+ if consume:+ term.pending_prompt_attachment_batches[:] = [+ batch+ for batch in term.pending_prompt_attachment_batches+ if batch.batch_id not in batch_ids+ ]+ term.pending_prompt_attachment_reservations.difference_update(batch_ids)+++async def _finish_prompt_attachments_shielded(+ term: Any, batches: Sequence[Any], *, consume: bool+) -> None:+ """Settle a reservation even when its delivery task is being cancelled."""+ if not batches:+ return+ cleanup = asyncio.create_task(+ _finish_prompt_attachments(term, batches, consume=consume)+ )+ try:+ await asyncio.shield(cleanup)+ except asyncio.CancelledError:+ # Shield keeps the state transition alive; wait for its lock-protected+ # commit before forwarding cancellation to the caller.+ await cleanup+ raise++async def _default_compose(utterance: str, **kwargs: Any) -> Any:from .prompt_composer import compose as compose_prompt@@ -153,6 +206,7 @@ async def deliver(compose: Callable[..., Awaitable[Any]] | None = None,send: Callable[[str, str], Awaitable[Any]] | None = None,limit: int = DEFAULT_CONCURRENCY,+ include_pending_attachments: bool = False,) -> FanOutResult:"""Compose and deliver a prompt for each of ``terminals``.@@ -170,6 +224,10 @@ async def deliver(``compose`` and ``send`` are injectable so this can be tested without a livePTY or a provider; production leaves them at their defaults.+ ``include_pending_attachments`` belongs only to the spoken Agentic-IDE+ delivery path. Manual REST/CLI fan-out must not steal a drop that was+ explicitly staged for the next spoken prompt.+Never raises for a single pane. A pane that is missing, not running, whoseprompt could not be written, or whose PTY write failed comes back as anundelivered ``Delivery`` carrying the reason.@@ -238,7 +296,15 @@ async def deliver()own_instruction = (assignments or {}).get(term.name) or instruction+ pending_batches: tuple[Any, ...] = ()+ pending_attachments: tuple[Any, ...] = ()async with gate:+ # Reserve after acquiring the concurrency slot so cancellation+ # while waiting cannot leave an invisible batch stuck as reserved.+ if include_pending_attachments:+ pending_batches, pending_attachments = (+ await _reserve_prompt_attachments(term)+ )try:from .session import AGENT_DISPLAY@@ -249,8 +315,17 @@ async def deliver(agent_display=AGENT_DISPLAY.get(term.agent, term.agent),instruction=own_instruction,conversation=tuple(conversation or ()),+ attachments=pending_attachments,)+ except asyncio.CancelledError:+ await _finish_prompt_attachments_shielded(+ term, pending_batches, consume=False+ )+ raiseexcept Exception as exc: # noqa: BLE001 - one pane must not sink the fleet+ await _finish_prompt_attachments_shielded(+ term, pending_batches, consume=False+ )log.warning("Agentic IDE fan-out: composing for %s failed", term.name,exc_info=True,@@ -264,6 +339,9 @@ async def deliver(text = getattr(composed, "text", "") or ""if not text.strip():+ await _finish_prompt_attachments_shielded(+ term, pending_batches, consume=False+ )# An empty prompt would submit a bare Enter into the agent, which# reads as "the user pressed return" and can re-run its last task.return Delivery(@@ -275,7 +353,15 @@ async def deliver(try:sent = await send_fn(term.name, text)+ except asyncio.CancelledError:+ await _finish_prompt_attachments_shielded(+ term, pending_batches, consume=False+ )+ raiseexcept Exception as exc: # noqa: BLE001 - report, never propagate+ await _finish_prompt_attachments_shielded(+ term, pending_batches, consume=False+ )log.info("Agentic IDE fan-out: could not send to %s: %s", term.name, exc)return Delivery(terminal=term.name,@@ -284,6 +370,10 @@ async def deliver(reason=f"it did not accept the prompt ({exc})",)+ await _finish_prompt_attachments_shielded(+ term, pending_batches, consume=True+ )+# The sender reports whether the agent actually STARTED. A sender that# says nothing leaves it None (unknown) rather than claiming success —# the readback then stays silent about it instead of overstating.diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex f254709d33..8fbb72ed38 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -783,6 +783,15 @@ class PaneViewer:rows: int+@dataclass(frozen=True, slots=True)+class PendingPromptAttachmentBatch:+ """One explicitly targeted drop waiting for a spoken pane prompt."""++ batch_id: str+ attachments: tuple[Any, ...]+ files: tuple[str, ...]++@dataclass(slots=True)class Terminal:"""One named pane: a call-sign, an agent, and its live PTY (if attached)."""@@ -854,6 +863,20 @@ class Terminal:prompt_records: list[prompt_history.PromptHistoryEntry] = field(default_factory=list, repr=False, compare=False)+ # Explicitly targeted drops waiting for this pane's next spoken prompt.+ # A batch is reserved by identity before composition and removed only after+ # a successful PTY write. The lock protects short state transitions; model+ # and PTY awaits never run while it is held. Ephemeral by design: this is a+ # pending gesture, not workspace history worth restoring after a restart.+ pending_prompt_attachment_batches: list[PendingPromptAttachmentBatch] = field(+ default_factory=list, repr=False, compare=False+ )+ pending_prompt_attachment_reservations: set[str] = field(+ default_factory=set, repr=False, compare=False+ )+ pending_prompt_attachment_lock: asyncio.Lock = field(+ default_factory=asyncio.Lock, repr=False, compare=False+ )# When the last prompt was handed to this pane, as a wall-clock timestamp.## The receipt the user is shown is built from THIS rather than from thediff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex b927aa8b1e..e07d833690 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -5904,6 +5904,7 @@ class BrainManager:user_text: str,*,trace_id: UUID | None = None,+ consume_pending_voice_attachments: bool = False,) -> str | None:"""Deliver a spoken instruction to the addressed Agentic-IDE terminal.@@ -6022,6 +6023,9 @@ class BrainManager:utterance=original,instruction="",language=out_lang,+ consume_pending_voice_attachments=(+ consume_pending_voice_attachments+ ),)if not addressed:@@ -6050,6 +6054,9 @@ class BrainManager:session=session,candidates=candidates,language=out_lang,+ consume_pending_voice_attachments=(+ consume_pending_voice_attachments+ ),)if retry is not None:return retry@@ -6127,6 +6134,7 @@ class BrainManager:instruction=found.instruction,language=out_lang,assignments=assignments,+ consume_pending_voice_attachments=consume_pending_voice_attachments,)if leftover is not None:# Armed only now: a question about the rest of the fleet is worth@@ -6178,6 +6186,7 @@ class BrainManager:instruction: str,language: str,assignments: dict[str, str] | None = None,+ consume_pending_voice_attachments: bool = False,) -> str | None:"""Compose and type one instruction into the addressed panes.@@ -6212,6 +6221,7 @@ class BrainManager:instruction=instruction,assignments=assignments,conversation=self._agentic_ide_conversation(utterance),+ include_pending_attachments=consume_pending_voice_attachments,)except Exception: # noqa: BLE001 - never crash the turn over a panelog.warning("Agentic IDE fast-path failed", exc_info=True)@@ -6241,6 +6251,7 @@ class BrainManager:session: Any,candidates: list[str],language: str,+ consume_pending_voice_attachments: bool = False,) -> str | None:"""Deliver the PREVIOUS turn's briefing when the user says it never went.@@ -6324,6 +6335,7 @@ class BrainManager:utterance=previous,instruction="",language=language,+ consume_pending_voice_attachments=consume_pending_voice_attachments,)def _ask_which_agentic_ide_terminal(@@ -9098,6 +9110,7 @@ class BrainManager:publish_response: bool = True,history_override: Iterable[BrainMessage] | None = None,force_output_language: str | None = None,+ consume_pending_voice_attachments: bool = False,) -> str:"""Generate a turn, optionally leaving its public response event to the caller.@@ -9127,6 +9140,9 @@ class BrainManager:prefer_tool_model=prefer_tool_model,emit_tool_ack=emit_tool_ack,force_output_language=force_output_language,+ consume_pending_voice_attachments=(+ consume_pending_voice_attachments+ ),)finally:# Keep the last completed turn inspectable for diagnostics/tests,@@ -9154,6 +9170,7 @@ class BrainManager:prefer_tool_model: bool = False,emit_tool_ack: bool = True,force_output_language: str | None = None,+ consume_pending_voice_attachments: bool = False,) -> str:# 1. Intercept meta-commands (cancel, switch, depth override).# User request 2026-04-25: no standardised confirmation phrases@@ -9620,7 +9637,9 @@ class BrainManager:# moves the UI even when a pane happens to share that word. Returns None# on every turn that does not address a terminal.ide_reply = await self._run_agentic_ide_fast_path(- user_text, trace_id=turn_trace_id,+ user_text,+ trace_id=turn_trace_id,+ consume_pending_voice_attachments=consume_pending_voice_attachments,)if ide_reply is not None:await self._record_response_side_effects(@@ -10859,6 +10878,7 @@ class BrainManager:on_progress: Callable[[], None] | None = None,allow_voice_confirm: bool = False,conversation_id: str | None = None,+ consume_pending_voice_attachments: bool = False,) -> AsyncIterator[str]:"""Latency sprint 1: streaming variant of ``generate``.@@ -10917,6 +10937,9 @@ class BrainManager:on_progress=on_progress,allow_voice_confirm=allow_voice_confirm,conversation_id=conversation_id,+ consume_pending_voice_attachments=(+ consume_pending_voice_attachments+ ),)finally:# Sentinel signals "brain is done (or crashed)".diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex c11d952bbb..9967ad0e0e 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -12183,7 +12183,11 @@ class SpeechPipeline:# path above, which uses it as a no-progress (stall) window. This path# is a production minority; the stall fix lives on the streaming path.response = await asyncio.wait_for(- self._brain_with_ack(text, lang),+ self._brain_with_ack(+ text,+ lang,+ consume_pending_voice_attachments=True,+ ),timeout=self._brain_timeout_s,)except TimeoutError:@@ -12895,7 +12899,15 @@ class SpeechPipeline:self._brain_streaming(text, lang))else:- reply = await self._brain.generate(text)+ try:+ generate_call = self._brain.generate(+ text, consume_pending_voice_attachments=True+ )+ except TypeError:+ # Compatibility for small test/provider adapters that still+ # expose the pre-modality Brain protocol.+ generate_call = self._brain.generate(text)+ reply = await generate_callif reply:await self._speak(reply, language=lang, kind=SPOKEN_KIND_COMPLETION)except Exception as exc: # noqa: BLE001 — AD-OE6: never crash the turn@@ -13176,11 +13188,14 @@ class SpeechPipeline:text,on_progress=self._mark_brain_progress,allow_voice_confirm=True,+ consume_pending_voice_attachments=True,)except TypeError:try:stream = self._brain.generate_stream(- text, on_progress=self._mark_brain_progress,+ text,+ on_progress=self._mark_brain_progress,+ consume_pending_voice_attachments=True,)except TypeError:stream = self._brain.generate_stream(text)@@ -13929,7 +13944,13 @@ class SpeechPipeline:except Exception as exc: # noqa: BLE001log.warning("Brain-timeout fallback speak failed: %s", exc)- async def _brain_with_ack(self, text: str, lang: str) -> str:+ async def _brain_with_ack(+ self,+ text: str,+ lang: str,+ *,+ consume_pending_voice_attachments: bool = False,+ ) -> str:"""Brain-Call mit optionalem Zwischen-Ack.Startet Brain-Call und einen ``_task_ack_delay_s``-Timer parallel.@@ -13939,7 +13960,18 @@ class SpeechPipeline:Brain weiterwarten. Nach Ack-Playback wieder THINKING anzeigen,damit der Orb den richtigen Modus hat."""- brain_task = asyncio.create_task(self._brain(text), name="brain")+ generate = getattr(self._brain, "generate", None)+ if consume_pending_voice_attachments and callable(generate):+ try:+ brain_call = generate(+ text, consume_pending_voice_attachments=True+ )+ except TypeError:+ # Compatibility for older Brain adapters without turn modality.+ brain_call = generate(text)+ else:+ brain_call = self._brain(text)+ brain_task = asyncio.create_task(brain_call, name="brain")timer_task = asyncio.create_task(asyncio.sleep(self._task_ack_delay_s), name="ack-timer")diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 413369eb93..10a0ad70e3 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -37,6 +37,9 @@ Endpoints (prefix ``/api/agentic-ide``):* ``GET /terminals/{name}/prompts`` → every prompt handed to that pane* ``POST /terminals/{name}/prompt`` → type a prompt into it and press Enter* ``POST /terminals/{name}/attach`` → drop/paste files onto a pane+* ``GET /voice-attachments`` → every pending orb-drop receipt+* ``GET /terminals/{name}/voice-attachments`` → pending orb-drop receipts+* ``DELETE /terminals/{name}/voice-attachments/{batch_id}`` → cancel one drop* ``WS /pty/{name}`` → the pane's live terminal stream``{name}`` accepts the call-sign ("t2", "T2") or a spoken phrase containing it@@ -50,6 +53,7 @@ import asyncioimport loggingfrom dataclasses import asdictfrom pathlib import Path+from uuid import uuid4from fastapi import (APIRouter,@@ -90,6 +94,7 @@ from jarvis.agentic_ide.session import (MAX_TERMINAL_NAME,MAX_TERMINALS,MAX_WORKSPACES,+ PendingPromptAttachmentBatch,Session,SessionError,SessionNotReady,@@ -119,6 +124,13 @@ router = APIRouter(prefix="/api/agentic-ide", tags=["agentic-ide"])#: than waited for indefinitely.SPAWN_READY_TIMEOUT_S = 20.0+# The prompt composer already caps one analysed drop at 20k characters. Keep+# repeated orb drops within the same total budget so a forgotten queue cannot+# grow without bound or crowd the spoken instruction out of its own prompt.+MAX_PENDING_VOICE_BATCHES = 8+MAX_PENDING_VOICE_ATTACHMENTS = 16+MAX_PENDING_VOICE_CHARS = 20_000+async def _announce_coding_mode(request: Request) -> None:"""Tell every connected client what the coding mode is NOW.@@ -2259,6 +2271,20 @@ async def get_prompt_history()+def _terminal_or_http_error(name: str) -> tuple[Session, Terminal]:+ """Resolve a globally unique pane name with consistent HTTP errors."""+ registry = get_registry()+ found = registry.find_terminal(name)+ if found is not None:+ return found+ if not registry.sessions:+ raise HTTPException(status_code=409, detail="No Agentic-IDE session is running.")+ known = ", ".join(t.name for s in registry.sessions for t in s.terminals) or "none"+ raise HTTPException(+ status_code=404, detail=f"No terminal called {name!r}. Running: {known}."+ )++@router.get("/terminals/{name}/report", summary="What one terminal is doing")async def terminal_report(name: str, lines: int = 40) -> dict:"""Status plus the recent readable output of the terminal called ``name``."""@@ -2268,6 +2294,83 @@ async def terminal_report(name: str, lines: int = 40) -> dict:raise HTTPException(status_code=404, detail=str(exc)) from exc+ "/voice-attachments",+ summary="List every file batch waiting for a spoken terminal prompt",+)+async def all_terminal_voice_attachments() -> dict:+ """Hydrate the persistent orb panel after navigation or a remount."""+ batches: list[dict] = []+ for session in get_registry().sessions:+ for term in session.terminals:+ async with term.pending_prompt_attachment_lock:+ batches.extend(+ {+ "terminal": term.name,+ "batch_id": batch.batch_id,+ "files": list(batch.files),+ "reserved": (+ batch.batch_id+ in term.pending_prompt_attachment_reservations+ ),+ }+ for batch in term.pending_prompt_attachment_batches+ )+ return {"batches": batches}+++ "/terminals/{name}/voice-attachments",+ summary="List files waiting for a terminal's next spoken prompt",+)+async def terminal_voice_attachments(name: str) -> dict:+ """Return authoritative pending batches for the orb receipt."""+ found = get_registry().find_terminal(name)+ if found is None:+ # A closed pane owns no pending context. Returning an empty authoritative+ # list lets a preserved voice panel retire its old receipt cleanly.+ return {"terminal": name, "batches": []}+ _session, term = found+ async with term.pending_prompt_attachment_lock:+ batches = [+ {+ "batch_id": batch.batch_id,+ "files": list(batch.files),+ "reserved": (+ batch.batch_id in term.pending_prompt_attachment_reservations+ ),+ }+ for batch in term.pending_prompt_attachment_batches+ ]+ return {"terminal": term.name, "batches": batches}+++ "/terminals/{name}/voice-attachments/{batch_id}",+ summary="Remove files waiting for a terminal's spoken prompt",+)+async def remove_terminal_voice_attachments(name: str, batch_id: str) -> dict:+ """Cancel one unconsumed orb drop; stored files remain in the workspace."""+ found = get_registry().find_terminal(name)+ if found is None:+ return {"terminal": name, "batch_id": batch_id, "removed": False}+ _session, term = found+ async with term.pending_prompt_attachment_lock:+ if batch_id in term.pending_prompt_attachment_reservations:+ raise HTTPException(+ status_code=409,+ detail="That attachment batch is already being added to a prompt.",+ )+ before = len(term.pending_prompt_attachment_batches)+ term.pending_prompt_attachment_batches[:] = [+ batch+ for batch in term.pending_prompt_attachment_batches+ if batch.batch_id != batch_id+ ]+ removed = len(term.pending_prompt_attachment_batches) != before+ return {"terminal": term.name, "batch_id": batch_id, "removed": removed}++@router.post("/terminals/{name}/attach", summary="Drop or paste files onto a terminal")async def terminal_attach(name: str,@@ -2277,6 +2380,7 @@ async def terminal_attach(note: str | None = Form(default=None), # noqa: B008analyze: bool = Form(default=False), # noqa: B008deliver: bool = Form(default=True), # noqa: B008+ stage_for_voice: bool = Form(default=False), # noqa: B008) -> dict:"""Put dropped or pasted files in front of the agent in terminal ``name``.@@ -2306,20 +2410,26 @@ async def terminal_attach(pane, for a caller that is assembling a prompt rather than handing theagent a path right now. The files are on disk and referenced either way,so nothing is lost if the user then walks away.+ * ``stage_for_voice=true`` keeps the returned analyses on this pane until+ its next spoken prompt is composed. It requires ``deliver=false`` so one+ gesture cannot both type a loose path and attach the same file to a later+ brief."""+ if stage_for_voice and deliver:+ raise HTTPException(+ status_code=422,+ detail="Staging a voice-prompt attachment requires deliver=false.",+ )+ # Staging without analysis would preserve only a filename, which is exactly+ # what makes screenshots useless to text-only coding CLIs. Treat the staging+ # flag as the stronger request instead of relying on every client to send+ # both booleans forever.+ analyze = analyze or stage_for_voiceregistry = get_registry()# Resolved across every open workspace, not just the front one: call-signs# are unique across them, and a file dropped on a pane belongs to THAT# pane's folder — which is also where a copied file has to land.- found = registry.find_terminal(name)- if found is None:- if not registry.sessions:- raise HTTPException(status_code=409, detail="No Agentic-IDE session is running.")- known = ", ".join(t.name for s in registry.sessions for t in s.terminals) or "none"- raise HTTPException(- status_code=404, detail=f"No terminal called {name!r}. Running: {known}."- )- session, term = found+ session, term = _terminal_or_http_error(name)references: list[str] = []stored_names: list[str] = []@@ -2407,9 +2517,45 @@ async def terminal_attach(detail="That drop carried nothing this pane could use.",)- analysis: list[dict] = []+ analysis_items: list[drop_analysis.DropAnalysis] = []if analyze and readable:- analysis = [item.to_dict() for item in await _analyze_drops(readable)]+ analysis_items = await _analyze_drops(readable)++ voice_batch: PendingPromptAttachmentBatch | None = None+ if stage_for_voice and analysis_items:+ voice_batch = PendingPromptAttachmentBatch(+ batch_id=uuid4().hex,+ attachments=tuple(analysis_items),+ files=tuple(stored_names),+ )+ async with term.pending_prompt_attachment_lock:+ pending = term.pending_prompt_attachment_batches+ attachment_count = sum(len(batch.attachments) for batch in pending)+ char_count = sum(+ len(item.name) + len(item.reference) + len(item.detail) + len(item.note)+ for batch in pending+ for item in batch.attachments+ )+ new_chars = sum(+ len(item.name) + len(item.reference) + len(item.detail) + len(item.note)+ for item in analysis_items+ )+ if (+ len(pending) >= MAX_PENDING_VOICE_BATCHES+ or attachment_count + len(analysis_items)+ > MAX_PENDING_VOICE_ATTACHMENTS+ or char_count + new_chars > MAX_PENDING_VOICE_CHARS+ ):+ raise HTTPException(+ status_code=409,+ detail=(+ "This pane already has the maximum amount of voice-prompt "+ "context waiting. Use or remove a pending drop first."+ ),+ )+ pending.append(voice_batch)++ analysis = [item.to_dict() for item in analysis_items]payload = " ".join(references)if note and note.strip():@@ -2445,6 +2591,8 @@ async def terminal_attach("submitted": bool(submit and delivered),"delivered": delivered,"analysis": analysis,+ "staged_for_voice": len(analysis_items) if stage_for_voice else 0,+ "voice_batch_id": voice_batch.batch_id if voice_batch else None,}diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsxindex aff9ec82d6..87aad3ad39 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx@@ -356,6 +356,17 @@ function renderGrid(session = BASE, extra: Record<string, unknown> = {}) {return { onSessionChanged, onClose, rerender };}+describe("prompt target bridge", () => {+ it("keeps the voice orb aimed at the written prompt target", async () => {+ const onPromptTargetChange = vi.fn();+ renderGrid(BASE, { onPromptTargetChange });++ await waitFor(() => expect(onPromptTargetChange).toHaveBeenCalledWith("Mika"));+ fireEvent.click(screen.getByTestId("prompt-target-Nova"));+ await waitFor(() => expect(onPromptTargetChange).toHaveBeenLastCalledWith("Nova"));+ });+});+describe("pane actions", () => {it("splitting right asks for a column beside the anchor", async () => {const { onSessionChanged } = renderGrid();diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsxindex f071af6812..fb434bdbf5 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx@@ -128,6 +128,8 @@ interface AgenticGridProps {* on its own has always been.*/onScreen?: boolean;+ /** Keep the voice orb aimed at the same pane as the written prompt bar. */+ onPromptTargetChange?: (name: string) => void;/*** The row of open workspaces, rendered INSIDE this workspace's toolbar.*@@ -517,6 +519,7 @@ export function AgenticGrid({onJumpToWorkspace,jumpTo = null,onScreen = true,+ onPromptTargetChange,}: AgenticGridProps) {const t = useT();const pushToast = useEventStore((s) => s.pushToast);@@ -581,6 +584,9 @@ export function AgenticGrid({};}, []);const [target, setTarget] = useState(session.terminals.find(takesPrompts)?.name ?? "");+ useEffect(() => {+ onPromptTargetChange?.(target);+ }, [onPromptTargetChange, target]);const [statuses, setStatuses] = useState<Record<string, { status: PaneStatus; detail?: string }>>({},);diff --git a/jarvis/ui/web/frontend/src/components/agentic/VoiceOrb.tsx b/jarvis/ui/web/frontend/src/components/agentic/VoiceOrb.tsxindex 4405dd4231..abd6003861 100644--- a/jarvis/ui/web/frontend/src/components/agentic/VoiceOrb.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/VoiceOrb.tsx@@ -44,31 +44,31 @@ const MOTIONS: Record<VoiceState, Motion> = {voiceImpact: 0,},listening: {- flowX: 0.075,- flowY: 0.025,- breathAmp: 0.01,- breathHz: 0.58,- turbulence: 0.94,+ flowX: 0.11,+ flowY: 0.035,+ breathAmp: 0.016,+ breathHz: 0.72,+ turbulence: 1.02,energy: 0.98,voiceImpact: 0,},thinking: {- flowX: 0.24,- flowY: -0.11,- breathAmp: 0.005,- breathHz: 0.2,- turbulence: 1.08,- energy: 0.95,+ flowX: 0.42,+ flowY: -0.19,+ breathAmp: 0.009,+ breathHz: 0.32,+ turbulence: 1.28,+ energy: 1.02,voiceImpact: 0,},speaking: {- flowX: 0.3,- flowY: 0.075,- breathAmp: 0.01,- breathHz: 0.72,+ flowX: 0.34,+ flowY: 0.085,+ breathAmp: 0.016,+ breathHz: 0.82,turbulence: 1.02,energy: 1,- voiceImpact: 0.028,+ voiceImpact: 0.045,},error: {flowX: 0.012,diff --git a/jarvis/ui/web/frontend/src/components/agentic/VoicePanel.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/VoicePanel.test.tsxindex 699d51e8d3..257f535621 100644--- a/jarvis/ui/web/frontend/src/components/agentic/VoicePanel.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/VoicePanel.test.tsx@@ -6,7 +6,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";* renders. Through `vi.hoisted` because the mock factory is lifted above* ordinary module code.*/-const { storeState } = vi.hoisted(() => ({+const { pendingVoiceBatches, storeState } = vi.hoisted(() => ({+ pendingVoiceBatches: new Map<+ string,+ { batch_id: string; files: string[]; reserved?: boolean }+ >(),storeState: {} as Record<string, unknown>,}));@@ -20,14 +24,53 @@ vi.mock("@/lib/voiceApi", () => ({requestVoiceHangup: vi.fn(async () => ({ stopped: true })),}));+vi.mock("@/lib/agenticIdeApi", () => ({+ attachToTerminal: vi.fn(async (name: string, payload: { files?: File[] }) => {+ const files = payload.files?.map((file) => file.name) ?? [];+ pendingVoiceBatches.set("batch-1", { batch_id: "batch-1", files });+ return {+ terminal: name,+ references: ["@.jarvis/drops/layout.png"],+ files,+ copied: 1,+ submitted: false,+ delivered: false,+ staged_for_voice: 1,+ voice_batch_id: "batch-1",+ analysis: [],+ };+ }),+ fetchVoiceAttachments: vi.fn(async (terminal: string) => ({+ terminal,+ batches: Array.from(pendingVoiceBatches.values()).map((batch) => ({+ ...batch,+ reserved: batch.reserved ?? false,+ })),+ })),+ fetchAllVoiceAttachments: vi.fn(async () => ({+ batches: Array.from(pendingVoiceBatches.values()).map((batch) => ({+ ...batch,+ terminal: "Mika",+ reserved: batch.reserved ?? false,+ })),+ })),+ removeVoiceAttachment: vi.fn(async (_terminal: string, batchId: string) => {+ pendingVoiceBatches.delete(batchId);+ }),+}));++vi.mock("@/lib/sound", () => ({ playDropConfirm: vi.fn() }));+import { VoicePanel } from "./VoicePanel";import * as api from "@/lib/voiceApi";+import * as ideApi from "@/lib/agenticIdeApi";const pushToast = vi.fn();beforeEach(() => {vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);window.localStorage.clear();+ pendingVoiceBatches.clear();for (const key of Object.keys(storeState)) delete storeState[key];Object.assign(storeState, {voiceState: "idle",@@ -49,7 +92,7 @@ describe("voice panel", () => {expect(screen.getByTestId("voice-panel")).toBeTruthy();const orb = screen.getByTestId("voice-orb-canvas");expect(orb.getAttribute("data-state")).toBe("idle");- expect(orb.getAttribute("style")).toContain("width: 160px");+ expect(orb.getAttribute("style")).toContain("width: 176px");expect(screen.getByTestId("voice-panel-status").textContent).toBe("Ready");// The brand rule: the assistant's own name, never a hardcoded one.expect(screen.getByTestId("voice-orb-button").getAttribute("title")).toContain(@@ -64,6 +107,79 @@ describe("voice panel", () => {expect(api.requestVoiceHangup).not.toHaveBeenCalled();});+ it("stages a file dropped on the orb for the selected pane's next prompt", async () => {+ render(<VoicePanel promptTarget="Mika" />);+ const orb = screen.getByTestId("voice-orb-button");+ const file = new File(["pixels"], "layout.png", { type: "image/png" });+ const dataTransfer = {+ files: [file],+ types: ["Files"],+ getData: () => "",+ dropEffect: "none",+ } as unknown as DataTransfer;++ fireEvent.dragEnter(orb, { dataTransfer });+ expect(screen.getByTestId("voice-orb-stage").getAttribute("data-drop-state")).toBe(+ "over",+ );+ fireEvent.drop(orb, { dataTransfer });++ await waitFor(() => expect(ideApi.attachToTerminal).toHaveBeenCalledTimes(1));+ expect(ideApi.attachToTerminal).toHaveBeenCalledWith(+ "Mika",+ expect.objectContaining({+ files: [file],+ analyze: true,+ deliver: false,+ stageForVoice: true,+ }),+ );+ expect(+ (await screen.findByTestId("voice-orb-drop-context")).textContent,+ ).toContain("layout.png");+ });++ it("keeps a receipt bound to its original pane until the backend consumes it", async () => {+ const { rerender } = render(<VoicePanel promptTarget="Mika" />);+ const file = new File(["pixels"], "layout.png", { type: "image/png" });+ const dataTransfer = {+ files: [file],+ types: ["Files"],+ getData: () => "",+ dropEffect: "none",+ } as unknown as DataTransfer;+ fireEvent.drop(screen.getByTestId("voice-orb-button"), { dataTransfer });+ const receipt = await screen.findByTestId("voice-orb-drop-context");+ expect(receipt.textContent).toContain("Mika");++ storeState.voiceState = "thinking";+ rerender(<VoicePanel promptTarget="Bruno" />);+ expect(screen.getByTestId("voice-orb-drop-context").textContent).toContain("Mika");+ pendingVoiceBatches.clear();+ storeState.voiceState = "speaking";+ rerender(<VoicePanel promptTarget="Bruno" />);+ await waitFor(() =>+ expect(screen.queryByTestId("voice-orb-drop-context")).toBeNull(),+ );+ });++ it("hydrates pending context after a panel remount and locks reserved context", async () => {+ pendingVoiceBatches.set("batch-old", {+ batch_id: "batch-old",+ files: ["existing.png"],+ reserved: true,+ });+ render(<VoicePanel promptTarget="Mika" />);++ const receipt = await screen.findByTestId("voice-orb-drop-context");+ expect(receipt.textContent).toContain("existing.png");+ expect(receipt.textContent).toContain("Adding");+ expect(+ (screen.getByLabelText("Remove this pending context") as HTMLButtonElement)+ .disabled,+ ).toBe(true);+ });+it("a click during a conversation hangs up", async () => {storeState.voiceState = "speaking";render(<VoicePanel />);diff --git a/jarvis/ui/web/frontend/src/components/agentic/VoicePanel.tsx b/jarvis/ui/web/frontend/src/components/agentic/VoicePanel.tsxindex 3de26869ad..5c92217ed2 100644--- a/jarvis/ui/web/frontend/src/components/agentic/VoicePanel.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/VoicePanel.tsx@@ -17,11 +17,32 @@* reopen affordance and a minimal state dot on screen, the same reasoning as* the prompt bar's collapsed strip.*/-import { useCallback, useState } from "react";-import { PanelRightClose, PanelRightOpen } from "lucide-react";+import { type DragEvent, useCallback, useEffect, useRef, useState } from "react";+import {+ Check,+ FilePlus2,+ PanelRightClose,+ PanelRightOpen,+ Paperclip,+ X,+} from "lucide-react";import { cn } from "@/lib/utils";import { useEventStore, type VoiceState } from "@/store/events";import { requestVoiceCall, requestVoiceHangup } from "@/lib/voiceApi";+import {+ attachToTerminal,+ fetchAllVoiceAttachments,+ fetchVoiceAttachments,+ removeVoiceAttachment,+} from "@/lib/agenticIdeApi";+import { playDropConfirm } from "@/lib/sound";+import { useT } from "@/i18n";+import {+ dragCarriesFiles,+ extractPaneDrop,+ isEmptyPayload,+ type PaneDropPayload,+} from "./paneDrop";import { VoiceOrb } from "./VoiceOrb";const OPEN_KEY = "jarvis.agenticIde.voicePanelOpen";@@ -42,13 +63,13 @@ function storeOpen(open: boolean): void {}}-/** What the line under the orb says, per state. */-const STATUS: Record<VoiceState, string> = {- idle: "Ready",- listening: "Listening…",- thinking: "Thinking…",- speaking: "Speaking",- error: "Voice trouble",+/** Locale keys for the line under the orb, per state. */+const STATUS_KEY: Record<VoiceState, string> = {+ idle: "agentic_grid.voice_panel.ready",+ listening: "agentic_grid.voice_panel.listening",+ thinking: "agentic_grid.voice_panel.thinking",+ speaking: "agentic_grid.voice_panel.speaking",+ error: "agentic_grid.voice_panel.error",};/** Is a conversation running — the half of the toggle a click would end? */@@ -56,17 +77,138 @@ function isActive(state: VoiceState): boolean {return state === "listening" || state === "thinking" || state === "speaking";}-export function VoicePanel() {+type DropPhase = "idle" | "over" | "reading";++interface DropReceipt {+ batchId: string;+ target: string;+ files: string[];+ reserved: boolean;+}++function format(text: string, ...values: Array<string | number>): string {+ return values.reduce<string>(+ (result, value, index) => result.replace(`{${index}}`, String(value)),+ text,+ );+}++export function VoicePanel({ promptTarget = "" }: { promptTarget?: string }) {+ const t = useT();const voiceState = (useEventStore((s) => s.voiceState) ?? "idle") as VoiceState;const transcription = useEventStore((s) => s.transcription) ?? "";const assistantName =- (useEventStore((s) => s.assistantName) ?? "").trim() || "your assistant";+ (useEventStore((s) => s.assistantName) ?? "").trim() ||+ t("agentic_grid.voice_panel.assistant_fallback");const pushToast = useEventStore((s) => s.pushToast);const [open, setOpen] = useState(storedOpen);const [busy, setBusy] = useState(false);+ const [dropPhase, setDropPhase] = useState<DropPhase>("idle");+ const [dropTarget, setDropTarget] = useState("");+ const [receipts, setReceipts] = useState<DropReceipt[]>([]);+ const fileInputRef = useRef<HTMLInputElement>(null);const active = isActive(voiceState);+ const receiptKey = receipts+ .map((receipt) => `${receipt.target}:${receipt.batchId}`)+ .join("|");++ // The panel can remount while the backend queue survives (navigation, an+ // error boundary, frontend reload). Hydrate every terminal, not just the one+ // currently selected, so no pending context can become invisible.+ useEffect(() => {+ let cancelled = false;+ void fetchAllVoiceAttachments()+ .then((response) => {+ if (cancelled) return;+ if (response.batches.length === 0) return;+ setReceipts((current) => {+ const merged = new Map(current.map((item) => [item.batchId, item]));+ for (const batch of response.batches) {+ merged.set(batch.batch_id, {+ batchId: batch.batch_id,+ target: batch.terminal,+ files: batch.files,+ reserved: batch.reserved,+ });+ }+ return Array.from(merged.values());+ });+ })+ .catch(() => {+ // A transient reconnect must not invent an empty queue. Per-state+ // reconciliation retries once the voice pipeline moves again.+ });+ return () => {+ cancelled = true;+ };+ }, []);++ // Voice state is global, but attachment ownership is per pane. Ask the+ // backend which batch IDs still exist instead of guessing that any global+ // listening/thinking transition consumed the receipt currently on screen.+ useEffect(() => {+ if (receipts.length === 0) return;+ let cancelled = false;+ const targets = [...new Set(receipts.map((receipt) => receipt.target))];+ let timer: number | undefined;+ const reconcile = () => {+ void Promise.allSettled(+ targets.map(async (target) => {+ const response = await fetchVoiceAttachments(target);+ return { target, batches: response.batches };+ }),+ )+ .then((results) => {+ if (cancelled) return;+ setReceipts((current) => {+ let next = current;+ for (const result of results) {+ if (result.status !== "fulfilled") continue;+ const byId = new Map(+ result.value.batches.map((batch) => [batch.batch_id, batch]),+ );+ next = next+ .filter(+ (receipt) =>+ receipt.target !== result.value.target ||+ byId.has(receipt.batchId),+ )+ .map((receipt) => {+ if (receipt.target !== result.value.target) return receipt;+ const batch = byId.get(receipt.batchId);+ return batch+ ? { ...receipt, files: batch.files, reserved: batch.reserved }+ : receipt;+ });+ }+ return next;+ });+ })+ .finally(() => {+ if (active && !cancelled) timer = window.setTimeout(reconcile, 750);+ });+ };+ reconcile();+ return () => {+ cancelled = true;+ if (timer !== undefined) window.clearTimeout(timer);+ };+ }, [active, receiptKey, voiceState]);++ // A drag may leave the app without sending this button a final dragleave.+ // Clear only the hover state; reading/ready are real work and must remain.+ useEffect(() => {+ if (dropPhase !== "over") return;+ const clear = () => setDropPhase("idle");+ window.addEventListener("drop", clear);+ window.addEventListener("dragend", clear);+ return () => {+ window.removeEventListener("drop", clear);+ window.removeEventListener("dragend", clear);+ };+ }, [dropPhase]);const toggleOpen = useCallback(() => {setOpen((current) => {@@ -88,7 +230,7 @@ export function VoicePanel() {if (!armed) {pushToast("warning",- "Could not start listening — a conversation may already be running.",+ t("agentic_grid.voice_panel.start_failed"),);}}@@ -97,7 +239,82 @@ export function VoicePanel() {} finally {setBusy(false);}- }, [busy, active, pushToast]);+ }, [busy, active, pushToast, t]);++ const stageFiles = useCallback(+ async (payload: PaneDropPayload, target: string) => {+ if (isEmptyPayload(payload)) {+ pushToast("warning", t("agentic_grid.voice_drop.empty"));+ return;+ }+ if (!target) {+ pushToast("warning", t("agentic_grid.voice_drop.no_target"));+ return;+ }++ setDropTarget(target);+ setDropPhase("reading");+ try {+ const result = await attachToTerminal(target, {+ ...payload,+ analyze: true,+ deliver: false,+ stageForVoice: true,+ });+ if (!result.staged_for_voice || !result.voice_batch_id) {+ pushToast("warning", t("agentic_grid.voice_drop.empty"));+ return;+ }+ setReceipts((current) => [+ ...current,+ {+ batchId: result.voice_batch_id as string,+ target,+ files: result.files,+ reserved: false,+ },+ ]);+ playDropConfirm();+ } catch (error) {+ pushToast("error", (error as Error).message);+ } finally {+ setDropPhase("idle");+ setDropTarget("");+ }+ },+ [pushToast, t],+ );++ const handleDrop = useCallback(+ (event: DragEvent<HTMLButtonElement>) => {+ event.preventDefault();+ event.stopPropagation();+ // Read synchronously: DataTransfer is emptied as soon as this handler+ // yields, so extracting after the first await would produce a ghost drop.+ const payload = extractPaneDrop(event.dataTransfer);+ if (!dragCarriesFiles(event.dataTransfer)) {+ setDropPhase("idle");+ pushToast("warning", t("agentic_grid.voice_drop.empty"));+ return;+ }+ void stageFiles(payload, promptTarget);+ },+ [promptTarget, pushToast, stageFiles, t],+ );++ const removeReceipt = useCallback(+ async (receipt: DropReceipt) => {+ try {+ await removeVoiceAttachment(receipt.target, receipt.batchId);+ setReceipts((current) =>+ current.filter((item) => item.batchId !== receipt.batchId),+ );+ } catch (error) {+ pushToast("error", (error as Error).message);+ }+ },+ [pushToast],+ );if (!open) {return (@@ -109,8 +326,11 @@ export function VoicePanel() {type="button"data-testid="voice-panel-open"onClick={toggleOpen}- title={`Open the voice panel — talk to ${assistantName} here`}- aria-label="Open the voice panel"+ title={format(+ t("agentic_grid.voice_panel.open_title"),+ assistantName,+ )}+ aria-label={t("agentic_grid.voice_panel.open")}className="flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"><PanelRightOpen className="h-4 w-4" />@@ -137,59 +357,187 @@ export function VoicePanel() {><div className="flex items-center justify-between px-3 py-2"><span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">- Voice+ {t("agentic_grid.voice_panel.label")}</span><buttontype="button"data-testid="voice-panel-close"onClick={toggleOpen}- title="Collapse the voice panel"- aria-label="Collapse the voice panel"+ title={t("agentic_grid.voice_panel.close")}+ aria-label={t("agentic_grid.voice_panel.close")}className="flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"><PanelRightClose className="h-4 w-4" /></button></div>- <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-5 px-5 pb-6">- <button- type="button"- data-testid="voice-orb-button"- onClick={() => void toggleCall()}- disabled={busy}- aria-pressed={active}- title={- active- ? "Hang up the conversation"- : `Talk to ${assistantName} — or just say the wake word`+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-4 px-5 pb-6">+ <div+ data-testid="voice-orb-stage"+ data-state={voiceState}+ data-drop-state={+ dropPhase === "idle" && receipts.some((receipt) => receipt.reserved)+ ? "using"+ : dropPhase === "idle" && receipts.length > 0+ ? "ready"+ : dropPhase}- aria-label={active ? "Hang up" : `Talk to ${assistantName}`}- className={cn(- "rounded-full outline-none transition-[transform,box-shadow,opacity] duration-500 ease-out hover:scale-[1.01] active:scale-[0.985] focus-visible:ring-2 focus-visible:ring-[#e7c46e]/55 motion-reduce:transform-none",- // A restrained ambient pool; the sphere itself remains borderless.- active- ? "shadow-[0_20px_56px_-38px_rgba(231,196,110,0.48)]"- : "shadow-[0_18px_48px_-40px_rgba(231,196,110,0.3)]",- busy && "cursor-wait opacity-70",- )}+ className="agentic-voice-orb-stage relative grid h-48 w-48 shrink-0 place-items-center">- <VoiceOrb state={voiceState} size={160} />- </button>+ <span aria-hidden="true" className="agentic-voice-orb-ring agentic-voice-orb-ring-a" />+ <span aria-hidden="true" className="agentic-voice-orb-ring agentic-voice-orb-ring-b" />+ <button+ type="button"+ data-testid="voice-orb-button"+ onClick={() => void toggleCall()}+ onDragEnter={(event) => {+ event.preventDefault();+ if (dragCarriesFiles(event.dataTransfer)) setDropPhase("over");+ }}+ onDragOver={(event) => {+ event.preventDefault();+ event.dataTransfer.dropEffect = dragCarriesFiles(event.dataTransfer)+ ? "copy"+ : "none";+ }}+ onDragLeave={(event) => {+ const next = event.relatedTarget as Node | null;+ if (next && event.currentTarget.contains(next)) return;+ if (dropPhase === "over") setDropPhase("idle");+ }}+ onDrop={(event) => void handleDrop(event)}+ disabled={busy || dropPhase === "reading"}+ aria-pressed={active}+ title={+ active+ ? t("agentic_grid.voice_panel.hang_up_title")+ : format(+ t("agentic_grid.voice_panel.talk_title"),+ assistantName,+ )+ }+ aria-label={+ active+ ? t("agentic_grid.voice_panel.hang_up")+ : format(t("agentic_grid.voice_panel.talk"), assistantName)+ }+ className={cn(+ "relative z-10 rounded-full outline-none transition-[transform,box-shadow,opacity] duration-500 ease-out hover:scale-[1.015] active:scale-[0.98] focus-visible:ring-2 focus-visible:ring-[#e7c46e]/55 motion-reduce:transform-none",+ active+ ? "shadow-[0_20px_56px_-38px_rgba(231,196,110,0.48)]"+ : "shadow-[0_18px_48px_-40px_rgba(231,196,110,0.3)]",+ dropPhase === "over" && "scale-[1.045]",+ (busy || dropPhase === "reading") && "cursor-wait opacity-80",+ )}+ >+ <VoiceOrb state={voiceState} size={176} />+ </button>+ </div><div className="flex flex-col items-center gap-1.5 text-center">- <span- data-testid="voice-panel-status"- className="font-display text-base font-semibold"- >- {STATUS[voiceState] ?? STATUS.idle}+ <span className="flex items-center gap-2">+ <span+ aria-hidden="true"+ data-state={voiceState}+ className="agentic-voice-state-dot"+ />+ <span+ data-testid="voice-panel-status"+ aria-live="polite"+ className={cn(+ "font-display text-base font-semibold transition-colors",+ active && "text-[#e7c46e]",+ )}+ >+ {dropPhase === "over"+ ? format(+ t("agentic_grid.voice_drop.hover"),+ promptTarget || t("agentic_grid.voice_drop.target_fallback"),+ )+ : dropPhase === "reading"+ ? format(t("agentic_grid.voice_drop.reading"), dropTarget)+ : t(STATUS_KEY[voiceState] ?? STATUS_KEY.idle)}+ </span></span><span className="text-xs text-muted-foreground">{active- ? "Click the orb to hang up."- : `Click the orb — or say the wake word — to talk to ${assistantName}.`}+ ? t("agentic_grid.voice_panel.active_hint")+ : format(+ t("agentic_grid.voice_panel.idle_hint"),+ assistantName,+ )}</span></div>+ {receipts.map((receipt) => (+ <div+ key={receipt.batchId}+ data-testid="voice-orb-drop-context"+ aria-live="polite"+ className="flex max-w-full items-start gap-2 rounded-xl border border-[#e7c46e]/30 bg-[#e7c46e]/[0.07] px-3 py-2 text-left"+ >+ <span className="mt-0.5 grid h-5 w-5 shrink-0 place-items-center rounded-full bg-[#e7c46e]/15 text-[#e7c46e]">+ <Check className="h-3 w-3" aria-hidden="true" />+ </span>+ <span className="min-w-0 flex-1 text-[11px] leading-relaxed text-muted-foreground">+ <span className="block truncate font-medium text-foreground">+ <FilePlus2+ className="mr-1 inline h-3.5 w-3.5 text-[#e7c46e]"+ aria-hidden="true"+ />+ {receipt.files.join(", ")}+ </span>+ {receipt.reserved+ ? format(+ t("agentic_grid.voice_drop.using"),+ receipt.files.length,+ receipt.target,+ )+ : format(+ t(+ receipt.files.length === 1+ ? "agentic_grid.voice_drop.ready_one"+ : "agentic_grid.voice_drop.ready_many",+ ),+ receipt.files.length,+ receipt.target,+ )}+ </span>+ <button+ type="button"+ disabled={receipt.reserved}+ onClick={() => void removeReceipt(receipt)}+ title={t("agentic_grid.voice_drop.remove")}+ aria-label={t("agentic_grid.voice_drop.remove")}+ className="grid h-5 w-5 shrink-0 place-items-center rounded text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground disabled:cursor-not-allowed disabled:opacity-35"+ >+ <X className="h-3 w-3" aria-hidden="true" />+ </button>+ </div>+ ))}++ <input+ ref={fileInputRef}+ type="file"+ multiple+ className="sr-only"+ tabIndex={-1}+ onChange={(event) => {+ const files = Array.from(event.currentTarget.files ?? []);+ event.currentTarget.value = "";+ void stageFiles({ paths: [], files }, promptTarget);+ }}+ />+ <button+ type="button"+ disabled={!promptTarget || dropPhase === "reading"}+ onClick={() => fileInputRef.current?.click()}+ className="flex items-center gap-1.5 rounded-md px-2 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40"+ >+ <Paperclip className="h-3.5 w-3.5" aria-hidden="true" />+ {t("agentic_grid.voice_drop.choose")}+ </button>+{/* What the microphone is hearing, as it hears it. Shown only while aconversation runs — an idle panel repeating the last sentence of afinished one would read as a stuck microphone. */}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 7031261ca2..2173727e4a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -3719,6 +3719,37 @@"kind_exited": "GESTOPPT","kind_failed": "FEHLGESCHLAGEN","gone": "{0} gibt es in diesem Workspace nicht mehr — das Terminal wurde geschlossen, seit die Benachrichtigung kam."+ },+ "voice_panel": {+ "assistant_fallback": "Assistent",+ "label": "Stimme",+ "ready": "Bereit",+ "listening": "Hört zu…",+ "thinking": "Denkt nach…",+ "speaking": "Spricht",+ "error": "Sprachfunktion gestört",+ "open": "Sprachbereich öffnen",+ "open_title": "Sprachbereich öffnen — hier mit {0} sprechen",+ "close": "Sprachbereich einklappen",+ "hang_up": "Auflegen",+ "hang_up_title": "Gespräch beenden",+ "talk": "Mit {0} sprechen",+ "talk_title": "Mit {0} sprechen — oder einfach das Aktivierungswort sagen",+ "active_hint": "Zum Auflegen auf die Kugel klicken.",+ "idle_hint": "Auf die Kugel klicken — oder das Aktivierungswort sagen — um mit {0} zu sprechen.",+ "start_failed": "Das Zuhören konnte nicht gestartet werden — möglicherweise läuft bereits ein Gespräch."+ },+ "voice_drop": {+ "hover": "Für den nächsten Prompt an {0} ablegen",+ "reading": "Dateien werden für den nächsten Prompt an {0} gelesen…",+ "ready_one": "1 Datei ist für den nächsten Prompt an {1} bereit.",+ "ready_many": "{0} Dateien sind für den nächsten Prompt an {1} bereit.",+ "using": "{0} Datei(en) werden dem Prompt an {1} hinzugefügt…",+ "target_fallback": "einen Agenten",+ "empty": "Dieser Drop enthielt keine verwendbare Datei.",+ "no_target": "Öffne oder wähle zuerst ein Agent-Terminal aus.",+ "choose": "Dateien auswählen",+ "remove": "Diesen wartenden Kontext entfernen"}},"prompt_writer": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 855697ce72..4abf0e50cd 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -3720,6 +3720,37 @@"kind_exited": "STOPPED","kind_failed": "FAILED","gone": "{0} is not in this workspace any more — that terminal was closed since the notification arrived."+ },+ "voice_panel": {+ "assistant_fallback": "Assistant",+ "label": "Voice",+ "ready": "Ready",+ "listening": "Listening…",+ "thinking": "Thinking…",+ "speaking": "Speaking",+ "error": "Voice trouble",+ "open": "Open the voice panel",+ "open_title": "Open the voice panel — talk to {0} here",+ "close": "Collapse the voice panel",+ "hang_up": "Hang up",+ "hang_up_title": "Hang up the conversation",+ "talk": "Talk to {0}",+ "talk_title": "Talk to {0} — or just say the wake word",+ "active_hint": "Click the orb to hang up.",+ "idle_hint": "Click the orb — or say the wake word — to talk to {0}.",+ "start_failed": "Could not start listening — a conversation may already be running."+ },+ "voice_drop": {+ "hover": "Drop for {0}'s next prompt",+ "reading": "Reading files for {0}'s next prompt…",+ "ready_one": "1 file is ready for {1}'s next prompt.",+ "ready_many": "{0} files are ready for {1}'s next prompt.",+ "using": "Adding {0} file(s) to {1}'s prompt…",+ "target_fallback": "an agent",+ "empty": "That drop did not contain a usable file.",+ "no_target": "Open or select an agent terminal before attaching a file.",+ "choose": "Choose files",+ "remove": "Remove this pending context"}},"prompt_writer": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 43c394fd15..f7b5ecc378 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -3719,6 +3719,37 @@"kind_exited": "DETENIDO","kind_failed": "FALLIDO","gone": "{0} ya no está en este espacio de trabajo: ese terminal se cerró después de llegar la notificación."+ },+ "voice_panel": {+ "assistant_fallback": "Asistente",+ "label": "Voz",+ "ready": "Listo",+ "listening": "Escuchando…",+ "thinking": "Pensando…",+ "speaking": "Hablando",+ "error": "Problema de voz",+ "open": "Abrir el panel de voz",+ "open_title": "Abrir el panel de voz — habla con {0} aquí",+ "close": "Contraer el panel de voz",+ "hang_up": "Colgar",+ "hang_up_title": "Finalizar la conversación",+ "talk": "Hablar con {0}",+ "talk_title": "Habla con {0} — o di la palabra de activación",+ "active_hint": "Haz clic en el orbe para colgar.",+ "idle_hint": "Haz clic en el orbe — o di la palabra de activación — para hablar con {0}.",+ "start_failed": "No se pudo empezar a escuchar — puede que ya haya una conversación en curso."+ },+ "voice_drop": {+ "hover": "Soltar para el próximo prompt de {0}",+ "reading": "Leyendo archivos para el próximo prompt de {0}…",+ "ready_one": "1 archivo está listo para el próximo prompt de {1}.",+ "ready_many": "{0} archivos están listos para el próximo prompt de {1}.",+ "using": "Añadiendo {0} archivo(s) al prompt de {1}…",+ "target_fallback": "un agente",+ "empty": "Los elementos soltados no contenían ningún archivo utilizable.",+ "no_target": "Abre o selecciona un terminal de agente antes de adjuntar un archivo.",+ "choose": "Elegir archivos",+ "remove": "Eliminar este contexto pendiente"}},"prompt_writer": {diff --git a/jarvis/ui/web/frontend/src/index.css b/jarvis/ui/web/frontend/src/index.cssindex 953b1eb393..4057017f05 100644--- a/jarvis/ui/web/frontend/src/index.css+++ b/jarvis/ui/web/frontend/src/index.css@@ -16,6 +16,134 @@scrollbar-width: thin;scrollbar-color: hsl(var(--border)) transparent;}++@layer components {+ /*+ * Voice-orb state language. The procedural material stays inside the sphere;+ * these two soft waves make lifecycle changes readable from across the desk.+ * Every loop uses only transform and opacity, and none rotates, so the active+ * surface remains calm even when a long prompt is being written.+ */+ .agentic-voice-orb-ring {+ @apply pointer-events-none absolute inset-2 rounded-full border border-[#e7c46e]/45;+ opacity: 0;+ transform: scale(0.94);+ will-change: transform, opacity;+ }++ .agentic-voice-orb-stage[data-state="listening"] .agentic-voice-orb-ring-a {+ animation: agentic-orb-wave 1.35s cubic-bezier(0.22, 1, 0.36, 1) infinite;+ }++ .agentic-voice-orb-stage[data-state="thinking"] .agentic-voice-orb-ring-a,+ .agentic-voice-orb-stage[data-state="thinking"] .agentic-voice-orb-ring-b {+ animation: agentic-orb-work 1.55s cubic-bezier(0.4, 0, 0.2, 1) infinite;+ }++ .agentic-voice-orb-stage[data-state="thinking"] .agentic-voice-orb-ring-b {+ animation-delay: 0.58s;+ }++ .agentic-voice-orb-stage[data-state="speaking"] .agentic-voice-orb-ring-a,+ .agentic-voice-orb-stage[data-state="speaking"] .agentic-voice-orb-ring-b {+ animation: agentic-orb-wave 0.82s cubic-bezier(0.22, 1, 0.36, 1) infinite;+ }++ .agentic-voice-orb-stage[data-state="speaking"] .agentic-voice-orb-ring-b {+ animation-delay: 0.31s;+ }++ .agentic-voice-orb-stage[data-drop-state="over"] .agentic-voice-orb-ring,+ .agentic-voice-orb-stage[data-drop-state="reading"] .agentic-voice-orb-ring {+ animation: agentic-orb-drop 1.1s cubic-bezier(0.22, 1, 0.36, 1) infinite;+ border-style: dashed;+ border-width: 2px;+ }++ .agentic-voice-state-dot {+ @apply h-2 w-2 rounded-full bg-muted-foreground/45;+ }++ .agentic-voice-state-dot[data-state="listening"],+ .agentic-voice-state-dot[data-state="thinking"],+ .agentic-voice-state-dot[data-state="speaking"] {+ background: #e7c46e;+ animation: agentic-orb-dot 1.25s ease-in-out infinite;+ }++ .agentic-voice-state-dot[data-state="thinking"] {+ animation-duration: 0.85s;+ }++ .agentic-voice-state-dot[data-state="speaking"] {+ animation-duration: 0.62s;+ }++ .agentic-voice-state-dot[data-state="error"] {+ @apply bg-destructive;+ }++ @keyframes agentic-orb-wave {+ 0% {+ opacity: 0.62;+ transform: scale(0.91);+ }+ 72%,+ 100% {+ opacity: 0;+ transform: scale(1.18);+ }+ }++ @keyframes agentic-orb-work {+ 0%,+ 100% {+ opacity: 0.16;+ transform: scale3d(0.95, 1.01, 1);+ }+ 50% {+ opacity: 0.64;+ transform: scale3d(1.13, 1.08, 1);+ }+ }++ @keyframes agentic-orb-drop {+ 0%,+ 100% {+ opacity: 0.42;+ transform: scale(1.01);+ }+ 50% {+ opacity: 0.92;+ transform: scale(1.12);+ }+ }++ @keyframes agentic-orb-dot {+ 0%,+ 100% {+ opacity: 0.45;+ transform: scale(0.78);+ }+ 50% {+ opacity: 1;+ transform: scale(1.18);+ }+ }++ @media (prefers-reduced-motion: reduce) {+ .agentic-voice-orb-ring,+ .agentic-voice-state-dot {+ animation: none !important;+ }++ .agentic-voice-orb-stage[data-state]:not([data-state="idle"])+ .agentic-voice-orb-ring-a {+ opacity: 0.45;+ transform: scale(1.08);+ }+ }+}::-webkit-scrollbar {width: 10px;height: 10px;diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.tsindex 11da9f01dd..b963eda940 100644--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts@@ -1213,6 +1213,29 @@ export interface AttachResult {delivered?: boolean;/** Present only when `analyze` was asked for. */analysis?: DropAttachment[];+ /** Analysed files queued for this pane's next spoken prompt. */+ staged_for_voice?: number;+ /** Stable identity used to verify or cancel the pending orb drop. */+ voice_batch_id?: string | null;+}++export interface VoiceAttachmentBatch {+ batch_id: string;+ files: string[];+ reserved: boolean;+}++export interface OwnedVoiceAttachmentBatch extends VoiceAttachmentBatch {+ terminal: string;+}++export interface VoiceAttachmentsResponse {+ terminal: string;+ batches: VoiceAttachmentBatch[];+}++export interface AllVoiceAttachmentsResponse {+ batches: OwnedVoiceAttachmentBatch[];}/**@@ -1239,6 +1262,8 @@ export async function attachToTerminal(analyze?: boolean;/** Default true. False stores and analyses without typing into the pane. */deliver?: boolean;+ /** Queue the analysis for this pane's next spoken prompt. */+ stageForVoice?: boolean;},): Promise<AttachResult> {const form = new FormData();@@ -1248,6 +1273,7 @@ export async function attachToTerminal(if (payload.submit) form.append("submit", "true");if (payload.analyze) form.append("analyze", "true");if (payload.deliver === false) form.append("deliver", "false");+ if (payload.stageForVoice) form.append("stage_for_voice", "true");const res = await fetch(`/api/agentic-ide/terminals/${encodeURIComponent(name)}/attach`,@@ -1257,6 +1283,34 @@ export async function attachToTerminal(return (await res.json()) as AttachResult;}+/** Read authoritative orb drops still waiting for one pane. */+export function fetchVoiceAttachments(+ name: string,+): Promise<VoiceAttachmentsResponse> {+ return getJson<VoiceAttachmentsResponse>(+ `/api/agentic-ide/terminals/${encodeURIComponent(name)}/voice-attachments`,+ );+}++/** Hydrate every pending orb receipt after navigation or a panel remount. */+export function fetchAllVoiceAttachments(): Promise<AllVoiceAttachmentsResponse> {+ return getJson<AllVoiceAttachmentsResponse>(+ "/api/agentic-ide/voice-attachments",+ );+}++/** Cancel one pending orb drop; the copied workspace file is left intact. */+export async function removeVoiceAttachment(+ name: string,+ batchId: string,+): Promise<void> {+ const res = await fetch(+ `/api/agentic-ide/terminals/${encodeURIComponent(name)}/voice-attachments/${encodeURIComponent(batchId)}`,+ { method: "DELETE" },+ );+ if (!res.ok) throw new Error(await detail(res));+}+export interface PromptResult {terminal: string;/** What was actually typed into the agent. */diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsxindex 41d56109fe..dbc95680ae 100644--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx@@ -111,6 +111,7 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {const [loading, setLoading] = useState(true);const [meta, setMeta] = useState<AgentsResponse | null>(null);const [session, setSession] = useState<SessionState | null>(null);+ const [promptTarget, setPromptTarget] = useState("");const [focusMode, setFocus] = useState(false);const [busy, setBusy] = useState(false);@@ -749,6 +750,7 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {accounts={ideAccounts}onStateChanged={applyStateFromSettings}onScreen={onScreen}+ onPromptTargetChange={setPromptTarget}/></div>{/*@@ -757,7 +759,18 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {belongs to the app, not to a workspace, so switching tabs must notreset the orb mid-sentence.*/}- <VoicePanel />+ <VoicePanel+ promptTarget={+ session.terminals.some(+ (terminal) =>+ terminal.name === promptTarget && terminal.accepts_prompts !== false,+ )+ ? promptTarget+ : session.terminals.find(+ (terminal) => terminal.accepts_prompts !== false,+ )?.name ?? ""+ }+ /></div>{modeIntroFor === session.id && (<CodingModeIntrodiff --git a/tests/unit/agentic_ide/test_attach_analysis_route.py b/tests/unit/agentic_ide/test_attach_analysis_route.pyindex 45f106cc2b..a1e0773ab0 100644--- a/tests/unit/agentic_ide/test_attach_analysis_route.py+++ b/tests/unit/agentic_ide/test_attach_analysis_route.py@@ -153,6 +153,86 @@ async def test_deliver_false_types_nothing_into_the_pane(assert term is not None+async def test_voice_orb_drop_is_staged_on_the_selected_pane(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ name = await _workspace(registry, tmp_path)++ response = client.post(+ f"/api/agentic-ide/terminals/{name}/attach",+ files=_upload(),+ data={"stage_for_voice": "true", "deliver": "false"},+ )++ assert response.status_code == 200+ body = response.json()+ assert body["staged_for_voice"] == 1+ assert body["voice_batch_id"]+ assert registry.session is not None+ term = registry.session.find(name)+ assert term is not None+ assert len(term.pending_prompt_attachment_batches) == 1+ batch = term.pending_prompt_attachment_batches[0]+ assert batch.batch_id == body["voice_batch_id"]+ assert isinstance(batch.attachments[0], DropAnalysis)+ assert "submit button overflows" in batch.attachments[0].detail+++async def test_pending_voice_drop_can_be_listed_and_removed(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ name = await _workspace(registry, tmp_path)+ staged = client.post(+ f"/api/agentic-ide/terminals/{name}/attach",+ files=_upload(),+ data={"stage_for_voice": "true", "deliver": "false"},+ ).json()++ pending = client.get(+ f"/api/agentic-ide/terminals/{name}/voice-attachments"+ )+ assert pending.status_code == 200+ assert pending.json()["batches"] == [+ {+ "batch_id": staged["voice_batch_id"],+ "files": ["shot.png"],+ "reserved": False,+ }+ ]+ assert client.get("/api/agentic-ide/voice-attachments").json()["batches"] == [+ {+ "terminal": name,+ "batch_id": staged["voice_batch_id"],+ "files": ["shot.png"],+ "reserved": False,+ }+ ]++ removed = client.delete(+ f"/api/agentic-ide/terminals/{name}/voice-attachments/"+ f"{staged['voice_batch_id']}"+ )+ assert removed.status_code == 200+ assert client.get(+ f"/api/agentic-ide/terminals/{name}/voice-attachments"+ ).json()["batches"] == []+++async def test_voice_staging_refuses_to_also_type_the_loose_path(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ name = await _workspace(registry, tmp_path)++ response = client.post(+ f"/api/agentic-ide/terminals/{name}/attach",+ files=_upload(),+ data={"stage_for_voice": "true"},+ )++ assert response.status_code == 422+ assert "deliver=false" in response.json()["detail"]++async def test_a_pane_drop_still_types_and_does_no_analysis(client: TestClient, registry: Registry, tmp_path: Path) -> None:diff --git a/tests/unit/agentic_ide/test_fanout.py b/tests/unit/agentic_ide/test_fanout.pyindex bf3e2b7f70..a167fcf784 100644--- a/tests/unit/agentic_ide/test_fanout.py+++ b/tests/unit/agentic_ide/test_fanout.py@@ -26,6 +26,7 @@ import pytestfrom jarvis.agentic_ide import fanoutfrom jarvis.agentic_ide.prompt_composer import ComposedPrompt+from jarvis.agentic_ide.session import PendingPromptAttachmentBatch@dataclass@@ -34,6 +35,11 @@ class FakeTerminal:agent: str = "claude"status: str = "live"pty_id: str | None = "pty-1"+ pending_prompt_attachment_batches: list[PendingPromptAttachmentBatch] = field(+ default_factory=list+ )+ pending_prompt_attachment_reservations: set[str] = field(default_factory=set)+ pending_prompt_attachment_lock: asyncio.Lock = field(default_factory=asyncio.Lock)@dataclass@@ -54,6 +60,7 @@ class Recorder:sent: dict[str, str] = field(default_factory=dict)composed_for: list[str] = field(default_factory=list)+ attachments_for: dict[str, tuple[object, ...]] = field(default_factory=dict)active: int = 0peak: int = 0fail_compose_for: tuple[str, ...] = ()@@ -64,6 +71,7 @@ class Recorder:async def compose(self, utterance: str, **kwargs) -> ComposedPrompt:name = kwargs["terminal_name"]self.composed_for.append(name)+ self.attachments_for[name] = tuple(kwargs.get("attachments") or ())self.active += 1self.peak = max(self.peak, self.active)try:@@ -112,6 +120,232 @@ async def test_every_addressed_terminal_receives_a_prompt() -> None:assert [d.terminal for d in result.delivered] == ["Iris", "Bruno"]+async def test_voice_orb_attachments_reach_exactly_the_next_spoken_prompt() -> None:+ session = _session("Iris")+ attachment = SimpleNamespace(name="layout.png")+ session.terminals[0].pending_prompt_attachment_batches.append(+ PendingPromptAttachmentBatch("batch-a", (attachment,), ("layout.png",))+ )+ rec = Recorder()++ await fanout.deliver(+ session=session,+ terminals=["Iris"],+ utterance="fix what the screenshot shows",+ include_pending_attachments=True,+ compose=rec.compose,+ send=rec.send,+ )++ assert rec.attachments_for["Iris"] == (attachment,)+ assert session.terminals[0].pending_prompt_attachment_batches == []+++async def test_manual_fanout_does_not_consume_a_voice_orb_drop() -> None:+ session = _session("Iris")+ attachment = SimpleNamespace(name="layout.png")+ batch = PendingPromptAttachmentBatch("batch-a", (attachment,), ("layout.png",))+ session.terminals[0].pending_prompt_attachment_batches.append(batch)+ rec = Recorder()++ await fanout.deliver(+ session=session,+ terminals=["Iris"],+ utterance="an unrelated manual prompt",+ compose=rec.compose,+ send=rec.send,+ )++ assert rec.attachments_for["Iris"] == ()+ assert session.terminals[0].pending_prompt_attachment_batches == [batch]+++async def test_voice_orb_attachments_survive_a_failed_delivery() -> None:+ session = _session("Iris")+ attachment = SimpleNamespace(name="layout.png")+ batch = PendingPromptAttachmentBatch("batch-a", (attachment,), ("layout.png",))+ session.terminals[0].pending_prompt_attachment_batches.append(batch)+ rec = Recorder(fail_send_for=("Iris",))++ await fanout.deliver(+ session=session,+ terminals=["Iris"],+ utterance="fix what the screenshot shows",+ include_pending_attachments=True,+ compose=rec.compose,+ send=rec.send,+ )++ assert session.terminals[0].pending_prompt_attachment_batches == [batch]+ assert session.terminals[0].pending_prompt_attachment_reservations == set()+++async def test_overlapping_deliveries_reserve_batches_by_identity() -> None:+ session = _session("Iris")+ first = SimpleNamespace(name="first.png")+ second = SimpleNamespace(name="second.png")+ term = session.terminals[0]+ term.pending_prompt_attachment_batches.append(+ PendingPromptAttachmentBatch("batch-a", (first,), ("first.png",))+ )+ first_started = asyncio.Event()+ release_first = asyncio.Event()+ composed_attachments: list[tuple[object, ...]] = []++ async def compose(utterance: str, **kwargs) -> ComposedPrompt:+ attachments = tuple(kwargs.get("attachments") or ())+ composed_attachments.append(attachments)+ if attachments == (first,):+ first_started.set()+ await release_first.wait()+ return ComposedPrompt(text=utterance)++ async def send(_name: str, _text: str) -> SimpleNamespace:+ return SimpleNamespace(submitted=True)++ delivery_a = asyncio.create_task(+ fanout.deliver(+ session=session,+ terminals=["Iris"],+ utterance="first prompt",+ include_pending_attachments=True,+ compose=compose,+ send=send,+ )+ )+ await first_started.wait()+ async with term.pending_prompt_attachment_lock:+ term.pending_prompt_attachment_batches.append(+ PendingPromptAttachmentBatch("batch-b", (second,), ("second.png",))+ )+ delivery_b = asyncio.create_task(+ fanout.deliver(+ session=session,+ terminals=["Iris"],+ utterance="second prompt",+ include_pending_attachments=True,+ compose=compose,+ send=send,+ )+ )+ await asyncio.sleep(0)+ release_first.set()+ await asyncio.gather(delivery_a, delivery_b)++ assert composed_attachments == [(first,), (second,)]+ assert term.pending_prompt_attachment_batches == []+++async def test_cancelled_delivery_releases_its_attachment_reservation() -> None:+ session = _session("Iris")+ attachment = SimpleNamespace(name="layout.png")+ term = session.terminals[0]+ batch = PendingPromptAttachmentBatch(+ "batch-a", (attachment,), ("layout.png",)+ )+ term.pending_prompt_attachment_batches.append(batch)+ composing = asyncio.Event()++ async def compose(_utterance: str, **_kwargs) -> ComposedPrompt:+ composing.set()+ await asyncio.Event().wait()+ return ComposedPrompt(text="unreachable")++ task = asyncio.create_task(+ fanout.deliver(+ session=session,+ terminals=["Iris"],+ utterance="fix the layout",+ include_pending_attachments=True,+ compose=compose,+ )+ )+ await composing.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ assert term.pending_prompt_attachment_batches == [batch]+ assert term.pending_prompt_attachment_reservations == set()+++async def test_cancellation_while_waiting_for_gate_never_reserves_a_batch() -> None:+ session = _session("Iris", "Bruno")+ first_started = asyncio.Event()+ never_release = asyncio.Event()+ for index, term in enumerate(session.terminals):+ attachment = SimpleNamespace(name=f"layout-{index}.png")+ term.pending_prompt_attachment_batches.append(+ PendingPromptAttachmentBatch(+ f"batch-{index}", (attachment,), (attachment.name,)+ )+ )++ async def compose(_utterance: str, **kwargs) -> ComposedPrompt:+ if kwargs["terminal_name"] == "Iris":+ first_started.set()+ await never_release.wait()+ return ComposedPrompt(text="brief")++ task = asyncio.create_task(+ fanout.deliver(+ session=session,+ terminals=["Iris", "Bruno"],+ utterance="brief both panes",+ include_pending_attachments=True,+ compose=compose,+ limit=1,+ )+ )+ await first_started.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ assert all(+ term.pending_prompt_attachment_reservations == set()+ for term in session.terminals+ )+++async def test_cancellation_during_commit_still_consumes_a_sent_batch() -> None:+ session = _session("Iris")+ term = session.terminals[0]+ attachment = SimpleNamespace(name="layout.png")+ term.pending_prompt_attachment_batches.append(+ PendingPromptAttachmentBatch("batch-a", (attachment,), ("layout.png",))+ )+ send_returned = asyncio.Event()++ async def compose(utterance: str, **_kwargs) -> ComposedPrompt:+ return ComposedPrompt(text=utterance)++ async def send(_name: str, _text: str) -> SimpleNamespace:+ await term.pending_prompt_attachment_lock.acquire()+ send_returned.set()+ return SimpleNamespace(submitted=True)++ task = asyncio.create_task(+ fanout.deliver(+ session=session,+ terminals=["Iris"],+ utterance="fix the layout",+ include_pending_attachments=True,+ compose=compose,+ send=send,+ )+ )+ await send_returned.wait()+ await asyncio.sleep(0)+ task.cancel()+ term.pending_prompt_attachment_lock.release()+ with pytest.raises(asyncio.CancelledError):+ await task++ assert term.pending_prompt_attachment_batches == []+ assert term.pending_prompt_attachment_reservations == set()++async def test_prompts_are_composed_concurrently() -> None:"""Composed one after another, eight panes cannot fit in a voice turn."""rec = Recorder()diff --git a/tests/unit/brain/test_agentic_ide_fanout_fast_path.py b/tests/unit/brain/test_agentic_ide_fanout_fast_path.pyindex a0eaacb472..4fca2d68c2 100644--- a/tests/unit/brain/test_agentic_ide_fanout_fast_path.py+++ b/tests/unit/brain/test_agentic_ide_fanout_fast_path.py@@ -19,13 +19,14 @@ from __future__ import annotationsimport timefrom pathlib import Path+from types import SimpleNamespaceimport pytestfrom jarvis.agentic_ide import prompt_composerfrom jarvis.agentic_ide import session as session_modfrom jarvis.agentic_ide.prompt_composer import ComposedPrompt-from jarvis.agentic_ide.session import Registry+from jarvis.agentic_ide.session import PendingPromptAttachmentBatch, Registryfrom jarvis.brain.manager import BrainManagerfrom jarvis.core.bus import EventBusfrom jarvis.core.config import JarvisConfig@@ -127,6 +128,35 @@ async def test_two_addressed_panes_both_receive_the_prompt(assert _sent_to(registry, second)+async def test_only_a_spoken_brain_turn_consumes_orb_context(+ manager: BrainManager, registry: Registry, tmp_path: Path+) -> None:+ await _open(registry, tmp_path, 1)+ (name,) = _names(registry)+ assert registry.session is not None+ term = registry.session.find(name)+ assert term is not None+ attachment = SimpleNamespace(name="layout.png")+ batch = PendingPromptAttachmentBatch(+ "batch-a", (attachment,), ("layout.png",)+ )+ term.pending_prompt_attachment_batches.append(batch)++ # Chat, CLI, and every other ordinary BrainManager caller keep the drop.+ await manager.generate(+ f"Tell {name} to inspect the current layout", use_history=False+ )+ assert term.pending_prompt_attachment_batches == [batch]++ # SpeechPipeline is the sole caller that opts this turn modality in.+ await manager.generate(+ f"Tell {name} to fix the current layout",+ use_history=False,+ consume_pending_voice_attachments=True,+ )+ assert term.pending_prompt_attachment_batches == []++async def test_the_reply_names_every_pane_that_got_it(manager: BrainManager, registry: Registry, tmp_path: Path) -> None:diff --git a/tests/unit/speech/test_thinking_interrupt_monitor.py b/tests/unit/speech/test_thinking_interrupt_monitor.pyindex 0761c768eb..25a905caca 100644--- a/tests/unit/speech/test_thinking_interrupt_monitor.py+++ b/tests/unit/speech/test_thinking_interrupt_monitor.py@@ -232,6 +232,45 @@ def _streaming_pipeline(brain) -> SpeechPipeline:return pipeline+async def test_voice_stream_opts_into_pending_orb_context() -> None:+ """A spoken turn, unlike ordinary BrainManager callers, consumes orb drops."""+ received: dict[str, object] = {}++ class _CapturingBrain:+ async def generate_stream(self, text, **kwargs):+ received.update(kwargs)+ yield "Done."++ pipeline = _streaming_pipeline(_CapturingBrain())++ await pipeline._brain_streaming("Inspect the attached layout", "en")++ assert received["consume_pending_voice_attachments"] is True+++async def test_non_streaming_voice_opts_into_pending_orb_context() -> None:+ """The callback-based voice mode carries the same explicit modality."""+ received: dict[str, object] = {}++ class _CapturingBrain:+ async def generate(self, text, **kwargs):+ received.update(kwargs)+ return "Done."++ pipeline = _streaming_pipeline(_CapturingBrain())++ result = await pipeline._brain_with_ack(+ "Inspect the attached layout",+ "en",+ consume_pending_voice_attachments=True,+ )++ assert result == "Done."+ assert received["consume_pending_voice_attachments"] is True++@pytest.mark.asyncioasync def test_real_streaming_interrupt_fires_before_first_chunk():"""Interrupt must fire while the brain is still thinking (no token yet),