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
fix: connect Jarvis Bar drops to Agentic IDE
Ruben Lütke6fe8f6f18bfc
diff --git a/jarvis/agentic_ide/prompt_attachments.py b/jarvis/agentic_ide/prompt_attachments.pynew file mode 100644index 0000000000..7922fdbf17--- /dev/null+++ b/jarvis/agentic_ide/prompt_attachments.py@@ -0,0 +1,133 @@+"""Shared staging for files waiting on a spoken Agentic-IDE prompt.++The orb, the web dock, and the native Jarvis Bar are three surfaces for one+gesture: attach these files to the next instruction for the selected coding+pane. This module owns the common queue operation so every surface gets the+same limits, workspace-local copies, analysis, and consumption path.+"""++from __future__ import annotations++import asyncio+from collections.abc import Sequence+from dataclasses import dataclass+from typing import Any+from uuid import uuid4++from jarvis.agentic_ide import drop_analysis, drops+from jarvis.agentic_ide.session import PendingPromptAttachmentBatch, get_registry+from jarvis.brain.drop_context import DroppedItem++MAX_PENDING_BATCHES = 8+MAX_PENDING_ATTACHMENTS = 16+MAX_PENDING_CHARS = 20_000+++class PromptAttachmentQueueFull(RuntimeError):+ """The selected pane already carries the maximum pending context."""+++@dataclass(frozen=True, slots=True)+class StagedPromptAttachments:+ """A completed staging operation and the pane that owns it."""++ terminal: str+ batch_id: str+ files: tuple[str, ...]+++def _analysis_chars(items: Sequence[Any]) -> int:+ return sum(+ len(str(getattr(item, field, "") or ""))+ for item in items+ for field in ("name", "reference", "detail", "note")+ )+++async def enqueue(+ term: Any,+ attachments: Sequence[Any],+ files: Sequence[str],+) -> PendingPromptAttachmentBatch:+ """Append one bounded batch to ``term`` under its attachment lock."""+ batch = PendingPromptAttachmentBatch(+ batch_id=uuid4().hex,+ attachments=tuple(attachments),+ files=tuple(files),+ )+ async with term.pending_prompt_attachment_lock:+ pending = term.pending_prompt_attachment_batches+ attachment_count = sum(len(item.attachments) for item in pending)+ char_count = sum(_analysis_chars(item.attachments) for item in pending)+ if (+ len(pending) >= MAX_PENDING_BATCHES+ or attachment_count + len(batch.attachments) > MAX_PENDING_ATTACHMENTS+ or char_count + _analysis_chars(batch.attachments) > MAX_PENDING_CHARS+ ):+ raise PromptAttachmentQueueFull(+ "This pane already has the maximum amount of voice-prompt "+ "context waiting. Use or remove a pending drop first."+ )+ pending.append(batch)+ return batch+++async def stage_items_for_prompt_target(+ items: Sequence[DroppedItem],+ *,+ registry: Any = None,+) -> StagedPromptAttachments | None:+ """Copy and analyse ``items`` for the prompt target currently on screen.++ ``None`` means no Agentic-IDE pane is an honest target right now. The+ caller can then retain the drop as ordinary assistant context instead.+ Once a target is chosen, the batch remains bound to that pane even if the+ user selects another one while image analysis is running.+ """+ usable = [item for item in items if item.name and item.data]+ if not usable:+ return None++ active_registry = registry if registry is not None else get_registry()+ session = active_registry.session+ if session is None:+ return None+ term = session.prompt_target_terminal()+ if term is None:+ return None++ stored = await asyncio.to_thread(+ drops.store,+ session.folder,+ [(item.name, item.data) for item in usable],+ )+ pairs: list[tuple[DroppedItem, str]] = []+ for item, saved in zip(usable, stored, strict=True):+ pairs.append((item, drops.reference(saved.relative_path, agent=term.agent)))+ analyses = await drop_analysis.analyze(pairs)+ if not analyses:+ return None++ # The pane may have been closed while a vision provider described an image.+ # Never park context on a detached Terminal object the UI cannot list.+ found = active_registry.find_terminal(term.name)+ if found is None or found[0] is not session or found[1] is not term:+ return None++ batch = await enqueue(term, analyses, [saved.name for saved in stored])+ return StagedPromptAttachments(+ terminal=term.name,+ batch_id=batch.batch_id,+ files=batch.files,+ )+++__all__ = [+ "MAX_PENDING_ATTACHMENTS",+ "MAX_PENDING_BATCHES",+ "MAX_PENDING_CHARS",+ "PromptAttachmentQueueFull",+ "StagedPromptAttachments",+ "enqueue",+ "stage_items_for_prompt_target",+]diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex 9da2bf9277..3a081cc48c 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -1218,6 +1218,12 @@ class Session:# snapshots: after a restart the UI reports what it actually shows again.surface_chat_visible: bool = Falsesurface_terminal: str = ""+ # The written prompt bar and the voice orb share one explicit pane target.+ # Unlike ``surface_terminal``, this remains meaningful in grid view: every+ # pane may be visible, but the selected prompt chip says exactly where the+ # next dropped file or instruction belongs.+ surface_on_screen: bool = False+ surface_prompt_target: str = ""# When this workspace was last brought to the front. Orders the "most# recently used" answer the resume snapshot and the UI both want, which is# NOT the order the workspaces were opened in.@@ -1264,6 +1270,15 @@ class Session:return Nonereturn self.find(self.surface_terminal)+ def prompt_target_terminal(self) -> Terminal | None:+ """The pane selected by the visible prompt bar and voice orb."""+ if not self.surface_on_screen or not self.surface_prompt_target:+ return None+ selected = self.find(self.surface_prompt_target)+ if selected is None or not accepts_prompts(selected.agent):+ return None+ return selected+def to_dict(self) -> dict[str, Any]:return {"id": self.id,@@ -2296,6 +2311,7 @@ class Registry:chat_view: bool,on_screen: bool,terminal: str | None,+ prompt_target: str | None = None,) -> bool:"""Record which single pane the active UI visibly puts on its stage.@@ -2306,9 +2322,16 @@ class Registry:session = self.sessionif session is None or session.id != workspace_id:return False+ session.surface_on_screen = bool(on_screen)session.surface_chat_visible = bool(chat_view and on_screen)selected = session.find(terminal or "") if session.surface_chat_visible else Nonesession.surface_terminal = selected.name if selected is not None else ""+ prompt = session.find(prompt_target or "") if session.surface_on_screen else None+ session.surface_prompt_target = (+ prompt.name+ if prompt is not None and accepts_prompts(prompt.agent)+ else ""+ )return True# ------------------------------------------------------------------ ptydiff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 7abd20f73c..6f5c3afad6 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -1640,18 +1640,18 @@ class DesktopApp:server.bus.subscribe(MessageSent, _on_user_message)- # Drag-drop onto the floating overlay (bar/mascot) → a proactive brain- # turn, reusing the SAME intake as the web dock (jarvis/brain/- # drop_context.ingest_drop). The overlay (Tk thread) calls dispatch_drop;- # we marshal here onto the long-running backend loop and run the intake.- # A no-op until tkdnd is present (NullDropTarget); brain may be None- # (build error) → ingest_drop degrades to a text-only turn.+ # Drag-drop onto the floating overlay (bar/mascot) reuses the SAME+ # intake as the web dock. In the Agentic IDE it stages files for the+ # selected pane; elsewhere it retains them as silent brain context. The+ # overlay thread calls dispatch_drop, so the actual intake is marshalled+ # onto the long-running backend loop here.try:- from jarvis.brain.drop_context import ingest_drop, items_from_paths+ from jarvis.brain.drop_context import items_from_pathsfrom jarvis.overlay.drop_bridge import (report_drop_result,set_drop_handler,)+ from jarvis.ui.drop_intake import capture_presence_dropdef _on_overlay_drop(paths: list[str], text: str) -> None:items = items_from_paths(paths) if paths else []@@ -1668,15 +1668,13 @@ class DesktopApp:accepted = Falsetry:current_brain = await _await_brain_ready()- accepted = bool(- await ingest_drop(- bus=server.bus,- brain=current_brain,- thread_id="default",- items=items,- dragged_text=dragged,- )+ result = await capture_presence_drop(+ brain=current_brain,+ thread_id="default",+ items=items,+ dragged_text=dragged,)+ accepted = result.capturedfinally:# The overlay gets an honest answer either way: a# confirmation tick that appears when the content neverdiff --git a/jarvis/ui/drop_intake.py b/jarvis/ui/drop_intake.pynew file mode 100644index 0000000000..be9ec763fb--- /dev/null+++ b/jarvis/ui/drop_intake.py@@ -0,0 +1,80 @@+"""Route one Jarvis-presence drop to the context that is actually on screen."""++from __future__ import annotations++from collections.abc import Sequence+from dataclasses import dataclass+from typing import Any++from loguru import logger++from jarvis.brain.drop_context import DroppedItem, ingest_drop+++@dataclass(frozen=True, slots=True)+class DropCapture:+ """What accepted a drop and, when applicable, which pane owns it."""++ captured: bool+ terminal: str = ""+ batch_id: str = ""+ files: tuple[str, ...] = ()+++async def capture_presence_drop(+ *,+ brain: Any,+ items: Sequence[DroppedItem],+ dragged_text: str | None = None,+ thread_id: str = "default",+) -> DropCapture:+ """Capture one native/web dock drop without splitting its meaning.++ When the Agentic IDE is on screen, its selected prompt target is explicit:+ files belong to that pane's next spoken instruction and are copied,+ analysed, displayed by the orb, and consumed through the existing guarded+ queue. Everywhere else the same files remain ordinary assistant context.+ Dragged text always stays ordinary context because it is not a file the+ coding agent can open.+ """+ staged = None+ if items:+ try:+ from jarvis.agentic_ide.prompt_attachments import (+ stage_items_for_prompt_target,+ )++ staged = await stage_items_for_prompt_target(items)+ except Exception as exc: # noqa: BLE001 - ordinary context remains available+ logger.warning(+ "Jarvis presence drop could not stage Agentic-IDE attachments: {}",+ exc,+ )++ # A staged file must not also remain as global image context: an addressed+ # pane turn exits through the deterministic IDE path before global images+ # are consumed, which would leak the old picture into a later unrelated+ # assistant turn. Text dragged alongside files is independent and retained.+ context_items: Sequence[DroppedItem] = () if staged is not None else items+ context_captured = False+ if context_items or (dragged_text and dragged_text.strip()):+ context_captured = bool(+ await ingest_drop(+ brain=brain,+ thread_id=thread_id,+ items=context_items,+ dragged_text=dragged_text,+ )+ )++ if staged is not None:+ return DropCapture(+ captured=True,+ terminal=staged.terminal,+ batch_id=staged.batch_id,+ files=staged.files,+ )+ return DropCapture(captured=context_captured)+++__all__ = ["DropCapture", "capture_presence_drop"]diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 62bc41c7c0..032e6d10dd 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -53,7 +53,6 @@ import asyncioimport loggingfrom dataclasses import asdictfrom pathlib import Path-from uuid import uuid4from fastapi import (APIRouter,@@ -73,6 +72,7 @@ from jarvis.agentic_ide import (interrupted,native_picker,notifications,+ prompt_attachments,prompt_history,recap_engine,recents,@@ -124,14 +124,6 @@ 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.@@ -301,7 +293,7 @@ class ModeRequest(BaseModel):class SurfaceContextRequest(BaseModel):- """Which single terminal the Agentic-IDE UI visibly puts on stage."""+ """Which terminal the Agentic-IDE UI shows and targets for prompts."""workspace_id: str = Field(description="Workspace currently rendered by this view.")chat_view: bool = Field(description="True only while the one-pane chat view is selected.")@@ -310,6 +302,13 @@ class SurfaceContextRequest(BaseModel):default=None,description="Visible pane call-sign; null when no single pane is shown.",)+ prompt_target: str | None = Field(+ default=None,+ description=(+ "Pane selected by the prompt bar and voice orb; null when no pane "+ "can accept an instruction."+ ),+ )class TerminalTextSizeRequest(BaseModel):@@ -1772,6 +1771,7 @@ async def set_surface_context(req: SurfaceContextRequest) -> dict:chat_view=req.chat_view,on_screen=req.on_screen,terminal=req.terminal,+ prompt_target=req.prompt_target,)return {"ok": True, "accepted": accepted}@@ -2523,37 +2523,12 @@ async def terminal_attach(voice_batch: PendingPromptAttachmentBatch | None = Noneif 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+ try:+ voice_batch = await prompt_attachments.enqueue(+ term, analysis_items, stored_names)- 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)+ except prompt_attachments.PromptAttachmentQueueFull as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from excanalysis = [item.to_dict() for item in analysis_items]diff --git a/jarvis/ui/web/drop_routes.py b/jarvis/ui/web/drop_routes.pyindex 43124348f8..a75485d828 100644--- a/jarvis/ui/web/drop_routes.py+++ b/jarvis/ui/web/drop_routes.py@@ -1,21 +1,22 @@"""``POST /api/chat/drop`` — drag-and-drop intake for the Jarvis dock / overlay.A dropped file (image, document, code, …) or dragged text is posted here as-multipart; the route normalises it to :class:`DroppedItem`s and hands it to-``ingest_drop``, which composes one proactive ``MessageSent`` brain turn (spoken-on the voice build, shown in chat, landed in ``_history``). Images ride the-multimodal path so the brain can see a dropped picture.+multipart. In the Agentic IDE, files are staged for the selected coding pane's+next spoken prompt; elsewhere they become silent assistant context for the next+real user turn. The drop itself never starts a brain turn.Mirrors the avatar-upload pattern (multipart + size cap). The reply flows backover the normal WS event stream — this route only kicks off the turn."""+from __future__ import annotationsfrom typing import Anyfrom fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile-from jarvis.brain.drop_context import DroppedItem, ingest_drop+from jarvis.brain.drop_context import DroppedItem+from jarvis.ui.drop_intake import capture_presence_droprouter = APIRouter(tags=["chat"])@@ -33,16 +34,14 @@ async def drop_into_context(text: str | None = Form(default=None), # noqa: B008surface: str | None = Form(default=None), # noqa: B008) -> dict[str, Any]:- """Ingest dropped content as a proactive brain turn.+ """Capture dropped content for the selected pane or assistant context.Returns ``{"dispatched": bool}`` — ``False`` when the drop carried nothingusable (no turn dispatched). 413 when the total payload exceeds the cap."""brain = getattr(request.app.state, "brain", None)if brain is None:- raise HTTPException(- status_code=503, detail="Brain unavailable to hold dropped context."- )+ raise HTTPException(status_code=503, detail="Brain unavailable to hold dropped context.")items: list[DroppedItem] = []total = 0@@ -64,7 +63,7 @@ async def drop_into_context())- captured = await ingest_drop(+ captured = await capture_presence_drop(brain=brain,thread_id=thread_id or "default",items=items,@@ -72,4 +71,9 @@ async def drop_into_context()# ``dispatched`` kept as the response key for frontend compatibility; it now# means "captured into context" (a drop never dispatches a turn on its own).- return {"dispatched": captured}+ return {+ "dispatched": captured.captured,+ "terminal": captured.terminal or None,+ "voice_batch_id": captured.batch_id or None,+ "files": list(captured.files),+ }diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsxindex 87aad3ad39..bf50a725cd 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx@@ -2408,6 +2408,7 @@ describe("chat view", () => {chatView: false,onScreen: true,terminal: null,+ promptTarget: "Mika",}),);@@ -2420,6 +2421,7 @@ describe("chat view", () => {chatView: true,onScreen: true,terminal: "Aria",+ promptTarget: "Aria",}),);@@ -2430,6 +2432,7 @@ describe("chat view", () => {chatView: false,onScreen: true,terminal: null,+ promptTarget: "Aria",}),);});diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsxindex fb434bdbf5..a463600223 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx@@ -1189,10 +1189,11 @@ export function AgenticGrid({chatView,onScreen,terminal: chatView && onScreen ? chatSelected : null,+ promptTarget: onScreen ? target || null : null,}).catch((error) => {console.warn("Agentic IDE: could not sync the visible terminal:", error);});- }, [chatSelected, chatView, onScreen, session.id]);+ }, [chatSelected, chatView, onScreen, session.id, target]);/** Rail click: show the pane, and aim the composer at it when it can listen. */const selectChatPane = useCallback((name: string, promptable: boolean) => {diff --git a/jarvis/ui/web/frontend/src/components/agentic/VoicePanel.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/VoicePanel.test.tsxindex 257f535621..84e05de11a 100644--- a/jarvis/ui/web/frontend/src/components/agentic/VoicePanel.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/VoicePanel.test.tsx@@ -180,6 +180,22 @@ describe("voice panel", () => {).toBe(true);});+ it("discovers a native Jarvis Bar drop after the panel is already mounted", async () => {+ render(<VoicePanel promptTarget="Mika" />);+ await waitFor(() => expect(ideApi.fetchAllVoiceAttachments).toHaveBeenCalled());+ expect(screen.queryByTestId("voice-orb-drop-context")).toBeNull();++ pendingVoiceBatches.set("batch-native", {+ batch_id: "batch-native",+ files: ["bar-drop.png"],+ });+ fireEvent.focus(window);++ const receipt = await screen.findByTestId("voice-orb-drop-context");+ expect(receipt.textContent).toContain("bar-drop.png");+ expect(receipt.textContent).toContain("Mika");+ });+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 5c92217ed2..d5d8b013f4 100644--- a/jarvis/ui/web/frontend/src/components/agentic/VoicePanel.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/VoicePanel.tsx@@ -32,7 +32,6 @@ import { requestVoiceCall, requestVoiceHangup } from "@/lib/voiceApi";import {attachToTerminal,fetchAllVoiceAttachments,- fetchVoiceAttachments,removeVoiceAttachment,} from "@/lib/agenticIdeApi";import { playDropConfirm } from "@/lib/sound";@@ -93,7 +92,13 @@ function format(text: string, ...values: Array<string | number>): string {);}-export function VoicePanel({ promptTarget = "" }: { promptTarget?: string }) {+export function VoicePanel({+ promptTarget = "",+ onScreen = true,+}: {+ promptTarget?: string;+ onScreen?: boolean;+}) {const t = useT();const voiceState = (useEventStore((s) => s.voiceState) ?? "idle") as VoiceState;const transcription = useEventStore((s) => s.transcription) ?? "";@@ -110,92 +115,63 @@ export function VoicePanel({ promptTarget = "" }: { promptTarget?: string }) {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.+ // The native Jarvis Bar lives in another process, so it cannot update this+ // component's local state when a file lands. Reconcile the authoritative+ // backend queue while the panel is mounted: this both discovers external+ // drops and removes a receipt only after the spoken delivery consumed it.useEffect(() => {+ if (!onScreen) return;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, {+ let inFlight = false;+ let refreshQueued = false;+ let timer: number | undefined;+ const reconcile = () => {+ if (cancelled) return;+ if (inFlight) {+ refreshQueued = true;+ return;+ }+ inFlight = true;+ void fetchAllVoiceAttachments()+ .then((response) => {+ if (cancelled) return;+ setReceipts(+ response.batches.map((batch) => ({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;- });+ })),+ );+ })+ .catch(() => {+ // A transient reconnect must not invent an empty queue. The next+ // interval/focus reconciliation retries without erasing the receipt.}).finally(() => {- if (active && !cancelled) timer = window.setTimeout(reconcile, 750);+ inFlight = false;+ if (refreshQueued) {+ refreshQueued = false;+ reconcile();+ } else if (!cancelled) {+ timer = window.setTimeout(reconcile, active ? 750 : 1_500);+ }});};reconcile();+ const refreshNow = () => {+ if (timer !== undefined) window.clearTimeout(timer);+ timer = undefined;+ reconcile();+ };+ window.addEventListener("focus", refreshNow);return () => {cancelled = true;if (timer !== undefined) window.clearTimeout(timer);+ window.removeEventListener("focus", refreshNow);};- }, [active, receiptKey, voiceState]);+ }, [active, onScreen]);// 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.diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.tsindex b963eda940..4285cedfb6 100644--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts@@ -1113,17 +1113,18 @@ export async function setFocusMode(enabled: boolean): Promise<boolean> {}/**- * Tell the backend which single pane is visibly filling the chat stage.+ * Tell the backend which pane is visible and which one owns the next prompt.** Ephemeral by design: this is grounding for "this terminal", not a display- * preference. Grid view and hidden sections send no terminal because neither- * has one honest implicit target.+ * preference. Grid view has no single visible terminal, but its selected prompt+ * chip remains an explicit target for the prompt bar, voice orb, and file drops.*/export async function syncAgenticIdeSurface(payload: {workspaceId: string;chatView: boolean;onScreen: boolean;terminal: string | null;+ promptTarget: string | null;}): Promise<void> {const res = await fetch("/api/agentic-ide/surface-context", {method: "PUT",@@ -1134,6 +1135,7 @@ export async function syncAgenticIdeSurface(payload: {chat_view: payload.chatView,on_screen: payload.onScreen,terminal: payload.terminal,+ prompt_target: payload.promptTarget,}),});if (!res.ok) throw new Error(await detail(res));diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsxindex dbc95680ae..f80d4c0085 100644--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx@@ -760,6 +760,7 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {reset the orb mid-sentence.*/}<VoicePanel+ onScreen={onScreen}promptTarget={session.terminals.some((terminal) =>diff --git a/tests/unit/agentic_ide/test_prompt_attachment_staging.py b/tests/unit/agentic_ide/test_prompt_attachment_staging.pynew file mode 100644index 0000000000..cb7d296d67--- /dev/null+++ b/tests/unit/agentic_ide/test_prompt_attachment_staging.py@@ -0,0 +1,99 @@+"""Jarvis Bar drops become real attachments for the selected coding pane."""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++import pytest++from jarvis.agentic_ide import fanout+from jarvis.agentic_ide import session as session_mod+from jarvis.agentic_ide.prompt_attachments import stage_items_for_prompt_target+from jarvis.agentic_ide.session import Registry+from jarvis.brain.drop_context import DroppedItem+from tests.fakes.fake_pty_manager import FakePtyManager+++async def test_bar_drop_is_copied_analysed_and_queued_for_prompt_target(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))+ registry = Registry(pty_manager=FakePtyManager())+ session = await registry.start(str(tmp_path), [{"agent": "claude"}, {"agent": "codex"}])+ registry.set_surface_context(+ workspace_id=session.id,+ chat_view=False,+ on_screen=True,+ terminal=None,+ prompt_target="T2",+ )++ staged = await stage_items_for_prompt_target(+ [+ DroppedItem(+ name="failure.txt",+ mime="text/plain",+ data=b"BAR_FILE_TOKEN_42",+ )+ ],+ registry=registry,+ )++ assert staged is not None+ assert staged.terminal == "T2"+ assert staged.files == ("failure.txt",)+ term = session.find("T2")+ assert term is not None+ assert len(term.pending_prompt_attachment_batches) == 1+ batch = term.pending_prompt_attachment_batches[0]+ assert batch.batch_id == staged.batch_id+ assert batch.attachments[0].detail == "BAR_FILE_TOKEN_42"+ copied = tmp_path / batch.attachments[0].reference.strip('"').lstrip("@")+ assert copied.read_bytes() == b"BAR_FILE_TOKEN_42"++ received: list = []++ async def _compose(_utterance: str, **kwargs):+ received.extend(kwargs["attachments"])+ return SimpleNamespace(+ text="Use the attached failure report.",+ files=(batch.attachments[0].reference,),+ composed_by="test",+ )++ async def _send(_name: str, _text: str):+ return SimpleNamespace(submitted=True)++ term.status = "live"+ term.pty_id = "pty-t2"+ delivered = await fanout.deliver(+ session=session,+ terminals=["T2"],+ utterance="Fix the failure in the file I dropped.",+ compose=_compose,+ send=_send,+ include_pending_attachments=True,+ )++ assert delivered.delivered+ assert received[0].detail == "BAR_FILE_TOKEN_42"+ assert term.pending_prompt_attachment_batches == []+++async def test_bar_drop_without_visible_prompt_target_stays_unstaged(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))+ registry = Registry(pty_manager=FakePtyManager())+ await registry.start(str(tmp_path), [{"agent": "claude"}])++ staged = await stage_items_for_prompt_target(+ [DroppedItem(name="notes.txt", mime="text/plain", data=b"context")],+ registry=registry,+ )++ assert staged is None+ assert not (tmp_path / ".jarvis").exists()diff --git a/tests/unit/agentic_ide/test_surface_context_route.py b/tests/unit/agentic_ide/test_surface_context_route.pyindex a59abf2e63..db095e406a 100644--- a/tests/unit/agentic_ide/test_surface_context_route.py+++ b/tests/unit/agentic_ide/test_surface_context_route.py@@ -1,4 +1,5 @@"""The one-pane chat stage is the grounding for "this terminal"."""+from __future__ import annotationsfrom pathlib import Path@@ -31,9 +32,7 @@ def client(registry: Registry) -> TestClient:async def test_chat_surface_records_the_visible_terminal(client: TestClient, registry: Registry, tmp_path: Path) -> None:- session = await registry.start(- str(tmp_path), [{"agent": "claude"}, {"agent": "codex"}]- )+ session = await registry.start(str(tmp_path), [{"agent": "claude"}, {"agent": "codex"}])response = client.put("/api/agentic-ide/surface-context",@@ -42,12 +41,14 @@ async def test_chat_surface_records_the_visible_terminal("chat_view": True,"on_screen": True,"terminal": "T2",+ "prompt_target": "T2",},)assert response.status_code == 200assert response.json()["accepted"] is Trueassert session.contextual_terminal() is session.find("T2")+ assert session.prompt_target_terminal() is session.find("T2")async def test_grid_or_hidden_view_clears_the_implicit_terminal(@@ -68,6 +69,41 @@ async def test_grid_or_hidden_view_clears_the_implicit_terminal(assert session.contextual_terminal() is None+async def test_grid_keeps_the_explicit_prompt_target_for_bar_drops(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ session = await registry.start(str(tmp_path), [{"agent": "claude"}, {"agent": "codex"}])++ response = client.put(+ "/api/agentic-ide/surface-context",+ json={+ "workspace_id": session.id,+ "chat_view": False,+ "on_screen": True,+ "terminal": None,+ "prompt_target": "T2",+ },+ )++ assert response.status_code == 200+ assert session.contextual_terminal() is None+ assert session.prompt_target_terminal() is session.find("T2")++ response = client.put(+ "/api/agentic-ide/surface-context",+ json={+ "workspace_id": session.id,+ "chat_view": False,+ "on_screen": False,+ "terminal": None,+ "prompt_target": "T2",+ },+ )++ assert response.status_code == 200+ assert session.prompt_target_terminal() is None++async def test_stale_workspace_cannot_replace_the_active_surface(client: TestClient, registry: Registry, tmp_path: Path) -> None:diff --git a/tests/unit/overlay/test_overlay_drop_to_brain.py b/tests/unit/overlay/test_overlay_drop_to_brain.pyindex 200e6d3a07..d8d497d008 100644--- a/tests/unit/overlay/test_overlay_drop_to_brain.py+++ b/tests/unit/overlay/test_overlay_drop_to_brain.py@@ -15,13 +15,14 @@ from uuid import uuid4import pytest-from jarvis.brain.drop_context import ingest_drop, items_from_paths+from jarvis.brain.drop_context import items_from_pathsfrom jarvis.brain.manager import BrainManagerfrom jarvis.brain.streaming import StreamingAggregatefrom jarvis.core.bus import EventBusfrom jarvis.core.config import JarvisConfigfrom jarvis.core.protocols import BrainDelta, BrainRequestfrom jarvis.overlay import drop_bridge+from jarvis.ui.drop_intake import capture_presence_dropclass _FakeBrain:@@ -82,14 +83,13 @@ def _wire_desktop_app_drop(manager, loop, done: asyncio.Event) -> None:async def _run() -> None:accepted = Falsetry:- accepted = bool(- await ingest_drop(- brain=manager,- thread_id="default",- items=items,- dragged_text=dragged,- )+ result = await capture_presence_drop(+ brain=manager,+ thread_id="default",+ items=items,+ dragged_text=dragged,)+ accepted = result.capturedfinally:drop_bridge.report_drop_result(accepted)done.set()diff --git a/tests/unit/ui/test_drop_intake.py b/tests/unit/ui/test_drop_intake.pynew file mode 100644index 0000000000..467976605f--- /dev/null+++ b/tests/unit/ui/test_drop_intake.py@@ -0,0 +1,59 @@+"""The shared native/web Jarvis-presence drop routing."""++from __future__ import annotations++import pytest++from jarvis.agentic_ide import prompt_attachments+from jarvis.agentic_ide.prompt_attachments import StagedPromptAttachments+from jarvis.brain.drop_context import DroppedItem+from jarvis.ui.drop_intake import capture_presence_drop+++class _Brain:+ def __init__(self) -> None:+ self.dropped: list[tuple[str, tuple]] = []++ def add_dropped_context(self, text: str, images=()) -> None:+ self.dropped.append((text, tuple(images)))+++async def test_visible_ide_target_owns_file_without_duplicate_global_context(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def _stage(_items):+ return StagedPromptAttachments(terminal="Mika", batch_id="batch-1", files=("shot.png",))++ monkeypatch.setattr(prompt_attachments, "stage_items_for_prompt_target", _stage)+ brain = _Brain()++ result = await capture_presence_drop(+ brain=brain,+ items=[DroppedItem(name="shot.png", mime="image/png", data=b"png")],+ )++ assert result.captured is True+ assert result.terminal == "Mika"+ assert result.batch_id == "batch-1"+ assert brain.dropped == []+++async def test_drop_falls_back_to_assistant_context_without_ide_target(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def _stage(_items):+ return None++ monkeypatch.setattr(prompt_attachments, "stage_items_for_prompt_target", _stage)+ brain = _Brain()++ result = await capture_presence_drop(+ brain=brain,+ items=[DroppedItem(name="notes.txt", mime="text/plain", data=b"hello")],+ )++ assert result.captured is True+ assert result.terminal == ""+ assert "notes.txt" in brain.dropped[0][0]