Skip to content

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.

feat(jarvisbar): let a drop on the bar answer for itself

Ruben Lütke1d5dac9a87a0
diff --git a/docs/os-parity.md b/docs/os-parity.md
index ce245525a8..d6d288646c 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -58,6 +58,8 @@ experiences today.
| P-13 | Info | Wiki | Wiki DB/vault anchor at `repo_root()` — read-only *wheel* installs would fail writes (not OS-specific; `JARVIS_DATA_DIR` override exists) | `jarvis/memory/wiki/db_path.py:9`, `vault_root.py:59` | None on the advertised install paths |
| P-14 | Info | CU extras | macOS/Linux actuation and UI trees depend on optional extras (pynput, pyobjc, pyatspi); without them everything degrades honestly to screenshot + pixel-click | `jarvis/cu/actuate/posix.py`, `jarvis/vision/tree_factory.py` | By design (§3); bare install keeps the CU loop functional |
| P-15 | Low | Desktop downloads | Native drag-out has Windows OLE and macOS AppKit sources but no GTK/WebKitGTK source yet | `jarvis/ui/native_drag.py` | Linux desktop: the saved-file toast keeps reliable **Show in folder** and **Open** actions but is not itself a drag handle; headless: the normal browser download path remains available |
+| P-18 | Low | Overlay drop | Dropping a file ONTO the floating bar/mascot uses two backends: tkdnd on the Tk surfaces (Windows/Linux) and native Qt drag events on the macOS Qt bar (added 2026-07-27 — before that, dropping on the bar did nothing at all on a Mac). The bundled `libtkdnd*.so` links against X11 libs, so a Linux host without them registers no drop target | `jarvis/overlay/drop_target.py`, `jarvis/ui/jarvisbar/qt_overlay.py::dropEvent` | macOS and Windows: full parity. Linux desktop: needs `libxcursor1 libxrender1 libxext6` + `python3-tk` (otherwise `register()` returns False and it is a logged no-op). Headless: no overlay exists — the in-app dock (`POST /api/chat/drop`) carries the feature on every OS |
+| P-19 | — | Overlay drop | RESOLVED 2026-07-27. The macOS bar runs in a companion process, whose drop bridge had no handler — the parent's is the real one. A file dropped on the macOS bar was accepted by the window (the OS even showed the "copy" cursor) and then silently discarded; it never became conversation context. Windows/Linux were unaffected (their bar is in-process). Fixed by forwarding the drop over the existing host protocol and returning the intake's verdict as `drop_result` | `jarvis/ui/jarvisbar/host.py::_wire_drop_forwarding`, `jarvis/ui/jarvisbar/subprocess_overlay.py::_dispatch_drop_event` | All three OSes deliver a dropped file into the conversation context and confirm it on the bar. Guards: `tests/unit/ui/jarvisbar/test_host_drop_roundtrip.py` |
| P-16 | Low | Wiki | `VaultLock` dead-owner fast-steal is POSIX-only (`os.kill(pid, 0)` liveness probe; on Windows `os.kill` cannot probe — a non-CTRL signal terminates the target) | `jarvis/memory/wiki/lock.py::_pid_alive` | Windows: a lock left by a crashed/restarted process is stolen only after the `stale_after_seconds` wall-clock window (300 s) — the pre-fix behavior everywhere; a Win32 `OpenProcess` probe could close this |
| P-17 | Low | JarvisBar | "Follow the mouse to the active monitor" has per-OS monitor backends (Windows `MonitorFromPoint`+`rcWork`, macOS Qt available-geometry / Quartz, Linux X11 `xrandr`) but no Wayland backend — Wayland exposes no reliable global monitor geometry without portal support | `jarvis/platform/monitors.py::work_area_at`, `jarvis/ui/jarvisbar/overlay.py`, `qt_overlay.py` | Wayland: `work_area_at` returns `None`, so the bar keeps the single-monitor behaviour (it does not migrate; a cross-monitor drag pins to the primary work area). The feature is a graceful no-op there, never a crash |
| P-18 | Low | Agent accounts | Multi-subscription switching gives each account its own CLI config directory (`CLAUDE_CONFIG_DIR` / `CODEX_HOME`) — the CLIs' own documented override. On macOS, Claude Code keeps its credentials in the **Keychain** rather than in that directory, and whether a second config dir earns a second Keychain entry is UNVERIFIED on this hardware (everything here was measured on Windows) | `jarvis/agent_accounts.py::describe`, `env_overrides` | Windows/Linux: a second Claude seat works as designed (its `.credentials.json` lives in its own folder). macOS: the added account may come back reporting **"Not signed in"** after a completed sign-in — which is the honest outcome, not a crash: the switcher never claims a login it cannot read, so a pane is never silently routed to the first account's credentials. Codex is unaffected on all three OSes (`auth.json` is a plain file). Next Mac session: add a second Claude account, sign in, and check whether `describe()` reports it connected |
diff --git a/jarvis/overlay/drop_bridge.py b/jarvis/overlay/drop_bridge.py
index 9ab702d1c4..b9381e2ce8 100644
--- a/jarvis/overlay/drop_bridge.py
+++ b/jarvis/overlay/drop_bridge.py
@@ -8,9 +8,14 @@ calls :func:`dispatch_drop` from the Tk thread; the desktop bridge
:func:`set_drop_handler` — which marshals onto the asyncio loop and runs
``jarvis.brain.drop_context.ingest_drop``.
+The bridge is bidirectional. The return leg (:func:`set_drop_result_sink` /
+:func:`report_drop_result`) carries the intake's verdict back to the overlay so
+it can confirm the drop visually — the outbound leg alone cannot, because the
+intake runs later on the asyncio loop.
+
This avoids threading a callback through the surface factory / orb / bar
-constructors (low-touch wiring into fragile GUI code). The handler is a single
-process-global slot — there is one overlay per process.
+constructors (low-touch wiring into fragile GUI code). Both slots are single
+process-globals — there is one overlay per process.
"""
from __future__ import annotations
@@ -22,7 +27,15 @@ log = logging.getLogger(__name__)
#: ``(file_paths, dragged_text)`` — exactly one populated per drop.
OnDrop = Callable[[list[str], str], None]
+#: ``on_result(accepted)`` — the RETURN leg of the same bridge. The intake runs
+#: asynchronously on the backend loop, so the overlay cannot learn from
+#: ``dispatch_drop`` whether the content actually became context; without this
+#: leg the bar had nothing to confirm with and stayed silent after every drop.
+#: ``True`` = captured, ``False`` = nothing usable was in it.
+OnDropResult = Callable[[bool], None]
+
_HANDLER: OnDrop | None = None
+_RESULT_SINK: OnDropResult | None = None
def set_drop_handler(handler: OnDrop | None) -> None:
@@ -31,6 +44,35 @@ def set_drop_handler(handler: OnDrop | None) -> None:
_HANDLER = handler
+def set_drop_result_sink(sink: OnDropResult | None) -> None:
+ """Register (or clear with ``None``) the overlay's drop-result receiver.
+
+ The overlay surface registers this when it wires its drop target; the
+ backend calls :func:`report_drop_result` once the intake has run. One
+ process-global slot, for the same reason the handler is one: there is a
+ single overlay per process.
+ """
+ global _RESULT_SINK
+ _RESULT_SINK = sink
+
+
+def report_drop_result(accepted: bool) -> bool:
+ """Tell the overlay how the drop it delivered ended. Never raises.
+
+ Returns ``True`` if a sink was present. A sink that fails internally is
+ swallowed and still counts as delivered — a broken confirmation animation
+ must never propagate into the backend turn that produced it.
+ """
+ sink = _RESULT_SINK
+ if sink is None:
+ return False
+ try:
+ sink(bool(accepted))
+ except Exception: # noqa: BLE001 — cosmetic feedback, never fatal.
+ log.debug("overlay drop-result sink failed", exc_info=True)
+ return True
+
+
def dispatch_drop(paths: list[str], text: str) -> bool:
"""Deliver a drop to the registered handler. Never raises (Tk-thread safe).
@@ -48,4 +90,11 @@ def dispatch_drop(paths: list[str], text: str) -> bool:
return True
-__all__ = ["OnDrop", "set_drop_handler", "dispatch_drop"]
+__all__ = [
+ "OnDrop",
+ "OnDropResult",
+ "dispatch_drop",
+ "report_drop_result",
+ "set_drop_handler",
+ "set_drop_result_sink",
+]
diff --git a/jarvis/overlay/drop_target.py b/jarvis/overlay/drop_target.py
index e7880d3b85..9c4b8bd105 100644
--- a/jarvis/overlay/drop_target.py
+++ b/jarvis/overlay/drop_target.py
@@ -41,12 +41,29 @@ log = logging.getLogger(__name__)
#: populated per drop: a file drop → (paths, ""), a text/URL drop → ([], text).
OnDrop = Callable[[list[str], str], None]
+#: ``on_drag_state(active)`` — True while a drag hovers the widget, False when
+#: it leaves or lands. A surface that also treats a click as a command uses this
+#: to stand its click handling down for the duration.
+#:
+#: This exists because of a real regression, not for symmetry: on a frameless
+#: color-key topmost Tk window, tkdnd's activity produces SYNTHETIC press/release
+#: events, and during a genuine drop the pointer IS over the window — so the
+#: overlay's own "is the pointer really here?" phantom-click guard cannot tell
+#: that pair apart from a deliberate click on the close-X. Dropping a file
+#: hung up the call (BUG-JB-DROP). The drag state is the missing signal.
+OnDragState = Callable[[bool], None]
+
@runtime_checkable
class DropTarget(Protocol):
"""Registers OS drag-drop on a Tk widget. ``register`` never raises."""
- def register(self, widget: Any, on_drop: OnDrop) -> bool:
+ def register(
+ self,
+ widget: Any,
+ on_drop: OnDrop,
+ on_drag_state: OnDragState | None = None,
+ ) -> bool:
"""Wire ``on_drop`` to drops on ``widget``; True if actually registered."""
...
@@ -86,7 +103,12 @@ def _parse_dnd_files(data: str) -> list[str]:
class NullDropTarget:
"""No-op target — overlay drop is unavailable on this host (logged once)."""
- def register(self, widget: Any, on_drop: OnDrop) -> bool: # noqa: ARG002
+ def register(
+ self,
+ widget: Any, # noqa: ARG002
+ on_drop: OnDrop, # noqa: ARG002
+ on_drag_state: OnDragState | None = None, # noqa: ARG002
+ ) -> bool:
log.debug("Overlay drop target unavailable (tkdnd absent) — no-op.")
return False
@@ -99,12 +121,27 @@ class TkDnDDropTarget:
degrades to ``False`` — the overlay keeps working, drop is simply off.
"""
- def register(self, widget: Any, on_drop: OnDrop) -> bool:
+ def register(
+ self,
+ widget: Any,
+ on_drop: OnDrop,
+ on_drag_state: OnDragState | None = None,
+ ) -> bool:
try:
import os
from tkinterdnd2 import COPY, DND_FILES, DND_TEXT, TkinterDnD # lazy (HN-7)
+ def _drag_state(active: bool) -> None:
+ # The surface's click handling depends on this, so a broken
+ # callback must not also break the drop it is reporting.
+ if on_drag_state is None:
+ return
+ try:
+ on_drag_state(active)
+ except Exception: # noqa: BLE001 — advisory signal, never fatal
+ log.debug("overlay drag-state callback failed", exc_info=True)
+
root = widget.winfo_toplevel()
# Load the tkdnd Tcl package into the EXISTING root — no new Tk root
# (BUG-031 cached-root constraint). Idempotent across overlays.
@@ -132,14 +169,20 @@ class TkDnDDropTarget:
# delivering drag events to this frameless/topmost/color-key window.
action = str(getattr(event, "action", "") or COPY)
_highlight(True)
+ _drag_state(True)
log.info("overlay DRAG over bar (tkdnd delivering) action=%s", action)
return action
def _leave(_event: Any) -> None:
_highlight(False)
+ _drag_state(False)
def _on_drop(event: Any) -> None:
_highlight(False)
+ # Reported BEFORE the payload is handled: the synthetic
+ # press/release the drop itself produces arrives around now, and
+ # the surface has to be stood down for it, not after it.
+ _drag_state(False)
try:
data = str(getattr(event, "data", "") or "")
paths = _parse_dnd_files(data)
@@ -195,6 +238,8 @@ def make_drop_target() -> DropTarget:
__all__ = [
"DropTarget",
"NullDropTarget",
+ "OnDragState",
+ "OnDrop",
"TkDnDDropTarget",
"make_drop_target",
]
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 1ce55ea610..cce8601f4e 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -1558,23 +1558,40 @@ class DesktopApp:
# (build error) → ingest_drop degrades to a text-only turn.
try:
from jarvis.brain.drop_context import ingest_drop, items_from_paths
- from jarvis.overlay.drop_bridge import set_drop_handler
+ from jarvis.overlay.drop_bridge import (
+ report_drop_result,
+ set_drop_handler,
+ )
def _on_overlay_drop(paths: list[str], text: str) -> None:
items = items_from_paths(paths) if paths else []
dragged = (text or "").strip() or None
if not items and dragged is None:
+ # A drop the user definitely made, carrying nothing we can
+ # use (an empty folder, an unreadable path). Say so — this
+ # is precisely the case where silence leaves them guessing
+ # whether the bar even noticed.
+ report_drop_result(False)
return
async def _handle_drop() -> None:
- current_brain = await _await_brain_ready()
- await ingest_drop(
- bus=server.bus,
- brain=current_brain,
- thread_id="default",
- items=items,
- dragged_text=dragged,
- )
+ accepted = False
+ try:
+ 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,
+ )
+ )
+ finally:
+ # The overlay gets an honest answer either way: a
+ # confirmation tick that appears when the content never
+ # reached the context would be worse than none at all.
+ report_drop_result(accepted)
asyncio.run_coroutine_threadsafe(_handle_drop(), loop)
diff --git a/jarvis/ui/jarvisbar/host.py b/jarvis/ui/jarvisbar/host.py
index bf8e751e6d..926316e42a 100644
--- a/jarvis/ui/jarvisbar/host.py
+++ b/jarvis/ui/jarvisbar/host.py
@@ -21,8 +21,13 @@ Protocol (UTF-8, one JSON object per line):
exits, so no ownerless bar can linger on the user's desktop.
- child → parent (stdout): events — ``{"event": "ready"}`` once the surface
is initialized, plus user interactions (``talk``, ``hangup``,
- ``mute_toggle``, ``feedback``, ``show_window``). Logging goes to stderr so
- stdout stays pure protocol.
+ ``mute_toggle``, ``feedback``, ``show_window``, ``drop``). Logging goes to
+ stderr so stdout stays pure protocol.
+
+``drop`` is the one round trip: the child forwards a file/text dropped on the
+hosted surface, the parent runs the intake (the brain lives there), and the
+verdict comes back down as the ``drop_result`` command so the surface can
+confirm it visually.
The host works on every OS (the parent simply only uses it where in-process
hosting is impossible). ``JARVIS_BAR_HOST_FAKE=1`` swaps the Tk bar for an
@@ -128,6 +133,11 @@ def dispatch(surface: Any, msg: dict[str, Any]) -> bool:
_call(surface, "start_mouth_animation", int(msg.get("duration_ms", 60000)))
elif op == "stop_mouth_animation":
_call(surface, "stop_mouth_animation")
+ elif op == "drop_result":
+ # The return leg of a drop this host forwarded: the parent ran the
+ # intake and says whether the content became context, so the surface
+ # can confirm it visually.
+ _call(surface, "notify_drop_result", bool(msg.get("accepted", False)))
elif op == "reset_position":
# The double-click reset seam.
_call(surface, "_on_reset_double_click")
@@ -363,6 +373,27 @@ def _wire_surface_events(surface: Any) -> None:
lambda kind, payload: emit("feedback", kind=kind, payload=payload),
)
_call(surface, "set_on_show_window", lambda: emit("show_window"))
+ _wire_drop_forwarding()
+
+
+def _wire_drop_forwarding() -> None:
+ """Forward drops onto the hosted surface to the parent process.
+
+ Both hosted surfaces (the Qt bar, the mascot) deliver a drop by calling
+ ``drop_bridge.dispatch_drop`` — but the real handler is registered in the
+ PARENT, where the brain lives. Without this the child's bridge has no
+ handler at all, so on macOS a file dropped on the bar was accepted by the
+ window, reported "copy" to the OS, and then silently discarded: the drop
+ never reached the conversation. Installing the child-side handler makes the
+ forward explicit; ``SubprocessBarOverlay`` re-dispatches it parent-side and
+ sends the verdict back as a ``drop_result`` command.
+ """
+ try:
+ from jarvis.overlay.drop_bridge import set_drop_handler
+
+ set_drop_handler(lambda paths, text: emit("drop", paths=list(paths), text=str(text)))
+ except Exception: # noqa: BLE001 — drop is optional; never block the host
+ log.debug("bar-host drop forwarding unavailable", exc_info=True)
def main() -> int:
diff --git a/jarvis/ui/jarvisbar/overlay.py b/jarvis/ui/jarvisbar/overlay.py
index 34156eb0f9..35700b6320 100644
--- a/jarvis/ui/jarvisbar/overlay.py
+++ b/jarvis/ui/jarvisbar/overlay.py
@@ -46,6 +46,12 @@ _WARNED_NO_APPKIT = False
COLOR_KEY_HEX = "#FF00FF"
DRAG_THRESHOLD_PX = 16
MARGIN_PX = 12
+# How long after a file drop the bar keeps ignoring clicks. The synthetic
+# press/release a drop produces on this window arrives around the drop event,
+# not reliably before it, so the guard has to outlive the drop itself. Short
+# enough that a user who drops a file and then deliberately clicks the bar is
+# not left wondering why nothing happened.
+DROP_CLICK_QUIET_S = 0.6
# Gap above the taskbar (~0.2 cm) when anchoring at the default bottom-center.
TASKBAR_GAP_PX = 8
# Window opacity (the pill goes semi-transparent; magenta stays fully keyed
@@ -399,7 +405,7 @@ class JarvisBarOverlay:
# _schedule_frame): tracks how many consecutive ticks have shared the
# same (effective_mode, hovered, muted) key, so a settled idle pill's
# repaint can be skipped once its eased size has stopped moving.
- self._static_tick_key: tuple[str, bool, bool] | None = None
+ self._static_tick_key: tuple[str, bool, bool, str] | None = None
self._static_tick_count = 0
self._root: Any = None
self._canvas: Any = None
@@ -414,6 +420,18 @@ class JarvisBarOverlay:
self._x = 0
self._y = 0
self._drag: dict | None = None
+ # Set while a file drag hovers the bar, plus a short tail after it lands
+ # — see ``_set_drop_active``. Both are plain attributes read from the Tk
+ # thread only, so no lock is involved.
+ self._drop_active = False
+ self._drop_quiet_until = 0.0
+ # What the bar SHOWS about a drop (renderer.DROP_STATE_*), and the
+ # perf_counter() the current verdict started at. Distinct from
+ # ``_drop_active`` on purpose: that one governs click suppression and
+ # ends the moment the payload lands, while the visible confirmation has
+ # to outlive it by design. Tk thread only.
+ self._drop_visual = renderer.DROP_STATE_NONE
+ self._drop_visual_t0 = 0.0
# Multi-monitor follow: when on, the bar migrates to the monitor under
# the mouse. ``_rel_pos`` is the monitor-independent free-space fraction
# (the persisted placement truth); ``_cur_work`` is the work area the
@@ -748,23 +766,38 @@ class JarvisBarOverlay:
self._canvas.bind("<Leave>", self._on_leave)
# Drag-drop onto the bar (desktop extra, cross-platform via tkdnd).
- # TEMPORARILY DISABLED 2026-06-23 (wake-fix session): on this frameless
- # color-key topmost window, tkdnd's ``_require(root)`` + drop_target_register
- # injected PHANTOM mouse press/release events on every turn mode-switch,
- # which the click handler read as a close-X click -> a ``request_hangup``
- # STORM (6+/turn) that aborted every voice answer mid-thought (Hangup during
- # thinking). The file-drop-onto-bar feature is purely additive — the web
- # dock (POST /api/chat/drop) carries it on every OS — so disabling JUST the
- # bar registration restores voice without losing the capability. Re-enable
- # once the tkdnd phantom-event issue on the color-key window is resolved.
- if False: # noqa: SIM223 — intentional kill-switch (see note above)
- try:
- from jarvis.overlay.drop_bridge import dispatch_drop
- from jarvis.overlay.drop_target import make_drop_target
+ #
+ # This was disabled 2026-06-23: on a frameless color-key topmost window
+ # tkdnd's registration made the window emit SYNTHETIC press/release
+ # events on every turn mode-switch, the click handler read them as a
+ # close-X click, and a ``request_hangup`` storm (6+/turn) aborted every
+ # voice answer mid-thought. Re-enabled now that both halves of that are
+ # actually fixed rather than avoided:
+ #
+ # 1. ``_on_release`` honours a click only when the OS pointer is really
+ # over the bar (``_pointer_over_bar``), which kills every phantom
+ # pair fired under a stationary cursor.
+ # 2. That guard alone is NOT enough for a real drop — during one the
+ # pointer genuinely IS over the bar, so a synthetic pair emitted by
+ # the drop would pass it and hang up the call the user was in the
+ # middle of. Hence ``_set_drop_active``: while a drag hovers, and for
+ # a moment after it lands, the bar takes no clicks at all.
+ try:
+ from jarvis.overlay.drop_bridge import (
+ dispatch_drop,
+ set_drop_result_sink,
+ )
+ from jarvis.overlay.drop_target import make_drop_target
- make_drop_target().register(self._canvas, dispatch_drop)
- except Exception: # noqa: BLE001 — drop is optional; never block bar boot.
- log.debug("bar drop target registration skipped", exc_info=True)
+ if make_drop_target().register(
+ self._canvas, dispatch_drop, self._set_drop_active
+ ):
+ # Only claim the return leg once the target actually registered
+ # — a host without tkdnd has no drops to confirm, and leaving a
+ # stale sink installed would point at a bar that never sees one.
+ set_drop_result_sink(self.notify_drop_result)
+ except Exception: # noqa: BLE001 — drop is optional; never block bar boot.
+ log.debug("bar drop target registration skipped", exc_info=True)
try:
from jarvis.audio import level_tap
@@ -788,6 +821,15 @@ class JarvisBarOverlay:
def stop(self) -> None:
self._running = False
+ # Release the drop return leg before the Tk root goes: a swap to
+ # another surface installs its own sink, and a stale one pointing at a
+ # destroyed bar would enqueue onto a dead UI queue.
+ try:
+ from jarvis.overlay.drop_bridge import set_drop_result_sink
+
+ set_drop_result_sink(None)
+ except Exception: # noqa: BLE001 — teardown must never raise
+ log.debug("drop result sink release failed", exc_info=True)
if self._level_unsub is not None:
try:
self._level_unsub()
@@ -1195,14 +1237,23 @@ class JarvisBarOverlay:
# the render/PhotoImage/itemconfig work entirely. Any change in
# mode, hover, or mute resets the counter, so a real transition
# (including a hover/mute flip) always renders immediately.
- tick_key = (effective_mode, self._hovered, self._muted)
+ # Drag-drop feedback is time-DEPENDENT (a pulsing rim, a tick that
+ # strokes itself on and fades), so it belongs in the tick key AND
+ # must veto the skip outright. Without the veto the confirmation
+ # would never be seen: an idle bar has usually been settled for
+ # long before a file arrives, so the very frames the tick lives in
+ # are exactly the ones the fast path skips.
+ drop_visual = self._current_drop_visual()
+ tick_key = (effective_mode, self._hovered, self._muted, drop_visual)
if tick_key != self._static_tick_key:
self._static_tick_key = tick_key
self._static_tick_count = 0
else:
self._static_tick_count += 1
is_settled_idle = (
- effective_mode == "idle" and self._static_tick_count >= _IDLE_SETTLE_TICKS
+ effective_mode == "idle"
+ and drop_visual == renderer.DROP_STATE_NONE
+ and self._static_tick_count >= _IDLE_SETTLE_TICKS
)
if not is_settled_idle:
@@ -1217,6 +1268,8 @@ class JarvisBarOverlay:
self._ext_level,
hovered=self._hovered,
muted=self._muted,
+ drop_state=drop_visual,
+ drop_elapsed=now - self._drop_visual_t0,
)
if getattr(self, "_mac_transparent", False):
# macOS: no color key — carry real per-pixel alpha instead.
@@ -1432,11 +1485,87 @@ class JarvisBarOverlay:
except Exception: # noqa: BLE001
log.debug("jarvisbar geometry update failed", exc_info=True)
+ def _set_drop_active(self, active: bool) -> None:
+ """A file drag is over the bar (or has just landed on it).
+
+ Called from the tkdnd callbacks. While this is armed the bar takes no
+ clicks: a drop makes the window emit a synthetic press/release with the
+ pointer genuinely over the bar, which is indistinguishable from a
+ deliberate close-X click by position alone — and reading it as one hung
+ up the user's call the moment they dropped a file.
+
+ The trailing window matters as much as the flag: the synthetic pair can
+ arrive just AFTER the drop is delivered, so clearing on the drop event
+ alone would let the very event this exists for through.
+ """
+ if active:
+ self._drop_active = True
+ self._set_drop_visual(renderer.DROP_STATE_ARMED)
+ return
+ self._drop_active = False
+ self._drop_quiet_until = time.monotonic() + DROP_CLICK_QUIET_S
+ # Leaving without dropping must not leave the rim pulsing. A verdict
+ # already on screen wins — the drop that produced it also reports
+ # ``False`` here, and clearing then would erase the confirmation the
+ # instant it appeared.
+ if self._drop_visual == renderer.DROP_STATE_ARMED:
+ self._set_drop_visual(renderer.DROP_STATE_NONE)
+
+ def _set_drop_visual(self, state: str) -> None:
+ """Switch what the bar shows about a drop and repaint promptly.
+
+ Restamps the clock on every transition so each verdict gets its full
+ animation, and invalidates the static-frame fast path so a long-settled
+ idle bar starts painting again for it.
+ """
+ self._drop_visual = state
+ self._drop_visual_t0 = time.perf_counter()
+ self._invalidate_static_frame()
+
+ def _current_drop_visual(self) -> str:
+ """The drop state to render now, expiring a finished confirmation.
+
+ The renderer is deliberately stateless about time, so somebody has to
+ retire a verdict once its animation has run out — doing it here means
+ the bar also falls back out of the fast-path veto and can settle again.
+ """
+ state = self._drop_visual
+ if state in (renderer.DROP_STATE_OK, renderer.DROP_STATE_REJECTED):
+ elapsed = time.perf_counter() - self._drop_visual_t0
+ if elapsed >= renderer.DROP_CONFIRM_TOTAL_S:
+ self._drop_visual = renderer.DROP_STATE_NONE
+ return renderer.DROP_STATE_NONE
+ return state
+
+ def notify_drop_result(self, accepted: bool) -> None:
+ """Show the verdict of a drop this bar delivered. Thread-safe.
+
+ Called from the backend loop (via ``drop_bridge.report_drop_result``),
+ so the state change is marshalled onto the Tk thread like every other
+ cross-thread mutation. ``accepted=False`` deliberately still shows
+ something: a drop that produced nothing usable is exactly the case
+ where silence would leave the user guessing.
+ """
+ state = (
+ renderer.DROP_STATE_OK if accepted else renderer.DROP_STATE_REJECTED
+ )
+ if self._root is None:
+ # Not started (or already torn down) — nothing to animate on.
+ return
+ self._enqueue_ui(lambda s=state: self._set_drop_visual(s))
+
+ def _clicks_suppressed(self) -> bool:
+ """True while a drag/drop is claiming the bar's pointer events."""
+ return self._drop_active or time.monotonic() < self._drop_quiet_until
+
def _on_release(self, event: Any) -> None:
d = self._drag
self._drag = None
if d is None:
return
+ if self._clicks_suppressed():
+ log.debug("jarvisbar: ignoring click (a file drop is in flight)")
+ return
if interaction.classify_release(moved=bool(d["moved"])) == "click":
# Phantom-click guard (root cause of the request_hangup STORM): a
# frameless color-key topmost Tk window emits SYNTHETIC press/release
diff --git a/jarvis/ui/jarvisbar/qt_overlay.py b/jarvis/ui/jarvisbar/qt_overlay.py
index 24cca88eb7..21b23cdb32 100644
--- a/jarvis/ui/jarvisbar/qt_overlay.py
+++ b/jarvis/ui/jarvisbar/qt_overlay.py
@@ -51,6 +51,11 @@ DRAG_THRESHOLD_PX = 16
MARGIN_PX = 12
TASKBAR_GAP_PX = 8
HANGUP_CLICK_GUARD_S = 1.0
+# How long after a file drop the bar keeps ignoring clicks. Mirrors the Tk bar's
+# value for the same reason it exists there: a drop and a deliberate click on
+# the close-X are both "pointer down on the bar", and reading the first as the
+# second hangs up the call the user was in the middle of.
+DROP_CLICK_QUIET_S = 0.6
_IDLE_SETTLE_TICKS = 30
# Cursor-monitor follow poll (ms). When enabled, the bar hops to whichever
@@ -324,6 +329,36 @@ def _window_class() -> type:
self.setMouseTracking(True)
self.setFixedSize(renderer.WIN_W, renderer.WIN_H)
self.setWindowOpacity(owner._opacity)
+ # Drag-drop onto the bar. The Tk bar gets this from tkdnd; on macOS
+ # this window IS the bar, so without these four handlers dropping a
+ # file on it did nothing at all while the same gesture worked on
+ # Windows and Linux — an OS-parity gap, not a missing extra.
+ self.setAcceptDrops(True)
+
+ # ------------------------------------------------------------------ #
+ # Drag-drop (parity with the Tk bar's tkdnd path) #
+ # ------------------------------------------------------------------ #
+ def dragEnterEvent(self, event: Any) -> None: # noqa: N802 - Qt override
+ if self._owner._drag_carries_drop(event.mimeData()):
+ self._owner._set_drop_active(True)
+ event.acceptProposedAction()
+ return
+ event.ignore()
+
+ def dragMoveEvent(self, event: Any) -> None: # noqa: N802 - Qt override
+ if self._owner._drag_carries_drop(event.mimeData()):
+ event.acceptProposedAction()
+ return
+ event.ignore()
+
+ def dragLeaveEvent(self, event: Any) -> None: # noqa: N802 - Qt override
+ self._owner._set_drop_active(False)
+ event.accept()
+
+ def dropEvent(self, event: Any) -> None: # noqa: N802 - Qt override
+ self._owner._set_drop_active(False)
+ self._owner._deliver_drop_ui(event.mimeData())
+ event.acceptProposedAction()
def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt override
del event
@@ -398,7 +433,7 @@ class QtJarvisBarOverlay:
self._last_audible_t = 0.0
self._muted = False
self._hovered = False
- self._static_tick_key: tuple[str, bool, bool] | None = None
+ self._static_tick_key: tuple[str, bool, bool, str] | None = None
self._static_tick_count = 0
self._hangup_click_block_until = 0.0
@@ -440,6 +475,16 @@ class QtJarvisBarOverlay:
self._rel_pos: tuple[float, float] | None = None
self._cur_work: GeometryBounds | None = None
self._drag: dict[str, Any] | None = None
+ # Set while a file drag hovers the bar, plus a short tail after it lands
+ # — see ``_set_drop_active``. Qt UI thread only, so no lock is involved.
+ self._drop_active = False
+ self._drop_quiet_until = 0.0
+ # What the bar SHOWS about a drop (renderer.DROP_STATE_*) and when the
+ # current verdict started. Separate from ``_drop_active``, which governs
+ # click suppression and ends when the payload lands — the visible
+ # confirmation has to outlive it. Qt UI thread only.
+ self._drop_visual = renderer.DROP_STATE_NONE
+ self._drop_visual_t0 = 0.0
self._on_mute_toggle: Callable[[], None] | None = None
self._feedback_publisher: Callable[[str, dict], None] | None = None
@@ -695,14 +740,21 @@ class QtJarvisBarOverlay:
# here, so recent real level samples are the truthful signal.
playback_active=False,
)
- tick_key = (effective_mode, self._hovered, self._muted)
+ # Drag-drop feedback animates (pulsing rim, a tick that strokes on
+ # and fades), so it joins the tick key AND vetoes the idle skip.
+ # Without the veto the confirmation is never seen: a settled idle
+ # bar skips exactly the frames the tick would live in.
+ drop_visual = self._current_drop_visual()
+ tick_key = (effective_mode, self._hovered, self._muted, drop_visual)
if tick_key != self._static_tick_key:
self._static_tick_key = tick_key
self._static_tick_count = 0
else:
self._static_tick_count += 1
settled_idle = (
- effective_mode == "idle" and self._static_tick_count >= _IDLE_SETTLE_TICKS
+ effective_mode == "idle"
+ and drop_visual == renderer.DROP_STATE_NONE
+ and self._static_tick_count >= _IDLE_SETTLE_TICKS
)
if settled_idle:
return
@@ -713,6 +765,8 @@ class QtJarvisBarOverlay:
self._ext_level,
hovered=self._hovered,
muted=self._muted,
+ drop_state=drop_visual,
+ drop_elapsed=now - self._drop_visual_t0,
)
rgba_frame = renderer.key_to_alpha(pil_frame)
input_mask_key = rgba_frame.getchannel("A").tobytes()
@@ -1276,9 +1330,105 @@ class QtJarvisBarOverlay:
self._persist_position_ui()
return True
+ # ---------------------------------------------------------------- #
+ # Drag-drop onto the bar (parity with the Tk bar's tkdnd path) #
+ # ---------------------------------------------------------------- #
+ def _drag_carries_drop(self, mime: Any) -> bool:
+ """True when this drag holds something the bar can actually take.
+
+ Files first, then text. A drag carrying neither is refused outright so
+ the cursor says "no drop" instead of promising something the bar would
+ then silently discard.
+ """
+ try:
+ return bool(mime is not None and (mime.hasUrls() or mime.hasText()))
+ except Exception: # noqa: BLE001 — a malformed drag is simply not ours
+ return False
+
+ def _set_drop_active(self, active: bool) -> None:
+ """A file drag is over the bar, or has just landed on it.
+
+ Arms the same click stand-down the Tk bar uses: during a drop the
+ pointer genuinely IS on the bar, so position alone cannot separate the
+ drop from a deliberate close-X click, and the trailing quiet window
+ covers a release delivered just after the drop.
+ """
+ if active:
+ self._drop_active = True
+ self._set_drop_visual_ui(renderer.DROP_STATE_ARMED)
+ return
+ self._drop_active = False
+ self._drop_quiet_until = time.monotonic() + DROP_CLICK_QUIET_S
+ # A drag that leaves without landing must stop the rim pulsing; a
+ # verdict already on screen wins (the landing drop reports False here
+ # too, and clearing then would erase the confirmation immediately).
+ if self._drop_visual == renderer.DROP_STATE_ARMED:
+ self._set_drop_visual_ui(renderer.DROP_STATE_NONE)
+
+ def _set_drop_visual_ui(self, state: str) -> None:
+ """Switch the visible drop state and repaint promptly (Qt UI thread)."""
+ self._drop_visual = state
+ self._drop_visual_t0 = time.perf_counter()
+ self._invalidate_static_frame()
+
+ def _current_drop_visual(self) -> str:
+ """The drop state to render now, expiring a finished confirmation.
+
+ The renderer holds no clock of its own, so the surface retires a
+ verdict once its animation has run out — which also releases the
+ fast-path veto and lets a resting bar settle again.
+ """
+ state = self._drop_visual
+ if state in (renderer.DROP_STATE_OK, renderer.DROP_STATE_REJECTED):
+ if time.perf_counter() - self._drop_visual_t0 >= renderer.DROP_CONFIRM_TOTAL_S:
+ self._drop_visual = renderer.DROP_STATE_NONE
+ return renderer.DROP_STATE_NONE
+ return state
+
+ def notify_drop_result(self, accepted: bool) -> None:
+ """Show the verdict of a drop this bar delivered. Thread-safe.
+
+ On macOS the verdict travels from the parent process over the host
+ protocol, so this is reached from the stdin reader thread and marshals
+ onto the Qt UI thread like every other cross-thread mutation.
+ """
+ state = (
+ renderer.DROP_STATE_OK if accepted else renderer.DROP_STATE_REJECTED
+ )
+ self._enqueue_if_started(lambda s=state: self._set_drop_visual_ui(s))
+
+ def _deliver_drop_ui(self, mime: Any) -> None:
+ """Hand a dropped payload to the process-global drop bridge.
+
+ Runs on the Qt UI thread and must never raise out of an event handler:
+ an exception here would take the overlay's event loop with it.
+ """
+ try:
+ paths: list[str] = []
+ if mime is not None and mime.hasUrls():
+ for url in mime.urls():
+ local = url.toLocalFile()
+ if local:
+ paths.append(local)
+ text = ""
+ if not paths and mime is not None and mime.hasText():
+ text = (mime.text() or "").strip()
+ if not paths and not text:
+ return
+
+ from jarvis.overlay.drop_bridge import dispatch_drop
+
+ log.info("Qt bar DROP received: %d file(s), text=%s", len(paths), bool(text))
+ dispatch_drop(paths, text)
+ except Exception: # noqa: BLE001 — a drop must never wedge the Qt loop
+ log.debug("Qt bar drop handling failed", exc_info=True)
+
def _dispatch_click_ui(self, click_x: float, *, hovered: bool | None = None) -> str:
if time.monotonic() < self._hangup_click_block_until:
return "none"
+ if self._drop_active or time.monotonic() < self._drop_quiet_until:
+ log.debug("Qt bar: ignoring click (a file drop is in flight)")
+ return "none"
is_hovered = self._hovered if hovered is None else bool(hovered)
active = self._mode in ("listen", "think", "speak")
action = interaction.resolve_click(
diff --git a/jarvis/ui/jarvisbar/renderer.py b/jarvis/ui/jarvisbar/renderer.py
index 577a37ded3..dd3a8be1b8 100644
--- a/jarvis/ui/jarvisbar/renderer.py
+++ b/jarvis/ui/jarvisbar/renderer.py
@@ -51,6 +51,123 @@ CLOSE_X = (228, 110, 96)
# at a glance they are muted (the pill border turns this colour whenever the
# voice mic is muted FOR JARVIS, even at rest). Tune freely — purely cosmetic.
MUTED_RED = (220, 80, 72)
+# Drop confirmation tick: a calm green that reads as "landed" against the dark
+# pill without competing with the gold activity accent.
+DROP_OK_GREEN = (126, 200, 133)
+
+# --- drag-drop feedback on the bar -------------------------------------------
+# Dropping a file onto the bar used to give NOTHING back: the window went from
+# 60% to 100% opacity while the drag hovered, and after the release there was
+# no signal at all — so a user could not tell an accepted drop from one the bar
+# silently discarded. These four states drive the visible answer, and every
+# dimension below is a FRACTION of the live pill size, so the feedback scales
+# with the monitor's DPI and the user's "Bar size" slider exactly like the mic
+# glyph does. Nothing here is measured in fixed pixels.
+DROP_STATE_NONE = "none"
+DROP_STATE_ARMED = "armed" # a droppable payload hovers the bar
+DROP_STATE_OK = "ok" # it landed and became context
+DROP_STATE_REJECTED = "rejected" # nothing usable was in it
+DROP_STATES = (
+ DROP_STATE_NONE, DROP_STATE_ARMED, DROP_STATE_OK, DROP_STATE_REJECTED
+)
+
+# Confirmation timeline (seconds): the glyph strokes itself on, holds long
+# enough to be read without a second glance, then fades. Total is deliberately
+# short — this is an acknowledgement, not a notification the user must dismiss.
+DROP_CONFIRM_DRAW_S = 0.24
+DROP_CONFIRM_HOLD_S = 0.80
+DROP_CONFIRM_FADE_S = 0.36
+DROP_CONFIRM_TOTAL_S = DROP_CONFIRM_DRAW_S + DROP_CONFIRM_HOLD_S + DROP_CONFIRM_FADE_S
+# Rim pulse while a payload hovers: the drop zone is small and frameless, so
+# the rim breathing brightly is what tells the user WHERE to let go.
+DROP_ARM_PULSE_RAD_S = 5.0
+
+# Glyph geometry, all relative to the live pill height.
+_DROP_GLYPH_W = 0.13 # stroke thickness / pill height
+# The tick's three corner points (x, y) as pill-height fractions from centre.
+_DROP_TICK_POINTS = ((-0.34, 0.02), (-0.11, 0.24), (0.38, -0.26))
+_DROP_CROSS_R = 0.24 # half-diagonal of the "nothing usable" cross / pill height
+
+
+def drop_confirm_phase(elapsed_s: float) -> tuple[float, float]:
+ """``(stroke_fraction, alpha)`` of the post-drop glyph at ``elapsed_s``.
+
+ ``stroke_fraction`` runs 0 → 1 while the glyph draws itself on, then stays
+ at 1. ``alpha`` is 1 until the hold expires and eases to 0 over the fade.
+ Past ``DROP_CONFIRM_TOTAL_S`` both are 0, which is the surface's signal to
+ drop the confirmation state and let the bar settle back to normal.
+
+ Pure and monotonic in ``elapsed_s`` so the whole animation is unit-testable
+ without a display.
+ """
+ if elapsed_s < 0.0:
+ return (0.0, 0.0)
+ if elapsed_s < DROP_CONFIRM_DRAW_S:
+ # Ease-out so the stroke lands softly instead of snapping to its end.
+ u = elapsed_s / DROP_CONFIRM_DRAW_S
+ return (1.0 - (1.0 - u) ** 2, 1.0)
+ if elapsed_s < DROP_CONFIRM_DRAW_S + DROP_CONFIRM_HOLD_S:
+ return (1.0, 1.0)
+ if elapsed_s < DROP_CONFIRM_TOTAL_S:
+ held = elapsed_s - DROP_CONFIRM_DRAW_S - DROP_CONFIRM_HOLD_S
+ return (1.0, max(0.0, 1.0 - held / DROP_CONFIRM_FADE_S))
+ return (0.0, 0.0)
+
+
+def tick_polyline(
+ cx: float, cy: float, ph: float, fraction: float
+) -> list[tuple[float, float]]:
+ """The confirmation tick's points, revealed up to ``fraction`` of its length.
+
+ Returns absolute coordinates around ``(cx, cy)``, sized from the LIVE pill
+ height ``ph`` — so the tick is the same shape on a 4K monitor, a laptop
+ screen, and at any "Bar size" setting. ``fraction <= 0`` yields fewer than
+ two points (nothing to draw yet); ``fraction >= 1`` yields the whole tick.
+ """
+ pts = [(cx + dx * ph, cy + dy * ph) for dx, dy in _DROP_TICK_POINTS]
+ if fraction >= 1.0:
+ return pts
+ if fraction <= 0.0:
+ return pts[:1]
+ segments = [
+ math.dist(pts[i], pts[i + 1]) for i in range(len(pts) - 1)
+ ]
+ total = sum(segments)
+ if total <= 0.0:
+ return pts[:1]
+ remaining = total * fraction
+ out = [pts[0]]
+ for i, seg in enumerate(segments):
+ if remaining >= seg:
+ out.append(pts[i + 1])
+ remaining -= seg
+ continue
+ u = remaining / seg if seg > 0 else 0.0
+ x0, y0 = pts[i]
+ x1, y1 = pts[i + 1]
+ out.append((x0 + (x1 - x0) * u, y0 + (y1 - y0) * u))
+ break
+ return out
+
+
+def drop_rim_color(
+ t: float, base: tuple[int, int, int], state: str
+) -> tuple[int, int, int]:
+ """Pill rim colour for the current drop state (pure).
+
+ ``armed`` breathes the rim toward white so the small frameless drop zone
+ announces itself; ``ok`` / ``rejected`` hold the verdict colour for as long
+ as the glyph is up; ``none`` returns ``base`` untouched, which keeps every
+ non-drop frame byte-identical to before this feature existed.
+ """
+ if state == DROP_STATE_ARMED:
+ pulse = 0.5 + 0.5 * math.sin(t * DROP_ARM_PULSE_RAD_S)
+ return _lerp_rgb(base, (255, 255, 255), 0.25 + 0.45 * pulse)
+ if state == DROP_STATE_OK:
+ return DROP_OK_GREEN
+ if state == DROP_STATE_REJECTED:
+ return MUTED_RED
+ return base
# Size factors. ``_SCALE`` is the overall shrink (1.0 was the original, far too
# big). ``_W`` / ``_H`` then stretch width / height independently on top of it:
@@ -327,7 +444,9 @@ def evenly_spaced(cx: float, span: float, n: int) -> list[float]:
return [x0 + i * step for i in range(n)]
-def target_pill_size(mode: str, hovered: bool, muted: bool = False) -> tuple[int, int]:
+def target_pill_size(
+ mode: str, hovered: bool, muted: bool = False, drop_open: bool = False
+) -> tuple[int, int]:
"""Pick the pill's target (w, h): ACTIVE while a session is live, OPEN on
hover (to show controls), COLLAPSED at rest. Only a live session is 2x —
matching 'bigger only while in the conversation'.
@@ -336,10 +455,17 @@ def target_pill_size(mode: str, hovered: bool, muted: bool = False) -> tuple[int
pill (where the red rim is a hairline and the mic glyph is hidden), the
muted bar stays at the OPEN size so the slashed-mic + red rim stay visible.
A muted user is otherwise trapped — they can't unmute by voice (Jarvis is
- deaf while muted), so the click target must always be on screen."""
+ deaf while muted), so the click target must always be on screen.
+
+ ``drop_open`` opens the pill for the same reason during a drag-drop: the
+ resting pill is ~37x6 px on a 1440p monitor (and ~22x4 at the smallest "Bar
+ size"), which is both a punishing target to release a file on and far too
+ small to render a legible tick in. Opening on the first drag-enter turns
+ the sliver into a real landing zone and gives the confirmation room to
+ show."""
if mode in ("listen", "speak", "think"):
return ACTIVE_W, ACTIVE_H
- if hovered or muted:
+ if hovered or muted or drop_open:
return OPEN_W, OPEN_H
return COLLAPSED_W, COLLAPSED_H
@@ -604,12 +730,28 @@ class JarvisBarRenderer:
ext_level: float,
hovered: bool = False,
muted: bool = False,
+ drop_state: str = DROP_STATE_NONE,
+ drop_elapsed: float = 0.0,
) -> Image.Image:
active = mode in ("listen", "speak")
+ # Drag-drop feedback. ``drop_state`` is what the surface currently sees
+ # (a hovering payload, or the verdict of one that landed) and
+ # ``drop_elapsed`` how long the verdict has been up; the glyph's own
+ # timeline lives in the pure ``drop_confirm_phase``.
+ confirming = drop_state in (DROP_STATE_OK, DROP_STATE_REJECTED)
+ tick_frac, tick_alpha = (
+ drop_confirm_phase(drop_elapsed) if confirming else (0.0, 0.0)
+ )
+ # A finished confirmation is treated as no drop at all, so a surface
+ # that is slow to clear the state can never pin the pill open.
+ if confirming and tick_alpha <= 0.0:
+ drop_state, confirming = DROP_STATE_NONE, False
+ drop_open = drop_state != DROP_STATE_NONE
# Ease the pill toward its target size: ACTIVE (2x) while a session is
- # live, OPEN on hover (controls) OR while muted (keep the mute cue +
- # unmute target visible), COLLAPSED at rest.
- tw, th = target_pill_size(mode, hovered, muted)
+ # live, OPEN on hover (controls), while muted (keep the mute cue +
+ # unmute target visible) OR during a drop (landing zone + tick room),
+ # COLLAPSED at rest.
+ tw, th = target_pill_size(mode, hovered, muted, drop_open)
# Snappy grow/shrink: 0.5 reaches the target in ~4 frames (~70 ms) so the
# bar pops to full size almost immediately on "Hey Jarvis" instead of
# crawling there over a third of a second.
@@ -636,8 +778,12 @@ class JarvisBarRenderer:
cy = pill_center_y(ph) # bottom-anchored: grows upward, idle stays put
# The rim turns red whenever the mic is muted FOR JARVIS — drawn on
# EVERY frame (even idle/standby, no hover) so the muted cue is visible
- # at a glance without having to reveal the controls.
+ # at a glance without having to reveal the controls. A drop in flight
+ # takes the rim over for its duration: it is the one cue visible from
+ # the corner of the eye while the user's attention is on the file they
+ # are dragging.
outline_color = MUTED_RED if muted else PILL_BORDER
+ outline_color = drop_rim_color(t, outline_color, drop_state)
d.rounded_rectangle(
[cx - pw / 2, cy - ph / 2, cx + pw / 2, cy + ph / 2],
radius=ph / 2,
@@ -649,7 +795,20 @@ class JarvisBarRenderer:
# Hover splits the bar into controls: LEFT X (hang up, only while a
# session is live) + RIGHT mic (toggle voice mute for Jarvis).
x_right = cx + 0.33 * pw # pulled in so the mic glyph never clips the rim
- if hovered:
+ if confirming:
+ # The verdict owns the pill alone. Equalizer bars or the orbital
+ # core behind a tick would be mush at this pill height — and the
+ # whole point of the glyph is that it reads in one glance.
+ self._draw_drop_glyph(
+ img,
+ cx,
+ cy,
+ ph,
+ fraction=tick_frac,
+ alpha=tick_alpha,
+ ok=drop_state == DROP_STATE_OK,
+ )
+ elif hovered:
x_left = cx - 0.42 * pw
active_sess = mode in ("listen", "speak", "think")
# Keep the speech indicator VISIBLE while interacting — narrow bars
@@ -747,6 +906,61 @@ class JarvisBarRenderer:
small = layer.resize(img.size, Image.Resampling.LANCZOS)
img.paste(small, (0, 0), small)
+ def _draw_drop_glyph(
+ self,
+ img: Image.Image,
+ cx: float,
+ cy: float,
+ ph: float,
+ *,
+ fraction: float,
+ alpha: float,
+ ok: bool,
+ ) -> None:
+ """The post-drop verdict: a tick that lands, or a cross that says no.
+
+ Supersampled (4x → LANCZOS) like the mic glyph — the pill is ~16 px
+ tall at the signed-off size, where a 2 px stroke drawn directly turns
+ into a staircase. Every dimension derives from ``ph`` (the LIVE, eased
+ pill height), so the glyph tracks the monitor's DPI, the user's "Bar
+ size" slider and the open/close easing without a single fixed pixel.
+
+ ``fraction`` reveals the tick progressively (it strokes itself on);
+ ``alpha`` fades the whole glyph out at the end of the confirmation.
+ """
+ if alpha <= 0.0:
+ return
+ ss = 4
+ layer = Image.new("RGBA", (img.width * ss, img.height * ss), (0, 0, 0, 0))
+ ld = ImageDraw.Draw(layer)
+ a = max(0, min(255, round(255 * alpha)))
+ color = (*(DROP_OK_GREEN if ok else MUTED_RED), a)
+ w = max(1, round(ph * _DROP_GLYPH_W * ss))
+
+ if ok:
+ points = tick_polyline(cx, cy, ph, fraction)
+ if len(points) >= 2:
+ ld.line(
+ [(x * ss, y * ss) for x, y in points],
+ fill=color,
+ width=w,
+ joint="curve",
+ )
+ else:
+ # "Nothing usable in that" — a plain cross, drawn whole (there is
+ # no progressive reveal to sell: the answer is immediate).
+ r = ph * _DROP_CROSS_R
+ for (x0, y0), (x1, y1) in (
+ ((cx - r, cy - r), (cx + r, cy + r)),
+ ((cx - r, cy + r), (cx + r, cy - r)),
+ ):
+ ld.line(
+ [(x0 * ss, y0 * ss), (x1 * ss, y1 * ss)], fill=color, width=w
+ )
+
+ small = layer.resize(img.size, Image.Resampling.LANCZOS)
+ img.paste(small, (0, 0), small)
+
def _draw_bars(
self,
d: ImageDraw.ImageDraw,
diff --git a/jarvis/ui/jarvisbar/subprocess_overlay.py b/jarvis/ui/jarvisbar/subprocess_overlay.py
index 893b1f8b2b..9450878499 100644
--- a/jarvis/ui/jarvisbar/subprocess_overlay.py
+++ b/jarvis/ui/jarvisbar/subprocess_overlay.py
@@ -4,9 +4,12 @@
``OrbBusBridge`` drives, but renders nothing itself: it spawns
``python -m jarvis.ui.jarvisbar.host`` — whose MAIN thread may legally own
Aqua-Tk — and forwards every surface call as one JSON line on the child's
-stdin. Child events (talk, hang-up, mute toggle, feedback, show-window) stream
-back on stdout. Voice actions are executed against the live parent-process
-pipeline; bridge-owned actions are dispatched to its registered callbacks.
+stdin. Child events (talk, hang-up, mute toggle, feedback, show-window, drop)
+stream back on stdout. Voice actions are executed against the live
+parent-process pipeline; bridge-owned actions are dispatched to its registered
+callbacks. A forwarded drop is replayed onto THIS process's drop bridge (the
+brain lives here, not in the host) and its verdict is sent back down so the
+hosted bar can confirm the drop on screen.
Failure contract: while the host is down, every method degrades to a one-log
no-op (``NullOverlay`` behavior) — the bar is cosmetic and must never take
@@ -176,6 +179,14 @@ class SubprocessBarOverlay:
# is this flag — it must be set even when there is no live process
# to tear down right now.
self._stopping = True
+ # Release the drop return leg: a swap to another surface installs its
+ # own sink, and a stale one would write to a host that is going away.
+ try:
+ from jarvis.overlay.drop_bridge import set_drop_result_sink
+
+ set_drop_result_sink(None)
+ except Exception: # noqa: BLE001 — teardown must never raise
+ log.debug("drop result sink release failed", exc_info=True)
proc = self._proc
if proc is None:
return
@@ -469,9 +480,39 @@ class SubprocessBarOverlay:
cb_show = self._on_show_window
if cb_show is not None:
cb_show()
+ elif event == "drop":
+ self._dispatch_drop_event(msg)
except Exception: # noqa: BLE001 — a bad callback must not kill the pump
log.exception("bar host event callback failed: %r", event)
+ def _dispatch_drop_event(self, msg: dict[str, Any]) -> None:
+ """Re-dispatch a drop the hosted bar received, here in the parent.
+
+ The child process has no brain and no asyncio loop — its bridge only
+ forwards. This process has the real handler (installed by the desktop
+ app), so the drop is replayed onto the parent-side bridge and the
+ verdict is sent back down as a ``drop_result`` command, which the host
+ turns into the bar's visible confirmation.
+ """
+ from jarvis.overlay.drop_bridge import dispatch_drop, set_drop_result_sink
+
+ paths = [str(p) for p in (msg.get("paths") or [])]
+ text = str(msg.get("text") or "")
+ # Install the return leg lazily and idempotently: it can only be
+ # answered while a host is alive, and binding it here keeps it on the
+ # instance that actually received the drop.
+ set_drop_result_sink(self._send_drop_result)
+ if not dispatch_drop(paths, text):
+ # No handler in this process either (headless embedder, or a drop
+ # that beat the desktop wiring). Say so rather than leaving the bar
+ # waiting on a confirmation that will never come.
+ log.debug("bar host drop had no parent-side handler")
+ self._send_drop_result(False)
+
+ def _send_drop_result(self, accepted: bool) -> None:
+ """Send a drop verdict down to the hosted bar (never raises)."""
+ self._send({"op": "drop_result", "accepted": bool(accepted)})
+
def _dispatch_talk_action(self) -> None:
"""Start a voice session in the parent process.
diff --git a/scripts/crossplatform/verify_drop_target.py b/scripts/crossplatform/verify_drop_target.py
index f58afd482f..faa2a61478 100644
--- a/scripts/crossplatform/verify_drop_target.py
+++ b/scripts/crossplatform/verify_drop_target.py
@@ -10,6 +10,8 @@ works at the OS level:
the live-overlay window type).
4. A ``<<Drop>>`` event runs the full chain through the process-global bridge
to the registered handler.
+ 5. The bridge's RETURN leg carries the intake's verdict back, which is what
+ the bar's visible drop confirmation is driven by.
Run in CI on a real ``macos-latest`` runner this is the autonomous macOS proof
that cannot be produced on a Windows dev box (no macOS container exists). Exits
@@ -106,7 +108,21 @@ def main() -> int:
print("FAIL: the <<Drop>> chain did not reach the handler.")
return 4
- print("OK: drag-drop works on this OS (load + parse + register + chain).")
+ # 5. the return leg — without it the bar cannot confirm a drop, which is
+ # how a silently-discarded drop stayed invisible for so long.
+ verdicts: list[bool] = []
+ db.set_drop_result_sink(verdicts.append)
+ delivered = db.report_drop_result(True)
+ db.set_drop_result_sink(None)
+ print(f"result leg -> delivered={delivered} verdicts={verdicts}")
+ if not delivered or verdicts != [True]:
+ print("FAIL: the drop verdict did not reach the overlay sink.")
+ return 5
+
+ print(
+ "OK: drag-drop works on this OS "
+ "(load + parse + register + chain + verdict)."
+ )
return 0
diff --git a/tests/unit/overlay/test_drop_drag_state.py b/tests/unit/overlay/test_drop_drag_state.py
new file mode 100644
index 0000000000..1c1415f044
--- /dev/null
+++ b/tests/unit/overlay/test_drop_drag_state.py
@@ -0,0 +1,170 @@
+"""A drop on the Jarvis Bar must not be read as a click on its close-X.
+
+This is the reason bar drop was switched off for a month. On a frameless
+color-key topmost window, tkdnd's activity makes the window emit SYNTHETIC
+press/release events; the click handler read them as a hang-up, and a
+``request_hangup`` storm aborted live voice answers.
+
+The overlay's phantom-click guard (``_pointer_over_bar``) fixed the version of
+that which fires under a stationary cursor — but NOT the one that matters for
+this feature: during a genuine drop the pointer really IS over the bar, so
+position alone cannot separate a dropped file from a deliberate close-X click.
+The drag-state signal is what closes that gap, and these pin it.
+"""
+from __future__ import annotations
+
+import sys
+import types
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
+from typing import Any
+
+import pytest
+
+from jarvis.overlay.drop_target import NullDropTarget, OnDragState, TkDnDDropTarget
+
+
+class _FakeEvent:
+ def __init__(self, data: str = "", action: str = "copy") -> None:
+ self.data = data
+ self.action = action
+
+
+class _FakeRoot:
+ def __init__(self) -> None:
+ self.alpha = 0.6
+
+ def wm_attributes(self, key: str, value: Any = None) -> Any:
+ if value is None:
+ return self.alpha
+ self.alpha = value
+ return None
+
+
+class _FakeWidget:
+ """A Tk widget stand-in that records what tkdnd bound to it."""
+
+ def __init__(self) -> None:
+ self.root = _FakeRoot()
+ self.bindings: dict[str, Any] = {}
+ self.registered: tuple = ()
+
+ def winfo_toplevel(self) -> _FakeRoot:
+ return self.root
+
+ def drop_target_register(self, *types: str) -> None:
+ self.registered = types
+
+ def dnd_bind(self, event: str, handler: Any) -> None:
+ self.bindings[event] = handler
+
+
+@contextmanager
+def _stub_tkdnd() -> Iterator[None]:
+ """Stand in for ``tkinterdnd2`` so no Tk root or tkdnd binary is needed.
+
+ The registration path is what is under test, not the Tcl extension — and a
+ real one cannot be loaded in CI or on a headless host anyway.
+ """
+ module = types.ModuleType("tkinterdnd2")
+ module.COPY = "copy" # type: ignore[attr-defined]
+ module.DND_FILES = "DND_Files" # type: ignore[attr-defined]
+ module.DND_TEXT = "DND_Text" # type: ignore[attr-defined]
+ module.TkinterDnD = types.SimpleNamespace(_require=lambda _root: None) # type: ignore[attr-defined]
+ saved = sys.modules.get("tkinterdnd2")
+ sys.modules["tkinterdnd2"] = module
+ try:
+ yield
+ finally:
+ if saved is None:
+ sys.modules.pop("tkinterdnd2", None)
+ else:
+ sys.modules["tkinterdnd2"] = saved
+
+
+def _register(
+ widget: _FakeWidget,
+ on_drag_state: OnDragState | None,
+ on_drop: Callable[[list[str], str], None] | None = None,
+) -> bool:
+ with _stub_tkdnd():
+ return TkDnDDropTarget().register(
+ widget, on_drop or (lambda _p, _t: None), on_drag_state
+ )
+
+
+def widget() -> _FakeWidget:
+ return _FakeWidget()
+
+
+def test_a_drag_entering_the_bar_reports_active(widget: _FakeWidget) -> None:
+ states: list[bool] = []
+
+ assert _register(widget, states.append) is True
+ widget.bindings["<<DropEnter>>"](_FakeEvent())
+
+ assert states == [True]
+
+
+def test_a_drag_leaving_without_dropping_stands_the_bar_back_up(
+ widget: _FakeWidget,
+) -> None:
+ states: list[bool] = []
+ _register(widget, states.append)
+
+ widget.bindings["<<DropEnter>>"](_FakeEvent())
+ widget.bindings["<<DropLeave>>"](_FakeEvent())
+
+ assert states == [True, False]
+
+
+def test_the_drop_reports_inactive_before_the_payload_is_handled(
+ widget: _FakeWidget,
+) -> None:
+ """Ordering is load-bearing.
+
+ The synthetic press/release arrives around the drop, so the surface has to
+ be stood down BEFORE the drop callback runs, not after it.
+ """
+ order: list[str] = []
+ handled: list[tuple] = []
+
+ _register(
+ widget,
+ lambda active: order.append(f"state:{active}"),
+ lambda paths, text: (order.append("drop"), handled.append((paths, text))) and None,
+ )
+
+ widget.bindings["<<DropEnter>>"](_FakeEvent())
+ widget.bindings["<<Drop>>"](_FakeEvent(data="some dragged text"))
+
+ assert order == ["state:True", "state:False", "drop"]
+ assert handled == [([], "some dragged text")]
+
+
+def test_a_broken_drag_state_callback_never_breaks_the_drop(
+ widget: _FakeWidget,
+) -> None:
+ handled: list[tuple] = []
+
+ def _boom(_active: bool) -> None:
+ raise RuntimeError("surface is mid-teardown")
+
+ _register(widget, _boom, lambda paths, text: handled.append((paths, text)))
+ widget.bindings["<<Drop>>"](_FakeEvent(data="text"))
+
+ assert handled == [([], "text")]
+
+
+def test_the_drag_state_callback_is_optional(widget: _FakeWidget) -> None:
+ """The mascot passes none — its click handling has no close-X to protect."""
+ assert _register(widget, None) is True
+ widget.bindings["<<DropEnter>>"](_FakeEvent()) # must not raise
+
+
+def test_the_null_target_accepts_the_same_call_shape() -> None:
+ # A host without tkdnd must not blow up on the extra argument — that would
+ # turn a graceful no-op into a boot failure on exactly the hosts §3 cares
+ # about.
+ assert NullDropTarget().register(object(), lambda _p, _t: None, lambda _a: None) is False
diff --git a/tests/unit/overlay/test_drop_result_feedback.py b/tests/unit/overlay/test_drop_result_feedback.py
new file mode 100644
index 0000000000..db2fb38060
--- /dev/null
+++ b/tests/unit/overlay/test_drop_result_feedback.py
@@ -0,0 +1,155 @@
+"""The bar must tell the user what became of the file they dropped on it.
+
+A drop travels one way — surface → bridge → backend — and the intake that
+decides whether the content became context runs later, on the asyncio loop. So
+without a return leg the bar had nothing to confirm with and stayed silent
+after every drop, accepted or not. These pin the return leg itself and the two
+ways it used to be defeated: a settled idle bar that had stopped painting, and
+a verdict that never expired.
+"""
+from __future__ import annotations
+
+import time
+from typing import Any
+
+import pytest
+
+from jarvis.overlay import drop_bridge
+from jarvis.ui.jarvisbar import renderer
+from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
+
+
[email protected](autouse=True)
+def _clean_bridge() -> Any:
+ """Never leak a process-global handler or sink across tests."""
+ drop_bridge.set_drop_handler(None)
+ drop_bridge.set_drop_result_sink(None)
+ yield
+ drop_bridge.set_drop_handler(None)
+ drop_bridge.set_drop_result_sink(None)
+
+
+# --------------------------------------------------------------------- #
+# The return leg #
+# --------------------------------------------------------------------- #
+def test_a_verdict_reaches_the_registered_sink() -> None:
+ seen: list[bool] = []
+ drop_bridge.set_drop_result_sink(seen.append)
+
+ assert drop_bridge.report_drop_result(True) is True
+ assert drop_bridge.report_drop_result(False) is True
+ assert seen == [True, False]
+
+
+def test_reporting_without_a_sink_is_a_quiet_no_op() -> None:
+ """Headless, or a bar that never registered a drop target."""
+ assert drop_bridge.report_drop_result(True) is False
+
+
+def test_a_broken_sink_never_propagates_into_the_backend_turn() -> None:
+ def _boom(_accepted: bool) -> None:
+ raise RuntimeError("bar is mid-teardown")
+
+ drop_bridge.set_drop_result_sink(_boom)
+
+ # Still reports as delivered — a cosmetic animation failing must not make
+ # the intake that produced it look failed.
+ assert drop_bridge.report_drop_result(True) is True
+
+
+# --------------------------------------------------------------------- #
+# The bar's own drop state machine #
+# --------------------------------------------------------------------- #
+def _bar() -> JarvisBarOverlay:
+ """An unstarted bar: the drop state machine is plain attributes, so it is
+ exercisable without a Tk root or a display."""
+ return JarvisBarOverlay()
+
+
+def test_a_hovering_payload_arms_the_bar() -> None:
+ bar = _bar()
+ bar._set_drop_active(True)
+
+ assert bar._current_drop_visual() == renderer.DROP_STATE_ARMED
+
+
+def test_a_drag_that_leaves_without_landing_disarms_the_bar() -> None:
+ bar = _bar()
+ bar._set_drop_active(True)
+ bar._set_drop_active(False)
+
+ assert bar._current_drop_visual() == renderer.DROP_STATE_NONE
+
+
+def test_the_landing_drop_does_not_erase_its_own_confirmation() -> None:
+ """Ordering trap: the drop reports drag-state False, and the verdict can
+ arrive before that callback runs. Clearing on it unconditionally would wipe
+ the confirmation the instant it appeared."""
+ bar = _bar()
+ bar._set_drop_active(True)
+ bar._set_drop_visual(renderer.DROP_STATE_OK) # verdict lands first
+ bar._set_drop_active(False) # ...then the drag stands down
+
+ assert bar._current_drop_visual() == renderer.DROP_STATE_OK
+
+
+def test_a_finished_confirmation_expires_on_its_own() -> None:
+ bar = _bar()
+ bar._set_drop_visual(renderer.DROP_STATE_OK)
+ # Backdate the start so the whole timeline has elapsed.
+ bar._drop_visual_t0 = time.perf_counter() - renderer.DROP_CONFIRM_TOTAL_S - 0.1
+
+ assert bar._current_drop_visual() == renderer.DROP_STATE_NONE
+
+
+def test_a_rejected_drop_is_shown_rather_than_swallowed() -> None:
+ """Nothing usable in the payload is still an answer the user needs."""
+ bar = _bar()
+ bar._set_drop_visual(renderer.DROP_STATE_REJECTED)
+
+ assert bar._current_drop_visual() == renderer.DROP_STATE_REJECTED
+
+
+# --------------------------------------------------------------------- #
+# The idle-repaint trap #
+# --------------------------------------------------------------------- #
+def test_a_drop_state_change_wakes_a_settled_bar() -> None:
+ """THE defect this feature would otherwise have shipped with.
+
+ The bar stops repainting after ~30 static idle ticks. A confirmation
+ animation lives entirely inside those skipped frames, so unless a drop
+ invalidates the fast path the tick is computed and never drawn.
+ """
+ bar = _bar()
+ bar._static_tick_key = ("idle", False, False, renderer.DROP_STATE_NONE)
+ bar._static_tick_count = 999
+
+ bar._set_drop_visual(renderer.DROP_STATE_ARMED)
+
+ assert bar._static_tick_key is None
+ assert bar._static_tick_count == 0
+
+
+def test_the_drop_state_is_part_of_the_static_frame_key() -> None:
+ """Second half of the same guard: even if the counter survived, the key
+ itself must change so the settle count restarts on every transition."""
+ bar = _bar()
+ assert bar._static_tick_key is None # 4-tuple shape, seeded by the loop
+
+ # The renderer's own contract: a frame with a drop differs from one without.
+ r = renderer.JarvisBarRenderer()
+ for _ in range(12):
+ r.render(0.0, "idle", 0.0)
+ plain = r.render(0.0, "idle", 0.0)
+ armed = r.render(0.0, "idle", 0.0, drop_state=renderer.DROP_STATE_ARMED)
+
+ assert plain.tobytes() != armed.tobytes()
+
+
+def test_notify_drop_result_on_an_unstarted_bar_is_harmless() -> None:
+ """The verdict can arrive after a surface swap or during teardown."""
+ bar = _bar()
+ bar.notify_drop_result(True) # must not raise
+
+ # Nothing was queued onto a root that does not exist.
+ assert bar._drop_visual == renderer.DROP_STATE_NONE
diff --git a/tests/unit/overlay/test_overlay_drop_to_brain.py b/tests/unit/overlay/test_overlay_drop_to_brain.py
index e9e7956001..200e6d3a07 100644
--- a/tests/unit/overlay/test_overlay_drop_to_brain.py
+++ b/tests/unit/overlay/test_overlay_drop_to_brain.py
@@ -60,31 +60,54 @@ def _manager() -> tuple[BrainManager, _RecordingDispatcher]:
def teardown_function() -> None:
drop_bridge.set_drop_handler(None)
+ drop_bridge.set_drop_result_sink(None)
-async def test_bar_drop_reaches_brain_and_next_turn_uses_it(tmp_path) -> None:
- manager, rec = _manager()
- loop = asyncio.get_running_loop()
- done = asyncio.Event()
+def _wire_desktop_app_drop(manager, loop, done: asyncio.Event) -> None:
+ """Wire the overlay drop EXACTLY as jarvis/ui/desktop_app.py does.
+
+ Including the return leg: the bar's visible confirmation is driven by the
+ verdict reported here, so a test that omitted it would prove a chain the
+ app no longer has.
+ """
- # Wire the overlay drop EXACTLY as jarvis/ui/desktop_app.py does.
def _on_overlay_drop(paths: list[str], text: str) -> None:
items = items_from_paths(paths) if paths else []
dragged = (text or "").strip() or None
if not items and dragged is None:
+ drop_bridge.report_drop_result(False)
+ done.set()
return
async def _run() -> None:
- await ingest_drop(
- brain=manager, thread_id="default", items=items, dragged_text=dragged
- )
- done.set()
+ accepted = False
+ try:
+ accepted = bool(
+ await ingest_drop(
+ brain=manager,
+ thread_id="default",
+ items=items,
+ dragged_text=dragged,
+ )
+ )
+ finally:
+ drop_bridge.report_drop_result(accepted)
+ done.set()
asyncio.run_coroutine_threadsafe(_run(), loop)
drop_bridge.set_drop_handler(_on_overlay_drop)
+
+async def test_bar_drop_reaches_brain_and_next_turn_uses_it(tmp_path) -> None:
+ manager, rec = _manager()
+ loop = asyncio.get_running_loop()
+ done = asyncio.Event()
+ verdicts: list[bool] = []
+ drop_bridge.set_drop_result_sink(verdicts.append)
+ _wire_desktop_app_drop(manager, loop, done)
+
# A real dropped file, as the bar would hand over a path.
f = tmp_path / "report.txt"
f.write_text("the bar marker is BAR_TOKEN_777, remember it")
@@ -98,7 +121,34 @@ async def test_bar_drop_reaches_brain_and_next_turn_uses_it(tmp_path) -> None:
assert rec.calls == []
assert any("BAR_TOKEN_777" in str(m.content) for m in manager._history)
+ # ...and the bar is told so, which is what raises its confirmation tick.
+ assert verdicts == [True]
+
# The user's NEXT real turn (voice or chat → generate) USES it.
await manager.generate("what is the marker?", trace_id=uuid4(), use_history=True)
hist = " ".join(str(getattr(m, "content", "")) for m in (rec.calls[0]["history"] or []))
assert "BAR_TOKEN_777" in hist
+
+
+async def test_a_drop_with_nothing_usable_tells_the_bar_so(tmp_path) -> None:
+ """Silence here is what left the user guessing whether the bar noticed.
+
+ A directory, a vanished path, an empty payload — the drop happened, it just
+ carried nothing we can hold. The bar has to say that rather than nothing.
+ """
+ manager, _rec = _manager()
+ loop = asyncio.get_running_loop()
+ done = asyncio.Event()
+ verdicts: list[bool] = []
+ drop_bridge.set_drop_result_sink(verdicts.append)
+ _wire_desktop_app_drop(manager, loop, done)
+
+ folder = tmp_path / "a-folder"
+ folder.mkdir()
+
+ assert drop_bridge.dispatch_drop([str(folder)], "") is True
+ await asyncio.wait_for(done.wait(), timeout=5)
+
+ assert verdicts == [False]
+ assert manager._history == []
diff --git a/tests/unit/ui/jarvisbar/test_frame_pacing.py b/tests/unit/ui/jarvisbar/test_frame_pacing.py
index 9ebcec2c89..3ae602005f 100644
--- a/tests/unit/ui/jarvisbar/test_frame_pacing.py
+++ b/tests/unit/ui/jarvisbar/test_frame_pacing.py
@@ -25,6 +25,7 @@ from __future__ import annotations
import pytest
+from jarvis.ui.jarvisbar import renderer
from jarvis.ui.jarvisbar.overlay import (
_IDLE_SETTLE_TICKS,
MIN_FRAME_DELAY_MS,
@@ -94,6 +95,10 @@ def _bare_bar(
bar._last_frame_ns = 0
bar._static_tick_key = None
bar._static_tick_count = 0
+ # Drag-drop feedback state. It participates in the tick key and vetoes the
+ # idle skip, so the frame loop reads it on every tick.
+ bar._drop_visual = renderer.DROP_STATE_NONE
+ bar._drop_visual_t0 = 0.0
root = _FakeRoot()
canvas = _FakeCanvas()
bar._root = root
@@ -222,6 +227,54 @@ def test_active_mode_never_skips_render():
)
+def test_a_drag_over_a_settled_idle_bar_starts_painting_again():
+ """The trap the drop confirmation would otherwise have died in.
+
+ An idle bar has almost always been settled for far longer than
+ _IDLE_SETTLE_TICKS by the time a file is dragged onto it — and the
+ confirmation (a pulsing rim, a tick that strokes on and fades) lives
+ entirely inside frames the skip would swallow. So a drop has to both change
+ the tick key and veto the skip outright.
+ """
+ renderer_obj = _CountingRenderer()
+ bar, _root, _canvas = _bare_bar(renderer_obj, mode="idle")
+
+ for _ in range(_IDLE_SETTLE_TICKS + 5):
+ bar._schedule_frame()
+ calls_while_settled = renderer_obj.calls
+
+ bar._set_drop_visual(renderer.DROP_STATE_ARMED)
+ for _ in range(10):
+ bar._schedule_frame()
+
+ assert renderer_obj.calls == calls_while_settled + 10, (
+ "a settled idle bar kept skipping frames while a file hovered it — "
+ "the drop feedback would never be drawn"
+ )
+
+
+def test_the_bar_settles_again_once_the_confirmation_has_run_out():
+ """The veto must be temporary: a permanent one would burn the DWM
+ compositing tax on every tick forever after the first drop."""
+ renderer_obj = _CountingRenderer()
+ bar, _root, _canvas = _bare_bar(renderer_obj, mode="idle")
+
+ bar._set_drop_visual(renderer.DROP_STATE_OK)
+ # Backdate the verdict so its animation has fully elapsed.
+ bar._drop_visual_t0 -= renderer.DROP_CONFIRM_TOTAL_S + 1.0
+
+ for _ in range(_IDLE_SETTLE_TICKS + 5):
+ bar._schedule_frame()
+ calls_before = renderer_obj.calls
+
+ for _ in range(10):
+ bar._schedule_frame()
+
+ assert renderer_obj.calls == calls_before, (
+ "the bar never returned to the idle fast path after a drop"
+ )
+
+
class _SlowRenderer:
"""Simulates an unusually expensive render (e.g. the measured "think"+
hovered outlier, up to ~30ms) via a monotonic-clock stub injected by the
diff --git a/tests/unit/ui/jarvisbar/test_host_drop_roundtrip.py b/tests/unit/ui/jarvisbar/test_host_drop_roundtrip.py
new file mode 100644
index 0000000000..c8a687530d
--- /dev/null
+++ b/tests/unit/ui/jarvisbar/test_host_drop_roundtrip.py
@@ -0,0 +1,158 @@
+"""On macOS the bar lives in its own process — a drop there reached nobody.
+
+The hosted surfaces deliver a drop by calling ``drop_bridge.dispatch_drop``,
+but the real handler is registered by the desktop app in the PARENT process.
+In the host child that bridge was empty, so a file dropped on the macOS bar was
+accepted by the window (the cursor even said "copy") and then silently
+discarded — it never became conversation context. Windows and Linux were
+unaffected because their bar runs in-process.
+
+These pin the round trip that closes it: child forwards the drop, parent
+replays it onto its own bridge, verdict comes back down and reaches the bar.
+"""
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import pytest
+
+from jarvis.overlay import drop_bridge
+from jarvis.ui.jarvisbar import host
+from jarvis.ui.jarvisbar.subprocess_overlay import SubprocessBarOverlay
+
+
[email protected](autouse=True)
+def _clean_bridge() -> Any:
+ drop_bridge.set_drop_handler(None)
+ drop_bridge.set_drop_result_sink(None)
+ yield
+ drop_bridge.set_drop_handler(None)
+ drop_bridge.set_drop_result_sink(None)
+
+
+# --------------------------------------------------------------------- #
+# Child side: the drop leaves the host process #
+# --------------------------------------------------------------------- #
+def test_the_host_forwards_a_drop_to_the_parent(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ emitted: list[tuple[str, dict]] = []
+ monkeypatch.setattr(
+ host, "emit", lambda event, **payload: emitted.append((event, payload))
+ )
+
+ host._wire_drop_forwarding()
+ # This is exactly what the Qt bar / mascot call when a file lands on them.
+ assert drop_bridge.dispatch_drop(["/dropped/shot.png"], "") is True
+
+ assert emitted == [("drop", {"paths": ["/dropped/shot.png"], "text": ""})]
+
+
+def test_the_forwarded_drop_survives_json(monkeypatch: pytest.MonkeyPatch) -> None:
+ """It crosses a pipe as one line — the payload must be serialisable."""
+ emitted: list[tuple[str, dict]] = []
+ monkeypatch.setattr(
+ host, "emit", lambda event, **payload: emitted.append((event, payload))
+ )
+
+ host._wire_drop_forwarding()
+ drop_bridge.dispatch_drop([], "https://example.invalid/x")
+
+ event, payload = emitted[0]
+ round_tripped = json.loads(json.dumps({"event": event, **payload}))
+ assert round_tripped["paths"] == []
+ assert round_tripped["text"] == "https://example.invalid/x"
+
+
+# --------------------------------------------------------------------- #
+# Child side: the verdict comes back down #
+# --------------------------------------------------------------------- #
+class _RecordingSurface:
+ def __init__(self) -> None:
+ self.results: list[bool] = []
+
+ def notify_drop_result(self, accepted: bool) -> None:
+ self.results.append(accepted)
+
+
+def test_a_drop_result_command_reaches_the_hosted_bar() -> None:
+ surface = _RecordingSurface()
+
+ assert host.dispatch(surface, {"op": "drop_result", "accepted": True}) is True
+ assert host.dispatch(surface, {"op": "drop_result", "accepted": False}) is True
+
+ assert surface.results == [True, False]
+
+
+def test_a_surface_without_the_confirmation_ignores_the_command() -> None:
+ """The mascot host shares this protocol and has no bar renderer."""
+
+ class _Bare:
+ pass
+
+ assert host.dispatch(_Bare(), {"op": "drop_result", "accepted": True}) is True
+
+
+# --------------------------------------------------------------------- #
+# Parent side: replay + answer #
+# --------------------------------------------------------------------- #
+def _surface() -> SubprocessBarOverlay:
+ """A proxy with no live child — ``_send`` is what we observe."""
+ return SubprocessBarOverlay()
+
+
+def test_the_parent_replays_a_forwarded_drop_onto_its_own_bridge(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ handled: list[tuple[list[str], str]] = []
+ drop_bridge.set_drop_handler(lambda paths, text: handled.append((paths, text)))
+
+ surface = _surface()
+ sent: list[dict] = []
+ monkeypatch.setattr(surface, "_send", sent.append)
+
+ surface._dispatch_event(
+ {"event": "drop", "paths": ["/dropped/a.png"], "text": ""}
+ )
+
+ assert handled == [(["/dropped/a.png"], "")]
+ # The handler is async in production, so no verdict is sent synchronously —
+ # it arrives later via the result sink.
+ assert sent == []
+
+
+def test_the_parent_registers_the_return_leg_when_a_drop_arrives(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ drop_bridge.set_drop_handler(lambda _paths, _text: None)
+ surface = _surface()
+ sent: list[dict] = []
+ monkeypatch.setattr(surface, "_send", sent.append)
+
+ surface._dispatch_event({"event": "drop", "paths": ["/dropped/a.png"], "text": ""})
+ # ...and now the backend finishes the intake.
+ drop_bridge.report_drop_result(True)
+
+ assert sent == [{"op": "drop_result", "accepted": True}]
+
+
+def test_a_drop_with_no_parent_handler_is_answered_honestly(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Rather than leaving the bar waiting for a verdict that never comes."""
+ surface = _surface()
+ sent: list[dict] = []
+ monkeypatch.setattr(surface, "_send", sent.append)
+
+ surface._dispatch_event({"event": "drop", "paths": ["/dropped/a.png"], "text": ""})
+
+ assert sent == [{"op": "drop_result", "accepted": False}]
+
+
+def test_a_malformed_drop_event_does_not_kill_the_event_pump() -> None:
+ """The pump serves talk/hangup/mute too — one bad line must not end it."""
+ surface = _surface()
+
+ surface._dispatch_event({"event": "drop"}) # no paths, no text
+ surface._dispatch_event({"event": "drop", "paths": None, "text": None})
diff --git a/tests/unit/ui/jarvisbar/test_renderer_drop_feedback.py b/tests/unit/ui/jarvisbar/test_renderer_drop_feedback.py
new file mode 100644
index 0000000000..2d09127633
--- /dev/null
+++ b/tests/unit/ui/jarvisbar/test_renderer_drop_feedback.py
@@ -0,0 +1,210 @@
+"""A drop on the bar must be VISIBLY answered, at any size, on any monitor.
+
+Before this, dropping a file onto the bar gave nothing back: the window went
+opaque while the drag hovered and then said nothing at all about whether the
+content had become context. These pin the three properties that make the
+answer trustworthy:
+
+1. the confirmation runs a bounded timeline and then gets out of the way;
+2. every dimension of it derives from the LIVE pill height, so it survives the
+ "Bar size" slider and a different monitor's DPI (the resting pill is ~37x6
+ px on a 1440p screen — a fixed-pixel glyph would not even fit); and
+3. a frame with no drop in flight is byte-identical to one from before the
+ feature existed.
+"""
+from __future__ import annotations
+
+import numpy as np
+import pytest
+
+from jarvis.ui.jarvisbar import renderer
+
+
[email protected](autouse=True)
+def _reset_geometry() -> None:
+ """Every test starts from the signed-off default geometry."""
+ renderer.apply_display_scale(1.0, renderer.USER_SIZE_DEFAULT)
+
+
+# --------------------------------------------------------------------- #
+# The confirmation timeline #
+# --------------------------------------------------------------------- #
+def test_the_tick_strokes_itself_on_then_holds_then_fades() -> None:
+ at_start = renderer.drop_confirm_phase(0.0)
+ mid_draw = renderer.drop_confirm_phase(renderer.DROP_CONFIRM_DRAW_S / 2)
+ holding = renderer.drop_confirm_phase(
+ renderer.DROP_CONFIRM_DRAW_S + renderer.DROP_CONFIRM_HOLD_S / 2
+ )
+ fading = renderer.drop_confirm_phase(
+ renderer.DROP_CONFIRM_DRAW_S
+ + renderer.DROP_CONFIRM_HOLD_S
+ + renderer.DROP_CONFIRM_FADE_S / 2
+ )
+
+ assert at_start[0] == 0.0 # nothing drawn yet
+ assert 0.0 < mid_draw[0] < 1.0 # partially stroked
+ assert holding == (1.0, 1.0) # whole tick, fully opaque
+ assert fading[0] == 1.0 and 0.0 < fading[1] < 1.0 # complete but dimming
+
+
+def test_the_confirmation_expires_so_the_bar_can_settle_again() -> None:
+ """A verdict that never ended would pin the pill open forever.
+
+ The surface reads exactly this to retire the state and release the
+ idle-repaint veto, so "past the end" must be unambiguous.
+ """
+ assert renderer.drop_confirm_phase(renderer.DROP_CONFIRM_TOTAL_S) == (0.0, 0.0)
+ assert renderer.drop_confirm_phase(renderer.DROP_CONFIRM_TOTAL_S + 5.0) == (0.0, 0.0)
+
+
+def test_a_negative_elapsed_draws_nothing_rather_than_flashing() -> None:
+ # Clock sources differ across the surfaces (perf_counter here, an IPC hop
+ # on macOS); a slightly-in-the-future stamp must not paint a full tick.
+ assert renderer.drop_confirm_phase(-0.2) == (0.0, 0.0)
+
+
+# --------------------------------------------------------------------- #
+# The tick geometry — scale-relative, progressively revealed #
+# --------------------------------------------------------------------- #
+def test_the_tick_reveals_from_its_start_and_completes() -> None:
+ start = renderer.tick_polyline(50.0, 20.0, 16.0, 0.0)
+ half = renderer.tick_polyline(50.0, 20.0, 16.0, 0.5)
+ whole = renderer.tick_polyline(50.0, 20.0, 16.0, 1.0)
+
+ assert len(start) < 2 # nothing to stroke yet
+ assert 2 <= len(half) <= 3
+ assert len(whole) == 3
+ # The revealed part always begins at the tick's own start point.
+ assert half[0] == whole[0]
+
+
+def test_the_tick_scales_with_the_pill_not_with_fixed_pixels() -> None:
+ """The whole cross-platform requirement in one assertion.
+
+ Doubling the pill height must double the glyph — that is what keeps the
+ confirmation intact across the "Bar size" slider, a 4K monitor and a
+ laptop screen, all of which change only this number.
+ """
+ small = renderer.tick_polyline(0.0, 0.0, 10.0, 1.0)
+ large = renderer.tick_polyline(0.0, 0.0, 20.0, 1.0)
+
+ for (sx, sy), (lx, ly) in zip(small, large, strict=True):
+ assert lx == pytest.approx(sx * 2)
+ assert ly == pytest.approx(sy * 2)
+
+
+def test_the_tick_stays_inside_the_pill_it_is_drawn_in() -> None:
+ """A glyph poking through the rim shows the color key as a pink fleck."""
+ ph = float(renderer.OPEN_H)
+ pw = float(renderer.OPEN_W)
+ cx, cy = pw / 2, ph / 2
+
+ for x, y in renderer.tick_polyline(cx, cy, ph, 1.0):
+ assert 0.0 < x < pw
+ assert 0.0 < y < ph
+
+
+# --------------------------------------------------------------------- #
+# The pill opens for a drop #
+# --------------------------------------------------------------------- #
+def test_the_resting_pill_opens_for_a_drop() -> None:
+ """The resting sliver is far too small to release a file on or to show a
+ tick in — a hovering payload has to open it, exactly like hover does."""
+ resting = renderer.target_pill_size("idle", hovered=False)
+ dropping = renderer.target_pill_size("idle", hovered=False, drop_open=True)
+
+ assert resting == (renderer.COLLAPSED_W, renderer.COLLAPSED_H)
+ assert dropping == (renderer.OPEN_W, renderer.OPEN_H)
+ assert dropping[1] > resting[1]
+
+
+def test_a_live_session_keeps_its_own_size_during_a_drop() -> None:
+ # The active pill is already the biggest; a drop must not shrink it.
+ assert renderer.target_pill_size("speak", hovered=False, drop_open=True) == (
+ renderer.ACTIVE_W,
+ renderer.ACTIVE_H,
+ )
+
+
+# --------------------------------------------------------------------- #
+# The rim carries the state #
+# --------------------------------------------------------------------- #
+def test_no_drop_leaves_the_rim_exactly_as_it_was() -> None:
+ """Non-drop frames must be untouched by this feature."""
+ base = renderer.PILL_BORDER
+ assert renderer.drop_rim_color(1.23, base, renderer.DROP_STATE_NONE) == base
+ assert renderer.drop_rim_color(9.9, renderer.MUTED_RED, "none") == renderer.MUTED_RED
+
+
+def test_the_armed_rim_pulses_over_time() -> None:
+ """A static brightening would be missed; the point is that it breathes."""
+ period = 2 * 3.141592653589793 / renderer.DROP_ARM_PULSE_RAD_S
+ samples = {
+ renderer.drop_rim_color(period * frac, renderer.PILL_BORDER, "armed")
+ for frac in (0.0, 0.25, 0.5, 0.75)
+ }
+ assert len(samples) > 1
+
+
+def test_the_verdict_colors_are_distinguishable() -> None:
+ ok = renderer.drop_rim_color(0.0, renderer.PILL_BORDER, renderer.DROP_STATE_OK)
+ no = renderer.drop_rim_color(
+ 0.0, renderer.PILL_BORDER, renderer.DROP_STATE_REJECTED
+ )
+ assert ok == renderer.DROP_OK_GREEN
+ assert no == renderer.MUTED_RED
+ assert ok != no
+
+
+# --------------------------------------------------------------------- #
+# End to end through the real renderer #
+# --------------------------------------------------------------------- #
+def test_a_confirmed_drop_paints_something_a_plain_idle_bar_does_not() -> None:
+ bar = renderer.JarvisBarRenderer()
+ # Settle the eased pill at the open size first, so the comparison is about
+ # the glyph and not about the pill still growing.
+ for _ in range(12):
+ bar.render(0.0, "idle", 0.0, drop_state=renderer.DROP_STATE_ARMED)
+ armed = bar.render(0.0, "idle", 0.0, drop_state=renderer.DROP_STATE_ARMED)
+ confirmed = bar.render(
+ 0.0,
+ "idle",
+ 0.0,
+ drop_state=renderer.DROP_STATE_OK,
+ drop_elapsed=renderer.DROP_CONFIRM_DRAW_S + 0.1,
+ )
+
+ assert armed.tobytes() != confirmed.tobytes()
+ # The tick is green, and green is not in the bar's normal palette.
+ pixels = np.asarray(confirmed.convert("RGB"), dtype=np.int16)
+ target = np.asarray(renderer.DROP_OK_GREEN, dtype=np.int16)
+ assert bool((np.abs(pixels - target).max(axis=-1) < 60).any())
+
+
+def test_an_expired_confirmation_renders_as_no_drop_at_all() -> None:
+ """Belt and braces: a surface slow to retire the state cannot pin the pill.
+
+ The renderer downgrades a finished verdict itself, so the pill target
+ collapses back even if ``drop_state`` is still set.
+ """
+ stale = renderer.JarvisBarRenderer()
+ plain = renderer.JarvisBarRenderer()
+ for _ in range(40):
+ stale_img = stale.render(
+ 0.0,
+ "idle",
+ 0.0,
+ drop_state=renderer.DROP_STATE_OK,
+ drop_elapsed=renderer.DROP_CONFIRM_TOTAL_S + 1.0,
+ )
+ plain_img = plain.render(0.0, "idle", 0.0)
+
+ assert stale_img.tobytes() == plain_img.tobytes()
+
+
+def test_rendering_a_drop_never_changes_the_frame_size() -> None:
+ """The window is fixed; only the pill inside it eases."""
+ bar = renderer.JarvisBarRenderer()
+ for state in renderer.DROP_STATES:
+ img = bar.render(0.0, "idle", 0.0, drop_state=state, drop_elapsed=0.1)
+ assert img.size == (renderer.WIN_W, renderer.WIN_H)