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
refactor(overlay): remove the dormant OS-Level overlay subsystem
Ruben Lütke4f749f9118fb
diff --git a/OS-Level/OS-LEVEL_PLAN.md b/OS-Level/OS-LEVEL_PLAN.mddeleted file mode 100644index b4f7b3c72e..0000000000--- a/OS-Level/OS-LEVEL_PLAN.md+++ /dev/null@@ -1,2064 +0,0 @@-# OS-Level Edge-Glow Overlay — Engineering Plan--**Status:** Draft 1.0 — ready for prompt-chain derivation-**Scope:** Phase 9 (sequential, after the Phase 8 review pipeline)-**Language:** English-**Intended readers:** OpenClaw (autonomous implementer) and Ruben (owner/reviewer)--> This document is an **engineering spec**, not a prompt chain. It describes **what** is built and **why** — not **when** and in what order. The prompt chain with phases, definition-of-done per phase, and commit points is generated separately in the second step.-------## Table of contents--1. Vision & Motivation-2. Scope: In / Out-3. Pre-Conditions-4. Conceptual Architecture-5. Architecture Decisions (AD-1 through AD-18)-6. State Model-7. Visual Design System-8. Trigger Specification-9. External Interface (Hauptjarvis ↔ Overlay)-10. IPC Protocol-11. Shared Memory Layout-12. Window Management-13. Mascot Specification-14. Click Visualization-15. Cursor Trail-16. Typing Indicator-17. Performance Budgets-18. Privacy & Safety-19. Accessibility-20. Edge Cases (complete enumeration)-21. Configuration Schema-22. File Structure-23. Testing Strategy-24. Success Criteria (feature-level definition of done)-25. Risks & Mitigations-26. Implementer Discretion — what OpenClaw may decide itself-27. Glossary-------## 1. Vision & Motivation--### 1.1 What we are building--A **separate Python process** that draws an animated glow border around the screen edge, **when — and only when — the Hauptjarvis (main Jarvis) performs interactive PC actions**. Plus a small, persistent **mascot figure** that visualizes the status (idle/listening/speaking/acting), and point-in-time **click visualizations + cursor trail + typing indicator** for the phases in which Jarvis operates the computer.--Visual reference: Gemini Live's screen-edge glow, Apple Intelligence's edge effect, Perplexity Comet's browser-extension border. Strictly **black + yellow** in color (Jarvis design system), no rainbow, no blue, no purple.--### 1.2 Why this exists--**Trust problem with autonomous AI agents that operate the computer.** When Jarvis takes over the mouse and keyboard, the human should be able to recognize at a glance at any time:-- *"Jarvis is doing something right now"* (glow active)-- *"Jarvis is doing nothing right now"* (no glow)-- *"Jarvis clicked here"* (ripple at the click coordinate)-- *"Jarvis is typing right now"* (subtle sweep at the bottom screen edge)-- *"Jarvis is even alive"* (mascot idle pulse)--The effect is not primarily decorative. It is a **status signal with perceptual latency below the human perception threshold**, so the human does not have to guess whether Jarvis is currently active or whether the system is hung.--### 1.3 Mental model for the user--> *"My screen edge glows when Jarvis is working. As soon as it stops, it's gone. I can look at the mascot and know whether it's listening, thinking, or speaking. When it clicks, I see where. When it types, I see that it's typing. It is never louder than a discreet glow. It never distracts me. I can turn it off at any time."*--### 1.4 What "good" looks like--- **Latency Hauptjarvis action → glow appearance ≤ 50 ms.** Below the perceptual threshold for visible lag in mouse-based interaction (Forch et al. 2017: ~60 ms).-- **The glow visibly "breathes."** Not static, not aggressive. A 4–8 second idle period, gentle in/out like calm breathing.-- **The click ripple is sharp but short.** ≤ 600 ms lifetime, yellow on transparent, fade-out.-- **The mascot is small, calm, charming.** 160×160 px default. Reacts to state, but does not constantly dance around.-- **On multi-monitor it works as expected.** Glow only on the primary monitor (default), or on all (user setting). No odd DPI jumps.-- **In fullscreen games and during UAC it is simply gone.** No flicker, no z-order fights, no "try to be always-on-top over UAC".-- **It is quiet when nothing is happening.** No "I'm reminding you that I'm here" pulsing. Glow off = Hauptjarvis idle.--### 1.5 What "bad" looks like (anti-patterns)--- ❌ **Rainbow glow.** Visually impressive, but off-brand. Jarvis is black-yellow monochrome.-- ❌ **Glow even when Jarvis only speaks.** Glow only for *interactive PC actions* (mouse/keyboard). Pure speaking → no glow.-- ❌ **Sub-agents triggering the glow.** Only the Hauptjarvis. Sub-agents work in subprocesses, not "on your computer".-- ❌ **Character confetti while typing.** A tacky typing-game feel. A single subtle sweep at the screen edge, nothing more.-- ❌ **A dancing/waving mascot that reacts to user actions.** The mascot reacts to **Jarvis state**, not to user input. It is not Clippy.-- ❌ **WebGL shader for the glow.** Keeps a GPU context permanently open, costs 3–5 W continuously on integrated GPUs. CSS+SVG is the answer.-- ❌ **The glow surviving a Jarvis crash.** When the Hauptjarvis dies, the glow should disappear within ≤ 1 s. Job Object with `KILL_ON_JOB_CLOSE`.-- ❌ **Latency > 100 ms between action and glow.** Forch et al. 2017: 60 ms is the perception threshold. We want `<50 ms` of margin.-- ❌ **The voice loop being affected by the overlay.** Voice-path latency is sacrosanct (`<1.5 s` time-to-first-word, see CLAUDE.md). The overlay runs in a completely separate process.--### 1.6 Concrete user stories--**US-1.** *As Ruben I use the voice command "open my mail client and reply to the last email from Anna with a polite 'Sounds good, let's do it'." The Hauptjarvis then starts Browser-Use, navigates to GMX, clicks its way through. I see the glow around the screen, see a yellow ripple on every click, and a sweep at the bottom edge when it types. At any time I can recognize whether Jarvis is still active or already finished.*--**US-2.** *As Ruben I start a fullscreen game. The overlay disappears automatically, without me having to do anything. As soon as I leave the game, it is back.*--**US-3.** *As Ruben I start a Zoom call and share my screen. The glow is visible on my screen, but not in the transmission to the call participants. I can explicitly disable this privacy default setting if I want to record the overlay.*--**US-4.** *As Ruben I say "start 5 sub-agents in parallel to research". The Hauptjarvis spawns 5 Sub-Jarvis subprocesses. The glow does NOT appear — no sub-agent is "on my computer", they run in subprocesses. When the Hauptjarvis later aggregates the results and reads them out to me, the glow stays off.*--**US-5.** *As Ruben I right-click on the mascot → "Hide". The mascot disappears. On the next Jarvis start it is still hidden (persistence). I can show it again at any time via the tray menu.*--**US-6.** *As Ruben I drag the mascot to my second monitor. On the next start it is there again. When I unplug the second monitor, the mascot cleanly jumps to the first monitor (instead of ending up off-screen) and I get no crashes.*--### 1.7 Non-goals (see also §2.2)--Explicitly **not** part of this feature:-- Speech visualization (audio waveform). That is part of the voice UI, not the overlay.-- Notification toasts. Standard OS mechanisms suffice.-- Input via the overlay (no click on the glow starts an action). Only the mascot is clickable (drag, right-click menu).-- Communication with other apps (no "Jarvis controls OBS"). Only Hauptjarvis ↔ Overlay.-- Multi-user. One instance per Windows user session.-- Mobile/macOS/Linux. Windows-only.-------## 2. Scope: In / Out--### 2.1 In Scope--| Component | Description |-|---|---|-| **Edge-Glow window** | Per-monitor frameless transparent click-through window with animated glow at the screen edge |-| **Mascot window** | Small (~160×160 px) frameless window with a Rive-based mascot, draggable, persistent position |-| **Click-ripple layer** | Display of a short yellow ripple effect at each click coordinate |-| **Cursor-trail layer** | Subtle dot trail that marks Jarvis' cursor movements |-| **Typing indicator** | Bottom-edge sweep when Jarvis types |-| **State machine** | 8 states (idle/listening/thinking/typing/clicking/speaking/error/hidden) with defined transitions |-| **IPC layer** | WebSocket primary + SHM cursor channel + Named-Pipe fallback |-| **Trigger instrumentation** | Decorator + context-manager + direct-emit API in the Hauptjarvis |-| **Process supervisor** | Job Object, auto-restart with exponential backoff, health check |-| **Configuration schema** | `[overlay]` section in `jarvis.toml` with atomic write pipeline |-| **Privacy mode** | `WDA_EXCLUDEFROMCAPTURE` default-on, user toggle |-| **Multi-monitor support** | Per-monitor window, DPI-aware, hotplug handling |-| **Fullscreen detection** | `SHQueryUserNotificationState` polling, auto-hide |--### 2.2 Out of Scope (Non-Goals)--| What | Why not |-|---|---|-| **Linux/macOS support** | Windows-only stack (PySide6 + Win32 specifics); macOS would have completely different window-compositor semantics |-| **WebGL shader for the glow** | Keeps a GPU context permanently open, costs 3–5 W continuously on an iGPU; CSS+SVG looks just as nice and is ~10× cheaper |-| **Voice/audio code in the overlay** | The audio path is sacrosanct (see CLAUDE.md `<1.5 s TTFW`). The overlay NEVER imports audio modules |-| **Custom DirectComposition renderer** | PySide6 + QtWebEngine is enough; DComp is a potential v2 escape, should performance profiling demand it |-| **Lottie / Live2D mascot** | Rive is 5–10× smaller and has state machines built in. Lottie has worse performance, Live2D is anime-aesthetic-specific |-| **ZeroMQ / gRPC IPC** | WebSocket is enough for ~10 Hz state events; the ZMQ/gRPC advantages are invisible at this volume |-| **Game-overlay D3D hooking** | Kernel-driver territory, non-trivial signed code, a huge maintenance burden for minimal gain |-| **Multi-language UI in the overlay (V1)** | DE + EN for the tray menu and mascot tooltip is enough for now; full i18n in V2 |-| **Sub-agent status in the overlay** | Sub-agents are not "on your computer" — they are subprocesses. The overlay reflects only Hauptjarvis state |-| **Ambient idle-state glow** (e.g. "Jarvis is alive") | The glow should be **silent** when Jarvis is doing nothing. The mascot idle pulse is enough of a sign of life |-| **Decorative animations for state transitions** (e.g. sparkle effects) | Too playful; does not fit Jarvis' calm, understated assistant persona |-| **Custom mouse-cursor replacement** | We only draw a *trail* behind the system cursor, we do not replace the cursor itself |-------## 3. Pre-Conditions--These must be met **before** the implementation starts:--- **Phase 8 (review pipeline)** completed. `HarnessManager` and `SubprocessHarness` are stable.-- **The Hauptjarvis has a clear "action-path" choke point.** There must be a single point in the code through which all PC actions (mouse, keyboard, browser click via Browser-Use, Computer-Use tool) flow, at which trigger events can be emitted. If it does not yet exist, it must be created as a **pre-phase** (see §8.4).-- **`jarvis.toml`** is parseable and has a validated Pydantic model class. A new `[overlay]` section is added in parallel; existing content stays unchanged.-- **Python ≥ 3.12.** PySide6 ≥ 6.7 (Qt 6.7+, sufficient Win11 compositor stability).-- **Windows 11** (24H2 or newer recommended). Windows 10 works in principle, but is not explicitly tested (see AD-3).-- **Test suite green.** No red tests in `pytest tests/` before starting the OS-level feature. New tests land under `tests/overlay/`.-- **`uv` or `pip` as the package manager** for the separate overlay-dependency installation (see §22).--If a precondition is not met: pause, bring in the missing component.-------## 4. Conceptual Architecture--### 4.1 Big Picture--```-┌────────────────────────────────────────────────────────────────────┐-│ Personal Jarvis — Process Tree │-│ │-│ ┌──────────────────────────────────────┐ │-│ │ Hauptjarvis (FastAPI, existing) │ │-│ │ - Voice loop │ │-│ │ - RouterBrain (Haiku) │ │-│ │ - Sub-Jarvis-Manager │ │-│ │ - Browser-Use / Computer-Use │ │-│ │ - NEW: OverlayBridge (emits events) │ │-│ └────────────────────┬─────────────────┘ │-│ │ │-│ │ Job Object (KILL_ON_JOB_CLOSE) │-│ ▼ │-│ ┌──────────────────────────────────────┐ │-│ │ Overlay-Process (NEW, separate) │ │-│ │ PySide6 + QtWebEngine │ │-│ │ │ │-│ │ ┌──────────┐ ┌──────────┐ │ │-│ │ │ Edge- │ │ Mascot- │ │ │-│ │ │ Glow-Win │ │ Window │ │ Same process, │-│ │ │ (per │ │ (1×, │ │ separate top-level HWNDs │-│ │ │ monitor)│ │ optional) │ │-│ │ └──────────┘ └──────────┘ │ │-│ └────────────────────┬─────────────────┘ │-│ │ │-│ │ WebSocket (state, click, config) │-│ │ Shared Memory (60 Hz cursor stream) │-│ │ Named Pipe (fallback) │-└────────────────────────────────────────────────────────────────────┘-```--### 4.2 Trust and process boundary--**Hard rule:** The overlay is a **separate Python process**, not a thread, not a sub-window in the existing pywebview app. Reasons:--1. **Crash isolation.** An overlay crash must not kill the voice loop. A voice-loop crash must not kill the overlay (the reverse does, via Job Object).-2. **Latency isolation.** Qt's GUI event loop must not block FastAPI's asyncio event loop. Separate processes → separate event loops.-3. **Audio-path protection.** The voice loop has a `<1.5 s` time-to-first-word latency budget. Overlay code must never access the audio path, neither reading nor writing. The process boundary makes this *structurally impossible* — the overlay simply has no import access.-4. **Memory isolation.** PySide6 + QtWebEngine + Chromium = ~110–140 MB RSS. We do not want that in the main process.-5. **Independent restartability.** The overlay can be killed and restarted without disturbing the voice loop.--### 4.3 Lifecycle relationship--| Hauptjarvis event | Overlay reaction |-|---|---|-| Hauptjarvis starts | Spawns the overlay subprocess under a Job Object. The overlay registers via WS heartbeat. |-| Hauptjarvis crashes | The Job Object closes → Windows kills the overlay automatically within 1 s. |-| Overlay crashes | The Hauptjarvis' `OverlaySupervisor` detects it via heartbeat timeout (3 s), respawns the overlay. Exponential backoff with jitter. |-| User closes the Hauptjarvis cleanly | The Hauptjarvis sends `{"type": "shutdown"}` to the overlay → the overlay cleans up and exits. Job Object cleanup as a backstop. |-| Windows shuts down | Standard WM_QUERYENDSESSION handling in Qt. The overlay cleans up. |-| User turns the overlay off completely (`overlay.enabled = false`) | The Hauptjarvis does not even spawn an overlay. Toggled at runtime → the overlay is terminated. |-------## 5. Architecture Decisions--Format: **AD-N — Title.** Decision. Rationale. Alternatives rejected.-------### AD-1 — Stack: PySide6 (LGPLv3) + QtWebEngine--PySide6 as the Win32 host shell. An embedded `QWebEngineView` renders the glow and mascot CSS.--**Rationale:**-- **Python-native** (fits the FastAPI stack, no Rust/Node toolchain import).-- **LGPLv3** — compatible with commercially friendly OSS distribution. PyQt6 is GPLv3 → excluded.-- **Mature transparent click-through support** via `Qt.WindowTransparentForInput` → translates to `WS_EX_TRANSPARENT | WS_EX_LAYERED` at the HWND level. This is the same OS primitive that Tauri and Electron use.-- **Per-Monitor-V2 DPI awareness** built in via manifest.-- **Chromium renderer** supports CSS `@property`, `mask-composite`, `plus-lighter`, all modern glow primitives.--**Rejected:**-- **PyQt6:** GPLv3 — license-blocking.-- **pywebview transparent:** Broken on Windows (Issue #1611, #488, #745, #1200, #1271).-- **Electron sidecar:** ~200–300 MB RSS, too heavy.-- **Tauri 2.x:** 30–80 MB RSS, technically clean, but imports a Rust toolchain into a Python codebase. The ~50 MB memory win does not disqualify that.-- **Tkinter with `LWA_COLORKEY`:** Implemented like the Phase-1 Orb overlay — good for a static point, bad for animated glow with effects.-- **WPF via pythonnet:** Needs a .NET runtime distribution, worse DX than PySide6.-- **Pure Win32 + DirectComposition via ctypes:** Best performance (~35–55 MB RSS, <1% GPU), but ~600–900 LoC for v1. An escalation path for v2 if profiling demands it.-------### AD-2 — Renderer: CSS conic-gradient + SVG feGaussianBlur, no WebGL--The glow animation runs as CSS `@property --angle` with `conic-gradient` plus stacked SVG `feGaussianBlur` filters. Compositor-thread-driven, `transform`/`opacity`/registered-custom-property only.--**Rationale:**-- **Power.** WebGL keeps a GPU context permanently open → 3–5 W continuously on an iGPU. CSS compositor animation: <1 W active, ~0 W idle (DWM throttled).-- **Survives CPU spikes.** When the Hauptjarvis is currently inferring Sonnet 4.7 and the CPU spikes, the CSS animation keeps running because it runs on the compositor thread, not on the JS thread.-- **No own GPU-context conflict** with the mascot (Rive Canvas2D-only, no WebGL).-- **No own shader-compile path.** Cross-driver compatible.--**Rejected:**-- **WebGL2 / WebGPU:** Power cost.-- **Canvas-2D radial-gradient per frame:** Higher CPU cost than a declarative CSS animation.-- **Lottie for the glow:** Lottie is 5–10× larger than CSS, and `conic-gradient` with `@property` is *declaratively animated*, which Lottie is not.-------### AD-3 — Window configuration: per-monitor window, not virtual-screen window--In a multi-monitor setup, **a separate transparent window instance per `QGuiApplication.screens()` entry** is created, each sized to that monitor's `geometry()`. No single window across the entire virtual desktop area.--**Rationale:**-- **DWM has heterogeneous-DPI bugs** across monitors with different DPI settings when a layered window spans both.-- **Per-Monitor-V2 DPI awareness** works cleanly per window, not across a spanning window.-- **GPU cost** scales per actual pixel — a single spanning window across 2× 4K pays for the full 8K surface, even though only edges are drawn.--**Rejected:**-- **Single virtual-screen window:** DWM compositor problems with heterogeneous DPI, higher surface-memory cost.-------### AD-4 — The mascot is a **separate window** in the same process--Edge-Glow and Mascot are **two separate frameless transparent top-level HWNDs**, both under the same `QApplication`. Edge-Glow is click-through (`WS_EX_TRANSPARENT`), Mascot is **NOT** click-through (it must receive clicks for drag and the right-click menu).--**Rationale:**-- **`WS_EX_TRANSPARENT` is a window-level attribute**, not regional. If both were in the same window, we would have to build per-region hit-testing via a cross-window `setIgnoreMouseEvents(true, {forward: true})` (Electron) — known to be flaky (Electron issues #30808, #33281, #35030).-- **Mascot-window hit-testing via `setMask(QRegion)`**: We set a circular hit region matching the mascot silhouette (see §12.2). Clicks outside the region (transparent corners of the 160×160 box) fall through to the desktop. This is the only correct solution for the `WA_TranslucentBackground` setup — see the note in §12.2 below.-- **The mascot can be hidden / unmounted independently**, without affecting the glow (e.g. when `overlay.mascot_enabled = false` is toggled at runtime).--**Rejected:**-- **Single combined window** with per-region hit-testing.-- **Mascot in the pywebview main window**: then the mascot is only visible when the pywebview window is open — defeats the purpose.-------### AD-5 — IPC: WebSocket primary + Shared Memory for the cursor + Named Pipe fallback--Three channels with clear separation of duties:--| Channel | Frequency | Content | Rationale |-|---|---|---|---|-| **WebSocket** (FastAPI WS endpoint) | ≤ 10 Hz | State changes, click events, config, heartbeat | Existing FastAPI stack, JSON-debuggable, Pydantic-validatable |-| **Shared Memory** (`multiprocessing.shared_memory`) | 60 Hz | Cursor-position stream | 60 wakeups/s on asyncio competing with the voice loop is not acceptable; SHM is zero-copy, single-writer/single-reader |-| **Named Pipe** (`\\.\pipe\jarvis-overlay`) | Fallback | All WS channels, if the WS port is blocked | Corporate-firewall / AV-interference mitigation |--**Rationale:**-- **WebSocket** is already in the FastAPI stack, sub-25 ms end-to-end is comfortably within the 50 ms click-ping budget.-- **SHM for the cursor:** 60 Hz × WS roundtrip (~1–2 ms each) would generate 60 wakeups/s on the asyncio loop. The voice loop runs on the same loop. SHM = zero-copy, no loop wakeup.-- **Named Pipe** as a third leg: in our experience, corporate firewalls or AV tools sometimes block localhost WS ports on 7000–9999. A named pipe is not network-based and escapes such blocks.--**Rejected:**-- **ZeroMQ / nanomsg:** ~25–150 µs latency vs. WS ~0.5–2 ms. Invisible at our volume (~10 Hz). An additional dependency.-- **gRPC localhost:** ~2–6 ms in Python, binary (harder to debug).-- **Stdin/stdout JSON streaming:** OK for one-way, but bidirectionality gets ugly.-------### AD-6 — Trigger source: only the Hauptjarvis, never sub-agents--Sub-agents (Sub-Jarvis, dispatched harnesses) **never** trigger the Edge-Glow overlay. Rationale: they run in their own subprocesses and do not "work" *on your computer* but *in a sandbox*. The glow should only light up when Jarvis itself operates the mouse/keyboard/browser on the user session.--**Mechanics:**-- The Hauptjarvis calls `OverlayBridge.action(...)` directly. `OverlayBridge` is only instantiated in the Hauptjarvis process, not in sub-agent subprocesses.-- Sub-agents have **no access** to the WS connection to the overlay. Structurally.-- If a sub-agent should ever actually perform PC actions (e.g. via the Computer-Use tool inside the sub-agent), that is a **separate feature** (Phase 10+) with its own architecture decision.--**Rationale:** Avoids the concept "sub-agent X clicks — where is that shown?". Sub-agents are logical processing threads, not compute subjects of the user. If the user later wants to see it differently, the architectural entry point stays clear (`OverlayBridge` central).-------### AD-7 — Trigger API: decorator + context-manager + direct-emit--Three complementary entry points, all in `jarvis/overlay/bridge.py`:--```python-# 1. Decorator (for whole functions / tool-calls)-@overlay_action(kind="click")-async def click_at(x: int, y: int) -> None: ...--# 2. Context-Manager (for in-function scopes)-async def submit_form(...):- async with overlay_action_scope(kind="typing", duration_hint_ms=2000):- await pyautogui.typewrite(text)--# 3. Direct-Emit (for ad-hoc events outside functions)-await overlay_bridge.emit("click", x=x, y=y, monitor=monitor_id)-```--**Rationale:**-- The **decorator** is the default for all action functions in `jarvis/control/` and `jarvis/plugins/tool/computer_use.py` etc. → minimal code-change footprint.-- The **context-manager** for cases where a single function has multiple action phases (e.g. "open browser → enter URL → submit").-- **Direct-emit** as an escape hatch (e.g. for plugin code that cannot/should not be modified).-- All three paths land in the same `OverlayBridge.emit(...)` and are treated identically.--**Implementer note (see §26):** The exact signature and helper logic of the decorator is implementer discretion, as long as the three entry points exist logically.-------### AD-8 — The state machine is in the overlay process--The state machine (idle → listening → … see §6) lives **in the overlay process**, not in the Hauptjarvis. The Hauptjarvis sends **events** ("action_started", "action_ended"), the overlay converts those to state transitions.--**Rationale:**-- **Decoupling.** The Hauptjarvis does not need to know how the overlay organizes its states. The overlay can change its state model without the Hauptjarvis being touched.-- **Coalescing.** When two events arrive within 16 ms (e.g. a click and a follow-up click), the overlay can coalesce them into a single visualization without the Hauptjarvis needing to know.-- **Heartbeat-driven transitions.** When the Hauptjarvis crashes and no more events come, the overlay can autonomously transition to `idle` after a timeout.--**Rejected:**-- State machine in the Hauptjarvis: tighter coupling, the Hauptjarvis blocks on state render.-------### AD-9 — Process lifetime: Job Object with `KILL_ON_JOB_CLOSE`--The overlay subprocess is assigned to a Win32 Job Object, with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`. The handle is held by the Hauptjarvis and is not inheritable. When the Hauptjarvis process dies (even hard), Windows closes the job handle, which kills the overlay process as a job member.--**Rationale:** Guarantees no zombies, even on `os._exit()` or a process crash. Standard pattern (Raymond Chen canonical).--**Implementer note:** Doable via `pywin32` (`win32job.CreateJobObject`, `SetInformationJobObject`, `AssignProcessToJobObject`) or directly via `ctypes`. Pywin32 is preferred because it is already a dependency.-------### AD-10 — Auto-restart with exponential backoff--When the overlay runs stably for 60 s, the restart counter is reset. On crash:--```python-delay = min(30, 0.5 * 2**failures) * jitter(0.8, 1.2)-```--Cap at 5 restarts within a 5-minute window. When the cap fires: tray notification "Overlay could not be started", the overlay feature disabled for the running session. The user can manually re-enable.--**Rationale:** Avoids tight restart loops on structural problems (e.g. a missing DLL).-------### AD-11 — Atomic config pipeline for `[overlay]`--Changes to `[overlay]` in `jarvis.toml` are made via a `pre-validate → backup → write → reload-test → rollback` pipeline (analogous to the Self-Mod pipeline AD-7 there). Pydantic validation pre-write, backup to `jarvis.toml.bak`, atomic write via temp-file + rename, reload-test = Pydantic-parse + minimal-instantiate of the overlay-config class, rollback = copy the backup back if the reload test fails.--**Rationale:** Consistency with the rest of the system. Prevents broken configs from half-writes.-------### AD-12 — Constraints in the code, not in the config--Hard limits (e.g. max FPS, max glow width, max mascot size) are anchored in the Python code as constants / Pydantic validators, not in the TOML. The user cannot override them via TOML.--**Rationale:** Consistent with Self-Mod AD-7 and Review AD-12. Prevents the user from accidentally blowing the performance budgets via an inadvertent `fps_active = 240`.-------### AD-13 — Privacy default: `WDA_EXCLUDEFROMCAPTURE` on--`SetWindowDisplayAffinity(hWnd, WDA_EXCLUDEFROMCAPTURE)` is set **default-on** for all overlay HWNDs. Visible to the user, excluded from the DWM bitstream → invisible in OBS, Teams, Zoom, Snipping Tool.--**Opt-out:** `overlay.hide_from_capture = false` for legitimate recording use cases (tutorial video).--**Rationale:** Privacy-by-default. Prevents the user from accidentally sharing overlay content.--**Implementer note:** Win11 has a quirk in some builds (Microsoft Q&A 700122) where Chromium WebView2 does not honor the flag. Workaround (see §12.4).-------### AD-14 — Coordinate system: logical pixels, conversion at the boundary--All IPC messages carry coordinates in **physical pixels** (Win32 native). Conversion to CSS logical pixels happens in the JS bridge of the QtWebEngine renderer, with `window.devicePixelRatio` and the per-monitor DPI.--**Rationale:** The Hauptjarvis/Computer-Use works in Win32 coords (which pyautogui does too). The renderer works in CSS coords. Conversion at one point → no subtle off-by-DPI bugs spread throughout the code.-------### AD-15 — Schemas: Pydantic v2 (Python) and Zod (TS) symmetric--Each IPC message has a Pydantic v2 model on the Python side and an identical Zod schema on the TS side. A JSON schema is exported from Pydantic and checked against Zod (CI test).--**Rationale:** Prevents schema drift between sender and receiver. JSON-schema diffing as a CI gate.-------### AD-16 — Mascot engine: Rive--Rive (`@rive-app/canvas-lite`, MIT, ≤ 200 KB gz) for mascot animations and the state machine.--**Rationale:**-- **State machines built in.** Maps 1:1 onto the overlay state machine without frame-scrubbing logic.-- **Asset size.** ~80 KB for a .riv file with all states. Lottie would be 200–500 KB for an equivalent animation.-- **Canvas2D runtime** (`canvas-lite`), no WebGL → no GPU-context conflict with Edge-Glow.-- **The designer tool is free and good.** Rive Editor (web).--**Rejected:**-- **Lottie:** 5–10× larger, no state machine.-- **Live2D:** anime-aesthetic-specific, overkill.-- **Sprite sheets:** loop-boundary race conditions, no smooth state transitions.--**Fallback (implementer discretion):** If the Rive integration proves problematic (e.g. build-pipeline issues), OpenClaw may switch to a PNG sprite-sheet solution, documents the rationale, and the mascot is implemented as a static PNG with a CSS animation (`opacity` pulse). No deal-breaker.-------### AD-17 — Coalescing: 16 ms window for identical event types--When two events of the same type arrive within 16 ms (e.g. a double state change due to a race condition), the later one is ignored. Click events are NOT coalesced (every click deserves a ripple).--**Rationale:** 16 ms = 1 frame @ 60 Hz. State changes within one frame are perceptually identical.-------### AD-18 — No audit log--In contrast to Self-Mod (AD-6) and Review (AD-11), the overlay feature has **no** persistent audit log. Rationale: the overlay is *visual feedback*, not a *security-relevant code path*. A lost glow frame is not reproduction-relevant. Heartbeat telemetry (RSS, FPS, drops) is kept in memory and dumped via stack trace on crash, but not persistently logged.--**Rejected:** Per-event logging would have disk-IO cost and no clear recovery use case.-------## 6. State Model--### 6.1 States--| State | Description | Glow visual | Mascot animation |-|---|---|---|---|-| **idle** | Nothing is running | Glow off, mascot idle pulse | gentle 8-s sine breathing |-| **listening** | Wake word detected, STT running | Glow off (no PC action), mascot listening anim | mouth open, eyes alert |-| **thinking** | LLM inference running, no PC action | Glow off (no PC action), mascot thinking anim | head-tilt, dots above head |-| **typing** | Hauptjarvis types via keyboard input | Glow on (yellow conic-sweep), bottom-edge accent sweep | hands typing |-| **clicking** | Hauptjarvis clicks via the mouse | Glow on (yellow), Ripple at click coord | finger-point |-| **speaking** | TTS output running | Glow off (no PC action), mascot mouth-anim | mouth movement synced to RMS |-| **error** | Recoverable error in the Hauptjarvis | Glow shifts to amber/red flash 1× then off | confused expression |-| **hidden** | Overlay completely hidden (fullscreen detected, manual hide, or feature disabled) | Glow off, mascot hidden | n/a |--**Important:** **The glow is active ONLY in `typing` and `clicking`.** `listening`, `thinking`, `speaking` do not activate the glow — they only change the mascot. The whole point of the glow is "Jarvis is operating my computer right now".--### 6.2 Transitions--```- ┌─────────┐- ┌────────│ IDLE │◄────────┐- │ └────┬────┘ │ action_ended- │ │ wakeword │ utterance_done- │ ▼ │- │ ┌─────────┐ │- │ │LISTENING│─────────┤- │ └────┬────┘ │- │ │ utterance │- │ ▼ │- │ ┌─────────┐ │- │ ┌───►│THINKING │─────────┤- │ │ └────┬────┘ │- │ │ │ tool_call │- │ │ ▼ │- │ │ ┌─────────┐ │- │ │ │ TYPING │─────────┤ ← GLOW ON- │ │ └────┬────┘ │- │ │ │ click_event │- │ │ ▼ │- │ │ ┌─────────┐ │- │ │ │CLICKING │─────────┤ ← GLOW ON + RIPPLE- │ │ └────┬────┘ │- │ │ │ response_ready│- │ │ ▼ │- │ │ ┌─────────┐ │- │ └────│SPEAKING │─────────┘- │ └────┬────┘- │ │ recoverable error- │ ▼- │ ┌─────────┐- └────────│ ERROR │- └─────────┘--Special transitions:- any → HIDDEN (fullscreen detected, manual hide, feature disabled)- HIDDEN → idle (fullscreen ended, manual unhide, feature re-enabled)--Coalescing:- any → same state within 16 ms : ignored- TYPING ↔ CLICKING : free transition (no intermediate IDLE step needed)-```--### 6.3 Event sources--| Event | Source (in the Hauptjarvis) | Trigger |-|---|---|---|-| `wakeword_detected` | `jarvis.speech.wakeword` | Porcupine/openWakeWord |-| `utterance_started` | `jarvis.speech.stt` | VAD starts |-| `utterance_ended` | `jarvis.speech.stt` | VAD ends |-| `inference_started` | `jarvis.brain.router` | Brain call started |-| `inference_done` | `jarvis.brain.router` | Brain call finished |-| `action_started{kind=typing}` | `OverlayBridge.action(...)` | Decorator/context-manager fired |-| `action_ended` | `OverlayBridge` | Same |-| `click_event{x, y, monitor}` | `OverlayBridge.click(...)` | Direct emit after pyautogui.click() |-| `tts_started` | `jarvis.speech.tts` | TTS starts |-| `tts_ended` | `jarvis.speech.tts` | TTS ends |-| `tts_audio_rms{rms_db}` | `jarvis.speech.tts` | Optional, for mascot mouth-sync; 30 Hz |-| `error{recoverable, message}` | `jarvis.core.errors` | Recoverable exception caught |--**Implementer discretion:** The exact event names and signatures are left to the implementer, as long as every state transition is derivable from exactly one event source.--### 6.4 Latency budget per transition--| Transition | Budget Hauptjarvis event → overlay visual |-|---|---|-| State change (any → any) | ≤ 50 ms |-| Click event → ripple visible | ≤ 50 ms (perceptual threshold; see §1.4) |-| Cursor move → trail point visible | ≤ 33 ms (1 frame @ 30 Hz, at 60 Hz cursor stream) |-| Typing-indicator update | ≤ 100 ms (less critical, because ambient) |-| Hauptjarvis crash → overlay process killed | ≤ 1 s |-| Overlay crash → restart spawn started | ≤ 3 s (heartbeat timeout) |--Backing research: Forch et al. 2017 — mouse-based interaction latency-perception threshold ~60 ms; Pubnub blog — visual-perception ceiling ~13 ms but acute awareness only from 75–100 ms. We choose 50 ms as a safe target.-------## 7. Visual Design System--### 7.1 Colors--| Token | Hex | Usage |-|---|---|---|-| `--jarvis-yellow-primary` | `#FFC700` | Main glow stroke. Warm, high contrast on dark + light backgrounds |-| `--jarvis-yellow-soft` | `#FFE066` | Cream highlight in the conic sweep |-| `--jarvis-yellow-amber` | `#FFB300` | Drift target on hue rotation; also error-state tint |-| `--jarvis-black` | `#0A0A0A` | Mascot body, text |-| `--jarvis-error-red` | `#FF4D4D` | Only for the `error` state, a short flash |--**Hard rule:** No other colors. No blue, no green, no purple.--### 7.2 Glow geometry--| Token | Value | Notes |-|---|---|---|-| `glow-width` | 14 px | Edge-band width @ 1× DPI |-| `inner-stroke` | 2 px solid | Sharp wire-edge line |-| `box-shadow-inset` | `inset 0 0 6px / 18px` | Gentle inner halo, two stops |-| `feGaussianBlur stdDeviation` | `6, 22` (stacked) | Two-pass bloom |-| `mask-composite` | `exclude` | Punches out interior |-| `mix-blend-mode` | `plus-lighter` | Luminous accumulation (Chrome 105+) |--### 7.3 Animation timings--| Token | Value | Easing |-|---|---|---|-| `period-conic-sweep / typing` | 1.6 s | linear (rotation, anything else throbs) |-| `period-conic-sweep / clicking` | 0.9 s | linear |-| `period-halo-breathe` | 4.2 s | `cubic-bezier(0.25, 0.46, 0.45, 0.94)` (iOS Default) |-| `easing-state-change` | 250 ms | `cubic-bezier(0.4, 0, 0.2, 1)` (Material Standard) |-| `ripple-duration` | 600 ms | `cubic-bezier(0.2, 0.7, 0.3, 1)` |-| `cursor-trail-fade` | 400 ms | `linear` |-| `typing-sweep-period` | 800 ms (single sweep on each keystroke) | linear |--### 7.4 The five components of "liveliness"--Inspired by the Apple Intelligence Glow Effect (jacobamobin/AppleIntelligenceGlowEffect, MIT, SwiftUI, ~50 LoC). Transferred to CSS:--1. **Multi-layer composition with phase offset.** 3–5 layers, each with its own period and a negative `animation-delay` per corner. Each offset by 200 ms.-2. **Easing differentiation.** Material Standard (`cubic-bezier(0.4, 0, 0.2, 1)`) for state transitions; iOS Default (`cubic-bezier(0.25, 0.46, 0.45, 0.94)`) for idle breathing; **strict `linear`** for conic-sweep rotation.-3. **Hue drift.** A small ±15° rotation around the brand yellow. We drift between `#FFC700` (warm), `#FFE066` (cream), `#FFB300` (amber). Never a wide rainbow rotation.-4. **Opacity envelopes.** Each layer breathes 0.25 → 0.65 over 4 s. Never 0 (dead) or 1 (flat).-5. **Organic randomness via simplex noise.** 12 Hz updates on three CSS custom properties (`--hue-drift`, `--halo-a`, `--halo-b`) via the `simplex-noise` JS library (~2 KB). Microsecond cost. Separates "computer animation" from "alive".--### 7.5 Reference algorithm (paraphrased from AppleIntelligenceGlowEffect)--```javascript-// Pseudocode, runs in renderer-function regenerateGradientStops() {- return [- { color: 'var(--jarvis-yellow-primary)', location: Math.random() },- { color: 'var(--jarvis-yellow-soft)', location: Math.random() },- { color: 'var(--jarvis-yellow-amber)', location: Math.random() },- { color: 'var(--jarvis-yellow-primary)', location: Math.random() },- ].sort((a, b) => a.location - b.location);-}--setInterval(() => {- document.documentElement.style.transition = 'background 500ms ease-in-out';- document.documentElement.style.setProperty('--gradient-stops',- stopsToCss(regenerateGradientStops())- );-}, 250);-```--Plus the SVG filter layer for bloom (see §7.6).--### 7.6 SVG filter (bloom layer)--```xml-<filter id="jarvis-glow" x="-15%" y="-15%" width="130%" height="130%">- <feGaussianBlur in="SourceGraphic" stdDeviation="6" result="b1"/>- <feGaussianBlur in="SourceGraphic" stdDeviation="22" result="b2"/>- <feColorMatrix in="b2" type="matrix" result="b2y"- values="1 .2 0 0 .05- .8 .6 0 0 .03- 0 0 0 0 0- 0 0 0 1 0"/>- <feMerge>- <feMergeNode in="b2y"/>- <feMergeNode in="b1"/>- <feMergeNode in="SourceGraphic"/>- </feMerge>-</filter>-```--The `feColorMatrix` shifts the further-blurred pass toward Jarvis yellow, independent of the source stroke color. That is the trick that gives the Apple Intelligence edges their "color-bleed" character.--**Critical:** Extend the filter viewport with negative `x`/`y` (e.g., `x="-15%"`), otherwise the blur clips at the SVG bounds.--### 7.7 What it should **not** be--- ❌ Wide rainbow rotation (off-brand)-- ❌ Pulsing aggressively at a 0.5-second beat (tiring)-- ❌ Sparkles/particles ("AI Magic" cliché)-- ❌ Sound effects on state change (out of scope for the overlay)-------## 8. Trigger Specification--### 8.1 Ground rules--1. **Only the Hauptjarvis triggers.** Sub-agents never. (AD-6)-2. **Only PC actions trigger the Edge-Glow.** Speaking, thinking, listening → no glow.-3. **Latency Hauptjarvis action → overlay glow ≤ 50 ms.** (§6.4)-4. **Same-type events within 16 ms are coalesced.** (AD-17)-5. **The glow appears *before* the action, not after.** If possible: emit() → wait 1 frame → action(). Not critical, but ideal.--### 8.2 Categories of PC actions--| Category | Trigger | Glow state | Source module |-|---|---|---|---|-| **Mouse Click** | `pyautogui.click()`, Browser-Use click, Computer-Use mouse_click | `clicking` + Ripple at coord | `jarvis/control/mouse.py`, plugins |-| **Mouse Move** (extended) | `pyautogui.moveTo()` with duration > 0 | (no state change, but cursor trail active) | ditto |-| **Keyboard Type** | `pyautogui.typewrite()`, Browser-Use type, Computer-Use type | `typing` + bottom-edge sweep on each key | ditto |-| **Browser Navigate** | Browser-Use navigation action | `clicking` (treated as interactive) | `jarvis/plugins/browser_use/...` |-| **Keyboard Hotkey** | `pyautogui.hotkey()`, Computer-Use key | `typing` (without sweep — single event) | ditto |-| **Scroll** | `pyautogui.scroll()` | `clicking` | ditto |--**Implementer discretion:** The exact list of tool names that count as a "PC action" is extensible. The implementer documents the list in a module docstring (`jarvis/overlay/triggers.py`).--### 8.3 Where is instrumentation done?--**Choke-point approach:** There must be a single point in the Hauptjarvis codebase through which all PC actions flow. If it does not yet exist (which is likely, because the code has grown organically over time), it is created as a **pre-phase**:--```-jarvis/control/- __init__.py- mouse.py # Wrappers around pyautogui mouse calls — apply decorator HERE- keyboard.py # Wrappers around pyautogui keyboard calls — apply decorator HERE- browser.py # Wrappers around Browser-Use — apply decorator HERE-```--All other modules (plugins, tools) go through `jarvis.control.*` instead of importing `pyautogui` directly. This gives a clean single point of instrumentation.--**Implementer discretion:** If `jarvis.control.*` already exists or OpenClaw finds a better solution (e.g. instrumentation via an `import-hook` or an aspect-oriented-programming pattern), that may be adopted, as long as the "single point of instrumentation" property is preserved.--### 8.4 Decorator contract--```python-@overlay_action(kind: Literal["click", "type", "move", "navigate", "hotkey", "scroll"], duration_hint_ms: int | None = None)-async def my_action(...) -> ...- """- Decorator emits:- - 'action_started' event with kind to overlay BEFORE function call- - 'action_ended' event AFTER function call (in finally)- - On exception: 'action_ended' + 'error' event with recoverable=True- """-```--Synchronous variant `@overlay_action_sync` for sync functions.--### 8.5 Context-manager contract--```python-async def submit_form(...):- async with overlay_action_scope(kind="typing", duration_hint_ms=2000):- # pyautogui is synchronous — offload via asyncio.to_thread so the- # event loop is not blocked (see §17.1 Performance Budgets).- await asyncio.to_thread(pyautogui.typewrite, text)-```--Identical semantics to the decorator, but inline-applicable.--### 8.6 Direct-emit contract--```python-# Coords are resolved BEFORE the click from the call args (NOT after the-# click, because §14.3 requires the ripple visualization to beat the OS click-# in time). Monitor is derived via MonitorFromPoint(x, y) from the args.-monitor_id = monitor_from_point(x, y)-await overlay_bridge.emit_click(x=x, y=y, monitor=monitor_id) # PRE-click (§14.3)-await overlay_bridge.emit_action_started(kind="click")-await asyncio.to_thread(pyautogui.click, x, y)-await overlay_bridge.emit_action_ended()-```--Manual, for edge cases. The implementer recommends the decorator as the preferred pattern in the module docstring.--### 8.7 Sub-agent detection--`OverlayBridge.emit(...)` must detect whether it runs in the Hauptjarvis or in a sub-agent. Mechanics:--- `OverlayBridge` is a singleton, bound to a `jarvis.config.is_main_process()` check.-- In sub-agents (`JARVIS_DEPTH > 0` env var, see Phase 5 design) `OverlayBridge` is a **no-op stub** that silently does nothing.-- Sub-agent code sees the same interface, but events are sent nowhere.--**Implementer discretion:** The exact detection mechanics (env-var check, IPC flag, other) are the implementer's choice. The "sub-agents do not trigger the overlay" property is hard.--### 8.8 Click-coordinate capture--When a click happens: the `jarvis.control.mouse.click(x, y)` function is instrumented so that the coords are passed to `OverlayBridge.emit_click(x, y, monitor)` **before** the `pyautogui.click()` call — see §14.3 (the ripple must visually beat the OS click). The monitor ID is resolved locally via `MonitorFromPoint(x, y)`; if missing, the overlay derives it. The coords are the args given in the call (pyautogui does no DPI resolution anymore — `SetProcessDpiAwareness(PerMonitorV2)` is applied at startup, see §16).-------## 9. External Interface (Hauptjarvis ↔ Overlay)--### 9.1 Public API (in the Hauptjarvis codebase)--```python-# jarvis/overlay/__init__.py-from jarvis.overlay.bridge import OverlayBridge, overlay_action, overlay_action_scope--# Singleton accessor-def get_overlay() -> OverlayBridge:- """Returns the singleton OverlayBridge for the current process.- In sub-agents (JARVIS_DEPTH>0), returns a no-op stub.- Idempotent. Safe to call from any thread."""--# Configuration / lifecycle-async def start_overlay() -> None: ...-async def stop_overlay() -> None: ...-def is_overlay_enabled() -> bool: ...--# Direct event emit (escape hatch)-async def emit_state(state: OverlayState) -> None: ...-async def emit_click(x: int, y: int, monitor: str | None = None) -> None: ...-async def emit_action_started(kind: ActionKind, duration_hint_ms: int | None = None) -> str: ... # returns action_id-async def emit_action_ended(action_id: str) -> None: ...-async def emit_error(message: str, recoverable: bool = True) -> None: ...--# Decorator / Context-Manager-@overlay_action(kind="click")-def some_function(...): ...--async with overlay_action_scope(kind="typing"):- ...-```--### 9.2 Required caller documentation--Every caller of `emit_*` or `@overlay_action` must document in the code:-- **What kind of action it is** (in a module/function docstring).-- **Why it counts as an interactive PC action** (if non-obvious).--Example:--```python-@overlay_action(kind="click", duration_hint_ms=100)-async def click_button(button_locator: str) -> None:- """Click a button via Browser-Use.-- Counts as an interactive PC action because it directly drives the- browser to perform a click that the user can see.- """- ...-```--### 9.3 What the Hauptjarvis should NOT do--- ❌ Directly open a WS connection to the overlay. `OverlayBridge` does that internally.-- ❌ Duplicate state logic in the Hauptjarvis ("if I'm typing right now, I know the overlay is typing"). The state machine lives in the overlay (AD-8). The Hauptjarvis sends events.-- ❌ Wait synchronously for overlay reactions. All emits are fire-and-forget. If the overlay is down, it does not matter — the Hauptjarvis must not hang.-- ❌ Send sensitive data (API keys, passwords, voice audio) to the overlay. Never.-------## 10. IPC Protocol--### 10.1 Wire envelope (all channels)--```json-{- "v": 1,- "type": "state | click | action_started | action_ended | cursor | heartbeat | config | ack | error",- "id": "01HX9...ULID",- "ts_ns": 1714478400123456789,- "target": "edgeglow | mascot | *",- "payload": { /* per-type, see below */ }-}-```--| Field | Type | Notes |-|---|---|---|-| `v` | int | Schema version. Major bump = breaking. Currently `1`. |-| `type` | enum | Discriminant for payload schema |-| `id` | string (ULID) | Unique per message; for dedup and ack-correlation |-| `ts_ns` | int (ns since unix epoch) | Sender wallclock; for latency-debugging |-| `target` | enum | `*` = all overlay components |-| `payload` | object | Type-specific (see §10.2) |--### 10.2 Payload schemas--**state**-```json-{ "state": "idle | listening | thinking | typing | clicking | speaking | error | hidden",- "intensity": 1.0,- "since_ts_ns": 1714478400000000000,- "reason": "wakeword | user | tool | timeout | error" }-```--`intensity` (float, range `0.0..1.0`, normalized) modulates the visual strength of the current state — consumed by §14.1's CSS `--intensity` driver (mapped: `0.0` → lower state default, `1.0` → upper bump). Per-state defaults:--| State | intensity default | Effect |-|---|---|---|-| `idle` | 0.0 | Glow off (see §6.1 — only typing/clicking are on) |-| `hidden` | 0.0 | Glow off |-| `listening` | 0.6 | medium wake-word shimmer (if enabled) |-| `thinking` | 0.7 | slightly above, gentle pulse |-| `typing` | 1.0 | full sweep visual (§14.1) |-| `clicking` | 1.0 | full ripple visibility |-| `speaking` | 0.8 | TTS-driven modulation (see §13.2 mouth_intensity) |-| `error` | 1.0 | full error tint, no sub-bump |--**click**-```json-{ "x": 1024, "y": 768,- "monitor": "\\\\.\\DISPLAY1",- "button": "left | right | middle",- "modifiers": ["ctrl", "shift"],- "wallclock_ns": 1714478400500000000 }-```--**action_started**-```json-{ "kind": "click | type | move | navigate | hotkey | scroll",- "action_id": "01HX9...ULID",- "duration_hint_ms": 2000 }-```--**action_ended**-```json-{ "action_id": "01HX9...ULID",- "succeeded": true,- "duration_actual_ms": 1953 }-```--**cursor** (only sent if SHM is unavailable; normally cursor uses SHM)-```json-{ "x": 512, "y": 384, "monitor": "\\\\.\\DISPLAY1" }-```--**heartbeat** (bidirectional, 1 Hz)-```json-{ "uptime_s": 1234,- "rss_mb": 78.5,- "fps_actual": 59.8,- "fps_target": 60,- "drops": 0,- "ws_connected": true,- "shm_attached": true }-```--**config** (Hauptjarvis → Overlay, on config-reload)-```json-{ "theme": { "yellow_primary": "#FFC700", ... },- "mascot_enabled": true,- "mascot_pos": { "monitor": "\\\\.\\DISPLAY1", "x": 200, "y": 80 },- "fps_active": 30,- "fps_burst": 60,- "all_monitors": false,- "hide_on_fullscreen": true,- "hide_from_capture": true,- "respect_reduced_motion": true,- "shm_cursor_name": "jarvis-cursor-7f3e",- "shm_cursor_hz": 60 }-```--**ack** (Overlay → Hauptjarvis, optional, only for state-changes that have caller waiting)-```json-{ "ack_id": "01HX9...ULID", // id of the message being acked- "received_ts_ns": 1714478400123000000,- "rendered_ts_ns": 1714478400140000000 // optional, if measurable-}-```--**error**-```json-{ "code": "schema_invalid | render_failed | shm_unavailable | ...",- "message": "human-readable",- "recoverable": true,- "context": { /* free-form */ } }-```--### 10.3 Validation--- **Python side:** Pydantic v2 models in `jarvis/overlay/schema.py`.-- **TS side:** Zod schemas in `overlay-ui/src/schema.ts`.-- **CI gate:** `pytest tests/overlay/test_schema_symmetry.py` — exports JSON Schema from Pydantic, parses the Zod schema, compares structurally. CI fails on drift.--### 10.4 Backpressure--- Outbound queue (Python → Overlay) bounded at **256 messages**. If full: drop oldest non-state messages first (cursor, ack), drop state messages last. Log a warning. **Never block sender.**-- Inbound queue (Overlay → Python) bounded at **64 messages**.-- Coalescing per AD-17 happens at send-time, before queueing.--### 10.5 Reconnection Logic--- **Heartbeat interval:** 1 s (each side sends).-- **Heartbeat timeout:** 3 s. If no heartbeat received for 3 s, assume connection broken, attempt reconnect.-- **Reconnect-backoff:** 0.5 s, 1 s, 2 s, 4 s, 8 s, 30 s (cap).-- **Reconnect on either side:** Initial connection is always Overlay → Hauptjarvis (Hauptjarvis is the WS-server). If WS drops, Overlay attempts reconnect.-- **State-resync after reconnect:** Hauptjarvis sends current state as first message after reconnect; Overlay re-renders.--### 10.6 Channel-Routing--- Overlay process listens on **one** WS connection.-- Inside the Overlay process, messages are routed by `target` field to the appropriate Window (edge-glow, mascot, *).-------## 11. Shared Memory Layout--Cursor stream uses a fixed-layout `multiprocessing.shared_memory` block. Single-writer (Hauptjarvis), single-reader (Overlay). No locks needed — monotonic sequence counter gives lock-free read consistency.--### 11.1 Block Definition--- **Name:** `jarvis-cursor-{8 hex chars}` (random per-session, so multi-instance doesn't collide).-- **Size:** 32 bytes (fits one cache line on x86-64).--### 11.2 Byte Layout--| Offset | Size | Type | Field | Notes |-|---|---|---|---|---|-| 0 | 8 | int64 LE | `ts_ns` | Wallclock (Unix-epoch ns); written via `time.time_ns()`. Comparable across §10.1 envelope `ts_ns` and §10.2 `wallclock_ns` / `received_ts_ns` / `rendered_ts_ns` for cross-channel latency-debugging. |-| 8 | 4 | int32 LE | `x` | Physical pixel x |-| 12 | 4 | int32 LE | `y` | Physical pixel y |-| 16 | 4 | uint32 LE | `seq` | Monotonic sequence counter (writer-local; see §11.4 write-pattern) |-| 20 | 4 | uint32 LE | `monitor_idx` | Index into `QGuiApplication.screens()` |-| 24 | 8 | reserved | — | Padding to 32 |--### 11.3 Read pattern (Overlay)--Canonical seqlock pattern: an odd `seq` = writer mid-write (busy), an even `seq` = quiescent. The reader retries if busy or torn:--```python-# Pseudocode-def read_cursor():- seq_before = read_uint32_le(buf, offset=16)- if seq_before & 1:- return None # writer mid-write (odd seq) — retry next frame- if seq_before == self._last_seq:- return None # no new data- ts = read_int64_le(buf, offset=0)- x = read_int32_le(buf, offset=8)- y = read_int32_le(buf, offset=12)- monitor = read_uint32_le(buf, offset=20)- seq_after = read_uint32_le(buf, offset=16)- if seq_before != seq_after:- return None # writer started a new frame during our read — torn, retry- self._last_seq = seq_after- return (ts, x, y, monitor)-```--Read at 60 Hz from a `requestAnimationFrame` loop in the renderer (via a WebChannel bridge to Python that reads SHM, or directly if Python exposes an SHM-reader tick to JS). **Implementer discretion:** the exact bridge mechanism is up to the implementer.--### 11.4 Write pattern (Hauptjarvis)--Canonical seqlock writer: bump `seq` to odd first (busy marker), then write data, finally bump to even (done):--```python-# Pseudocode, called at 60 Hz when cursor-stream is enabled-def write_cursor(x, y, monitor_idx):- seq = self._seq + 1 # odd → BUSY- write_uint32_le(buf, offset=16, value=seq)- ts = time.time_ns() # Unix-epoch ns wallclock — comparable to §10.1/§10.2 timestamps- write_int64_le(buf, offset=0, value=ts)- write_int32_le(buf, offset=8, value=x)- write_int32_le(buf, offset=12, value=y)- write_uint32_le(buf, offset=20, value=monitor_idx)- seq += 1 # even → DONE- write_uint32_le(buf, offset=16, value=seq)- self._seq = seq-# `_seq` starts at 0 (even), so the first published frame ends with seq=2.-```--**Critical:** The single-counter pattern without an odd-busy marker is NOT a real seqlock and allows torn reads when reader and writer interleave before the writer bumps the counter. With the odd/even pattern here, the reader can detect any mid-write state (`seq & 1 == 1`) and distinguish two complete write operations (`seq_before != seq_after`).--**Why `time.time_ns()` (not `time.monotonic_ns()`):** the SHM cursor stream is correlated cross-channel against the WS envelope `ts_ns` (§10.1) and the click payload's `wallclock_ns` (§10.2) for latency-debugging. `time.monotonic_ns()` has an arbitrary per-process epoch (anchored to system boot or process start), so cross-clock subtraction would yield meaningless deltas — typically off by ~10¹⁸ ns (≈ negative 50 years). All three channels use Unix-epoch ns from `time.time_ns()` so debugging math is well-defined. Monotonicity is provided separately by `seq`.--### 11.5 When SHM is Disabled--If SHM creation fails (rare) or `cursor_trail_enabled = false`:-- Cursor-stream falls back to WS messages (`type: "cursor"`) at reduced frequency (10 Hz instead of 60 Hz).-- Overlay automatically detects via `config` message which channel to use.-------## 12. Window Management--### 12.1 Edge-Glow-Window--**Per-monitor.** One instance per `QGuiApplication.screens()` entry (unless `overlay.all_monitors = false`, then only `primaryScreen()`).--**Window flags:**-```python-window.setWindowFlags(- Qt.WindowType.FramelessWindowHint- | Qt.WindowType.WindowStaysOnTopHint- | Qt.WindowType.WindowTransparentForInput # → WS_EX_TRANSPARENT|WS_EX_LAYERED- | Qt.WindowType.Tool # excluded from taskbar/Alt+Tab- | Qt.WindowType.NoDropShadowWindowHint-)-window.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)-window.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True)-window.setAttribute(Qt.WidgetAttribute.WA_NoSystemBackground, True)-window.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, True)-```--**Geometry:** `screen.geometry()` (full physical monitor, in logical pixels — Qt handles DPI conversion).--**Privacy:** After `show()`, call `SetWindowDisplayAffinity(hWnd, WDA_EXCLUDEFROMCAPTURE)` via `ctypes`/`pywin32`.--**Renderer:** `QWebEngineView` with `setAttribute(Qt.WA_TranslucentBackground, True)` and a transparent background page. Page loads `overlay-ui/dist/edge-glow.html`.--### 12.2 Mascot-Window--**Single instance.** Spawned only if `overlay.mascot_enabled = true` (top-level key under `[overlay]`, NOT inside `[overlay.mascot]` — see §21.1 Schema).--**Window flags:**-```python-mascot.setWindowFlags(- Qt.WindowType.FramelessWindowHint- | Qt.WindowType.WindowStaysOnTopHint- # NOTE: NO WindowTransparentForInput — mascot needs to receive clicks- | Qt.WindowType.Tool- | Qt.WindowType.NoDropShadowWindowHint-)-mascot.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)-mascot.setAttribute(Qt.WidgetAttribute.WA_NoSystemBackground, True)-```--Plus Win32 extension via ctypes (because Qt doesn't expose all flags):-```python-GWL_EXSTYLE = -20-WS_EX_LAYERED = 0x00080000-WS_EX_NOACTIVATE = 0x08000000-WS_EX_TOOLWINDOW = 0x00000080-hwnd = int(mascot.winId())-ex = ctypes.windll.user32.GetWindowLongW(hwnd, GWL_EXSTYLE)-ctypes.windll.user32.SetWindowLongW(- hwnd, GWL_EXSTYLE, ex | WS_EX_LAYERED | WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW-)-```--**Hit-region via `setMask(QRegion)`:** Per-pixel-alpha hit-testing is **NOT** automatic for Qt's `WA_TranslucentBackground` path (which is DWM-composited, not the legacy `UpdateLayeredWindow(ULW_ALPHA)` path). Without an explicit hit-region, the entire 160×160 client rect would capture clicks — blocking ~21 % of the box (transparent corners around the silhouette) for click-through. Fix: install a circular `QRegion` matching the silhouette so transparent corners pass clicks through to the desktop.--```python-from PySide6.QtCore import QRect-from PySide6.QtGui import QRegion--# Approximate silhouette as inscribed circle (cheap, works for any pose).-mascot.setMask(QRegion(QRect(0, 0, 160, 160), QRegion.Ellipse))-```--For finer hit-tracking when the Rive pose changes significantly, optionally rebuild the mask from the current alpha buffer on each animation transition (not per-frame — too costly). For V1 the static circular region is sufficient.--**Drag-handling:** Implement `mousePressEvent` + `mouseMoveEvent` + `mouseReleaseEvent` for drag. Drag is initiated only inside the `setMask` region. Implementer discretion: alternative JS path `mouse-down → window.draggable = true → window.move()` if rendering inside the WebView.--**Right-click menu:** Standard `QMenu` with "Hide", "Move to default position", "Settings...".--**Privacy:** Same `WDA_EXCLUDEFROMCAPTURE` treatment.--### 12.3 Per-Monitor DPI Awareness--**Manifest** (`pyproject.toml` → `[tool.briefcase.windows]` or analogous, depending on packaging):--```xml-<asmv3:application xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">- <asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">- <dpiAwareness>PerMonitorV2</dpiAwareness>- </asmv3:windowsSettings>-</asmv3:application>-```--**Code-side fallback:**-```python-import ctypes-ctypes.windll.shcore.SetProcessDpiAwareness(2) # PROCESS_PER_MONITOR_DPI_AWARE-```--**Handling DPI changes mid-session:** Listen for `screenChanged` signal on each window and recompute geometry. Qt mostly handles this transparently; implementer should test the case `monitor unplugged at runtime` explicitly.--### 12.4 WDA_EXCLUDEFROMCAPTURE Win11 Quirk--Some Win11 builds fail to honor `WDA_EXCLUDEFROMCAPTURE` on Chromium-WebView2 child windows (Microsoft Q&A 700122). Mitigation:--- The Qt window IS a top-level Win32 HWND (no quirk).-- The WebEngineView is a child of the Qt window, gets clipped by the parent, doesn't render outside parent bounds.-- Affinity flag is set on the Qt top-level HWND.-- In practice this works for the layered-host pattern.--Implementer should test with OBS, Snipping Tool, and a Teams-share to verify.--### 12.5 Multi-Monitor Hotplug--- Subscribe to `QGuiApplication.screenAdded(QScreen*)` and `screenRemoved(QScreen*)`.-- On `screenAdded`: if `all_monitors = true`, instantiate new edge-glow-window for that screen.-- On `screenRemoved`: dispose any window pointing to that screen. Mascot-recovery (see §13.4).--### 12.6 Always-on-top Limitations--Universal across all GUI stacks (not a Qt limitation):-- **D3D Exclusive Fullscreen** (e.g., some games): `HWND_TOPMOST` doesn't draw over.-- **UAC Secure Desktop**: never drawn over.-- **Lock Screen**: never drawn over.--**Mitigation:** `SHQueryUserNotificationState` polled every 2 s on a low-priority thread. On `QUNS_RUNNING_D3D_FULL_SCREEN`, `QUNS_PRESENTATION_MODE`, or `QUNS_BUSY` (configurable), transition to `hidden` state.-------## 13. Mascot Specification--### 13.1 Visual Concept--Small, geometric, friendly — not anime, not Clippy, not corporate. **Black-and-yellow only.**--Design direction (implementer discretion):-- A simple rounded shape (could be a "J" monogram with eyes, a stylized circle with a face, a hexagon with subtle features, etc.).-- Dark body (`--jarvis-black` or near-black with yellow accents).-- Eyes (or eye-stand-in) that can change to indicate state: closed/relaxed (idle), open/wide (listening), focused (thinking), animated (speaking).-- 160×160 px default size. Scale-able via config (clamped to 80–256 px).--**The mascot is NOT a personality.** It's a status indicator with charm. No "speech bubbles", no winking, no wandering around the screen. It stays where the user puts it.--**Implementer discretion:** The exact mascot illustration is up to the implementer. Free choice as long as: black + yellow, geometric (not anime/photoreal), state-readable, ≤ 80 KB Rive asset.--### 13.2 State Animations--Each Rive State Machine input maps 1:1 to an OverlayState:--| Rive Input | Type | Triggered when state == |-|---|---|---|-| `idle` | trigger | `idle` |-| `listening` | trigger | `listening` |-| `thinking` | trigger | `thinking` |-| `acting` | trigger | `typing` or `clicking` |-| `speaking` | trigger | `speaking` |-| `error` | trigger | `error` |-| `mouth_intensity` | number 0..1 | continuously updated from `tts_audio_rms` |--### 13.3 Drag Behavior--- **Click + hold + drag** moves the mascot.-- Position persisted on `mouseRelease`.-- Snaps to monitor edges within 16 px tolerance (gentle "magnetic" feel).-- Cannot be dragged off-screen (clamped to monitor work-area minus 16 px margin).--### 13.4 Position Persistence + Monitor Recovery--Persist to `jarvis.toml` under `[overlay.mascot]`:-```toml-position_monitor = "\\\\.\\DISPLAY1" # device name (szDevice from GetMonitorInfo)-position_x_relative = 200 # pixels from monitor's top-left work-area-position_y_relative = 80-```--**Why szDevice only (not EDID):** `EnumDisplayMonitors` + `GetMonitorInfoW` (the only enumeration APIs we use) return `szDevice` (e.g. `\\.\DISPLAY1`) but **not** EDID. Retrieving EDID would require a separate path (WMI `WmiMonitorID`, `SetupDi*`, or registry under `HKLM\SYSTEM\CurrentControlSet\Enum\DISPLAY\…\Device Parameters\EDID`) — out of scope for V1. `szDevice` matching is therefore best-effort across port-swaps; the deterministic fallback in step 3 handles the case where the saved device name is gone.--**On startup:**-1. Enumerate live monitors via `EnumDisplayMonitors` + `GetMonitorInfoW`. Build a map `{szDevice → (rcWork, hMonitor)}`.-2. Look up `position_monitor` (the persisted `szDevice`) in the map.- - **Found:** Restore mascot at `(rcWork.left + position_x_relative, rcWork.top + position_y_relative)`. Clamp into `rcWork` minus 16-px margin if the relative offset would put the mascot off the work-area (covers the case of resolution changes on the same monitor).-3. **Not found** (laptop undocked, port-swapped, monitor unplugged) — deterministic fallback:- - Pick the **primary monitor** via `MonitorFromWindow(hwnd_desktop, MONITOR_DEFAULTTOPRIMARY)`.- - Place mascot at the **default position** for that monitor: `(rcWork.left + 200, rcWork.top + 80)`.- - Log `mascot.position_recovered = "primary_fallback"` to telemetry; user's customized relative offset is intentionally discarded because it was anchored to a now-missing virtual-desktop region that cannot be reconstructed from the persisted relative coords alone.-4. Listen to `WM_DISPLAYCHANGE` and `WM_DEVICECHANGE` (via Qt's `screenAdded`/`screenRemoved`); on event re-run steps 1–3.-5. Validate the final placement against `GetSystemMetrics(SM_X/Y/CX/CYVIRTUALSCREEN)` as last sanity-check; if outside virtual-screen bounds for any reason, force-clamp into primary `rcWork`.--### 13.5 Hide / Disable Toggles--- **Right-click → "Hide for this session"**: mascot hidden, re-appears on next Jarvis-start.-- **Tray-Icon-Menu → "Show Mascot"**: re-show after session-hide.-- **Config: `overlay.mascot_enabled = false`** (top-level key, see §21.1): mascot never spawns. Window-process doesn't even create the mascot HWND.--### 13.6 What Mascot Does NOT Do--- ❌ Wander around the screen (Open-LLM-VTuber's "pet mode" pattern).-- ❌ Speak in speech-bubbles ("Hi! I see you're trying to write a letter…").-- ❌ React to user mouse movements ("looking at you" pattern).-- ❌ Play sounds.-- ❌ Spawn additional windows or popups.-- ❌ Draw attention to itself when nothing is happening (idle pulse is gentle, not eye-catching).-------## 14. Click Visualization--### 14.1 Visual--When `click` event arrives:-- Spawn a `<div>` at the click coordinate.-- Initial size: 8×8 px circle, opacity 1.-- Animate via CSS to: scale(40), opacity 0, over 600 ms with `cubic-bezier(0.2, 0.7, 0.3, 1)`.-- Color: yellow gradient with falloff:- ```css- background: radial-gradient(circle,- var(--jarvis-yellow-primary) 0%,- rgba(255, 199, 0, 0.25) 60%,- transparent 70%);- box-shadow: 0 0 24px 6px rgba(255, 199, 0, 0.55);- ```--### 14.2 Performance--- **Pre-warm a div pool of 8 reusable divs** to avoid `appendChild` jank during burst clicks.-- CSS animations only on `transform: scale()` and `opacity` (compositor-thread-safe).-- After 600 ms: reset div, return to pool.--### 14.3 Latency Budget--End-to-end target ≤ 50 ms:-- pyautogui `click()` → OS event: ~5 ms-- WS send: ~1–3 ms-- WS recv + DOM/paint: ~12–17 ms-- **Total: ~20–25 ms.** Comfortably under budget.--**Critical implementation detail:** Issue WS-send-emit **first**, then `pyautogui.click()` second. Order matters because the visual should reach the WebView **before** the OS click finishes propagating, so the user sees the ripple at the moment of impact rather than after.--### 14.4 Coordinate Transformation--- Hauptjarvis sends physical pixel coords (Win32 native, what pyautogui uses).-- Overlay renderer converts to CSS-logical-pixels: `cssX = physicalX / window.devicePixelRatio`.-- Per-monitor: ripple is rendered in the monitor that owns the click coord. If `all_monitors = false`, ripples on non-primary monitors are silently dropped.--### 14.5 Edge Cases--- **Click coordinates outside any monitor** (rare; can happen with stale screen-config): drop silently, log warning.-- **Click during HIDDEN state** (e.g., fullscreen game): drop silently. We don't visualize what we can't draw.-- **Multiple clicks within 50 ms** (rapid double-click): each gets a ripple. They overlap visually — that's fine.-------## 15. Cursor Trail--### 15.1 Visual--A subtle yellow trail follows Jarvis' cursor when Hauptjarvis is moving the mouse.--- Tail of 20 points, 16-px-radius circles.-- Each point fades over 400 ms (`linear`), so the trail length is ~20 points × (1000 / 60) ms = ~333 ms of trail.-- Color: `--jarvis-yellow-primary` with opacity 0.35 → 0.--### 15.2 Rendering--- **Canvas-2D in an OffscreenCanvas in a Web Worker.** Avoids main-thread re-rendering.-- Ring-buffer of 20 points; on each frame, draw all points with their respective opacity.-- `globalCompositeOperation = 'lighter'` for luminous accumulation.--### 15.3 Source--- **60 Hz cursor stream over SHM** (see §11).-- Hauptjarvis writes cursor position **only when** an action is in progress (i.e., `OverlayBridge` is in an active `action_started` scope). Idle = no writes.-- Overlay reads SHM at 60 Hz from the renderer.--### 15.4 When Disabled--- `cursor_trail_enabled = false` in config → SHM not allocated, renderer doesn't read.-- Mid-session toggle: `config` message updates `shm_cursor_name` to empty, renderer stops reading.-------## 16. Typing Indicator--### 16.1 Visual--Bottom-edge sweep effect on each keystroke when Hauptjarvis is in `typing` state.--- A thin yellow line (4px tall) at the bottom edge of the screen.-- Each keystroke triggers a 200ms `transform: translateX` from -100% to +100%.-- Plus: `--intensity` CSS variable bumps from 0.85 to 1.2 for 200 ms.--### 16.2 Why Not Character-Confetti--Character-by-character confetti effects (à la some chat apps) read as gimmicky for an assistant overlay. Subtle is the right register.--### 16.3 Optional Caret-Localized Pulse (V2)--Caret-following micro-pulse (using `uiautomation` Python wrapper to query the current focused control's caret rect via `TextPattern2.GetCaretRange().GetBoundingRectangles()`) is **out of scope for V1** — uiautomation calls can block 50–200 ms in unhealthy app trees, and the bottom-edge sweep is sufficient.--V2 candidate if user wants more visual feedback.-------## 17. Performance Budgets--### 17.1 Hard Ceilings--| Resource | Idle | Active | Hard Ceiling | Action if breached |-|---|---|---|---|---|-| **Overlay process CPU** | < 0.5% | < 3% | 5% | Throttle FPS, log warning |-| **Overlay process GPU** | < 0.5% | < 2% | 5% | Reduce glow complexity |-| **Overlay process RSS** | 60–100 MB | 80–140 MB | 200 MB | Restart process |-| **Network (WS)** | ~50 B/s | ~5 KB/s | 50 KB/s | Throttle event-emission |-| **Battery delta** | < 1%/h | < 3%/h | 5%/h | Force throttle |--### 17.2 FPS Targets per State--| State | FPS Target |-|---|---|-| `hidden` | 0 (paused) |-| `idle` (no glow) | 1 (mascot only, breath animation) |-| `listening` / `thinking` / `speaking` | 30 (mascot anim only) |-| `typing` / `clicking` (with glow) | 60 (compositor-driven) |-| `error` (red flash) | 60 for 600 ms, then back to source state |--### 17.3 Throttling Strategy--- **Idle Detection:**- - 30 s no events → mascot drops to 1 fps, edge-glow frozen.- - 5 min no events → set WebView `IsVisible = false` (Chromium throttles hidden views).--- **Wake on Event:**- - Any state change or click event → bump back to target FPS within 1 frame.--- **AC vs Battery:**- - `GetSystemPowerStatus`. On battery: halve all FPS targets (60→30, 30→15). Skip cosmetic particle effects.--- **Adaptive on perf-budget breach:**- - If heartbeat reports CPU > 5% for 3 consecutive seconds: drop FPS by 50%, log warning. If still over budget after 30 s: force `hidden` state and surface tray-warning.--### 17.4 Telemetry--Heartbeat (1 Hz) reports `rss_mb`, `fps_actual`, `fps_target`, `drops`. Hauptjarvis-side `OverlaySupervisor` keeps a rolling 60-sample window. On budget breach, log a `WARNING`-level entry to `jarvis.log` (no separate audit log per AD-18).-------## 18. Privacy & Safety--### 18.1 Hide-from-Capture Default--`SetWindowDisplayAffinity(hWnd, WDA_EXCLUDEFROMCAPTURE)` on every overlay HWND, every monitor, mascot included. Default-on.--User can opt-out via `overlay.hide_from_capture = false` in TOML.--**Reapply:** On `WM_DPICHANGED`, on `screenAdded`, after each `show()`.--### 18.2 No User Data Through Overlay--Hard rules:-- ❌ Voice audio NEVER through overlay.-- ❌ STT transcripts NEVER through overlay.-- ❌ LLM prompts/responses NEVER through overlay.-- ❌ API keys, credentials, OAuth tokens NEVER through overlay.-- ❌ Clipboard contents NEVER through overlay.--The only data flowing to the overlay:-- Coarse states (idle/listening/typing/...).-- Click coordinates (pixel positions, not what's at those positions).-- Cursor positions.-- TTS RMS levels (a single number; can't be reverse-engineered to audio content meaningfully).--### 18.3 Voice-Loop Isolation--Overlay process **NEVER** imports `jarvis.speech.*` or any audio module. Enforced via:-- Process-boundary (separate Python interpreter).-- Code-organization (overlay module tree has no `import jarvis.speech.*`).-- Lint-rule (CI-test that greps for forbidden imports in `os-level/`).--### 18.4 Credentials / Secrets--Overlay never reads `jarvis.toml`'s sensitive sections. It only receives the `[overlay]` section subset via the `config` IPC message, which Hauptjarvis filters before sending.--### 18.5 Network--**The Hauptjarvis** binds the WS listener on **`127.0.0.1` only** (not `0.0.0.0`) — see §10.5 (the Hauptjarvis is the WS server, the overlay is the client). Port chosen from a small range (default 7842). No auth (loopback-only is the security boundary).--**Implementer note:** The §24.4 DoD check ("WS port bound to `127.0.0.1` only — verified via `netstat`") looks at the Hauptjarvis process, not the overlay subprocess.--### 18.6 Code signing / EXE distribution--(Out of scope for V1, but flagged for future:) when packaged via Briefcase or PyInstaller, signed with the project's code-signing cert. Helps SmartScreen / AV-scanners not flag the overlay process.-------## 19. Accessibility--### 19.1 prefers-reduced-motion--```css-@media (prefers-reduced-motion: reduce) {- .edge-glow {- animation: none;- /* Replace animation with static low-intensity glow */- opacity: 0.4;- }- .ripple { animation-duration: 200ms; }- .mascot { animation-play-state: paused; }-}-```--Detected from Windows accessibility settings (Animations setting) via the OS-level media query that Chromium honors automatically.--### 19.2 Disable-Animations Toggle--User setting `overlay.respect_reduced_motion = true` (default) → CSS query honored. Setting `false` → animations always run regardless of OS setting (for users who explicitly want them despite reduced-motion preference).--Additional toggle `overlay.animations_enabled = true` → master switch. False = static low-intensity overlay only (no movement at all).--### 19.3 Screen Reader Compatibility--- All overlay HWNDs have `WS_EX_TOOLWINDOW` → screen readers usually skip them.-- Set `accessible role = "presentation"` on the renderer's root element so JAWS/NVDA don't try to announce glow animation states.-- Mascot has ARIA-label `"Jarvis status indicator"`; screen readers announce it once on focus.--### 19.4 High-Contrast Mode--- Detect via the `@media (forced-colors: active)` CSS query — that is the W3C standard query for OS-imposed forced-color schemes (Windows High Contrast Mode triggers it in Chromium). `prefers-contrast` would be wrong (it applies to user-preference modes such as macOS "Increase Contrast", not Windows HC), and `prefers-contrast: high` is not even a valid value (MQ5 allows only `no-preference | more | less | custom`).-- In high-contrast mode: drop the bloom blur (visual noise); use a solid 4-px stroke with the `CanvasText` system color (conformant to the user's HC theme). No `mix-blend-mode`, no acrylic, no gradients.-- Mascot: switch to a high-contrast variant (implementer discretion: simpler outline, fewer details).-- Example:- ```css- @media (forced-colors: active), (prefers-contrast: more) {- .edge-glow { filter: none; border: 4px solid CanvasText; }- .mascot { /* high-contrast variant */ }- }- ```--### 19.5 Color-Blind Safety--Yellow on dark monitors works for all common color-blindness types (deuteranopia, protanopia, tritanopia). No additional mitigation needed for V1. Verifiable via Coblis or similar simulation tool.-------## 20. Edge Cases (complete enumeration)--### 20.1 Display & Monitor--| Edge Case | Handling |-|---|---|-| **Multi-monitor (default)** | Per-monitor windows, primary-only by default |-| **Monitor hotplug (add)** | `screenAdded` listener; spawn new window if `all_monitors = true` |-| **Monitor hotplug (remove)** | `screenRemoved` listener; dispose window; recover mascot to nearest monitor |-| **DPI change mid-session** | Qt's `screenChanged` signal triggers recompute; verify under per-monitor-V2 |-| **Vertical monitor (90° rotated)** | Use `screen.geometry()` which respects rotation; glow follows the rotation |-| **Ultra-wide monitor (21:9, 32:9)** | Standard handling; conic-gradient adapts naturally to aspect ratio |-| **Monitor with extreme DPI (300%+)** | PerMonitorV2 ensures geometry stays right; visuals scale proportionally |-| **Monitor refresh rate >60 Hz (240, 360 Hz)** | Compositor-driven CSS animations (see AD-2) are essentially free at idle (DWM throttled). If a real FPS cap is needed: JS-driven `requestAnimationFrame` with timestamp-delta gating at ~16.6 ms (CSS `animation-iteration-count` is NOT FPS-related — it controls only the number of cycles, not the sampling rate). Default: accept the native cadence. |-| **Monitor refresh rate <60 Hz (50 Hz EU)** | Animations work fine; perceived speed slightly slower (linear easing on rotation makes this OK) |-| **Variable refresh rate (G-Sync, FreeSync)** | Standard browser handling; no special action |-| **HDR mode** | Yellow `#FFC700` is well within sRGB; renders correctly. No display-p3 / scRGB needed for V1 |-| **Mixed DPI displays (4K + 1080p)** | Per-monitor windows give correct DPI per surface |--### 20.2 Window-State--| Edge Case | Handling |-|---|---|-| **Fullscreen exclusive (D3D)** | `SHQueryUserNotificationState == QUNS_RUNNING_D3D_FULL_SCREEN` → `hidden` state |-| **Borderless fullscreen** | Foreground-window-rect equals monitor-rect heuristic + no `WS_CAPTION` → `hidden` |-| **UAC secure desktop** | Universal limitation; nothing to do |-| **Lock screen** | Universal limitation; nothing to do |-| **Remote Desktop session** | Detect via `GetSystemMetrics(SM_REMOTESESSION)`; auto-disable overlay (latency too high for visual feedback) |-| **Game Mode (Xbox Game Bar)** | Auto-detect via `QUNS_BUSY` heuristic; configurable opt-out |-| **Tablet Mode** | (Win11 has dropped Tablet Mode but for legacy: adjust mascot size, keep glow) |-| **Multi-user fast user switching** | Hauptjarvis is per-user; overlay is per-Hauptjarvis. No cross-talk possible |-| **System sleep** | `WM_POWERBROADCAST PBT_APMSUSPEND` → pause animations, save mascot state. On `RESUME`: re-init |-| **Theme change (light ↔ dark)** | No-op; glow yellow works on both |--### 20.3 IPC & Process--| Edge Case | Handling |-|---|---|-| **WS port already in use** | Pick next port, retry up to 10 ports. If all blocked: fall back to named pipe |-| **Backend crash mid-action** | Heartbeat-timeout in 3 s → overlay transitions to `idle` autonomously, attempts reconnect |-| **Overlay crash mid-frame** | Hauptjarvis' supervisor detects via 3-s heartbeat-timeout; spawns new overlay process |-| **Two state-changes within 16 ms** | Coalesce per AD-17 |-| **State change while overlay is mid-animation** | New state interrupts; CSS-transition between intensities |-| **Click coordinates outside any monitor** | Drop silently, log warning |-| **Cursor coordinates outside any monitor** | Drop silently |-| **WS message with unknown `type`** | Log warning, ignore; forward-compatible |-| **WS message with invalid schema** | Log warning, send `error` reply, ignore message |-| **Schema-version mismatch (`v` field)** | Log error, request newer overlay-update; continue with current schema if compatible |-| **Network unavailability for localhost (rare)** | Should never happen for loopback; if WS-bind to `127.0.0.1` fails, use named-pipe |-| **Hauptjarvis sends 1000 events in 100 ms** | Bounded queue (256 msgs), drops oldest non-state messages first |--### 20.4 Mascot--| Edge Case | Handling |-|---|---|-| **Mascot dragged off-screen** | Clamp to `rcWork` minus 16-px margin during drag |-| **Mascot's saved monitor disappears** | Snap to nearest live monitor's nearest valid position |-| **Two mascots accidentally spawned** | Singleton-check at startup; second spawn gets ignored, log warning |-| **Mascot drag while state is changing** | State updates continue normally; drag is independent |-| **User right-clicks mascot during animation** | Menu opens normally; animation continues in background |-| **Mascot Rive file fails to load** | Fall back to static PNG (implementer discretion: include a fallback PNG) |-| **System DPI change during drag** | Stop drag, recalculate position, resume |--### 20.5 Performance--| Edge Case | Handling |-|---|---|-| **Battery saver mode active** | Halve all FPS targets, skip cosmetic effects |-| **System under load (CPU > 80%)** | Throttle FPS; if can't meet target for 3 s, drop to lower FPS budget |-| **Heartbeat reports RSS > 200 MB** | Restart overlay process |-------## 21. Configuration Schema--### 21.1 `jarvis.toml` — `[overlay]` section--```toml-[overlay]-enabled = true # bool — master switch-edge_glow_enabled = true # bool — separate from `enabled`, allows mascot-only mode-mascot_enabled = true # bool — separate from `enabled`, allows glow-only mode-all_monitors = false # bool — if true, glow on every screen; if false, primary only-hide_on_fullscreen = true # bool-ignore_busy_state = false # bool — if true, don't hide on QUNS_BUSY (only on actual fullscreen)-hide_from_capture = true # bool — WDA_EXCLUDEFROMCAPTURE-respect_reduced_motion = true # bool — honor OS reduced-motion preference-animations_enabled = true # bool — master animation toggle (separate from reduced-motion)--# Throttling-fps_idle = 1 # int 0..30-fps_active = 30 # int 1..60-fps_burst = 60 # int 1..60 — for typing/clicking only-idle_timeout_s = 30 # int 5..600 — drop to fps_idle after this-hide_timeout_s = 300 # int 60..3600 — set IsVisible=false after this--# IPC-ws_port = 7842 # int 1024..65535-ws_host = "127.0.0.1" # str — must be loopback-ws_port_range_max = 7852 # int — search range if port is busy-fallback_pipe = "\\\\.\\pipe\\jarvis-overlay"-shm_cursor_name_prefix = "jarvis-cursor" # str — actual name has random suffix-heartbeat_interval_s = 1 # int 1..10-heartbeat_timeout_s = 3 # int 2..30--# Cursor trail-cursor_trail_enabled = true # bool-cursor_stream_hz = 60 # int 10..120--[overlay.theme]-yellow_primary = "#FFC700" # str (hex)-yellow_soft = "#FFE066"-yellow_amber = "#FFB300"-black = "#0A0A0A"-glow_width_px = 14 # int 4..40-hue_drift_degrees = 15 # int 0..30 — max drift around primary--[overlay.mascot]-position_monitor = "" # str (device name) — empty = use primary-position_x_relative = 200 # int — pixels from monitor's top-left-position_y_relative = 80 # int-size_px = 160 # int 80..256-draggable = true # bool-snap_to_edges_px = 16 # int 0..32 — snap distance to monitor edges-hidden_for_session = false # bool — runtime-set on right-click "Hide"-```--### 21.2 Pydantic Validation--All fields validated via `OverlayConfig(BaseModel)` in `jarvis/overlay/config.py`. Pydantic-validators enforce:-- Color strings match `#RRGGBB` regex.-- Numeric ranges as commented above.-- `ws_host` must be in `{"127.0.0.1", "::1", "localhost"}`.-- `position_monitor` is sanity-checked against `EnumDisplayMonitors` at startup; falls back to primary if invalid.--### 21.3 Atomic Write Pipeline (per AD-11)--```-1. pre-validate: parse new config via Pydantic-2. backup: copy jarvis.toml → jarvis.toml.bak-3. write: tempfile + os.replace() (atomic on Win32)-4. reload-test: re-parse new file, instantiate OverlayConfig-5. rollback if reload-test fails: copy jarvis.toml.bak → jarvis.toml-6. notify overlay via `config` IPC message-```--### 21.4 Defaults & Migration--If `[overlay]` section missing entirely → use Python-side defaults (above values), don't touch the TOML. On user's next manual config edit, they can add the section if they want to customize.--If individual fields missing from `[overlay]` → use Python-side defaults for those fields.--Schema-version: implicit. If we ever break compatibility (V2), add `[overlay] _schema_version = 2` and a Python migration path. V1: no version field needed.-------## 22. File Structure--```-OS-Level/ # NEW top-level project folder- pyproject.toml # PySide6, websockets, pydantic, psutil, pywin32- README.md- OS-LEVEL_PLAN.md # this document-- src/overlay/- __init__.py- __main__.py # python -m overlay [--self-test]- main.py # entry point; takes WS port as arg-- # Window management- window_glow.py # PySide6 transparent click-through edge-glow window- window_mascot.py # PySide6 transparent mascot window (clickable)- transparency.py # ctypes Win32 (WS_EX_TRANSPARENT, WDA_EXCLUDEFROMCAPTURE, ...)- monitors.py # EnumDisplayMonitors, DPI, hotplug-- # State + IPC- state.py # OverlayState enum, transition logic- schema.py # Pydantic v2 models (state, click, action, heartbeat, config, ...)- ipc_ws.py # WS client (connects to Hauptjarvis WS-server on 127.0.0.1; see §10.5)- ipc_pipe.py # Named-pipe fallback- cursor_shm.py # multiprocessing.shared_memory wrapper-- # Detection / supervision- fullscreen_detect.py # SHQueryUserNotificationState polling-- # Config (read-only inside overlay)- config.py # OverlayConfig Pydantic model-- # Self-test for CI / smoke- self_test.py # opens window, renders frame, exits with code-- overlay-ui/ # rendered inside QtWebEngine- package.json # vite, simplex-noise, @rive-app/canvas-lite- vite.config.ts- tsconfig.json- index.html # main entry- src/- main.ts # boots renderer, connects to bridge- bridge.ts # WebChannel ↔ Python; Zod validators- schema.ts # Zod schemas (mirror of Python schema.py)-- edge-glow/- index.html- edge-glow.css # @property --angle, conic-gradient, mask-composite- glow.svg # feGaussianBlur+feMerge+feColorMatrix bloom- glow.ts # state subscription, intensity bumps, rAF loop- ripple.ts # CSS-injected div pool- cursor-trail.ts # OffscreenCanvas worker- typing-sweep.ts # bottom-edge sweep- noise.ts # 12 Hz Simplex modulation-- mascot/- index.html- mascot.css- mascot.ts # Rive runtime, drag, right-click menu- mascot.riv # ≤80 KB Rive asset (or PNG fallback)- mascot-fallback.png # static fallback if Rive load fails--# Modifications in existing jarvis/ tree:-jarvis/overlay/ # NEW subpackage in main jarvis tree- __init__.py # re-exports public API (get_overlay, decorators, ...)- bridge.py # OverlayBridge singleton, WS-server, decorators, context-managers- supervisor.py # subprocess management, Job Object, restart logic- triggers.py # ActionKind enum, decorator/context-manager implementations- schema.py # SAME Pydantic schemas as overlay-side (DRY via shared module preferred)--jarvis/control/ # NEW (or augmented if exists) — single point of instrumentation- __init__.py- mouse.py # wrapped pyautogui mouse calls + decorators- keyboard.py # wrapped pyautogui keyboard calls + decorators- browser.py # wrapped Browser-Use calls + decorators--# Tests-tests/overlay/- test_state_machine.py- test_schema.py- test_schema_symmetry.py # Pydantic ↔ Zod CI gate- test_ipc_ws.py # mock ws server, verify reconnect, backpressure- test_ipc_pipe.py- test_cursor_shm.py # write/read cycle, torn-write detection- test_transparency.py # ctypes calls, hwnd flag verification- test_monitors.py # virtual displays, hotplug- test_supervisor.py # spawn, kill, auto-restart with backoff- test_triggers.py # decorator/context-manager fire correct events- test_subagent_noop.py # JARVIS_DEPTH > 0 → no events- test_visual_regression.py # Playwright screenshots of states (skipped on CI without display)--# Docs-docs/- overlay-ipc-protocol.md # detailed protocol reference (extracted from this plan)- overlay-state-machine.md # state diagram + transition tables- overlay-troubleshooting.md # known issues, debugging tips-```--**Implementer discretion:**-- Exact module-decomposition within `jarvis/overlay/` is implementer's choice (e.g., one file vs split).-- Whether `jarvis/overlay/schema.py` is a re-export of `OS-Level/src/overlay/schema.py` or a duplicated definition with CI-test for symmetry: implementer's choice. Single-source preferred.-- React vs vanilla TS for `overlay-ui/`: implementer's choice. Vanilla is leaner (no React-runtime cost); React reuses skill from existing pywebview frontend. Implementer documents the choice in the README.-------## 23. Testing Strategy--### 23.1 Unit Tests (`pytest`)--| Test | Verifies |-|---|---|-| `test_state_machine.py` | All 8 states + all valid transitions + invalid transitions raise; coalescing 16 ms window |-| `test_schema.py` | Pydantic round-trip JSON ↔ model for every message type; rejects invalid values |-| `test_schema_symmetry.py` | Export Pydantic schema → JSON Schema; parse Zod schema → JSON Schema; assert equal |-| `test_cursor_shm.py` | Create SHM, write 1000 frames, read concurrently, no torn reads; cleanup on exit |-| `test_transparency.py` | Mock `ctypes.windll.user32`, verify `WS_EX_TRANSPARENT` is set, `WDA_EXCLUDEFROMCAPTURE` is set |-| `test_monitors.py` | Mock `QGuiApplication.screens()`, verify per-monitor windows are created/destroyed correctly |-| `test_supervisor.py` | Mock subprocess, verify spawn → heartbeat → kill → respawn-with-backoff sequence |-| `test_triggers.py` | Apply decorator to dummy function, verify `action_started`/`action_ended` events fire in correct order |-| `test_subagent_noop.py` | Set `JARVIS_DEPTH=2` env, instantiate OverlayBridge, verify all `emit_*` calls are no-ops |-| `test_config.py` | Pydantic validation rejects out-of-range values; atomic write pipeline rolls back on invalid file |--### 23.2 Integration Tests--| Test | Verifies |-|---|---|-| `test_e2e_state_change.py` | Spawn overlay subprocess, send state via WS, assert WebView reports rendered state via heartbeat |-| `test_e2e_click_ripple.py` | Spawn overlay, send click event, assert ripple-event reaches DOM within 25 ms |-| `test_e2e_kill_parent.py` | Spawn overlay under Job Object, kill parent forcibly, assert overlay process exits within 1 s |-| `test_e2e_overlay_crash.py` | Spawn overlay, send SIGKILL to overlay, assert supervisor respawns within 3 s + 0.5 s backoff |--### 23.3 Visual Regression Tests--`test_visual_regression.py` uses Playwright + headless WebView2 to snapshot each state and compare to baseline images (stored in `tests/__visual__/`). Pixel-diff tolerance 5%. Updates require explicit `--update-baseline` flag.--Skipped on CI runners without display (Linux containers); runs locally and on Windows-equipped CI.--### 23.4 Performance Smoke--`test_perf_60s_idle.py`:-- Spawn overlay in idle state for 60 s.-- Sample CPU/GPU/RSS via `psutil` every 1 s.-- Assert: median CPU < 0.5%, median GPU < 0.5% (via `nvidia-smi` or equivalent), max RSS < 100 MB.-- Skipped on CI without GPU detection.--### 23.5 Multi-Monitor Smoke (manual / Windows-only)--Test plan in `docs/overlay-troubleshooting.md`:-1. Single-monitor: smoke test all states.-2. Two monitors, same DPI: verify overlay on primary only by default; opt-in to `all_monitors = true`, verify glow on both.-3. Two monitors, different DPI (100% + 200%): verify per-monitor DPI-correct rendering.-4. Hotplug: with overlay running, unplug secondary; verify no crash, mascot recovers.-5. Hotplug: with overlay running, plug in secondary; verify if `all_monitors = true`, glow appears on it.--### 23.6 Manual Test Plan (per Release)--A human verifies before each release:-- Wake-word triggers `listening` state visually.-- Click in browser triggers ripple within perceptible window.-- Typing triggers bottom-edge sweep.-- Fullscreen game causes overlay to vanish; exiting brings it back.-- OBS recording omits overlay (privacy default).-- Right-click mascot → "Hide" works; tray-menu re-shows.-- Drag mascot to second monitor; restart Jarvis; mascot returns to second monitor.-- Unplug second monitor with mascot on it; mascot snaps to primary.-------## 24. Success Criteria (Feature-Level Definition of Done)--The OS-Level Overlay feature ships when **all** of the following are true:--### 24.1 Functional-- ✅ Glow appears within 50 ms of any Hauptjarvis PC-action (typing/clicking/move/scroll/navigate).-- ✅ Glow does NOT appear during listening / thinking / speaking states.-- ✅ Glow does NOT appear when sub-agents perform actions in their subprocesses.-- ✅ Click ripple appears at exactly the click coordinate (within 1 logical pixel of accuracy) within 50 ms of the click.-- ✅ Cursor trail follows Jarvis-driven cursor moves smoothly at 60 Hz.-- ✅ Typing-indicator-sweep appears on each keystroke within 100 ms.-- ✅ Mascot displays correct state-animation for every state.-- ✅ Mascot is draggable; position persists across restarts.-- ✅ Mascot's monitor recovery works on hotplug.--### 24.2 Configuration-- ✅ All `[overlay]` config fields documented in this plan are validated, applied, and survive Atomic-write pipeline.-- ✅ Disabling `mascot_enabled` removes the mascot at runtime without restart.-- ✅ Disabling `edge_glow_enabled` removes the glow at runtime without restart.-- ✅ `enabled = false` cleanly stops the overlay process within 5 s.--### 24.3 Performance-- ✅ Idle CPU < 0.5%, idle GPU < 0.5%, idle RSS < 100 MB measured over a 5-min idle window.-- ✅ Active state (typing+ripple) CPU < 3%, GPU < 2%, RSS < 140 MB measured over a 60-s burst.-- ✅ Battery delta < 1% per hour idle, < 3% per hour active (measured on a battery-powered laptop).--### 24.4 Privacy & Safety-- ✅ Default OBS / Teams / Zoom / Snipping-Tool capture omits overlay (manually verified).-- ✅ User-toggleable to allow capture for legitimate use.-- ✅ No `import jarvis.speech.*` anywhere in `OS-Level/` (CI-grep enforced).-- ✅ No credentials, tokens, prompts, or audio ever transit overlay process (code-audit verified).-- ✅ WS port bound to `127.0.0.1` only (verified via `netstat`).--### 24.5 Process Lifecycle-- ✅ Overlay process exits within 1 s of Hauptjarvis hard-kill (verified via `taskkill /F`).-- ✅ Overlay-only crash triggers automatic restart within 3 s of heartbeat-timeout.-- ✅ Restart-cap (5 in 5 min) fires correctly; surfaces tray-warning.--### 24.6 Multi-Monitor / Edge Cases-- ✅ Per-monitor DPI works correctly (200% + 100% mixed monitors).-- ✅ Monitor hotplug doesn't crash overlay; mascot recovers.-- ✅ Fullscreen-exclusive game causes overlay to hide; exit brings it back within 2 s of `SHQueryUserNotificationState` poll.-- ✅ Vertical monitor renders glow correctly on rotated edge.--### 24.7 Tests-- ✅ All unit tests in `tests/overlay/` green.-- ✅ Integration tests for spawn / kill / respawn / IPC green.-- ✅ Visual regression baseline established and tests pass within 5% pixel-diff tolerance.-- ✅ Performance smoke test green on a reference machine.-- ✅ No regression in existing `pytest tests/` (still 248/250 or better).--### 24.8 Documentation-- ✅ `docs/overlay-ipc-protocol.md` complete.-- ✅ `docs/overlay-state-machine.md` with state diagram.-- ✅ `docs/overlay-troubleshooting.md` with known issues.-- ✅ CLAUDE.md updated to mention the new `jarvis/overlay/` and `OS-Level/` subtrees.-------## 25. Risks & Mitigations--### 25.1 Technical Risks--| Risk | Likelihood | Impact | Mitigation |-|---|---|---|---|-| **WS_EX_TRANSPARENT regression in future Win11 update** | Low | High | Spy++ verification in test plan; ctypes-fallback for direct `SetWindowLongPtrW` if Qt's flag stops working |-| **WDA_EXCLUDEFROMCAPTURE doesn't honor on some build** | Medium | Medium | Detect via test, fall back to "warn user that overlay may appear in screen-share" |-| **PySide6 + QtWebEngine memory bloat over time** | Medium | Medium | RSS monitoring via heartbeat; restart at 200 MB ceiling |-| **SHM cursor stream race conditions** | Low | Low | Sequence-counter pattern (write seq last, read seq before+after); 60 Hz × 16-ms-coalesce-window is forgiving |-| **Job Object doesn't kill subprocess on parent crash** | Very Low | High | Documented Win32 pattern; tested in `test_e2e_kill_parent.py` |-| **Browser-Use / Computer-Use plugins don't go through `jarvis/control/`** | Medium | Medium | Implementer must wrap or instrument them; CI-grep-test for direct `pyautogui` imports outside `jarvis/control/` |-| **Rive runtime version mismatch with `.riv` file** | Low | Low | Pin `@rive-app/canvas-lite` version; PNG-fallback path |-| **State change races (two events within 16 ms)** | Medium | Low | Coalescing per AD-17 |--### 25.2 Performance Risks--| Risk | Likelihood | Impact | Mitigation |-|---|---|---|---|-| **Glow tanks battery on integrated GPU** | Medium | Medium | CSS-only renderer (no WebGL); throttle on battery; FPS-cap |-| **60 Hz SHM read in Python competes with Voice-Loop** | Low | High | SHM is zero-copy, no asyncio-wakeup; verified in perf-smoke-test |-| **WebView2 hidden-throttling doesn't kick in** | Low | Low | Fallback: explicitly call `IsVisible = false` at hide-timeout |--### 25.3 UX Risks--| Risk | Likelihood | Impact | Mitigation |-|---|---|---|---|-| **Mascot annoying / distracting** | Medium | Medium | Disable-toggle; user-tested mascot design (implementer discretion + iteration) |-| **Glow visible in wrong contexts (e.g., during sleep)** | Low | Low | Power-state event handling |-| **Glow on Sub-Agent action confuses user (it shouldn't appear)** | Low | Medium | AD-6 explicit; CI-test verifies sub-agents are no-op |-| **Color too saturated, dazzles user** | Low | Low | Default `--intensity` calibrated; user can override yellow-primary in TOML |--### 25.4 Schedule Risks--| Risk | Likelihood | Impact | Mitigation |-|---|---|---|---|-| **Trigger-instrumentation requires touching too many files** | Medium | Medium | Pre-Phase: introduce `jarvis/control/*` choke-point first; future code uses it |-| **Visual design iteration takes longer than build** | Medium | Low | Ship with reasonable default; iterate post-V1 |-| **Multi-monitor edge cases consume disproportionate time** | Medium | Low | Default to primary-only; defer multi-monitor polish if needed |--### 25.5 Maintenance Risks--| Risk | Likelihood | Impact | Mitigation |-|---|---|---|---|-| **Future PySide6 6.x update breaks transparency** | Low | Medium | Pin major version; manual upgrade gating |-| **Schema-drift between Python and TS** | Medium | High | CI gate `test_schema_symmetry.py` |-| **Hauptjarvis schema-version bumps without overlay update** | Medium | Medium | `v` field in envelope; overlay logs warning, continues with V1-compatible behavior |-------## 26. Implementer Discretion — what OpenClaw may decide itself--This section explicitly lists choices left open. OpenClaw chooses these without re-confirming, documents the choice in commit-messages or inline comments.--### 26.1 Variable / Function / Module Naming--- Internal class names, method names, file names within the constraints of §22 file structure.-- CSS class names within `overlay-ui/`.-- Local variable names everywhere.--### 26.2 Decomposition--- How `jarvis/overlay/bridge.py` is internally decomposed (one file vs split modules) — implementer's choice.-- Helper functions, internal utility modules.-- Test helper fixtures.--### 26.3 Algorithmic Tuning Within Documented Ranges--- Exact tween coefficients within stated easing curves.-- Exact phase-offsets per layer (within "phase-offset" requirement).-- Exact Simplex-noise frequency within 8–16 Hz.-- Exact Hue-drift amplitude within ±15°.-- Pool-size for ripple divs (8 is suggested, 4–16 is acceptable).--### 26.4 Implementation Mechanism Choices--- **Decorator vs Context-Manager preference** in caller code (both must work; implementer can recommend one as primary in docstrings).-- **Pydantic vs dataclass** for non-IPC internal models (Pydantic for IPC is hard; internal stuff can be dataclass).-- **JSON vs MessagePack** for WS payload — JSON is hard (per AD-15 debugability). Internal SHM is binary (per §11). No room for choice here.-- **OffscreenCanvas vs main-thread Canvas** for cursor trail — OffscreenCanvas preferred but main-thread acceptable if Worker setup proves problematic.-- **WebChannel vs custom-postMessage** for Python ↔ JS bridge inside QtWebEngine — implementer's choice. WebChannel is slightly more idiomatic, but custom postMessage is fine if it works.--### 26.5 Fallback Paths--- If Rive integration is problematic: PNG-fallback (covered in AD-16).-- If WebView2 is problematic: pure QtWidgets-painting renderer (would require re-implementing CSS/SVG by hand — only as last resort).-- If `multiprocessing.shared_memory` has Windows-specific issues (Bug #82300 referenced): fall back to memory-mapped file via `mmap`.--### 26.6 Test Coverage Choices--- Exact test count per module (aim for "every public API + every state transition + every error path").-- Property-based tests (hypothesis) vs example-based: implementer's choice.-- E2E tests' setup-teardown style.--### 26.7 Documentation Style--- Format of inline docstrings (Google-style vs NumPy-style vs reST), as long as consistent within the OS-Level subtree.-- Whether to add ADR files (`docs/adr/00XX-*.md`) for sub-decisions or keep them inline in code.--### 26.8 Mascot Design--- Exact illustration of the mascot (per §13.1 — black + yellow + geometric + state-readable + ≤80 KB).-- Exact frame counts per state animation.-- Whether the mascot has eyes, an antenna, a face — implementer's call.--### 26.9 What is NOT Implementer's Discretion (hard requirements)--- The 18 Architecture Decisions in §5 are binding. Deviations require an ADR-update, not just a commit comment.-- The IPC envelope structure in §10.1 is binding for inter-version compatibility.-- The state names in §6 are binding (used in IPC).-- The privacy defaults in §18 are binding.-- The performance ceilings in §17.1 are binding (build to under them).-- The exclusion of voice/audio code from overlay (§18.3) is binding.-------## 27. Glossary--| Term | Definition |-|---|---|-| **Hauptjarvis** | The main Jarvis process that hosts the voice loop, the RouterBrain, and the Sub-Jarvis manager. Not to be confused with Sub-Jarvis (subprocesses) or sub-agents (delegated harnesses). |-| **Sub-Agent** | A Sub-Jarvis subprocess or a dispatched harness (openclaw, codex, etc.). NEVER triggers the overlay (AD-6). |-| **Edge Glow** | The animated glow border around the screen edge. Appears only during interactive PC actions (typing, clicking). |-| **Mascot** | The small mascot figure in a separate window. Reflects state, is persistent, draggable. |-| **Ripple** | The yellow click effect at the coordinate when Jarvis clicks. Lifetime 600 ms. |-| **Cursor Trail** | The subtle dot trail behind the cursor during Jarvis mouse activity. |-| **Typing Indicator** | The bottom-edge sweep on each keystroke while typing. |-| **State Machine** | The 8-state automaton (idle/listening/thinking/typing/clicking/speaking/error/hidden), hosted in the overlay process. |-| **Conic-Gradient** | CSS primitive (`conic-gradient(...)`) — a color gradient that rotates around a center point. Animatable with `@property --angle` via the compositor thread. |-| **`@property` (CSS)** | CSS Houdini custom-property definition — allows typed CSS variables that can be smoothly interpolated. Here: `--angle` as `<angle>`. |-| **mask-composite** | CSS property that controls the layering of `mask-image`s. We use `exclude` to punch the interior out of the glow. |-| **mix-blend-mode: plus-lighter** | Chrome 105+ blend mode for luminous additive composition without saturation loss. |-| **Click-Through** | Window property: mouse events pass through the window to apps underneath. Achieved via `WS_EX_TRANSPARENT`. |-| **WS_EX_TRANSPARENT** | Win32 extended window style. Makes the window transparent to mouse hit-testing. Combined with `WS_EX_LAYERED`. |-| **WS_EX_LAYERED** | Win32 EWS. Enables per-pixel alpha and makes transparency possible. A prerequisite for `WS_EX_TRANSPARENT`. |-| **WS_EX_TOPMOST** | Win32 EWS. The window is always-on-top. Does not work over exclusive fullscreen / UAC / lock screen. |-| **WS_EX_TOOLWINDOW** | Win32 EWS. The window is not in the taskbar / Alt-Tab. |-| **WS_EX_NOACTIVATE** | Win32 EWS. Clicking the window does not activate it (no focus steal). |-| **WDA_EXCLUDEFROMCAPTURE** | Win10 2004+ flag for `SetWindowDisplayAffinity`. The window is excluded from the DWM bitstream to screen-capture APIs → invisible in OBS, Teams, Zoom. |-| **DWM** | Desktop Window Manager — the compositor service in Windows since Vista. Combines all window outputs. |-| **DComp / DirectComposition** | Lower-level compositor API; enables animation interpolation on the DWM thread (CPU-free). |-| **DXGI** | DirectX Graphics Infrastructure — responsible for swap chains and fullscreen-exclusive. |-| **Layered Window** | Win32 window concept with per-pixel alpha and external render composition. Enabled via `WS_EX_LAYERED`. |-| **Redirection Bitmap** | A per-window off-screen bitmap that the DWM uses to compose layered windows. Memory cost scales with window size. |-| **Exclusive Fullscreen** | A game/app takes direct ownership of the display surface via DXGI; always-on-top is ignored. |-| **PerMonitorV2 DPI Awareness** | Win10 1607+ API; each monitor's DPI is handled separately; a window can "migrate" between monitors with correctly scaled content. |-| **Logical Pixel** | A DPI-scaled pixel (what JS/CSS sees). 1 logical px @ 100% = 1 physical px; @ 200% = 2 physical px. |-| **Physical Pixel** | A hardware pixel on the monitor (what Win32 / pyautogui sees). |-| **Refresh Rate** | The monitor's refresh rate in Hz. 60/120/240/360 typical. Variable Refresh Rate (G-Sync, FreeSync) is variable. |-| **Job Object** | A Win32 mechanism for grouping processes with shared limits. `KILL_ON_JOB_CLOSE` causes automatic killing of job members when the job handle is closed. |-| **SHM (Shared Memory)** | `multiprocessing.shared_memory` — zero-copy IPC between Python processes via a memory-mapped region. |-| **Named Pipe** | A Win32 IPC mechanism over `\\.\pipe\NAME`. Not TCP/IP; escapes firewall blocks. |-| **WebSocket** | A bidirectional TCP/WS protocol. Here: localhost loopback `127.0.0.1:7842`. |-| **Pydantic v2** | A Python data-validation library; v2 is Rust-backed (10× faster than v1). We use models for IPC schemas. |-| **Zod** | A TypeScript data-validation library, equivalent to Pydantic for TS. |-| **Rive** | A realtime animation tool and runtime; .riv files are binary animation assets with state machines. The `canvas-lite` runtime is Canvas2D-only (no WebGL conflict). |-| **Lottie** | An Adobe-After-Effects-based animation format (JSON). Larger and without state machines (for our purposes). |-| **OffscreenCanvas** | A canvas API for web workers; enables GPU-rendered drawing without blocking the main thread. |-| **rAF / requestAnimationFrame** | A browser API for 60-Hz-synchronized render callbacks. |-| **Simplex Noise** | A Perlin-noise variant; slightly faster, fewer artifacts. We use it for organic animation modulation. |-| **Coalescing** | Combining multiple identical events within a short time window into a single one. Here: a 16 ms window. |-| **Heartbeat** | A periodic "I'm alive" message between IPC endpoints. Here: 1 Hz; timeout 3 s. |-| **Backpressure** | A mechanism to throttle the sender when the receiver cannot keep up. Here: a bounded queue with drop-oldest. |-| **Atomic Write Pipeline** | Pre-validate → backup → tempfile-write → reload-test → rollback. Prevents broken configs. |-| **CSS Houdini** | A browser API for low-level CSS extension. `@property` is part of it. |-| **TTFW (Time To First Word)** | A voice-loop latency metric. Jarvis' target: < 1.5 s from the wake word to the first TTS sample. Sacrosanct. |-| **`prefers-reduced-motion`** | An OS accessibility setting; we respect it with reduced animations. |-| **`prefers-contrast: high`** | An OS accessibility setting; we respect it with increased contrasts. |-| **GIL (Global Interpreter Lock)** | Python's lock on bytecode execution. SHM bypasses the GIL for reads/writes. WS IPC uses asyncio tasks (cooperative, no GIL issue). |-| **JARVIS_DEPTH** | An env variable that marks the Sub-Jarvis recursion depth. `> 0` → sub-agent. Used to detect the sub-agent OverlayBridge no-op. |-------## Document Status--- **Version:** Draft 1.0-- **Author:** Joint output of Claude Opus 4.7 + Ruben (Personal Jarvis Project Owner)-- **Date:** 2026-05-01-- **Next step:** Prompt-chain derivation in a separate session. This plan file is the single source of truth against which the prompt chain is verified.-- **Review cycle:** Before the implementation starts, Ruben should go through the plan completely once and respond either with a ✅ approve or with an issue list.-----diff --git a/OS-Level/QUICKSTART.md b/OS-Level/QUICKSTART.mddeleted file mode 100644index 07b40a36a3..0000000000--- a/OS-Level/QUICKSTART.md+++ /dev/null@@ -1,221 +0,0 @@-# Personal Jarvis — Phase 9 Overlay Quickstart--Voice-driven Personal Jarvis gets visual feedback: a yellow-**edge glow** when Jarvis types/clicks, a **mascot** that shows the status,-**cursor trail** and **click ripple** during actions, and a-**privacy default** (invisible in OBS / screen recording / Teams share).--This document walks you through testing the feature in 4 steps.-------## TL;DR — Three commands--```powershell-# 1. Install the overlay package once-cd "C:\Users\Administrator\Desktop\Personal Jarvis-main\OS-Level"-pip install -e .--# 2. Smoke test (5-second sign of life)-python -m overlay --smoke--# 3. Production test with the main Jarvis-cd "C:\Users\Administrator\Desktop\Personal Jarvis-main"-run.bat --debug-```--If, after step 2, the **mascot appears in the top-left of your primary monitor**-(a black rounded square with yellow eyes), the setup is working.-------## Step 1 — Prerequisites--### a) Make the overlay package installable--Run once:--```powershell-cd "C:\Users\Administrator\Desktop\Personal Jarvis-main\OS-Level"-pip install -e .-```--This makes the `overlay` Python namespace globally available. Dependencies-(PySide6, websockets, pydantic, psutil, pywin32, python-ulid) are installed-along with it.--### b) Enable `jarvis.toml`--Open `C:\Users\Administrator\Desktop\Personal Jarvis-main\jarvis.toml`-and make sure the `[overlay]` section looks like this (or add it):--```toml-[overlay]-enabled = true # Master switch-edge_glow_enabled = true # Yellow border on typing/clicking-mascot_enabled = true # Status-indicator mascot-hide_from_capture = true # Privacy: invisible in OBS/Teams-respect_reduced_motion = true # Honor the OS animation setting-```--All defaults are `true` — if the section is missing entirely, the-overlay should still start (see plan §21.4).--### c) Check the frontend build--The renderer HTML/JS/CSS must be built:--```powershell-cd "C:\Users\Administrator\Desktop\Personal Jarvis-main\OS-Level\overlay-ui"-npm install # once-npm run build # produces dist/edge-glow.html + dist/mascot.html-```--The output should contain: `dist/edge-glow.html`, `dist/mascot.html`, plus-asset bundles in the `dist/assets/` folder. **0 warnings** is expected.-------## Step 2 — Standalone smoke--Test 1 checks whether the overlay starts on its own (without the main Jarvis):--```powershell-cd "C:\Users\Administrator\Desktop\Personal Jarvis-main\OS-Level"-python -m overlay --smoke-```--**What you should see:**--- After ~1 s the **mascot** appears in the top-left of the primary monitor- (position: ~200, 80 px from the desktop corner)-- Mascot look: a black rounded square with two yellow round eyes,- black pupils, and a yellow mouth arc at the bottom-- The edge glow is **NOT** visible (no main Jarvis = no action =- no glow — by design, plan §6.1)-- After **5 seconds** everything closes automatically--**If nothing appears:**--1. Read the console output — `python -m overlay --smoke` prints logs-2. Likely causes:- - `ModuleNotFoundError: No module named 'overlay'` → step 1.a- was skipped- - `ImportError: PySide6` → run `pip install PySide6` manually- - `FileNotFoundError: ...overlay-ui/dist/edge-glow.html` → step- 1.c was skipped (`npm run build`)-------## Step 3 — Production test with the main Jarvis--Test 2 checks whether the main Jarvis spawns + controls the overlay correctly:--```powershell-cd "C:\Users\Administrator\Desktop\Personal Jarvis-main"-run.bat --debug-```--`--debug` opens a console with live logs. Look for:--- `Supervisor: spawned PID=...` — the overlay subprocess was started-- `overlay WS-Server listening on ws://127.0.0.1:7842` — IPC connected--**Visual tests per state:**--| State | What is visible? | How to trigger? |-|---|---|---|-| **idle** | Mascot only, no glow | Default after boot |-| **listening** | Mascot pulses slightly brighter | Say "Jarvis" (wake word) |-| **thinking** | Mascot pulses faster | Ask a question |-| **typing** | Yellow rotating edge stroke + bottom sweep per keystroke | "Jarvis, type Hello World in Notepad" |-| **clicking** | Faster edge stroke + yellow ripple on every click | "Jarvis, click the OK button" |-| **error** | Brief red flash | When an action fails |-------## Step 4 — Mascot interactions--- **Drag**: hold the left mouse button on the mascot and drag → the position- is saved to `jarvis.toml` `[overlay.mascot]` after release-- **Snap**: within 16 px of a screen edge → it snaps automatically-- **Right-click**: context menu with "Hide for session" / "Reset- position" / "Settings..."-- **Restart test**: drag the mascot → fully close the app → restart it →- the mascot should reappear at the same position-- **Monitor recovery**: drag the mascot onto a secondary monitor → unplug- that monitor → restart the app → the mascot lands at the primary- default position (200, 80) (deterministic plan §13.4 fallback)-------## Step 5 — Privacy check--Plan §18.1 requires: the overlay is invisible in screen captures-(`WDA_EXCLUDEFROMCAPTURE`).--**Test:**--1. Open the **Snipping Tool** → take a screen clip → the mascot- should be **absent** from the screenshot-2. **OBS Studio** with display capture → the mascot should be **absent**- from the stream preview-3. Start a **Teams / Zoom** screen share → the mascot should be- **invisible** to recipients--If the overlay is visible: `hide_from_capture = false` in the TOML-disables the privacy function (for tutorial recordings).-------## Architecture in 5 sentences--1. **The main Jarvis** (FastAPI, existing) spawns the overlay as a- **separate subprocess** under a Win32 Job Object (plan AD-9, guarantees- kill-on-parent-crash within 1 s).-2. The overlay process uses **PySide6 + QtWebEngine** — edge glow and- mascot are two separate transparent top-level HWNDs (plan AD-1).-3. **IPC** goes over **WebSocket** (state, click, action), **shared- memory** (60 Hz cursor stream — avoids voice-loop contention),- and a **named pipe** as a fallback (AD-5).-4. The **state machine** lives in the overlay process (AD-8); the main Jarvis- only sends events, and the overlay translates them into state transitions.-5. **Sub-agents** (`JARVIS_DEPTH > 0` env) do **not** trigger the overlay- (plan §8.7) — structurally, not by convention.-------## When something doesn't work--A detailed list of 10 scenarios:-**`docs/overlay-troubleshooting.md`** (286 lines, all plan-§ references).--A few quick checks:--- Console log line `Overlay: disabled via config` → check `[overlay]- enabled = true` in jarvis.toml-- Console log line `Overlay: Sub-Agent-Process` → the `JARVIS_DEPTH`- env var is set by accident (`echo %JARVIS_DEPTH%` must be empty or- 0)-- Task Manager → `python.exe` with command line `... -m overlay- --ws-port=7842` must be running when the main Jarvis is started-------## Further documentation--- `OS-Level/OS-LEVEL_PLAN.md` — the master plan (~2000 lines,- architecture decisions, edge cases, performance budgets)-- `docs/overlay-ipc-protocol.md` — IPC wire format (all 9 envelope- types, backpressure, reconnection)-- `docs/overlay-state-machine.md` — 8 states + transition diagram +- latency budget-- `docs/overlay-troubleshooting.md` — end-user troubleshooting-------**Current state (post Phase 9.10):**-- 250+ tests green (`pytest tests/overlay/ -q`)-- Build clean (`npm run build`, 0 warnings)-- Phase 9.9 SHIP audit + all 12 audit findings fixed-- Production default path works (hook in DesktopApp + headless)diff --git a/OS-Level/README.md b/OS-Level/README.mddeleted file mode 100644index d979f7c003..0000000000--- a/OS-Level/README.md+++ /dev/null@@ -1,23 +0,0 @@-# OS-Level Edge-Glow Overlay--A separate Python process for Personal Jarvis that draws an animated glow border at the screen edge when the main Jarvis performs interactive PC actions (mouse, keyboard). Plus a mascot, click ripple, cursor trail, and typing indicator.--Full spec: `OS-LEVEL_PLAN.md` (Phase 9).--## Installation--```powershell-cd OS-Level-pip install -e . --no-deps-```--## Smoke test--```powershell-python -m overlay --self-test # Foundation check, exit 0-python -m overlay --smoke # Verify visually for 5 sec-```--## Status--Phase 9.1 — foundation and transparent click-through windows. A yellow 50x50px test square in the top right serves as a visual marker; it disappears in Phase 9.4 when the real glow render pipeline arrives.diff --git a/OS-Level/overlay-ui/edge-glow.html b/OS-Level/overlay-ui/edge-glow.htmldeleted file mode 100644index a71eeabb70..0000000000--- a/OS-Level/overlay-ui/edge-glow.html+++ /dev/null@@ -1,27 +0,0 @@-<!doctype html>-<html lang="en">- <head>- <meta charset="UTF-8" />- <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src qrc:; worker-src blob:;" />- <meta name="viewport" content="width=device-width, initial-scale=1.0" />- <title>Edge Glow</title>- <!--- qwebchannel.js is provided by Qt from the qrc resource path as- soon as the page is loaded in QWebEngineView. bridge.ts loads it- lazily via JS — that way Vite doesn't need to resolve the URL.- -->- </head>- <body>- <!-- Edge-Glow container — main.ts buildLayers() appends 5 layer divs- in here. CSS in edge-glow.css does the rest. -->- <div class="edge-glow" role="presentation"></div>-- <!-- Diagnostic marker. Hidden by default via CSS display:none; visible- with ?debug=1 in the URL. Plan §7 + Phase-9.4 spec. -->- <div id="state-display" role="presentation">- <span class="state">init</span>- </div>-- <script type="module" src="./src/edge-glow/main.ts"></script>- </body>-</html>diff --git a/OS-Level/overlay-ui/index.html b/OS-Level/overlay-ui/index.htmldeleted file mode 100644index 9c22b464e8..0000000000--- a/OS-Level/overlay-ui/index.html+++ /dev/null@@ -1,10 +0,0 @@-<!doctype html>-<html lang="en">- <head>- <meta charset="UTF-8" />- <title>overlay-ui</title>- </head>- <body>- <p>Stub. Build entries are in <code>src/edge-glow/index.html</code>.</p>- </body>-</html>diff --git a/OS-Level/overlay-ui/mascot.html b/OS-Level/overlay-ui/mascot.htmldeleted file mode 100644index 56269a5b9b..0000000000--- a/OS-Level/overlay-ui/mascot.html+++ /dev/null@@ -1,19 +0,0 @@-<!doctype html>-<html lang="en">- <head>- <meta charset="UTF-8" />- <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src qrc:; worker-src blob:;" />- <meta name="viewport" content="width=device-width, initial-scale=1.0" />- <title>Mascot</title>- <!-- qwebchannel.js is loaded lazily by bridge.ts. -->- </head>- <body>- <!-- Rive canvas is rendered by default, fails over to <img>- (PNG fallback) when the Rive asset doesn't load. Plan §13 + AD-16. -->- <div class="mascot-host" role="img" aria-label="Jarvis status indicator">- <canvas id="mascot-canvas" width="320" height="320" hidden></canvas>- <img id="mascot-fallback" alt="" src="" hidden />- </div>- <script type="module" src="./src/mascot/main.ts"></script>- </body>-</html>diff --git a/OS-Level/overlay-ui/package-lock.json b/OS-Level/overlay-ui/package-lock.jsondeleted file mode 100644index 0a9fef13f8..0000000000--- a/OS-Level/overlay-ui/package-lock.json+++ /dev/null@@ -1,1146 +0,0 @@-{- "name": "overlay-ui",- "version": "0.1.0",- "lockfileVersion": 3,- "requires": true,- "packages": {- "": {- "name": "overlay-ui",- "version": "0.1.0",- "dependencies": {- "@rive-app/canvas-lite": "^2.21.6",- "simplex-noise": "^4.0.3",- "zod": "^3.23.8"- },- "devDependencies": {- "typescript": "^5.5.4",- "vite": "^6.4.3"- }- },- "node_modules/@esbuild/aix-ppc64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",- "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",- "cpu": [- "ppc64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "aix"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/android-arm": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",- "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/android-arm64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",- "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/android-x64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",- "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/darwin-arm64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",- "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/darwin-x64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",- "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/freebsd-arm64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",- "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "freebsd"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/freebsd-x64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",- "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "freebsd"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-arm": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",- "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-arm64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",- "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-ia32": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",- "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",- "cpu": [- "ia32"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-loong64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",- "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",- "cpu": [- "loong64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-mips64el": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",- "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",- "cpu": [- "mips64el"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-ppc64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",- "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",- "cpu": [- "ppc64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-riscv64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",- "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",- "cpu": [- "riscv64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-s390x": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",- "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",- "cpu": [- "s390x"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-x64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",- "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/netbsd-arm64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",- "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "netbsd"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/netbsd-x64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",- "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "netbsd"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/openbsd-arm64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",- "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "openbsd"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/openbsd-x64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",- "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "openbsd"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/openharmony-arm64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",- "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "openharmony"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/sunos-x64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",- "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "sunos"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/win32-arm64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",- "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/win32-ia32": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",- "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",- "cpu": [- "ia32"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/win32-x64": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",- "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@rive-app/canvas-lite": {- "version": "2.37.5",- "resolved": "https://registry.npmjs.org/@rive-app/canvas-lite/-/canvas-lite-2.37.5.tgz",- "integrity": "sha512-IyJIm2cL2PlbTqQrgawoR2+k5rA4wP52IxAk7fksXGirKBURLvaUmCtTRqGCx4KfKzpK4z6O8M/LD/j7CQsT4Q==",- "license": "MIT"- },- "node_modules/@rollup/rollup-android-arm-eabi": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.2.tgz",- "integrity": "sha512-dnlp69efPPg6Uaw2dVqzWRfAWRnYVb1XJ8CyyhIbZeaq4CA5/mLeZ1IEt9QqQxmbdvagjLIm2ZL8BxXv5lH4Yw==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ]- },- "node_modules/@rollup/rollup-android-arm64": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.60.2.tgz",- "integrity": "sha512-OqZTwDRDchGRHHm/hwLOL7uVPB9aUvI0am/eQuWMNyFHf5PSEQmyEeYYheA0EPPKUO/l0uigCp+iaTjoLjVoHg==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ]- },- "node_modules/@rollup/rollup-darwin-arm64": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.60.2.tgz",- "integrity": "sha512-UwRE7CGpvSVEQS8gUMBe1uADWjNnVgP3Iusyda1nSRwNDCsRjnGc7w6El6WLQsXmZTbLZx9cecegumcitNfpmA==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ]- },- "node_modules/@rollup/rollup-darwin-x64": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.60.2.tgz",- "integrity": "sha512-gjEtURKLCC5VXm1I+2i1u9OhxFsKAQJKTVB8WvDAHF+oZlq0GTVFOlTlO1q3AlCTE/DF32c16ESvfgqR7343/g==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ]- },- "node_modules/@rollup/rollup-freebsd-arm64": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.60.2.tgz",- "integrity": "sha512-Bcl6CYDeAgE70cqZaMojOi/eK63h5Me97ZqAQoh77VPjMysA/4ORQBRGo3rRy45x4MzVlU9uZxs8Uwy7ZaKnBw==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "freebsd"- ]- },- "node_modules/@rollup/rollup-freebsd-x64": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.60.2.tgz",- "integrity": "sha512-LU+TPda3mAE2QB0/Hp5VyeKJivpC6+tlOXd1VMoXV/YFMvk/MNk5iXeBfB4MQGRWyOYVJ01625vjkr0Az98OJQ==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "freebsd"- ]- },- "node_modules/@rollup/rollup-linux-arm-gnueabihf": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.60.2.tgz",- "integrity": "sha512-2QxQrM+KQ7DAW4o22j+XZ6RKdxjLD7BOWTP0Bv0tmjdyhXSsr2Ul1oJDQqh9Zf5qOwTuTc7Ek83mOFaKnodPjg==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-arm-musleabihf": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.60.2.tgz",- "integrity": "sha512-TbziEu2DVsTEOPif2mKWkMeDMLoYjx95oESa9fkQQK7r/Orta0gnkcDpzwufEcAO2BLBsD7mZkXGFqEdMRRwfw==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-arm64-gnu": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.60.2.tgz",- "integrity": "sha512-bO/rVDiDUuM2YfuCUwZ1t1cP+/yqjqz+Xf2VtkdppefuOFS2OSeAfgafaHNkFn0t02hEyXngZkxtGqXcXwO8Rg==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-arm64-musl": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.60.2.tgz",- "integrity": "sha512-hr26p7e93Rl0Za+JwW7EAnwAvKkehh12BU1Llm9Ykiibg4uIr2rbpxG9WCf56GuvidlTG9KiiQT/TXT1yAWxTA==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-loong64-gnu": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.60.2.tgz",- "integrity": "sha512-pOjB/uSIyDt+ow3k/RcLvUAOGpysT2phDn7TTUB3n75SlIgZzM6NKAqlErPhoFU+npgY3/n+2HYIQVbF70P9/A==",- "cpu": [- "loong64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-loong64-musl": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.60.2.tgz",- "integrity": "sha512-2/w+q8jszv9Ww1c+6uJT3OwqhdmGP2/4T17cu8WuwyUuuaCDDJ2ojdyYwZzCxx0GcsZBhzi3HmH+J5pZNXnd+Q==",- "cpu": [- "loong64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-ppc64-gnu": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.60.2.tgz",- "integrity": "sha512-11+aL5vKheYgczxtPVVRhdptAM2H7fcDR5Gw4/bTcteuZBlH4oP9f5s9zYO9aGZvoGeBpqXI/9TZZihZ609wKw==",- "cpu": [- "ppc64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-ppc64-musl": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.60.2.tgz",- "integrity": "sha512-i16fokAGK46IVZuV8LIIwMdtqhin9hfYkCh8pf8iC3QU3LpwL+1FSFGej+O7l3E/AoknL6Dclh2oTdnRMpTzFQ==",- "cpu": [- "ppc64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-riscv64-gnu": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.60.2.tgz",- "integrity": "sha512-49FkKS6RGQoriDSK/6E2GkAsAuU5kETFCh7pG4yD/ylj9rKhTmO3elsnmBvRD4PgJPds5W2PkhC82aVwmUcJ7A==",- "cpu": [- "riscv64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-riscv64-musl": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.60.2.tgz",- "integrity": "sha512-mjYNkHPfGpUR00DuM1ZZIgs64Hpf4bWcz9Z41+4Q+pgDx73UwWdAYyf6EG/lRFldmdHHzgrYyge5akFUW0D3mQ==",- "cpu": [- "riscv64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-s390x-gnu": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.60.2.tgz",- "integrity": "sha512-ALyvJz965BQk8E9Al/JDKKDLH2kfKFLTGMlgkAbbYtZuJt9LU8DW3ZoDMCtQpXAltZxwBHevXz5u+gf0yA0YoA==",- "cpu": [- "s390x"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-x64-gnu": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.60.2.tgz",- "integrity": "sha512-UQjrkIdWrKI626Du8lCQ6MJp/6V1LAo2bOK9OTu4mSn8GGXIkPXk/Vsp4bLHCd9Z9Iz2OTEaokUE90VweJgIYQ==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-x64-musl": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.60.2.tgz",- "integrity": "sha512-bTsRGj6VlSdn/XD4CGyzMnzaBs9bsRxy79eTqTCBsA8TMIEky7qg48aPkvJvFe1HyzQ5oMZdg7AnVlWQSKLTnw==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-openbsd-x64": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.60.2.tgz",- "integrity": "sha512-6d4Z3534xitaA1FcMWP7mQPq5zGwBmGbhphh2DwaA1aNIXUu3KTOfwrWpbwI4/Gr0uANo7NTtaykFyO2hPuFLg==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "openbsd"- ]- },- "node_modules/@rollup/rollup-openharmony-arm64": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.60.2.tgz",- "integrity": "sha512-NetAg5iO2uN7eB8zE5qrZ3CSil+7IJt4WDFLcC75Ymywq1VZVD6qJ6EvNLjZ3rEm6gB7XW5JdT60c6MN35Z85Q==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "openharmony"- ]- },- "node_modules/@rollup/rollup-win32-arm64-msvc": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.60.2.tgz",- "integrity": "sha512-NCYhOotpgWZ5kdxCZsv6Iudx0wX8980Q/oW4pNFNihpBKsDbEA1zpkfxJGC0yugsUuyDZ7gL37dbzwhR0VI7pQ==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ]- },- "node_modules/@rollup/rollup-win32-ia32-msvc": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.60.2.tgz",- "integrity": "sha512-RXsaOqXxfoUBQoOgvmmijVxJnW2IGB0eoMO7F8FAjaj0UTywUO/luSqimWBJn04WNgUkeNhh7fs7pESXajWmkg==",- "cpu": [- "ia32"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ]- },- "node_modules/@rollup/rollup-win32-x64-gnu": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.60.2.tgz",- "integrity": "sha512-qdAzEULD+/hzObedtmV6iBpdL5TIbKVztGiK7O3/KYSf+HIzU257+MX1EXJcyIiDbMAqmbwaufcYPvyRryeZtA==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ]- },- "node_modules/@rollup/rollup-win32-x64-msvc": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.60.2.tgz",- "integrity": "sha512-Nd/SgG27WoA9e+/TdK74KnHz852TLa94ovOYySo/yMPuTmpckK/jIF2jSwS3g7ELSKXK13/cVdmg1Z/DaCWKxA==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ]- },- "node_modules/@types/estree": {- "version": "1.0.8",- "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",- "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",- "dev": true,- "license": "MIT"- },- "node_modules/esbuild": {- "version": "0.25.12",- "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",- "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",- "dev": true,- "hasInstallScript": true,- "license": "MIT",- "bin": {- "esbuild": "bin/esbuild"- },- "engines": {- "node": ">=18"- },- "optionalDependencies": {- "@esbuild/aix-ppc64": "0.25.12",- "@esbuild/android-arm": "0.25.12",- "@esbuild/android-arm64": "0.25.12",- "@esbuild/android-x64": "0.25.12",- "@esbuild/darwin-arm64": "0.25.12",- "@esbuild/darwin-x64": "0.25.12",- "@esbuild/freebsd-arm64": "0.25.12",- "@esbuild/freebsd-x64": "0.25.12",- "@esbuild/linux-arm": "0.25.12",- "@esbuild/linux-arm64": "0.25.12",- "@esbuild/linux-ia32": "0.25.12",- "@esbuild/linux-loong64": "0.25.12",- "@esbuild/linux-mips64el": "0.25.12",- "@esbuild/linux-ppc64": "0.25.12",- "@esbuild/linux-riscv64": "0.25.12",- "@esbuild/linux-s390x": "0.25.12",- "@esbuild/linux-x64": "0.25.12",- "@esbuild/netbsd-arm64": "0.25.12",- "@esbuild/netbsd-x64": "0.25.12",- "@esbuild/openbsd-arm64": "0.25.12",- "@esbuild/openbsd-x64": "0.25.12",- "@esbuild/openharmony-arm64": "0.25.12",- "@esbuild/sunos-x64": "0.25.12",- "@esbuild/win32-arm64": "0.25.12",- "@esbuild/win32-ia32": "0.25.12",- "@esbuild/win32-x64": "0.25.12"- }- },- "node_modules/fdir": {- "version": "6.5.0",- "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",- "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",- "dev": true,- "license": "MIT",- "engines": {- "node": ">=12.0.0"- },- "peerDependencies": {- "picomatch": "^3 || ^4"- },- "peerDependenciesMeta": {- "picomatch": {- "optional": true- }- }- },- "node_modules/fsevents": {- "version": "2.3.3",- "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",- "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",- "dev": true,- "hasInstallScript": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ],- "engines": {- "node": "^8.16.0 || ^10.6.0 || >=11.0.0"- }- },- "node_modules/nanoid": {- "version": "3.3.12",- "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz",- "integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==",- "dev": true,- "funding": [- {- "type": "github",- "url": "https://github.com/sponsors/ai"- }- ],- "license": "MIT",- "bin": {- "nanoid": "bin/nanoid.cjs"- },- "engines": {- "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"- }- },- "node_modules/picocolors": {- "version": "1.1.1",- "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",- "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",- "dev": true,- "license": "ISC"- },- "node_modules/picomatch": {- "version": "4.0.4",- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",- "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",- "dev": true,- "license": "MIT",- "peer": true,- "engines": {- "node": ">=12"- },- "funding": {- "url": "https://github.com/sponsors/jonschlinkert"- }- },- "node_modules/postcss": {- "version": "8.5.13",- "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.13.tgz",- "integrity": "sha512-qif0+jGGZoLWdHey3UFHHWP0H7Gbmsk8T5VEqyYFbWqPr1XqvLGBbk/sl8V5exGmcYJklJOhOQq1pV9IcsiFag==",- "dev": true,- "funding": [- {- "type": "opencollective",- "url": "https://opencollective.com/postcss/"- },- {- "type": "tidelift",- "url": "https://tidelift.com/funding/github/npm/postcss"- },- {- "type": "github",- "url": "https://github.com/sponsors/ai"- }- ],- "license": "MIT",- "dependencies": {- "nanoid": "^3.3.11",- "picocolors": "^1.1.1",- "source-map-js": "^1.2.1"- },- "engines": {- "node": "^10 || ^12 || >=14"- }- },- "node_modules/rollup": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.2.tgz",- "integrity": "sha512-J9qZyW++QK/09NyN/zeO0dG/1GdGfyp9lV8ajHnRVLfo/uFsbji5mHnDgn/qYdUHyCkM2N+8VyspgZclfAh0eQ==",- "dev": true,- "license": "MIT",- "dependencies": {- "@types/estree": "1.0.8"- },- "bin": {- "rollup": "dist/bin/rollup"- },- "engines": {- "node": ">=18.0.0",- "npm": ">=8.0.0"- },- "optionalDependencies": {- "@rollup/rollup-android-arm-eabi": "4.60.2",- "@rollup/rollup-android-arm64": "4.60.2",- "@rollup/rollup-darwin-arm64": "4.60.2",- "@rollup/rollup-darwin-x64": "4.60.2",- "@rollup/rollup-freebsd-arm64": "4.60.2",- "@rollup/rollup-freebsd-x64": "4.60.2",- "@rollup/rollup-linux-arm-gnueabihf": "4.60.2",- "@rollup/rollup-linux-arm-musleabihf": "4.60.2",- "@rollup/rollup-linux-arm64-gnu": "4.60.2",- "@rollup/rollup-linux-arm64-musl": "4.60.2",- "@rollup/rollup-linux-loong64-gnu": "4.60.2",- "@rollup/rollup-linux-loong64-musl": "4.60.2",- "@rollup/rollup-linux-ppc64-gnu": "4.60.2",- "@rollup/rollup-linux-ppc64-musl": "4.60.2",- "@rollup/rollup-linux-riscv64-gnu": "4.60.2",- "@rollup/rollup-linux-riscv64-musl": "4.60.2",- "@rollup/rollup-linux-s390x-gnu": "4.60.2",- "@rollup/rollup-linux-x64-gnu": "4.60.2",- "@rollup/rollup-linux-x64-musl": "4.60.2",- "@rollup/rollup-openbsd-x64": "4.60.2",- "@rollup/rollup-openharmony-arm64": "4.60.2",- "@rollup/rollup-win32-arm64-msvc": "4.60.2",- "@rollup/rollup-win32-ia32-msvc": "4.60.2",- "@rollup/rollup-win32-x64-gnu": "4.60.2",- "@rollup/rollup-win32-x64-msvc": "4.60.2",- "fsevents": "~2.3.2"- }- },- "node_modules/simplex-noise": {- "version": "4.0.3",- "resolved": "https://registry.npmjs.org/simplex-noise/-/simplex-noise-4.0.3.tgz",- "integrity": "sha512-qSE2I4AngLQG7BXqoZj51jokT4WUXe8mOBrvfOXpci8+6Yu44+/dD5zqDpOx3Ux792eamTd2lLcI8jqFntk/lg==",- "license": "MIT"- },- "node_modules/source-map-js": {- "version": "1.2.1",- "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",- "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",- "dev": true,- "license": "BSD-3-Clause",- "engines": {- "node": ">=0.10.0"- }- },- "node_modules/tinyglobby": {- "version": "0.2.17",- "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",- "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",- "dev": true,- "license": "MIT",- "dependencies": {- "fdir": "^6.5.0",- "picomatch": "^4.0.4"- },- "engines": {- "node": ">=12.0.0"- },- "funding": {- "url": "https://github.com/sponsors/SuperchupuDev"- }- },- "node_modules/typescript": {- "version": "5.9.3",- "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",- "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",- "dev": true,- "license": "Apache-2.0",- "bin": {- "tsc": "bin/tsc",- "tsserver": "bin/tsserver"- },- "engines": {- "node": ">=14.17"- }- },- "node_modules/vite": {- "version": "6.4.3",- "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",- "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==",- "dev": true,- "license": "MIT",- "dependencies": {- "esbuild": "^0.25.0",- "fdir": "^6.4.4",- "picomatch": "^4.0.2",- "postcss": "^8.5.3",- "rollup": "^4.34.9",- "tinyglobby": "^0.2.13"- },- "bin": {- "vite": "bin/vite.js"- },- "engines": {- "node": "^18.0.0 || ^20.0.0 || >=22.0.0"- },- "funding": {- "url": "https://github.com/vitejs/vite?sponsor=1"- },- "optionalDependencies": {- "fsevents": "~2.3.3"- },- "peerDependencies": {- "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",- "jiti": ">=1.21.0",- "less": "*",- "lightningcss": "^1.21.0",- "sass": "*",- "sass-embedded": "*",- "stylus": "*",- "sugarss": "*",- "terser": "^5.16.0",- "tsx": "^4.8.1",- "yaml": "^2.4.2"- },- "peerDependenciesMeta": {- "@types/node": {- "optional": true- },- "jiti": {- "optional": true- },- "less": {- "optional": true- },- "lightningcss": {- "optional": true- },- "sass": {- "optional": true- },- "sass-embedded": {- "optional": true- },- "stylus": {- "optional": true- },- "sugarss": {- "optional": true- },- "terser": {- "optional": true- },- "tsx": {- "optional": true- },- "yaml": {- "optional": true- }- }- },- "node_modules/zod": {- "version": "3.25.76",- "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",- "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",- "license": "MIT",- "funding": {- "url": "https://github.com/sponsors/colinhacks"- }- }- }-}diff --git a/OS-Level/overlay-ui/package.json b/OS-Level/overlay-ui/package.jsondeleted file mode 100644index 094acbebad..0000000000--- a/OS-Level/overlay-ui/package.json+++ /dev/null@@ -1,21 +0,0 @@-{- "name": "overlay-ui",- "private": true,- "version": "0.1.0",- "type": "module",- "description": "QtWebEngine renderer for Personal Jarvis Overlay (Phase 9)",- "scripts": {- "dev": "vite",- "build": "tsc --noEmit && vite build",- "preview": "vite preview"- },- "devDependencies": {- "typescript": "^5.5.4",- "vite": "^6.4.3"- },- "dependencies": {- "@rive-app/canvas-lite": "^2.21.6",- "simplex-noise": "^4.0.3",- "zod": "^3.23.8"- }-}diff --git a/OS-Level/overlay-ui/src/bridge.ts b/OS-Level/overlay-ui/src/bridge.tsdeleted file mode 100644index e84add50e5..0000000000--- a/OS-Level/overlay-ui/src/bridge.ts+++ /dev/null@@ -1,207 +0,0 @@-// Typed wrapper around qwebchannel.js. Qt provides qwebchannel.js out of-// the box via QWebEngineScript / qrc:///qtwebchannel/qwebchannel.js — we-// load it in the HTML head as <script src=...>. This is just the promise-// wrapper + the subscribe helpers so the renderer never touches globals-// directly.--import { StateChangeSchema, StateNameSchema, type StateName } from "./schema";--const QWEBCHANNEL_URL = "qrc:///qtwebchannel/qwebchannel.js";--/**- * qwebchannel.js is delivered by the Qt runtime from the qrc resource- * path. We load it lazily via DOM script insertion so Vite doesn't- * need to resolve the HTML (otherwise it triggers a build warning- * "qrc:/// can't be bundled").- */-function loadQWebChannelScript(): Promise<void> {- if (typeof globalThis.QWebChannel === "function") {- return Promise.resolve();- }- return new Promise((resolve, reject) => {- const existing = document.querySelector<HTMLScriptElement>(- `script[src="${QWEBCHANNEL_URL}"]`,- );- if (existing !== null) {- existing.addEventListener("load", () => resolve(), { once: true });- existing.addEventListener(- "error",- () => reject(new Error("qwebchannel.js script failed to load")),- { once: true },- );- return;- }- const script = document.createElement("script");- script.src = QWEBCHANNEL_URL;- script.async = false;- script.addEventListener("load", () => resolve(), { once: true });- script.addEventListener(- "error",- () => reject(new Error("qwebchannel.js script failed to load")),- { once: true },- );- document.head.appendChild(script);- });-}--// Minimal type for what QWebChannel exposes.-interface StateBridgeQObject {- // Qt-Signal -> {connect(callback): void}- stateChanged: {- connect: (cb: (oldState: string, nextState: string, reason: string) => void) => void;- disconnect?: (cb: (oldState: string, nextState: string, reason: string) => void) => void;- };- // Qt-Slot -> Promise<string>- currentState: (cb: (s: string) => void) => void;-}--interface EffectsBridgeQObject {- clickEvent: {- connect: (cb: (x: number, y: number, monitorIdx: number, button: string) => void) => void;- };- cursorMoved: {- connect: (cb: (x: number, y: number) => void) => void;- };- actionStarted: {- connect: (cb: (kind: string, durationHintMs: number) => void) => void;- };- actionEnded: {- connect: (cb: () => void) => void;- };-}--interface QtWebChannelTransport {- send: (data: string) => void;- onmessage?: ((event: MessageEvent) => void) | null;-}--interface QtGlobals {- webChannelTransport: QtWebChannelTransport;-}--declare global {- // qwebchannel.js setzt window.qt + window.QWebChannel.- // eslint-disable-next-line no-var- var qt: QtGlobals | undefined;- // eslint-disable-next-line no-var- var QWebChannel: new (- transport: QtWebChannelTransport,- callback: (channel: { objects: Record<string, unknown> }) => void,- ) => unknown;-}--export interface ClickEventData {- x: number;- y: number;- monitorIdx: number;- button: string;-}--export interface OverlayBridge {- currentState(): Promise<StateName>;- onStateChange(handler: (change: { old: StateName; next: StateName; reason: string }) => void): void;- /** Phase 9.5 — becomes non-null once the effectsBridge is registered. */- onClickEvent(handler: (ev: ClickEventData) => void): void;- onCursorMoved(handler: (x: number, y: number) => void): void;- onActionStarted(handler: (kind: string, durationHintMs: number) => void): void;- onActionEnded(handler: () => void): void;-}--/**- * Connect to QWebChannel and resolve with a typed bridge.- *- * Called from main.ts. If qwebchannel.js hasn't loaded yet (a race in- * pre-build dev mode), the wrapper briefly polls for- * `window.qt.webChannelTransport`.- *- * @remarks- * Re-Connect after teardown is not supported in v1. The bridge is- * connected once at boot and lives until the WebView is destroyed.- * Subscribers cannot be removed individually — the underlying- * QWebChannel-Signal `stateBridge.stateChanged.disconnect` is- * optional in our typed wrapper because it's never invoked. If- * Hot-Reload-Cycles in dev-mode become a debugging pain, expose- * a `teardownBridge()` function that calls `disconnect` on all- * registered handlers.- */-export async function connectBridge(timeoutMs = 5000): Promise<OverlayBridge> {- // Lazy load qwebchannel.js — this way Vite ignores the qrc:/// URL.- await loadQWebChannelScript();- return new Promise((resolve, reject) => {- const start = performance.now();-- const tryConnect = (): void => {- const qt = globalThis.qt;- if (!qt || !qt.webChannelTransport) {- if (performance.now() - start > timeoutMs) {- reject(new Error("QWebChannel transport not available within timeout"));- return;- }- setTimeout(tryConnect, 50);- return;- }- // eslint-disable-next-line @typescript-eslint/no-unused-expressions- new globalThis.QWebChannel(qt.webChannelTransport, (channel) => {- const obj = channel.objects["stateBridge"];- if (!obj) {- reject(new Error("stateBridge not registered on QWebChannel"));- return;- }- const stateBridge = obj as StateBridgeQObject;- const effectsBridge = channel.objects["effectsBridge"] as- | EffectsBridgeQObject- | undefined;-- resolve({- currentState() {- return new Promise<StateName>((res) => {- stateBridge.currentState((value) => {- res(StateNameSchema.parse(value));- });- });- },- onStateChange(handler) {- stateBridge.stateChanged.connect((oldState, nextState, reason) => {- const parsed = StateChangeSchema.safeParse({- old: oldState,- next: nextState,- reason,- });- if (!parsed.success) {- console.warn("StateChange validation failed", parsed.error.issues);- return;- }- handler(parsed.data);- });- },- onClickEvent(handler) {- if (effectsBridge === undefined) return;- effectsBridge.clickEvent.connect((x, y, monitorIdx, button) => {- handler({ x, y, monitorIdx, button });- });- },- onCursorMoved(handler) {- if (effectsBridge === undefined) return;- effectsBridge.cursorMoved.connect((x, y) => {- handler(x, y);- });- },- onActionStarted(handler) {- if (effectsBridge === undefined) return;- effectsBridge.actionStarted.connect((kind, dur) => {- handler(kind, dur);- });- },- onActionEnded(handler) {- if (effectsBridge === undefined) return;- effectsBridge.actionEnded.connect(() => {- handler();- });- },- });- });- };-- tryConnect();- });-}diff --git a/OS-Level/overlay-ui/src/edge-glow/cursor-trail-worker.ts b/OS-Level/overlay-ui/src/edge-glow/cursor-trail-worker.tsdeleted file mode 100644index 9235cf6906..0000000000--- a/OS-Level/overlay-ui/src/edge-glow/cursor-trail-worker.ts+++ /dev/null@@ -1,145 +0,0 @@-// cursor-trail-worker.ts — OffscreenCanvas Worker. Plan §15.2.-//-// Receives:-// - { type: "init", canvas: OffscreenCanvas, dpr: number }-// - { type: "resize", width: number, height: number, dpr: number }-// - { type: "push", x: number, y: number }-// // x, y are PHYSICAL px; the worker itself-// // converts them to CSS px via dpr.-// - { type: "clear" } // on action_ended-//-// Maintains a ring buffer of 20 points and draws every frame with-// fading opacity (Plan §15.1). Points fade out linearly after-// ``POINT_LIFETIME_MS``.--interface InitMsg {- type: "init";- canvas: OffscreenCanvas;- dpr: number;-}-interface ResizeMsg {- type: "resize";- width: number;- height: number;- dpr: number;-}-interface PushMsg {- type: "push";- x: number;- y: number;-}-interface ClearMsg {- type: "clear";-}-type WorkerMsg = InitMsg | ResizeMsg | PushMsg | ClearMsg;--const TRAIL_LENGTH = 20; // Plan §15.1-const POINT_RADIUS = 16; // CSS px-const POINT_LIFETIME_MS = 400; // Plan §15.1 — opacity 0.35 -> 0-const MAX_OPACITY = 0.35;--interface TrailPoint {- x: number; // CSS px- y: number;- ts: number; // performance.now() ms-}--let canvas: OffscreenCanvas | null = null;-let ctx: OffscreenCanvasRenderingContext2D | null = null;-let dpr = 1;--// Ring buffer — fixed size, head pointer.-const buf: TrailPoint[] = [];-let head = 0;--let rafHandle = 0;--function pushPoint(physX: number, physY: number): void {- const cssX = physX / dpr;- const cssY = physY / dpr;- const point: TrailPoint = { x: cssX, y: cssY, ts: performance.now() };- if (buf.length < TRAIL_LENGTH) {- buf.push(point);- } else {- buf[head] = point;- head = (head + 1) % TRAIL_LENGTH;- }- // Self-stopping RAF (Plan §17): if drawFrame stopped itself on the- // last empty frame, kick it off again now.- if (rafHandle === 0 && ctx !== null) {- rafHandle = requestAnimationFrame(drawFrame);- }-}--function clearTrail(): void {- buf.length = 0;- head = 0;- if (ctx !== null && canvas !== null) {- ctx.clearRect(0, 0, canvas.width, canvas.height);- }-}--function drawFrame(): void {- if (ctx === null || canvas === null) return;-- // Self-stopping RAF (Plan §17): pause the RAF loop entirely once the- // trail is empty — no clearRect GPU round-trip per frame for a blank- // canvas. Restart happens in pushPoint().- if (buf.length === 0) {- cancelAnimationFrame(rafHandle); // defensive — the RAF may have just self-fired- rafHandle = 0;- return;- }-- rafHandle = requestAnimationFrame(drawFrame);- ctx.clearRect(0, 0, canvas.width, canvas.height);-- // Plan §15.2: globalCompositeOperation = 'lighter' for luminous- // accumulation.- ctx.globalCompositeOperation = "lighter";- ctx.fillStyle = "#FFC700"; // Plan §7.1 yellow-primary-- const now = performance.now();- for (const p of buf) {- const age = now - p.ts;- if (age >= POINT_LIFETIME_MS) continue;- const fade = 1 - age / POINT_LIFETIME_MS; // 1 -> 0- ctx.globalAlpha = MAX_OPACITY * fade;- ctx.beginPath();- ctx.arc(p.x * dpr, p.y * dpr, POINT_RADIUS * dpr, 0, Math.PI * 2);- ctx.fill();- }- ctx.globalAlpha = 1.0;-}--self.addEventListener("message", (ev: MessageEvent<WorkerMsg>) => {- const msg = ev.data;- switch (msg.type) {- case "init":- canvas = msg.canvas;- dpr = msg.dpr;- ctx = canvas.getContext("2d");- if (ctx !== null && rafHandle === 0) {- rafHandle = requestAnimationFrame(drawFrame);- }- break;- case "resize":- if (canvas !== null) {- canvas.width = msg.width;- canvas.height = msg.height;- dpr = msg.dpr;- }- break;- case "push":- pushPoint(msg.x, msg.y);- break;- case "clear":- clearTrail();- break;- default: {- // Exhaustiveness check.- const _exhaustive: never = msg;- void _exhaustive;- }- }-});diff --git a/OS-Level/overlay-ui/src/edge-glow/cursor-trail.ts b/OS-Level/overlay-ui/src/edge-glow/cursor-trail.tsdeleted file mode 100644index 319e28d69c..0000000000--- a/OS-Level/overlay-ui/src/edge-glow/cursor-trail.ts+++ /dev/null@@ -1,112 +0,0 @@-// cursor-trail.ts — Main-thread coordinator. Plan §15.-//-// Creates the OffscreenCanvas, transferControlToOffscreen() to the worker,-// forwards cursor updates via postMessage. The worker does the actual-// drawing (see cursor-trail-worker.ts).-//-// Source of the cursor updates: the cursorBridge.cursorMoved signal from-// the Python SHM reader thread (see OS-Level/src/overlay/window_glow.py).-// We receive physical px (Plan §11.2 / §15.3) and pass them through-// unchanged to the worker — which converts them dpr-aware.--let worker: Worker | null = null;-let canvas: HTMLCanvasElement | null = null;--// Module-level resize handler — as a named function so teardown can-// unregister it via ``removeEventListener`` (hot-reload leak fix).-function _onWindowResize(): void {- if (canvas === null || worker === null) return;- resizeCanvasToViewport(canvas);- worker.postMessage({- type: "resize",- width: canvas.width,- height: canvas.height,- dpr: window.devicePixelRatio || 1,- });-}--interface InitOptions {- /** Container for the canvas. Default: ``document.body``. */- container?: HTMLElement;-}--/**- * Initializes the canvas + worker. Idempotent.- *- * Must be called BEFORE ``pushCursorPoint`` — otherwise pushes are- * silently dropped.- */-export function initCursorTrail(options: InitOptions = {}): void {- if (worker !== null) return;-- const container = options.container ?? document.body;-- canvas = document.createElement("canvas");- canvas.className = "cursor-trail-canvas";- // Fullscreen surface, click-through.- resizeCanvasToViewport(canvas);- container.appendChild(canvas);-- // OffscreenCanvas + worker — Plan §15.2.- const offscreen = canvas.transferControlToOffscreen();-- worker = new Worker(- new URL("./cursor-trail-worker.ts", import.meta.url),- { type: "module" },- );-- const dpr = window.devicePixelRatio || 1;- worker.postMessage(- { type: "init", canvas: offscreen, dpr },- [offscreen],- );-- // Resize listener — the Edge-Glow window can get resized by monitor- // hotplug. Named handler so teardown can remove it.- window.addEventListener("resize", _onWindowResize);-}--function resizeCanvasToViewport(c: HTMLCanvasElement): void {- const dpr = window.devicePixelRatio || 1;- const w = window.innerWidth;- const h = window.innerHeight;- c.style.width = `${w}px`;- c.style.height = `${h}px`;- c.width = Math.floor(w * dpr);- c.height = Math.floor(h * dpr);-}--/**- * Pushes a cursor point. Coords are PHYSICAL px (Plan §11.2);- * the worker converts via dpr.- */-export function pushCursorPoint(physicalX: number, physicalY: number): void {- if (worker === null) return;- worker.postMessage({ type: "push", x: physicalX, y: physicalY });-}--/**- * Clears the trail (e.g. on action_ended).- */-export function clearCursorTrail(): void {- if (worker === null) return;- worker.postMessage({ type: "clear" });-}--/**- * Test helper: tear-down between tests.- */-export function teardownCursorTrail(): void {- // Unregister the resize listener first — otherwise it can still fire- // while worker/canvas are being nulled out; it won't trigger any- // action, but it leaks the listener slot (hot-reload accumulation).- window.removeEventListener("resize", _onWindowResize);- if (worker !== null) {- worker.terminate();- worker = null;- }- if (canvas !== null) {- canvas.remove();- canvas = null;- }-}diff --git a/OS-Level/overlay-ui/src/edge-glow/edge-glow.css b/OS-Level/overlay-ui/src/edge-glow/edge-glow.cssdeleted file mode 100644index 284f2dc10e..0000000000--- a/OS-Level/overlay-ui/src/edge-glow/edge-glow.css+++ /dev/null@@ -1,411 +0,0 @@-/* edge-glow.css — Plan §7 Visual Design System- *- * Hard rules:- * - Palette §7.1 strict: only yellow + black + error-red.- * - Glow ACTIVE only in data-state="typing" or "clicking". (Plan §6.1)- * - Animations strict per §7.3:- * Conic-sweep rotation: linear (anything else stutters)- * Halo-breathing: cubic-bezier(0.25, 0.46, 0.45, 0.94) iOS default- * State-change: 250ms cubic-bezier(0.4, 0, 0.2, 1) Material standard- * - Hue-drift stays within the palette (+/- 15 deg).- * - prefers-reduced-motion: static low-intensity glow opacity 0.4.- * - contain: strict on the overlay root.- * - will-change: transform, filter ONLY on .edge-glow layers.- */--/* @property --angle allows CSS animations on custom properties.- * Without this declaration, conic-gradient(from var(--angle)) CANNOT- * be animated by the compositor. */-@property --angle {- syntax: "<angle>";- inherits: false;- initial-value: 0deg;-}--@property --hue-drift {- syntax: "<angle>";- inherits: true;- initial-value: 0deg;-}--@property --halo-a {- syntax: "<number>";- inherits: true;- initial-value: 0.45;-}--@property --halo-b {- syntax: "<number>";- inherits: true;- initial-value: 0.55;-}--:root {- /* Plan §7.1 palette — STRICT, no other colors. */- --jarvis-yellow-primary: #ffc700;- --jarvis-yellow-soft: #ffe066;- --jarvis-yellow-amber: #ffb300;- --jarvis-black: #0a0a0a;- --jarvis-error-red: #ff4d4d;-- /* Live-modulated properties — set by noise.ts 12x/s.- * Initial values via @property above. */- --intensity: 1;-}--html,-body {- margin: 0;- padding: 0;- width: 100vw;- height: 100vh;- background: transparent;- color: var(--jarvis-yellow-primary);- font-family: -apple-system, "Segoe UI", system-ui, sans-serif;- overflow: hidden;- /* Plan §7 + §17: contain: strict scopes layout/paint/style and- * gives the compositor maximum optimization freedom. */- contain: strict;-}--/* Edge-Glow container — Plan §7.4 multi-layer composition.- * Default: not visible. Active only via data-state typing/clicking. */-.edge-glow {- position: fixed;- inset: 0;- pointer-events: none;- /* Plan §7.6 SVG bloom filter is loaded inline in the HTML. */- filter: url(#jarvis-glow);- opacity: 0;- /* Plan §7.3: 250ms Material standard for state-change. */- transition: opacity 250ms cubic-bezier(0.4, 0, 0.2, 1);- /* The compositor writes this itself, not the renderer thread. */- will-change: opacity, filter;- /* a11y: the glow is not an interactive element, screen readers skip it. */- z-index: 0;-}--/* 5 layers with phase offset — Plan §7.4 items 1 + 2.- * Each layer has its own period variant via animation-delay; they all- * share the @keyframes rotate but start staggered. */-.edge-glow .layer {- position: absolute;- inset: 0;- /* Plan §7.2: 14px edge-band width @ 1x DPI. */- padding: 14px;- box-sizing: border-box;- /* Conic gradient as a rotating yellow stroke. Plan §7.5 reference- * algo takes 4 stops from the palette. */- background: conic-gradient(- from var(--angle),- transparent 0deg,- var(--jarvis-yellow-primary) 70deg,- var(--jarvis-yellow-soft) 160deg,- var(--jarvis-yellow-amber) 250deg,- var(--jarvis-yellow-primary) 340deg,- transparent 360deg- );- /* Mask-composite "exclude" punches out the inner area, so only- * the 14px edge stroke remains. Plan §7.2. */- -webkit-mask:- linear-gradient(#000, #000) content-box,- linear-gradient(#000, #000);- -webkit-mask-composite: xor;- mask:- linear-gradient(#000, #000) content-box,- linear-gradient(#000, #000);- mask-composite: exclude;- /* Plan §7.2: plus-lighter accumulates multiple layers into a luminous- * blend (Chrome 105+). */- mix-blend-mode: plus-lighter;- /* Hue-drift: modulated by noise.ts. Plan §7.4 item 3 — stays within- * the palette because the value is clamped to +/- 15deg (in JS). */- filter: hue-rotate(var(--hue-drift));- /* Phase 9.4: will-change strict ONLY here, NOT global. */- will-change: transform, filter, opacity;-}--/* @keyframes uses three separate periods to visually differentiate the- * phase offset without all layers running in exact lockstep. */-@keyframes rotate-edge {- to {- --angle: 360deg;- }-}--/* Halo-breathing per §7.3: 4.2s with iOS easing.- * Moves between --halo-a and --halo-b — both are modulated at 12 Hz by- * noise.ts, so the breathing never feels exactly periodic. */-@keyframes halo-breathe {- 0%,- 100% {- opacity: var(--halo-a);- }- 50% {- opacity: var(--halo-b);- }-}--/* Layer defaults — phase offset per Plan §7.4: approx. 200ms per corner. */-.edge-glow .layer.l1 {- animation:- rotate-edge var(--rot-period, 1.6s) linear infinite,- halo-breathe 4.2s cubic-bezier(0.25, 0.46, 0.45, 0.94) infinite;- animation-delay: 0s, 0s;-}-.edge-glow .layer.l2 {- animation:- rotate-edge var(--rot-period, 1.6s) linear infinite,- halo-breathe 4.2s cubic-bezier(0.25, 0.46, 0.45, 0.94) infinite;- animation-delay: -0.2s, -0.4s;-}-.edge-glow .layer.l3 {- animation:- rotate-edge var(--rot-period, 1.6s) linear infinite,- halo-breathe 4.2s cubic-bezier(0.25, 0.46, 0.45, 0.94) infinite;- animation-delay: -0.4s, -0.8s;-}-.edge-glow .layer.l4 {- animation:- rotate-edge var(--rot-period, 1.6s) linear infinite,- halo-breathe 4.2s cubic-bezier(0.25, 0.46, 0.45, 0.94) infinite;- animation-delay: -0.6s, -1.2s;-}-.edge-glow .layer.l5 {- animation:- rotate-edge var(--rot-period, 1.6s) linear infinite,- halo-breathe 4.2s cubic-bezier(0.25, 0.46, 0.45, 0.94) infinite;- animation-delay: -0.8s, -1.6s;-}--/* ----------------------------------------------------------------------- * State-driven activation — Plan §6.1: glow only typing/clicking/error.- * ---------------------------------------------------------------------- */--:root[data-state="typing"] .edge-glow {- opacity: var(--intensity);- --rot-period: 1.6s;-}--:root[data-state="clicking"] .edge-glow {- opacity: var(--intensity);- --rot-period: 0.9s;-}--/* Error flash: briefly red, faster. Plan §6.1 + §7.1 (error-red). */-:root[data-state="error"] .edge-glow {- opacity: 1;- --rot-period: 0.6s;-}-:root[data-state="error"] .edge-glow .layer {- background: conic-gradient(- from var(--angle),- transparent 0deg,- var(--jarvis-error-red) 120deg,- var(--jarvis-error-red) 240deg,- transparent 360deg- );- /* Hue-drift doesn't apply on the error path — consistent red tint. */- filter: none;-}--/* idle / listening / thinking / speaking / hidden: opacity 0 default.- * That's enough to keep the glow off. Layers keep running in the- * compositor — effectively zero cost because opacity:0 + will-change:opacity- * is handled trivially by the compositor. Phase 9.7 throttles FPS via- * setSuspended. */--/* ----------------------------------------------------------------------- * Reduced motion — Plan §19.1 + §19.2- * Static low-intensity glow opacity 0.4, no animations.- * ---------------------------------------------------------------------- */--@media (prefers-reduced-motion: reduce) {- .edge-glow .layer {- animation: none !important;- }- :root[data-state="typing"] .edge-glow,- :root[data-state="clicking"] .edge-glow,- :root[data-state="error"] .edge-glow {- opacity: 0.4;- }-}--/* ----------------------------------------------------------------------- * High contrast — Plan §19.4- * forced-colors: drop bloom, simple 4px CanvasText border.- * ---------------------------------------------------------------------- */--@media (forced-colors: active) {- .edge-glow {- filter: none;- }- .edge-glow .layer {- background: none;- animation: none;- border: 4px solid CanvasText;- }-}--/* ----------------------------------------------------------------------- * Phase 9.5 — Action effects: click ripple, cursor trail, typing sweep- * ---------------------------------------------------------------------- */--/* Ripple layer — fullscreen pointer-events:none container for the- * pool of 8 ripple divs. Plan §14.2. */-.ripple-layer {- position: fixed;- inset: 0;- pointer-events: none;- z-index: 2; /* above the .edge-glow layer */- overflow: hidden;-}--/* Single ripple slot in the pool. The outer div positions itself via- * inline ``transform: translate(x, y)`` at the click coordinate (8x8- * bounding box). The inner pseudo-::before does the- * ``scale(40) + opacity 1->0`` animation — that way scale doesn't- * override the position translate.- * Plan §14.1: 8x8 px circle, expands to scale(40), opacity 1 -> 0,- * 600 ms cubic-bezier(0.2, 0.7, 0.3, 1). */-.ripple {- position: absolute;- top: 0;- left: 0;- width: 8px;- height: 8px;- margin-left: -4px; /* visual center on the translate coord */- margin-top: -4px;- pointer-events: none;- will-change: transform;-}--.ripple::before {- content: "";- position: absolute;- inset: 0;- border-radius: 50%;- background: radial-gradient(- circle,- var(--jarvis-yellow-primary) 0%,- rgba(255, 199, 0, 0.25) 60%,- transparent 70%- );- box-shadow: 0 0 24px 6px rgba(255, 199, 0, 0.55);- transform: scale(0);- opacity: 0;- will-change: transform, opacity;-}--.ripple.active::before {- animation: ripple-expand 600ms cubic-bezier(0.2, 0.7, 0.3, 1) forwards;-}--@keyframes ripple-expand {- 0% {- transform: scale(0);- opacity: 1;- }- 100% {- transform: scale(40);- opacity: 0;- }-}--/* Cursor-trail canvas — the worker renders the OffscreenCanvas, Plan §15.2.- * Fullscreen, click-through, above the edge glow but below the ripple. */-.cursor-trail-canvas {- position: fixed;- inset: 0;- width: 100vw;- height: 100vh;- pointer-events: none;- z-index: 1;-}--/* Typing sweep — bottom-edge 4px line. Plan §16.1.- * -100% -> +100% via translateX, 200ms linear. */-.typing-sweep {- position: fixed;- left: 0;- bottom: 0;- width: 100vw;- height: 4px;- pointer-events: none;- z-index: 2;- /* Yellow gradient with a centrally-focused highlight — the sweep- * effect comes from translateX-ing a mid-highlight surface. */- background: linear-gradient(- 90deg,- transparent 0%,- rgba(255, 199, 0, 0.0) 30%,- var(--jarvis-yellow-primary) 50%,- rgba(255, 199, 0, 0.0) 70%,- transparent 100%- );- opacity: 0;- transform: translateX(-100%);- will-change: transform, opacity;-}--.typing-sweep.active {- animation: typing-sweep 200ms linear forwards;-}--@keyframes typing-sweep {- 0% {- opacity: 0;- transform: translateX(-100%);- }- 10% {- opacity: 1;- }- 90% {- opacity: 1;- }- 100% {- opacity: 0;- transform: translateX(100%);- }-}--/* Reduced motion: dim the effects too. Plan §19.1. */-@media (prefers-reduced-motion: reduce) {- .ripple,- .typing-sweep {- animation: none !important;- opacity: 0 !important;- }- .cursor-trail-canvas {- opacity: 0;- }-}--/* ----------------------------------------------------------------------- * Debug state display — only visible via ?debug=1.- * main.ts sets :root[data-debug="1"] at boot.- * ---------------------------------------------------------------------- */--#state-display {- position: fixed;- top: 8px;- right: 12px;- font-size: 12px;- line-height: 1.2;- padding: 4px 8px;- background: rgba(10, 10, 10, 0.55);- border: 1px solid var(--jarvis-yellow-primary);- border-radius: 4px;- pointer-events: none;- display: none;- z-index: 1;-}-#state-display .state {- font-weight: 700;-}-#state-display .reason {- opacity: 0.7;-}-:root[data-debug="1"] #state-display {- display: block;-}diff --git a/OS-Level/overlay-ui/src/edge-glow/glow.svg b/OS-Level/overlay-ui/src/edge-glow/glow.svgdeleted file mode 100644index 8d5dc78bc0..0000000000--- a/OS-Level/overlay-ui/src/edge-glow/glow.svg+++ /dev/null@@ -1,39 +0,0 @@-<!-- Plan §7.6 SVG Bloom-Filter (woertlich uebernommen aus dem Plan).- Wird via glow.ts ?raw-imported und in document.body injected. Das- 0x0-Wrapper-SVG ist visuell unsichtbar; der Filter ist ueber- `filter: url(#jarvis-glow)` im CSS referenziert.-- Critical (Plan §7.6): Filter-Viewport mit x="-15%" / y="-15%" und- width="130%" / height="130%" extended, sonst clippt der Blur an den- SVG-Bounds. -->-<svg- xmlns="http://www.w3.org/2000/svg"- width="0"- height="0"- style="position: absolute"- aria-hidden="true"->- <defs>- <filter id="jarvis-glow" x="-15%" y="-15%" width="130%" height="130%">- <feGaussianBlur in="SourceGraphic" stdDeviation="6" result="b1" />- <feGaussianBlur in="SourceGraphic" stdDeviation="22" result="b2" />- <!-- feColorMatrix shiftet den weiter-blurred Pass Richtung- Jarvis-Yellow, unabhaengig von der Source-Stroke-Farbe.- Apple-Intelligence "Color-Bleed"-Charakter. -->- <feColorMatrix- in="b2"- type="matrix"- result="b2y"- values="1 .2 0 0 .05- .8 .6 0 0 .03- 0 0 0 0 0- 0 0 0 1 0"- />- <feMerge>- <feMergeNode in="b2y" />- <feMergeNode in="b1" />- <feMergeNode in="SourceGraphic" />- </feMerge>- </filter>- </defs>-</svg>diff --git a/OS-Level/overlay-ui/src/edge-glow/glow.ts b/OS-Level/overlay-ui/src/edge-glow/glow.tsdeleted file mode 100644index 664b4aa3f1..0000000000--- a/OS-Level/overlay-ui/src/edge-glow/glow.ts+++ /dev/null@@ -1,104 +0,0 @@-// glow.ts — State-driven Edge-Glow setup. Plan §6.1 + §7.4.-//-// Responsibilities:-// - Inject the inline SVG filter into document.body at boot.-// - Set the data-state attribute on <html> (state machine -> CSS selectors).-// - Set the data-debug attribute when ?debug=1 is in the URL.-// - State-display text for diagnostics, gated by the debug flag.-//-// No animation control here — that all runs in CSS-// (@property compositor animation). noise.ts does the 12 Hz modulation.--import glowSvgRaw from "./glow.svg?raw";--import type { StateName } from "../schema";--const ROOT = document.documentElement;--/**- * Injects the inline SVG filter into the DOM. Plan §7.6 — the filter- * must be there before the first frame, otherwise `filter:- * url(#jarvis-glow)` has nothing to resolve for one frame.- */-export function injectGlowFilter(): void {- if (document.getElementById("jarvis-glow")) return;- // DOMParser instead of innerHTML — defense in depth against- // supply-chain XSS (even though glowSvgRaw comes from the build via- // ?raw). DOMParser marks non-SVG content with a <parsererror>- // element, which we catch.- const doc = new DOMParser().parseFromString(glowSvgRaw, "image/svg+xml");- const svg = doc.documentElement;- if (svg.getElementsByTagName("parsererror").length > 0) return;- if (svg.nodeName.toLowerCase() === "svg") {- document.body.insertAdjacentElement("afterbegin", svg as unknown as Element);- }-}--/**- * Appends 5 layer divs into the `.edge-glow` container. Plan §7.4 —- * multi-layer composition with a phase offset (5 layers, each staggered- * by 200 ms via animation-delay in the CSS).- */-export function buildLayers(container: HTMLElement): void {- if (container.children.length > 0) return;- for (let i = 1; i <= 5; i += 1) {- const layer = document.createElement("div");- layer.className = `layer l${i}`;- container.appendChild(layer);- }-}--/**- * Sets the ``data-state`` attribute on `<html>` — CSS reacts to it- * via `:root[data-state="typing"] .edge-glow { ... }`.- */-export function applyState(state: StateName): void {- ROOT.dataset["state"] = state;-}--/**- * Optional: explicit intensity modulation. Default 1.0 — Phase 9.5- * might bump this to 1.2 for activity bursts.- */-export function setIntensity(value: number): void {- const clamped = Math.max(0, Math.min(2, value));- ROOT.style.setProperty("--intensity", String(clamped));-}--/**- * ?debug=1 in the URL query → the state-display marker in the top- * right becomes visible. Otherwise #state-display stays hidden via- * CSS display:none.- */-export function applyDebugFlag(): boolean {- const params = new URLSearchParams(window.location.search);- const debug = params.get("debug") === "1";- if (debug) {- ROOT.dataset["debug"] = "1";- } else {- delete ROOT.dataset["debug"];- }- return debug;-}--/**- * Writes the current state + reason into #state-display. On the- * production path (no ?debug=1) the element is hidden via CSS — the- * update still costs nothing besides a dataset write.- */-export function setStateDisplay(state: StateName, reason: string): void {- const el = document.getElementById("state-display");- if (el === null) return;- const stateSpan = document.createElement("span");- stateSpan.className = "state";- stateSpan.textContent = state;- if (reason !== "") {- const reasonSpan = document.createElement("span");- reasonSpan.className = "reason";- reasonSpan.textContent = ` (${reason})`;- el.replaceChildren(stateSpan, reasonSpan);- } else {- el.replaceChildren(stateSpan);- }- el.dataset["state"] = state;-}diff --git a/OS-Level/overlay-ui/src/edge-glow/main.ts b/OS-Level/overlay-ui/src/edge-glow/main.tsdeleted file mode 100644index f80bfa235a..0000000000--- a/OS-Level/overlay-ui/src/edge-glow/main.ts+++ /dev/null@@ -1,142 +0,0 @@-// Edge-Glow Renderer Entry — Phase 9.5.-//-// Boot sequence:-// 1. Import the CSS (Vite injects the style tag).-// 2. Inject the SVG filter into the DOM (before the first frame!).-// 3. Append 5 layer divs into the .edge-glow container.-// 4. Set the ?debug=1 flag on <html>.-// 5. Build the effect surfaces (ripple pool, cursor-trail canvas,-// typing sweep).-// 6. Start the noise runner (12 Hz, except with prefers-reduced-motion).-// 7. Connect the QWebChannel bridge.-// - State -> data-state attribute on <html>.-// - Click -> ripple.triggerRipple.-// - Cursor -> cursor-trail.pushCursorPoint.-// - Action started/ended (kind=typing) -> typing-sweep.scheduleSweepBurst.-//-// Glow activation happens entirely via data-state attributes on-// <html> — see edge-glow.css. JS only pushes state strings, no-// imperative animation driving.--import "./edge-glow.css";--import { connectBridge } from "../bridge";-import { isGlowActive } from "../schema";-import { clearCursorTrail, initCursorTrail, pushCursorPoint } from "./cursor-trail";-import {- applyDebugFlag,- applyState,- buildLayers,- injectGlowFilter,- setStateDisplay,-} from "./glow";-import { startNoise } from "./noise";-import { buildRipplePool, triggerRipple } from "./ripple";-import {- applySweepBaseline,- buildTypingSweep,- cancelSweepBurst,- scheduleSweepBurst,-} from "./typing-sweep";--function bootEnv(): { debug: boolean; reducedMotion: boolean } {- injectGlowFilter();- const container = document.querySelector<HTMLElement>(".edge-glow");- if (container !== null) {- buildLayers(container);- } else {- console.warn("[edge-glow] .edge-glow container missing in HTML");- }- buildRipplePool();- buildTypingSweep();- initCursorTrail();- const debug = applyDebugFlag();- const reducedMotion =- typeof window.matchMedia === "function" &&- window.matchMedia("(prefers-reduced-motion: reduce)").matches;- return { debug, reducedMotion };-}--const TYPING_KINDS = new Set(["type", "hotkey"]);--async function boot(): Promise<void> {- const env = bootEnv();- console.log(- `[edge-glow] booting (debug=${env.debug}, reduced-motion=${env.reducedMotion})`,- );-- // Idle immediately as the default — matches StateMachine.IDLE's initial.- applyState("idle");- setStateDisplay("idle", "");-- // 12 Hz simplex noise — startNoise no-ops with reduced motion.- const noiseRunner = startNoise();-- // Power saving: when the WebView is hidden (e.g. overlay off, workspace- // switch), we stop the 12-Hz setInterval tick. Otherwise it keeps running- // for the whole WebView lifetime and writes CSS custom properties even in- // the hidden state (style-recalc cost with no visible effect). stop() is- // idempotent + no-ops if it was never started (reduced-motion path).- // Restarting on visible is out of scope — becoming visible means a- // page reload.- document.addEventListener("visibilitychange", () => {- if (document.hidden) {- noiseRunner.stop();- }- });-- try {- const bridge = await connectBridge();- const initial = await bridge.currentState();- console.log("[edge-glow] initial state", initial);- applyState(initial);- setStateDisplay(initial, "");-- bridge.onStateChange(({ old, next, reason }) => {- const willGlow = isGlowActive(next);- console.log(- `[edge-glow] ${old} -> ${next} (${reason || "n/a"}) glow=${willGlow}`,- );- applyState(next);- setStateDisplay(next, reason);- });-- // Phase 9.5 Effekte — alle drei Bridge-Hooks.- bridge.onClickEvent(({ x, y }) => {- triggerRipple(x, y);- });-- bridge.onCursorMoved((x, y) => {- pushCursorPoint(x, y);- });-- bridge.onActionStarted((kind, durationHintMs) => {- if (TYPING_KINDS.has(kind)) {- applySweepBaseline(true);- if (durationHintMs > 0) {- scheduleSweepBurst(durationHintMs);- } else {- // No hint -> a single sweep at the start.- scheduleSweepBurst(0);- }- }- });-- bridge.onActionEnded(() => {- cancelSweepBurst();- applySweepBaseline(false);- clearCursorTrail();- });- } catch (err) {- // Standalone Vite dev or a QWebChannel boot race: idle stays set- // (see above), we only update the diagnostic tag.- console.warn("[edge-glow] bridge unavailable", err);- setStateDisplay("idle", "no-bridge");- }-}--if (document.readyState === "loading") {- document.addEventListener("DOMContentLoaded", boot);-} else {- void boot();-}diff --git a/OS-Level/overlay-ui/src/edge-glow/noise.ts b/OS-Level/overlay-ui/src/edge-glow/noise.tsdeleted file mode 100644index ceb1543668..0000000000--- a/OS-Level/overlay-ui/src/edge-glow/noise.ts+++ /dev/null@@ -1,90 +0,0 @@-// noise.ts — 12 Hz simplex noise on 3 CSS custom properties.-// Plan §7.4 item 5: organic randomness via simplex noise.-//-// Drift ranges (values clamped):-// --hue-drift : -15deg .. +15deg (plan constraint, stays within the palette)-// --halo-a : 0.25 .. 0.45 (inner halo layer)-// --halo-b : 0.45 .. 0.65 (outer halo layer)-//-// 12 Hz = ~83.3 ms period. We use setInterval — the frame drift is-// intentional for organic noise and doesn't need rAF precision. Setting-// custom properties is microsecond-cheap; no style recalc because the-// properties are registered (@property).-//-// prefers-reduced-motion: drift is suspended entirely — values stay-// static at the CSS default.--import { createNoise2D } from "simplex-noise";--const ROOT = document.documentElement;--// Plan constraints — hue-drift NEVER outside +/- 15 deg.-const HUE_AMPLITUDE_DEG = 15;-const HALO_A_MIN = 0.25;-const HALO_A_MAX = 0.45;-const HALO_B_MIN = 0.45;-const HALO_B_MAX = 0.65;--// 12 Hz, slightly jittered so the pattern isn't perfectly periodic.-const PERIOD_MS = 1000 / 12;--interface NoiseRunner {- stop(): void;- isRunning(): boolean;-}--function lerp(min: number, max: number, t: number): number {- // simplex returns -1..1 -> remap to 0..1- const normalized = (t + 1) / 2;- return min + (max - min) * normalized;-}--/**- * Starts the 12-Hz modulation. Returns a handle with ``stop()``.- *- * If the browser reports ``prefers-reduced-motion: reduce``, the- * runner never starts in the first place — the custom properties stay- * at their CSS defaults and the glow is static (Plan §19.1).- */-export function startNoise(): NoiseRunner {- const reducedMotion =- typeof window.matchMedia === "function" &&- window.matchMedia("(prefers-reduced-motion: reduce)").matches;-- if (reducedMotion) {- return {- stop() {- /* no-op */- },- isRunning() {- return false;- },- };- }-- // 3 independent noise functions so hue/halo-a/halo-b aren't- // correlated with each other.- const hueNoise = createNoise2D();- const haloANoise = createNoise2D();- const haloBNoise = createNoise2D();-- let t = 0;- const intervalId = window.setInterval(() => {- t += 0.05; // slow walk through the noise field- const hue = hueNoise(t, 0) * HUE_AMPLITUDE_DEG;- const haloA = lerp(HALO_A_MIN, HALO_A_MAX, haloANoise(t, 1));- const haloB = lerp(HALO_B_MIN, HALO_B_MAX, haloBNoise(t, 2));- ROOT.style.setProperty("--hue-drift", `${hue.toFixed(2)}deg`);- ROOT.style.setProperty("--halo-a", haloA.toFixed(3));- ROOT.style.setProperty("--halo-b", haloB.toFixed(3));- }, PERIOD_MS);-- return {- stop() {- window.clearInterval(intervalId);- },- isRunning() {- return true;- },- };-}diff --git a/OS-Level/overlay-ui/src/edge-glow/ripple.ts b/OS-Level/overlay-ui/src/edge-glow/ripple.tsdeleted file mode 100644index 27e25ec660..0000000000--- a/OS-Level/overlay-ui/src/edge-glow/ripple.ts+++ /dev/null@@ -1,133 +0,0 @@-// ripple.ts — Click-ripple effect. Plan §14.-//-// Pre-warms a pool of 8 divs (Plan §14.2) so burst clicks don't trigger-// appendChild/layout jank. The animation runs entirely in CSS-// (transform+opacity, compositor-only).-//-// Coords from Hauptjarvis are PHYSICAL pixels (Plan §14.4). We convert-// to CSS-logical at the renderer boundary — one spot, not an-// off-by-DPI bug scattered everywhere.--const POOL_SIZE = 8;-const RIPPLE_LIFETIME_MS = 600; // Plan §14.1--interface RippleSlot {- el: HTMLDivElement;- inUse: boolean;- resetTimer: number | null;-}--let pool: RippleSlot[] | null = null;-let layer: HTMLElement | null = null;--/**- * Creates the pool. Idempotent — repeated calls are no-ops.- *- * The container must be a ``.ripple-layer`` surface (per CSS- * pointer-events:none, position:fixed inset:0). buildRipplePool- * appends it to ``document.body``; the caller can also pass its own- * container element (testable).- */-export function buildRipplePool(container?: HTMLElement): void {- if (pool !== null) return;-- layer = container ?? document.querySelector<HTMLElement>(".ripple-layer");- if (layer === null) {- layer = document.createElement("div");- layer.className = "ripple-layer";- document.body.appendChild(layer);- }-- pool = [];- for (let i = 0; i < POOL_SIZE; i += 1) {- const el = document.createElement("div");- el.className = "ripple";- el.dataset["slot"] = String(i);- // Initial off-screen + invisible — takes up no space.- el.style.opacity = "0";- el.style.transform = "translate(-9999px, -9999px) scale(0)";- layer.appendChild(el);- pool.push({ el, inUse: false, resetTimer: null });- }-}--/**- * Spawns a ripple at the click coordinate. Plan §14.4 — physical px in,- * CSS px out via ``window.devicePixelRatio``.- *- * Returns ``true`` if a pool slot was available, ``false`` if all 8- * slots are active (a burst of > 8 clicks within 600 ms — the 9th- * gets dropped; an acceptable edge case).- */-export function triggerRipple(physicalX: number, physicalY: number): boolean {- if (pool === null) {- buildRipplePool();- }- // pool was just built, guaranteed non-null.- const p = pool as RippleSlot[];-- const slot = p.find((s) => !s.inUse);- if (slot === undefined) {- // All 8 slots in use. Plan §14.5 (edge case) says "acceptable".- return false;- }-- const dpr = window.devicePixelRatio || 1;- const cssX = physicalX / dpr;- const cssY = physicalY / dpr;-- slot.inUse = true;- // Re-trigger the CSS animation: reset first, then set.- // Force reflow between the two class toggles so the animation- // actually restarts (important on pool reuse).- slot.el.classList.remove("active");- slot.el.style.transform = `translate(${cssX}px, ${cssY}px) scale(0)`;- slot.el.style.opacity = "1";- // Force reflow.- void slot.el.offsetWidth;- slot.el.classList.add("active");-- // Reset timer: back into the pool after 600 ms.- if (slot.resetTimer !== null) {- window.clearTimeout(slot.resetTimer);- }- slot.resetTimer = window.setTimeout(() => {- slot.el.classList.remove("active");- slot.el.style.opacity = "0";- slot.el.style.transform = "translate(-9999px, -9999px) scale(0)";- slot.inUse = false;- slot.resetTimer = null;- }, RIPPLE_LIFETIME_MS);-- return true;-}--/**- * Test helper: current pool utilization. Not relevant to production.- */-export function ripplePoolStats(): { total: number; inUse: number } {- if (pool === null) return { total: 0, inUse: 0 };- return {- total: pool.length,- inUse: pool.filter((s) => s.inUse).length,- };-}--/**- * Test helper: reset the pool between tests.- */-export function resetRipplePool(): void {- if (pool !== null) {- for (const slot of pool) {- if (slot.resetTimer !== null) {- window.clearTimeout(slot.resetTimer);- }- slot.el.remove();- }- }- if (layer !== null && layer.parentElement !== null) {- layer.remove();- }- pool = null;- layer = null;-}diff --git a/OS-Level/overlay-ui/src/edge-glow/typing-sweep.ts b/OS-Level/overlay-ui/src/edge-glow/typing-sweep.tsdeleted file mode 100644index cdb98ea1d7..0000000000--- a/OS-Level/overlay-ui/src/edge-glow/typing-sweep.ts+++ /dev/null@@ -1,145 +0,0 @@-// typing-sweep.ts — Bottom-edge sweep per keystroke. Plan §16.-//-// Single sweep div at the bottom (4 px tall). triggerSweep() runs a-// 200-ms animation (-100% -> +100% via translateX) and bumps-// --intensity from 0.85 to 1.2 for 200 ms.-//-// scheduleSweepBurst(durationHintMs, n) distributes n sweeps evenly-// over the action duration (Plan: "pulse N/100 sweeps spread evenly").-// This is the ambient variant for an entire typing phase.--const SWEEP_DURATION_MS = 200; // Plan §16.1-const INTENSITY_BOOST = 1.2;-const INTENSITY_BASELINE = 1.0; // matched edge-glow.css default-const INTENSITY_LOWER = 0.85;--let sweepEl: HTMLElement | null = null;-let sweepResetTimer: number | null = null;-let intensityResetTimer: number | null = null;-const burstHandles: number[] = [];-let burstIntervalId: number | null = null;--/**- * Creates the sweep div. Idempotent. Container default: ``document.body``.- */-export function buildTypingSweep(container?: HTMLElement): void {- if (sweepEl !== null) return;- const parent = container ?? document.body;- sweepEl = document.createElement("div");- sweepEl.className = "typing-sweep";- parent.appendChild(sweepEl);-}--/**- * Triggers a single sweep + intensity bump. Re-trigger safe:- * cancels a running sweep and starts a new one.- */-export function triggerSweep(): void {- if (sweepEl === null) buildTypingSweep();- const el = sweepEl as HTMLElement;- const root = document.documentElement;-- // Restart the sweep — remove class, reflow, re-add class.- el.classList.remove("active");- void el.offsetWidth;- el.classList.add("active");-- // Intensity bump.- root.style.setProperty("--intensity", String(INTENSITY_BOOST));- if (intensityResetTimer !== null) {- window.clearTimeout(intensityResetTimer);- }- intensityResetTimer = window.setTimeout(() => {- root.style.setProperty("--intensity", String(INTENSITY_BASELINE));- intensityResetTimer = null;- }, SWEEP_DURATION_MS);-- if (sweepResetTimer !== null) {- window.clearTimeout(sweepResetTimer);- }- sweepResetTimer = window.setTimeout(() => {- el.classList.remove("active");- sweepResetTimer = null;- }, SWEEP_DURATION_MS);-}--/**- * Ambient burst: pulses ``ceil(durationHintMs / 100)`` sweeps spread- * over the action duration. Plan: "pulse N/100 sweeps spread evenly".- *- * Cancels a running burst (e.g. when a new typing action overlaps- * the running one).- */-export function scheduleSweepBurst(durationHintMs: number): void {- cancelSweepBurst();- if (durationHintMs <= 0) {- triggerSweep();- return;- }- // 1 sweep per 100 ms, at least 1.- const total = Math.max(1, Math.ceil(durationHintMs / 100));- const interval = durationHintMs / total;-- // First sweep immediately, then interval-based.- triggerSweep();- let fired = 1;- burstIntervalId = window.setInterval(() => {- if (fired >= total) {- cancelSweepBurst();- return;- }- triggerSweep();- fired += 1;- }, interval);-}--/**- * Aborts a running burst. The sweep animation runs out, but no- * further sweeps get spawned.- */-export function cancelSweepBurst(): void {- if (burstIntervalId !== null) {- window.clearInterval(burstIntervalId);- burstIntervalId = null;- }- for (const h of burstHandles) {- window.clearTimeout(h);- }- burstHandles.length = 0;-}--/**- * Lower bound of intensity between sweep bursts (from action_started- * to action_ended, --intensity stays at INTENSITY_LOWER so the glow- * looks dimmer between keystrokes). Optional — main.ts calls this on- * typing-action_started.- */-export function applySweepBaseline(active: boolean): void {- document.documentElement.style.setProperty(- "--intensity",- active ? String(INTENSITY_LOWER) : String(INTENSITY_BASELINE),- );-}--/**- * Test helper: tear-down.- */-export function teardownTypingSweep(): void {- cancelSweepBurst();- if (sweepResetTimer !== null) {- window.clearTimeout(sweepResetTimer);- sweepResetTimer = null;- }- if (intensityResetTimer !== null) {- window.clearTimeout(intensityResetTimer);- intensityResetTimer = null;- }- if (sweepEl !== null) {- sweepEl.remove();- sweepEl = null;- }- document.documentElement.style.setProperty(- "--intensity",- String(INTENSITY_BASELINE),- );-}diff --git a/OS-Level/overlay-ui/src/mascot/main.ts b/OS-Level/overlay-ui/src/mascot/main.tsdeleted file mode 100644index bf12de5a5d..0000000000--- a/OS-Level/overlay-ui/src/mascot/main.ts+++ /dev/null@@ -1,148 +0,0 @@-// Mascot Renderer Entry. Plan §13 + AD-16.-//-// Phase 9.6 DECISION (documented in the commit): PNG fallback only.-// Rationale: Rive files (.riv) are a proprietary binary format that-// can only be created in the Rive editor; it can't be produced-// generatively. Plan AD-16 explicitly allows the fallback.-// A real Rive asset can be supplied later via 'overlay-ui/src/mascot/-// mascot.riv' — the code path below tries to load it first and falls-// back to the PNG if it's not there.-//-// Boot:-// 1. Import the CSS.-// 2. PNG via fallback.png import (Vite hashes the URL).-// 3. Try to load mascot.riv with @rive-app/canvas-lite. If the-// asset isn't there (404 or decode failure), show the PNG.-// 4. Connect QWebChannel -> set the data-state attribute on <html>.-// With Rive: additionally trigger state-machine inputs.--import "./mascot.css";--import fallbackPng from "./mascot-fallback.png";--import { connectBridge } from "../bridge";-import type { StateName } from "../schema";--const ROOT = document.documentElement;-// Vite ignores the URL — we explicitly want an optional file lookup at-// runtime. Without @vite-ignore, Vite would emit a build warning-// because the asset doesn't exist yet.-const RIVE_ASSET_URL = new URL(- /* @vite-ignore */ "./mascot.riv",- import.meta.url,-).href;--interface RiveLikeRuntime {- on(event: string, cb: () => void): void;- stateMachineInputs(name: string): RiveStateMachineInput[] | null;- cleanup?: () => void;-}--interface RiveStateMachineInput {- name: string;- fire?: () => void;- value?: unknown;-}--let rive: RiveLikeRuntime | null = null;--function showFallback(): void {- const img = document.getElementById("mascot-fallback") as HTMLImageElement | null;- const canvas = document.getElementById("mascot-canvas");- if (img !== null) {- img.src = fallbackPng;- img.hidden = false;- }- if (canvas !== null) {- canvas.setAttribute("hidden", "");- }-}--async function attemptRiveLoad(): Promise<boolean> {- // Lazy import so @rive-app/canvas-lite doesn't have to end up in the- // main bundle when the asset is missing.- let RiveModule: { Rive: new (cfg: Record<string, unknown>) => RiveLikeRuntime; Layout?: unknown };- try {- RiveModule = (await import("@rive-app/canvas-lite")) as unknown as typeof RiveModule;- } catch (err) {- console.warn("[mascot] @rive-app/canvas-lite import failed", err);- return false;- }-- // No HEAD preflight: avoids console network errors on file:// URLs- // (QtWebEngine production) and potential network leaks on remote URLs.- // Rive's onLoadError callback (below) is the canonical path for- // 404 -> PNG fallback.- const canvas = document.getElementById("mascot-canvas") as HTMLCanvasElement | null;- if (canvas === null) {- console.warn("[mascot] canvas#mascot-canvas missing");- return false;- }-- return new Promise((resolve) => {- try {- const r = new RiveModule.Rive({- src: RIVE_ASSET_URL,- canvas,- autoplay: true,- stateMachines: "State Machine 1",- onLoad: () => {- canvas.removeAttribute("hidden");- rive = r;- resolve(true);- },- onLoadError: (err: unknown) => {- console.warn("[mascot] Rive load error", err);- resolve(false);- },- });- } catch (err) {- console.warn("[mascot] Rive constructor error", err);- resolve(false);- }- });-}--function applyStateToRive(state: StateName): void {- if (rive === null) return;- const inputs = rive.stateMachineInputs("State Machine 1");- if (inputs === null) return;- // Plan §13.2: trigger-named input per state.- const triggerName = state === "typing" || state === "clicking" ? "acting" : state;- for (const inp of inputs) {- if (inp.name === triggerName && typeof inp.fire === "function") {- inp.fire();- return;- }- }-}--async function boot(): Promise<void> {- console.log("[mascot] booting");- ROOT.dataset["state"] = "idle";-- const riveLoaded = await attemptRiveLoad();- if (!riveLoaded) {- showFallback();- }-- try {- const bridge = await connectBridge();- const initial = await bridge.currentState();- ROOT.dataset["state"] = initial;- applyStateToRive(initial);-- bridge.onStateChange(({ next }) => {- ROOT.dataset["state"] = next;- applyStateToRive(next);- });- } catch (err) {- console.warn("[mascot] bridge unavailable", err);- }-}--if (document.readyState === "loading") {- document.addEventListener("DOMContentLoaded", boot);-} else {- void boot();-}diff --git a/OS-Level/overlay-ui/src/mascot/mascot-fallback.png b/OS-Level/overlay-ui/src/mascot/mascot-fallback.pngdeleted file mode 100644index 9fc561cf98..0000000000Binary files a/OS-Level/overlay-ui/src/mascot/mascot-fallback.png and /dev/null differdiff --git a/OS-Level/overlay-ui/src/mascot/mascot.css b/OS-Level/overlay-ui/src/mascot/mascot.cssdeleted file mode 100644index ac9c6d9999..0000000000--- a/OS-Level/overlay-ui/src/mascot/mascot.css+++ /dev/null@@ -1,104 +0,0 @@-/* mascot.css — Plan §13.- *- * Body + window are transparent, the mascot fills the full 160x160- * window. The Rive canvas or PNG fallback is stretched to a 100%- * surface; CSS only animates a subtle idle pulse for the case where- * neither Rive nor a state animation applies.- */--html,-body {- margin: 0;- padding: 0;- width: 100vw;- height: 100vh;- background: transparent;- overflow: hidden;- /* Plan §17: contain: strict on the mascot root. */- contain: strict;- /* The mascot is drag/right-click-sensitive — pointer-events default. */-}--.mascot-host {- position: fixed;- inset: 0;- display: flex;- align-items: center;- justify-content: center;- /* Subtle idle pulse via opacity. Plan §13.1 says "gentle, not eye-- * catching". Transform-only animation = compositor thread. */- animation: mascot-idle-pulse 8s ease-in-out infinite;-}--#mascot-canvas,-#mascot-fallback {- width: 100%;- height: 100%;- /* Pixel art / PNG should stay crisp-sharp when the user- * picks a different mascot size. */- image-rendering: pixelated;- image-rendering: crisp-edges;- user-select: none;- -webkit-user-drag: none;- pointer-events: none; /* Drag faengt das Qt-Window selbst */-}--#mascot-canvas[hidden],-#mascot-fallback[hidden] {- display: none;-}--@keyframes mascot-idle-pulse {- 0%,- 100% {- transform: scale(1);- opacity: 0.92;- }- 50% {- transform: scale(1.02);- opacity: 1;- }-}--/* State-driven tweaks — Plan §13.2 maps OverlayState onto Rive inputs;- * in the fallback we apply a static tint via CSS filter so the user- * at least sees the state change subtly. */-:root[data-state="error"] .mascot-host {- animation:- mascot-idle-pulse 8s ease-in-out infinite,- mascot-error-flash 0.6s linear 1;-}-:root[data-state="thinking"] .mascot-host {- animation: mascot-idle-pulse 4s ease-in-out infinite;-}-:root[data-state="speaking"] .mascot-host {- animation: mascot-speaking 0.4s ease-in-out infinite;-}--@keyframes mascot-error-flash {- 0%,- 100% {- filter: none;- }- 50% {- filter: hue-rotate(-30deg) saturate(2);- }-}--@keyframes mascot-speaking {- 0%,- 100% {- transform: scale(1.0);- }- 50% {- transform: scale(1.04);- }-}--/* prefers-reduced-motion: pause mascot animations, static. */-@media (prefers-reduced-motion: reduce) {- .mascot-host,- .mascot-host * {- animation: none !important;- }-}diff --git a/OS-Level/overlay-ui/src/schema.ts b/OS-Level/overlay-ui/src/schema.tsdeleted file mode 100644index 6ade9c8ee6..0000000000--- a/OS-Level/overlay-ui/src/schema.ts+++ /dev/null@@ -1,38 +0,0 @@-// Zod schemas, mirrored to the Pydantic v2 models in-// OS-Level/src/overlay/schema.py. Symmetry is Plan AD-15. Phase 9.3-// only needs the state slice; more envelopes will move here in-// 9.4 and beyond.--import { z } from "zod";--export const StateNameSchema = z.enum([- "idle",- "listening",- "thinking",- "typing",- "clicking",- "speaking",- "error",- "hidden",-]);--export type StateName = z.infer<typeof StateNameSchema>;--// (old, new, reason) — matches the signature of StateBridge.stateChanged-// on the Python side (window_glow.py).-export const StateChangeSchema = z.object({- old: StateNameSchema,- next: StateNameSchema,- reason: z.enum(["wakeword", "user", "tool", "timeout", "error", ""]),-});--export type StateChange = z.infer<typeof StateChangeSchema>;--export const GLOW_ACTIVE_STATES: ReadonlySet<StateName> = new Set<StateName>([- "typing",- "clicking",-]);--export function isGlowActive(state: StateName): boolean {- return GLOW_ACTIVE_STATES.has(state);-}diff --git a/OS-Level/overlay-ui/src/vite-env.d.ts b/OS-Level/overlay-ui/src/vite-env.d.tsdeleted file mode 100644index f042c5c7f7..0000000000--- a/OS-Level/overlay-ui/src/vite-env.d.ts+++ /dev/null@@ -1,22 +0,0 @@-// Ambient declarations for Vite-specific imports.-// Otherwise strict mode would complain that the default export is untyped.--declare module "*.svg?raw" {- const content: string;- export default content;-}--declare module "*.css" {- const content: string;- export default content;-}--declare module "*.png" {- const url: string;- export default url;-}--declare module "*.riv?url" {- const url: string;- export default url;-}diff --git a/OS-Level/overlay-ui/tsconfig.json b/OS-Level/overlay-ui/tsconfig.jsondeleted file mode 100644index e81db08af7..0000000000--- a/OS-Level/overlay-ui/tsconfig.json+++ /dev/null@@ -1,27 +0,0 @@-{- "compilerOptions": {- "target": "ES2022",- "module": "ESNext",- "moduleResolution": "Bundler",- "lib": ["ES2022", "DOM", "DOM.Iterable"],- "strict": true,- "noImplicitAny": true,- "strictNullChecks": true,- "strictFunctionTypes": true,- "noImplicitThis": true,- "alwaysStrict": true,- "noUnusedLocals": true,- "noUnusedParameters": true,- "noImplicitReturns": true,- "noFallthroughCasesInSwitch": true,- "esModuleInterop": true,- "isolatedModules": true,- "skipLibCheck": true,- "resolveJsonModule": true,- "allowSyntheticDefaultImports": true,- "useDefineForClassFields": true,- "types": []- },- "include": ["src/**/*.ts", "src/**/*.d.ts"],- "exclude": ["node_modules", "dist"]-}diff --git a/OS-Level/overlay-ui/vite.config.ts b/OS-Level/overlay-ui/vite.config.tsdeleted file mode 100644index ea4937b6a6..0000000000--- a/OS-Level/overlay-ui/vite.config.ts+++ /dev/null@@ -1,27 +0,0 @@-import { defineConfig } from "vite";-import { resolve } from "path";--// Multi-entry: edge-glow.html and (later) mascot.html. Vite places them-// flat in dist/ — window_glow.py loads dist/edge-glow.html via-// QUrl.fromLocalFile.-export default defineConfig({- base: "./",- build: {- outDir: "dist",- emptyOutDir: true,- sourcemap: true,- rollupOptions: {- input: {- "edge-glow": resolve(__dirname, "edge-glow.html"),- "mascot": resolve(__dirname, "mascot.html"),- },- output: {- // Flat output structure, so QtWebEngine can resolve relative- // paths easily (assets/ as a sibling folder to the HTML).- entryFileNames: "assets/[name]-[hash].js",- chunkFileNames: "assets/[name]-[hash].js",- assetFileNames: "assets/[name]-[hash][extname]",- },- },- },-});diff --git a/OS-Level/pyproject.toml b/OS-Level/pyproject.tomldeleted file mode 100644index ab29cf9739..0000000000--- a/OS-Level/pyproject.toml+++ /dev/null@@ -1,36 +0,0 @@-[build-system]-requires = ["setuptools>=68", "wheel"]-build-backend = "setuptools.build_meta"--[project]-name = "overlay"-version = "0.1.0"-description = "OS-Level Edge-Glow Overlay for Personal Jarvis (Phase 9)"-readme = "README.md"-requires-python = ">=3.11"-license = { text = "Proprietary" }-authors = [{ name = "Ruben Lütke" }] # i18n-allow: personal name, not translatable prose-dependencies = [- "PySide6>=6.7",- "websockets>=12",- "pydantic>=2",- "psutil>=5.9",- "pywin32>=306; sys_platform == 'win32'",- "python-ulid>=2.2",-]--[project.optional-dependencies]-dev = [- "pytest>=8",- "pytest-asyncio>=0.23",-]--[project.scripts]-overlay = "overlay.__main__:main"--[tool.setuptools.packages.find]-where = ["src"]-include = ["overlay*"]--[tool.setuptools.package-data]-overlay = ["py.typed"]diff --git a/OS-Level/src/overlay/__init__.py b/OS-Level/src/overlay/__init__.pydeleted file mode 100644index 9aebdd4ba4..0000000000--- a/OS-Level/src/overlay/__init__.py+++ /dev/null@@ -1,3 +0,0 @@-"""OS-Level Edge-Glow Overlay package."""--__version__ = "0.1.0"diff --git a/OS-Level/src/overlay/__main__.py b/OS-Level/src/overlay/__main__.pydeleted file mode 100644index ae22ca83aa..0000000000--- a/OS-Level/src/overlay/__main__.py+++ /dev/null@@ -1,18 +0,0 @@-"""Entry point for ``python -m overlay``."""--from __future__ import annotations--import faulthandler-import sys--# Native-crash forensics: Qt aborts (qFatal, STATUS_BREAKPOINT 0x80000003)-# normally print NOTHING to stderr — the process just dies.-# faulthandler.enable() installs a signal handler that writes a Python-# stack trace to stderr on a native crash. Without it, subprocess-# diagnosis is impossible.-faulthandler.enable()--from .main import main # noqa: E402--if __name__ == "__main__":- sys.exit(main())diff --git a/OS-Level/src/overlay/config.py b/OS-Level/src/overlay/config.pydeleted file mode 100644index 0141846b8f..0000000000--- a/OS-Level/src/overlay/config.py+++ /dev/null@@ -1,106 +0,0 @@-"""OverlayConfig — Pydantic v2 model per Plan §21.1.--Hot-reload is a Phase 9.2 topic. This only has the model + ``from_toml``.-"""--from __future__ import annotations--import re-import tomllib-from pathlib import Path-from typing import Any--from pydantic import BaseModel, ConfigDict, Field, field_validator--_HEX_COLOR_RE = re.compile(r"^#[0-9A-Fa-f]{6}$")-_LOOPBACK_HOSTS: frozenset[str] = frozenset({"127.0.0.1", "::1", "localhost"})---def _validate_hex_color(value: str) -> str:- if not _HEX_COLOR_RE.match(value):- raise ValueError(f"expected '#RRGGBB', got: {value!r}")- return value---class OverlayThemeConfig(BaseModel):- """Colors & glow geometry. Plan §7.1, §7.2, §21.1."""-- model_config = ConfigDict(extra="forbid")-- yellow_primary: str = "#FFC700"- yellow_soft: str = "#FFE066"- yellow_amber: str = "#FFB300"- black: str = "#0A0A0A"- glow_width_px: int = Field(default=14, ge=4, le=40)- hue_drift_degrees: int = Field(default=15, ge=0, le=30)-- @field_validator("yellow_primary", "yellow_soft", "yellow_amber", "black")- @classmethod- def _check_hex(cls, v: str) -> str:- return _validate_hex_color(v)---class OverlayMascotConfig(BaseModel):- """Mascot position + drag behavior. Plan §13.4, §21.1."""-- model_config = ConfigDict(extra="forbid")-- position_monitor: str = ""- position_x_relative: int = 200- position_y_relative: int = 80- size_px: int = Field(default=160, ge=80, le=256)- draggable: bool = True- snap_to_edges_px: int = Field(default=16, ge=0, le=32)- hidden_for_session: bool = False---class OverlayConfig(BaseModel):- """Top-level [overlay] section. Plan §21.1."""-- model_config = ConfigDict(extra="forbid")-- enabled: bool = True- edge_glow_enabled: bool = True- mascot_enabled: bool = True- all_monitors: bool = False- hide_on_fullscreen: bool = True- ignore_busy_state: bool = False- hide_from_capture: bool = True- respect_reduced_motion: bool = True- animations_enabled: bool = True-- fps_idle: int = Field(default=1, ge=0, le=30)- fps_active: int = Field(default=30, ge=1, le=60)- fps_burst: int = Field(default=60, ge=1, le=60)- idle_timeout_s: int = Field(default=30, ge=5, le=600)- hide_timeout_s: int = Field(default=300, ge=60, le=3600)-- ws_port: int = Field(default=7842, ge=1024, le=65535)- ws_host: str = "127.0.0.1"- ws_port_range_max: int = Field(default=7852, ge=1024, le=65535)- fallback_pipe: str = "\\\\.\\pipe\\jarvis-overlay"- shm_cursor_name_prefix: str = "jarvis-cursor"- heartbeat_interval_s: int = Field(default=1, ge=1, le=10)- heartbeat_timeout_s: int = Field(default=3, ge=2, le=30)-- cursor_trail_enabled: bool = True- cursor_stream_hz: int = Field(default=60, ge=10, le=120)-- theme: OverlayThemeConfig = Field(default_factory=OverlayThemeConfig)- mascot: OverlayMascotConfig = Field(default_factory=OverlayMascotConfig)-- @field_validator("ws_host")- @classmethod- def _check_loopback(cls, v: str) -> str:- if v not in _LOOPBACK_HOSTS:- raise ValueError(f"ws_host must be loopback, got: {v!r}")- return v-- @classmethod- def from_toml(cls, path: str | Path) -> "OverlayConfig":- """Read the ``[overlay]`` section from TOML. If missing: use defaults (Plan §21.4)."""- toml_path = Path(path)- with toml_path.open("rb") as f:- data: dict[str, Any] = tomllib.load(f)- section = data.get("overlay", {})- return cls.model_validate(section)diff --git a/OS-Level/src/overlay/cursor_shm.py b/OS-Level/src/overlay/cursor_shm.pydeleted file mode 100644index a664d8eebe..0000000000--- a/OS-Level/src/overlay/cursor_shm.py+++ /dev/null@@ -1,263 +0,0 @@-"""Cursor-stream shared-memory layout + reader. Plan §11 + AD-5.--32-byte fixed-layout block, single-writer (Hauptjarvis) /-single-reader (overlay). Lock-free via a seqlock pattern (odd seq =-writer mid-write, even seq = quiescent).--Plan §11.2 layout (little-endian, total 32 bytes):-- | offset | size | type | field |- | 0 | 8 | int64 LE | ts_ns | Unix-epoch ns- | 8 | 4 | int32 LE | x | physical px- | 12 | 4 | int32 LE | y | physical px- | 16 | 4 | uint32 LE | seq | seqlock counter- | 20 | 4 | uint32 LE | monitor_idx | screen index- | 24 | 8 | - | reserved | padding to 32--Reader pattern (Plan §11.3): seq_before, then data, then seq_after.-If seq_before & 1 -> writer mid-write, retry. If seq_before !=-seq_after -> torn read, retry. Otherwise the frame is valid.--Writer pattern (Plan §11.4): publish _seq+1 as odd BUSY, write data,-publish _seq+2 as even DONE.--This file contains BOTH classes (reader + writer) so the layout is-defined in exactly one place. On the Hauptjarvis side there's-``jarvis/overlay/cursor_writer.py`` as a convenience wrapper including-the streamer thread; it uses this writer under the hood.-"""--from __future__ import annotations--import logging-import secrets-import struct-import time-from dataclasses import dataclass-from multiprocessing import shared_memory-from typing import Optional--logger = logging.getLogger(__name__)---# Plan §11.1 — fixed 32-byte block.-CURSOR_SHM_SIZE: int = 32--# struct.pack/unpack format:-# < = little-endian, no padding-# q = int64 (ts_ns)-# i = int32 (x)-# i = int32 (y)-# I = uint32 (seq)-# I = uint32 (monitor_idx)-# 8s = 8 bytes padding to 32-# Sanity: struct.calcsize("<qiiII8s") == 32.-CURSOR_SHM_STRUCT: str = "<qiiII8s"-assert struct.calcsize(CURSOR_SHM_STRUCT) == CURSOR_SHM_SIZE--# Offsets for single-field reads (the reader pattern needs seq-only reads).-_OFFSET_TS = 0-_OFFSET_X = 8-_OFFSET_Y = 12-_OFFSET_SEQ = 16-_OFFSET_MONITOR = 20-_PADDING_BYTES = bytes(8) # zero-padding---def make_cursor_shm_name() -> str:- """Plan §11.1: ``jarvis-cursor-{8 hex chars}`` random per session."""- return f"jarvis-cursor-{secrets.token_hex(4)}"---@dataclass(frozen=True)-class CursorFrame:- """A successfully read cursor frame."""-- ts_ns: int- x: int- y: int- monitor_idx: int- seq: int---class CursorShmReader:- """Overlay-side reader. Non-blocking, seqlock pattern.-- Lifecycle::-- reader = CursorShmReader.attach(name)- try:- while running:- frame = reader.read()- if frame is not None:- handle(frame)- time.sleep(1/60)- finally:- reader.close()-- ``attach()`` binds to an existing block — raises- ``FileNotFoundError`` if the writer (Hauptjarvis) hasn't published- yet. ``close()`` only releases the reader reference; the writer- (owner) is responsible for ``unlink()``.- """-- def __init__(self, shm: shared_memory.SharedMemory) -> None:- if shm.size < CURSOR_SHM_SIZE:- raise ValueError(f"SHM block too small: {shm.size} < {CURSOR_SHM_SIZE}")- self._shm = shm- self._buf = shm.buf # memoryview- self._last_seq: int = 0-- @classmethod- def attach(cls, name: str) -> "CursorShmReader":- """Binds to an existing block. ``FileNotFoundError`` if it's gone."""- shm = shared_memory.SharedMemory(name=name, create=False)- return cls(shm)-- def read(self) -> Optional[CursorFrame]:- """Plan §11.3 seqlock read.-- Returns:- * ``CursorFrame`` on a clean read with new data.- * ``None`` if:- - the writer is mid-write (seq odd)- - there is no new data (seq == last_seq)- - it was a torn read (seq before != after)- """- # We can slice directly via memoryview; struct.unpack_from- # is just as fast and reads native int types.- seq_before = struct.unpack_from("<I", self._buf, _OFFSET_SEQ)[0]- if seq_before & 1:- return None # writer mid-write- if seq_before == self._last_seq:- return None # nothing new- if seq_before == 0:- # Block is initialized but the writer has never published.- return None-- ts_ns = struct.unpack_from("<q", self._buf, _OFFSET_TS)[0]- x = struct.unpack_from("<i", self._buf, _OFFSET_X)[0]- y = struct.unpack_from("<i", self._buf, _OFFSET_Y)[0]- monitor_idx = struct.unpack_from("<I", self._buf, _OFFSET_MONITOR)[0]- seq_after = struct.unpack_from("<I", self._buf, _OFFSET_SEQ)[0]-- if seq_before != seq_after:- return None # writer wrote while we were reading -> torn-- self._last_seq = seq_after- return CursorFrame(- ts_ns=ts_ns, x=x, y=y, monitor_idx=monitor_idx, seq=seq_after- )-- @property- def name(self) -> str:- return self._shm.name-- @property- def last_seq(self) -> int:- return self._last_seq-- def close(self) -> None:- """Releases the reader view. Does NOT unlink (the writer is owner)."""- try:- self._buf.release()- except (ValueError, BufferError):- # memoryview already released — OK.- pass- try:- self._shm.close()- except Exception: # noqa: BLE001- logger.debug("CursorShmReader.close swallowed", exc_info=True)---class CursorShmWriter:- """Producer-side writer. Plan §11.4 seqlock pattern.-- Owner of the SHM block — ``close()`` calls ``unlink()`` so the- block doesn't leak after process exit (relevant for Linux; Windows- GCs it anyway once all handles are gone).-- Defined here in OS-Level so the layout lives in one place.- Hauptjarvis uses ``jarvis.overlay.cursor_writer.CursorStreamer``,- which wraps this writer.- """-- def __init__(self, shm: shared_memory.SharedMemory, *, owner: bool = True) -> None:- if shm.size < CURSOR_SHM_SIZE:- raise ValueError(f"SHM block too small: {shm.size} < {CURSOR_SHM_SIZE}")- self._shm = shm- self._buf = shm.buf- self._owner = owner- # Plan §11.4: ``_seq`` starts at 0 (even), the first- # published frame ends with seq=2.- self._seq: int = 0- # Initial block content: all 0 (seq=0 -> "never published yet").- # ``shared_memory.SharedMemory(create=True)`` already delivers- # that zero'd on POSIX/Windows.-- @classmethod- def create(cls, name: Optional[str] = None) -> "CursorShmWriter":- """Creates a NEW block. Default name via ``make_cursor_shm_name()``."""- if name is None:- name = make_cursor_shm_name()- shm = shared_memory.SharedMemory(name=name, create=True, size=CURSOR_SHM_SIZE)- # Make sure the first 32 bytes are 0 (guaranteed on POSIX,- # true on Windows too — but explicit is more robust).- shm.buf[:CURSOR_SHM_SIZE] = bytes(CURSOR_SHM_SIZE)- return cls(shm, owner=True)-- def write(self, x: int, y: int, monitor_idx: int) -> int:- """Plan §11.4 seqlock write. Returns the final ``seq``.-- Pattern: seq_busy (odd) -> data -> seq_done (even).- After this call, ``self._seq`` is even and equals the new value.- """- seq_busy = self._seq + 1 # odd- struct.pack_into("<I", self._buf, _OFFSET_SEQ, seq_busy)- ts_ns = time.time_ns()- struct.pack_into("<q", self._buf, _OFFSET_TS, ts_ns)- struct.pack_into("<i", self._buf, _OFFSET_X, int(x))- struct.pack_into("<i", self._buf, _OFFSET_Y, int(y))- struct.pack_into("<I", self._buf, _OFFSET_MONITOR, int(monitor_idx))- struct.pack_into("<8s", self._buf, 24, _PADDING_BYTES)- seq_done = seq_busy + 1 # even- struct.pack_into("<I", self._buf, _OFFSET_SEQ, seq_done)- self._seq = seq_done- return seq_done-- @property- def name(self) -> str:- return self._shm.name-- @property- def seq(self) -> int:- return self._seq-- def close(self) -> None:- """Closes + unlinks (if owner)."""- try:- self._buf.release()- except (ValueError, BufferError):- pass- try:- self._shm.close()- except Exception: # noqa: BLE001- logger.debug("CursorShmWriter.close swallowed", exc_info=True)- if self._owner:- try:- self._shm.unlink()- except (FileNotFoundError, Exception): # noqa: BLE001- # On Windows, unlink is a no-op (resource_tracker- # handles that); FileNotFoundError is fine if closed- # twice.- pass---__all__ = [- "CURSOR_SHM_SIZE",- "CURSOR_SHM_STRUCT",- "CursorFrame",- "CursorShmReader",- "CursorShmWriter",- "make_cursor_shm_name",-]diff --git a/OS-Level/src/overlay/event_router.py b/OS-Level/src/overlay/event_router.pydeleted file mode 100644index e0cd2f26b6..0000000000--- a/OS-Level/src/overlay/event_router.py+++ /dev/null@@ -1,194 +0,0 @@-"""IPC envelope -> StateMachine transition mapping. Plan §6.3.--The EventRouter is the only component that connects IPC wire-format-knowledge with state semantics. It knows NO Qt and NO asyncio APIs —-that makes it independently testable and usable in both subprocess and-worker-thread contexts.--Mapping (per Plan §6.3):--| Envelope | Transition |-|----------------------------|----------------------------------|-| StateEnvelope | direct, from payload.state |-| ActionStartedEnvelope | TYPING (kind in {type, hotkey}) |-| | CLICKING (kind in {click, move, |-| | navigate, scroll}) |-| ActionEndedEnvelope | IDLE |-| ClickEnvelope | CLICKING |-| ErrorEnvelope (recoverable)| ERROR |-| Heartbeat / Cursor / Ack / | no-op |-| Config | |-"""--from __future__ import annotations--import logging-from typing import Any--from .schema import (- AckEnvelope,- ActionEndedEnvelope,- ActionStartedEnvelope,- ClickEnvelope,- ConfigEnvelope,- CursorEnvelope,- ErrorEnvelope,- HeartbeatEnvelope,- StateEnvelope,-)-from .state import OverlayState, StateMachine--logger = logging.getLogger(__name__)---# Action-kind -> state buckets. Plan §6.3 lists only TYPING and CLICKING-# as action states; all 6 Computer-Use kinds are mapped onto one of-# those two so every action-started event actually triggers the glow.-TYPING_KINDS: frozenset[str] = frozenset({"type", "hotkey"})-CLICKING_KINDS: frozenset[str] = frozenset({"click", "move", "navigate", "scroll"})--# Reasons for programmatic transitions — plan-allowed: ``StateReason`` literal.-REASON_TOOL = "tool"-REASON_ERROR = "error"---class EventRouter:- """Converts IPC envelopes into StateMachine transitions.-- Plan AD-8: state logic lives in the overlay process — this class is- the bridge between the wire format (``schema.py``) and the state- holder (``state.py``).-- Typically invoked via ``WSClient.set_on_message(router.handle)``.- """-- def __init__(self, machine: StateMachine) -> None:- self._machine = machine- # Phase 9.5 effect hooks. Subscribers receive the envelope- # object itself (not just the payload) so they can access all- # fields.- self._click_hooks: list[Any] = []- self._action_started_hooks: list[Any] = []- self._action_ended_hooks: list[Any] = []- self._cursor_hooks: list[Any] = []-- @property- def machine(self) -> StateMachine:- return self._machine-- def add_click_hook(self, fn: Any) -> None:- """Called with ``ClickEnvelope``, sync, on the caller thread."""- self._click_hooks.append(fn)-- def add_action_started_hook(self, fn: Any) -> None:- """Called with ``ActionStartedEnvelope``."""- self._action_started_hooks.append(fn)-- def add_action_ended_hook(self, fn: Any) -> None:- """Called with ``ActionEndedEnvelope``."""- self._action_ended_hooks.append(fn)-- def add_cursor_hook(self, fn: Any) -> None:- """Called with ``CursorEnvelope`` (WS fallback when SHM is off)."""- self._cursor_hooks.append(fn)-- def _safe_dispatch(self, hooks: list[Any], envelope: Any) -> None:- for h in hooks:- try:- h(envelope)- except Exception: # noqa: BLE001- logger.exception("EventRouter hook raised on %s", type(envelope).__name__)-- def handle(self, envelope: Any) -> bool:- """Processes a single envelope.-- Returns ``True`` if a real state transition was triggered,- ``False`` on a no-op (heartbeat, coalescing hit, unknown type).- """- # StateEnvelope: Hauptjarvis explicitly says "new state".- if isinstance(envelope, StateEnvelope):- try:- target = OverlayState(envelope.payload.state)- except ValueError:- logger.warning(- "EventRouter: unknown state literal %r",- envelope.payload.state,- )- return False- return self._machine.transition_to(- target, reason=envelope.payload.reason- )-- # ActionStarted: Hauptjarvis is operating the mouse/keyboard -> glow on.- if isinstance(envelope, ActionStartedEnvelope):- self._safe_dispatch(self._action_started_hooks, envelope)- kind = envelope.payload.kind- if kind in TYPING_KINDS:- return self._machine.transition_to(- OverlayState.TYPING, reason=REASON_TOOL- )- if kind in CLICKING_KINDS:- return self._machine.transition_to(- OverlayState.CLICKING, reason=REASON_TOOL- )- logger.debug("EventRouter: action_started kind %r has no mapping", kind)- return False-- # ActionEnded: action is over -> back to IDLE.- # Higher layers (wakeword/STT/TTS) then restore the next action- # state themselves via their own event.- if isinstance(envelope, ActionEndedEnvelope):- self._safe_dispatch(self._action_ended_hooks, envelope)- return self._machine.transition_to(- OverlayState.IDLE, reason=REASON_TOOL- )-- # ClickEvent: atomic click notification (Plan §6.3 +- # click-visualization §14). State bump to CLICKING + hook- # fires for the ripple trigger.- if isinstance(envelope, ClickEnvelope):- self._safe_dispatch(self._click_hooks, envelope)- return self._machine.transition_to(- OverlayState.CLICKING, reason=REASON_TOOL- )-- # Cursor: WS fallback Plan §11.5 — when SHM is disabled. Hook- # forwards the coords. NO state change.- if isinstance(envelope, CursorEnvelope):- self._safe_dispatch(self._cursor_hooks, envelope)- return False-- # Recoverable error -> ERROR state (brief amber/red phase, Plan- # §6.1). Non-recoverable isn't visualized because Hauptjarvis- # is about to crash anyway; the supervisor catches that at the- # process level.- if isinstance(envelope, ErrorEnvelope):- if envelope.payload.recoverable:- return self._machine.transition_to(- OverlayState.ERROR, reason=REASON_ERROR- )- return False-- # No-op envelope types — listed explicitly so unknown envelope- # classes surface as a WARNING below. (CursorEnvelope is- # handled above because it only fires a hook but has no state- # change.)- if isinstance(- envelope,- (HeartbeatEnvelope, ConfigEnvelope, AckEnvelope),- ):- return False-- logger.warning(- "EventRouter: unhandled envelope type %s", type(envelope).__name__- )- return False---__all__ = [- "CLICKING_KINDS",- "EventRouter",- "REASON_ERROR",- "REASON_TOOL",- "TYPING_KINDS",-]diff --git a/OS-Level/src/overlay/fullscreen_detect.py b/OS-Level/src/overlay/fullscreen_detect.pydeleted file mode 100644index 939902edcf..0000000000--- a/OS-Level/src/overlay/fullscreen_detect.py+++ /dev/null@@ -1,204 +0,0 @@-"""SHQueryUserNotificationState polling. Plan §12.6 + §20.2.--Polls every 2 seconds on a daemon thread with-``THREAD_PRIORITY_LOWEST`` (best effort). When the state changes to a-"hide-worthy" code (D3D fullscreen, presentation mode, or optionally-busy), it fires a callback. A classic pull-polling approach because-Windows has no push event for this status.--No PySide6 dependency, so the polling thread can also run in test-setups without a QApplication.-"""--from __future__ import annotations--import logging-import sys-import threading-from dataclasses import dataclass-from enum import IntEnum-from typing import Callable, Optional--logger = logging.getLogger(__name__)---# Plan §12.6 — SHQueryUserNotificationState Codes (winuser.h).-class UserNotificationState(IntEnum):- NOT_PRESENT = 1 # QUNS_NOT_PRESENT- BUSY = 2 # QUNS_BUSY- RUNNING_D3D_FULL_SCREEN = 3 # QUNS_RUNNING_D3D_FULL_SCREEN- PRESENTATION_MODE = 4 # QUNS_PRESENTATION_MODE- ACCEPTS_NOTIFICATIONS = 5 # QUNS_ACCEPTS_NOTIFICATIONS- QUIET_TIME = 6 # QUNS_QUIET_TIME- APP = 7 # QUNS_APP---# Plan §12.6: default hide codes (BUSY is optional via ignore_busy_state).-_HARD_HIDE_STATES: frozenset[UserNotificationState] = frozenset(- {UserNotificationState.RUNNING_D3D_FULL_SCREEN, UserNotificationState.PRESENTATION_MODE}-)-_SOFT_HIDE_STATES: frozenset[UserNotificationState] = frozenset(- {UserNotificationState.BUSY}-)---@dataclass(frozen=True)-class FullscreenStatus:- """Snapshot of the last polling tick."""-- state: UserNotificationState- should_hide: bool---# Callback signature: (FullscreenStatus) -> None.-StatusCallback = Callable[[FullscreenStatus], None]---def query_state() -> Optional[UserNotificationState]:- """Plan §12.6 — SHQueryUserNotificationState via ctypes.-- Returns None on non-Windows or when the API isn't available.- """- if sys.platform != "win32":- return None- import ctypes-- try:- sh = ctypes.windll.shell32- except (OSError, AttributeError): # pragma: no cover- return None-- sh.SHQueryUserNotificationState.restype = ctypes.c_long- out = ctypes.c_int(0)- hr = sh.SHQueryUserNotificationState(ctypes.byref(out))- if hr != 0:- logger.debug("SHQueryUserNotificationState HRESULT=%d", hr)- return None- try:- return UserNotificationState(out.value)- except ValueError:- logger.debug("Unknown UserNotificationState: %d", out.value)- return None---def should_hide_for_state(- state: UserNotificationState, *, ignore_busy_state: bool-) -> bool:- """Mapping state -> hide. Plan §12.6:- - always hide on RUNNING_D3D_FULL_SCREEN, PRESENTATION_MODE- - hide on BUSY only when ignore_busy_state == False (default)- """- if state in _HARD_HIDE_STATES:- return True- if state in _SOFT_HIDE_STATES and not ignore_busy_state:- return True- return False---class FullscreenDetector:- """Polling thread around SHQueryUserNotificationState.-- Plan §12.6: low-prio daemon thread, 2 s interval, clean exit.-- Lifecycle::-- det = FullscreenDetector(callback=on_change)- det.start()- ...- det.stop()- """-- def __init__(- self,- *,- callback: Optional[StatusCallback] = None,- poll_interval_s: float = 2.0,- ignore_busy_state: bool = False,- query_fn: Callable[[], Optional[UserNotificationState]] = query_state,- ) -> None:- self._callback = callback- self._poll_interval = poll_interval_s- self._ignore_busy_state = ignore_busy_state- self._query_fn = query_fn- self._stop = threading.Event()- self._thread: Optional[threading.Thread] = None- self._last_status: Optional[FullscreenStatus] = None-- @property- def last_status(self) -> Optional[FullscreenStatus]:- return self._last_status-- @property- def is_running(self) -> bool:- return self._thread is not None and self._thread.is_alive()-- def set_ignore_busy_state(self, ignore: bool) -> None:- """Runtime toggle (e.g. when a config reload happens)."""- self._ignore_busy_state = ignore-- def set_callback(self, callback: Optional[StatusCallback]) -> None:- self._callback = callback-- def poll_once(self) -> Optional[FullscreenStatus]:- """Synchronous poll cycle. Returns FullscreenStatus or None- (non-Windows / API error)."""- state = self._query_fn()- if state is None:- return None- status = FullscreenStatus(- state=state,- should_hide=should_hide_for_state(- state, ignore_busy_state=self._ignore_busy_state- ),- )- prev = self._last_status- self._last_status = status- if self._callback is not None and (- prev is None or prev.state is not status.state or prev.should_hide is not status.should_hide- ):- try:- self._callback(status)- except Exception: # noqa: BLE001- logger.exception("FullscreenDetector callback raised")- return status-- def start(self) -> None:- if self.is_running:- return- self._stop.clear()- self._thread = threading.Thread(- target=self._run, name="overlay-fullscreen-detect", daemon=True- )- self._thread.start()-- def stop(self) -> None:- self._stop.set()- if self._thread is not None:- self._thread.join(timeout=2.0)-- def _run(self) -> None:- # Best effort: lower the thread priority on Windows.- if sys.platform == "win32":- try:- import ctypes-- THREAD_PRIORITY_LOWEST = -2- handle = ctypes.windll.kernel32.GetCurrentThread()- ctypes.windll.kernel32.SetThreadPriority(handle, THREAD_PRIORITY_LOWEST)- except Exception: # noqa: BLE001- logger.debug("SetThreadPriority failed", exc_info=True)-- while not self._stop.is_set():- self.poll_once()- if self._stop.wait(timeout=self._poll_interval):- return---__all__ = [- "FullscreenDetector",- "FullscreenStatus",- "StatusCallback",- "UserNotificationState",- "query_state",- "should_hide_for_state",-]diff --git a/OS-Level/src/overlay/ipc_pipe.py b/OS-Level/src/overlay/ipc_pipe.pydeleted file mode 100644index 1495bc93d6..0000000000--- a/OS-Level/src/overlay/ipc_pipe.py+++ /dev/null@@ -1,189 +0,0 @@-"""Named-pipe fallback. Plan §5 AD-5 + §10.--Skeleton: connect helper + send/recv roundtrip. The full auto-failover-logic (WS down + pipe up) is a Phase 9.7 topic. This only has the-building blocks, so tests can simulate the pipe path.--For non-Windows environments: ``CAPABLE`` is ``False``, ``connect``-and ``send_recv`` raise ``RuntimeError``. Tests skip accordingly.-"""--from __future__ import annotations--import logging-import sys-from contextlib import contextmanager-from typing import Any, Iterator--logger = logging.getLogger(__name__)--DEFAULT_PIPE_NAME = r"\\.\pipe\jarvis-overlay"--# Pipe buffer defaults — uncritical, 64 KiB each direction.-_BUF = 64 * 1024---def _is_windows() -> bool:- return sys.platform == "win32"---def _import_win32() -> tuple[Any, Any]:- """Lazy import. Returns (win32file, win32pipe)."""- if not _is_windows():- raise RuntimeError("Named pipes are Windows-only")- try:- import win32file # type: ignore[import-not-found]- import win32pipe # type: ignore[import-not-found]- except ImportError as exc:- raise RuntimeError(- "pywin32 not installed — `pip install pywin32`"- ) from exc- return win32file, win32pipe---CAPABLE: bool = _is_windows()---@contextmanager-def open_client(pipe_name: str = DEFAULT_PIPE_NAME, *, timeout_ms: int = 5000) -> Iterator[Any]:- """Connects as a client to the existing pipe.-- Yields the ``HANDLE``. Closes it cleanly in the exit branch. Raises- ``RuntimeError`` if the pipe doesn't exist or we're running on- non-Windows.- """- win32file, win32pipe = _import_win32()- import pywintypes # type: ignore[import-not-found]- import time as _time-- # ``WaitNamedPipe`` is unreliable on Win11 (returns False even- # though the server is blocked in ``ConnectNamedPipe``). A more- # robust path: call ``CreateFile`` directly and retry at short- # intervals on ``ERROR_PIPE_BUSY``/``FILE_NOT_FOUND``.- deadline = _time.monotonic() + (timeout_ms / 1000.0)- last_err: Exception | None = None- handle = None- while True:- try:- handle = win32file.CreateFile(- pipe_name,- win32file.GENERIC_READ | win32file.GENERIC_WRITE,- 0,- None,- win32file.OPEN_EXISTING,- 0,- None,- )- break- except (OSError, pywintypes.error) as exc:- last_err = exc- if _time.monotonic() >= deadline:- raise RuntimeError(- f"Named-pipe connect error: {pipe_name} ({exc})"- ) from exc- _time.sleep(0.025)- assert handle is not None, "unreachable: handle must be set after loop"- del last_err # unused outside loop-- try:- # PIPE_READMODE_MESSAGE: every WriteFile corresponds to one ReadFile.- win32pipe.SetNamedPipeHandleState(- handle, win32pipe.PIPE_READMODE_MESSAGE, None, None- )- yield handle- finally:- try:- win32file.CloseHandle(handle)- except Exception: # noqa: BLE001- pass---def create_server_pipe(pipe_name: str = DEFAULT_PIPE_NAME) -> Any:- """Pure ``CreateNamedPipe``. Returns the handle without blocking.-- ``accept_server_connection(handle)`` then blocks separately until a- client connects. Splits the lifecycle so tests don't have to- resolve the race before ``WaitNamedPipe`` via sleep.- """- win32file, win32pipe = _import_win32()- return win32pipe.CreateNamedPipe(- pipe_name,- win32pipe.PIPE_ACCESS_DUPLEX,- win32pipe.PIPE_TYPE_MESSAGE- | win32pipe.PIPE_READMODE_MESSAGE- | win32pipe.PIPE_WAIT,- 1, # max instances- _BUF,- _BUF,- 0,- None,- )---def accept_server_connection(handle: Any) -> None:- """Blocks on ``ConnectNamedPipe(handle)``."""- _, win32pipe = _import_win32()- win32pipe.ConnectNamedPipe(handle, None)---def close_server_pipe(handle: Any) -> None:- """Disconnect + close handle. Idempotent."""- win32file, win32pipe = _import_win32()- try:- win32pipe.DisconnectNamedPipe(handle)- except Exception: # noqa: BLE001- pass- try:- win32file.CloseHandle(handle)- except Exception: # noqa: BLE001- pass---@contextmanager-def open_server(pipe_name: str = DEFAULT_PIPE_NAME) -> Iterator[Any]:- """Server-side pipe. Creates it and blocks on ``ConnectNamedPipe``.-- Gets replaced by a multi-connection variant in Phase 9.7; this is- only the single-connection skeleton, so tests can verify the- roundtrip. For finer test control see ``create_server_pipe`` +- ``accept_server_connection``.- """- handle = create_server_pipe(pipe_name)- try:- accept_server_connection(handle)- yield handle- finally:- close_server_pipe(handle)---def send(handle: Any, payload: bytes) -> int:- """Writes a message. Returns the number of bytes written."""- win32file, _ = _import_win32()- err, written = win32file.WriteFile(handle, payload)- if err != 0:- raise OSError(f"WriteFile error={err}")- return written---def recv(handle: Any, max_bytes: int = _BUF) -> bytes:- """Reads a message. Returns the raw bytes (UTF-8 JSON expected)."""- win32file, _ = _import_win32()- err, data = win32file.ReadFile(handle, max_bytes)- if err != 0:- raise OSError(f"ReadFile error={err}")- if isinstance(data, memoryview):- return bytes(data)- return bytes(data)---__all__ = [- "CAPABLE",- "DEFAULT_PIPE_NAME",- "accept_server_connection",- "close_server_pipe",- "create_server_pipe",- "open_client",- "open_server",- "recv",- "send",-]diff --git a/OS-Level/src/overlay/ipc_ws.py b/OS-Level/src/overlay/ipc_ws.pydeleted file mode 100644index f6eae9fba1..0000000000--- a/OS-Level/src/overlay/ipc_ws.py+++ /dev/null@@ -1,272 +0,0 @@-"""WS client. Connects to the Hauptjarvis WS server.--Plan §10.5 — lifecycle:-- Initial connect: tries ports ``[ws_port..ws_port_range_max]`` in order.-- Heartbeat: the client sends every 1s, and also expects a 1s cadence- from the server. If NO frame arrives for 3s -> mark the connection broken.-- Reconnect backoff: 0.5, 1, 2, 4, 8, 30 seconds with +/- 20% jitter.-- State resync: the first frame from the server after connect is the- current state; we pass it through unchanged to ``on_message``.-"""--from __future__ import annotations--import asyncio-import logging-import random-from typing import Any, Awaitable, Callable, Optional, Sequence--import websockets-from websockets.asyncio.client import connect--from .schema import (- HeartbeatEnvelope,- HeartbeatPayload,- IPCMessage,- SCHEMA_VERSION,-)--logger = logging.getLogger(__name__)--# Plan §10.5 — fixed backoff slots in seconds.-BACKOFF_SCHEDULE: tuple[float, ...] = (0.5, 1.0, 2.0, 4.0, 8.0, 30.0)-JITTER_FRACTION = 0.2--OnMessage = Callable[[object], Awaitable[None]]---def _backoff_with_jitter(slot: int, *, rng: random.Random | None = None) -> float:- rng = rng or random- base = BACKOFF_SCHEDULE[min(slot, len(BACKOFF_SCHEDULE) - 1)]- jitter = base * JITTER_FRACTION- return max(0.05, base + rng.uniform(-jitter, jitter))---class WSClient:- """Self-restarting WS client.-- Usage::-- client = WSClient(host="127.0.0.1", ports=range(7842, 7853))- client.set_on_message(handler)- task = asyncio.create_task(client.run())- ...- await client.aclose()- await task- """-- def __init__(- self,- *,- host: str = "127.0.0.1",- ports: Sequence[int] = tuple(range(7842, 7853)),- path: str = "/overlay",- heartbeat_interval_s: float = 1.0,- heartbeat_timeout_s: float = 3.0,- on_message: Optional[OnMessage] = None,- rng: Optional[random.Random] = None,- ) -> None:- self._host = host- self._ports = tuple(ports)- self._path = path- self._heartbeat_interval = heartbeat_interval_s- self._heartbeat_timeout = heartbeat_timeout_s- self._on_message = on_message- self._rng = rng or random.Random()-- self._stop = asyncio.Event()- self._connected_evt = asyncio.Event()- self._last_recv_ns: int = 0- self._connection_count = 0- # Outbound buffer for client-originated envelopes (e.g. mascot- # interaction events). Bounded so a long disconnect cannot grow- # memory without bound. We drop the OLDEST entry on overflow so- # the freshest user intent always wins.- self._outbound: asyncio.Queue[bytes] = asyncio.Queue(maxsize=64)- self._active_ws: Any = None-- def set_on_message(self, fn: Optional[OnMessage]) -> None:- self._on_message = fn-- @property- def connection_count(self) -> int:- return self._connection_count-- async def aclose(self) -> None:- self._stop.set()-- async def wait_connected(self, timeout: float | None = None) -> bool:- try:- await asyncio.wait_for(self._connected_evt.wait(), timeout)- except asyncio.TimeoutError:- return False- return True-- async def send(self, envelope: Any) -> None:- """Enqueue an outbound envelope for transmission to the server.-- Safe to call before the WS is connected — the envelope sits in- the bounded outbox until the send-loop is alive. On overflow we- drop the OLDEST entry so user-driven actions (mascot dbl-click- mute) are never starved by stale backlog.- """- raw = envelope.model_dump_json().encode("utf-8")- try:- self._outbound.put_nowait(raw)- except asyncio.QueueFull:- try:- self._outbound.get_nowait()- except asyncio.QueueEmpty:- pass- try:- self._outbound.put_nowait(raw)- except asyncio.QueueFull:- logger.warning("WSClient outbox still full after evict — drop new")-- async def run(self) -> None:- """Main loop. Returns after ``aclose()``."""- slot = 0- while not self._stop.is_set():- ws = await self._try_connect_any()- if ws is None:- # No port in range reachable -> backoff and retry.- await self._sleep_backoff(slot)- slot = min(slot + 1, len(BACKOFF_SCHEDULE) - 1)- continue- slot = 0 # Reset on a successful connection.- self._connection_count += 1- self._connected_evt.set()- try:- await self._serve_connection(ws)- except Exception: # noqa: BLE001- logger.exception("WSClient connection loop crashed")- finally:- self._connected_evt.clear()- try:- await ws.close()- except Exception: # noqa: BLE001- pass- if self._stop.is_set():- return- await self._sleep_backoff(slot)- slot = min(slot + 1, len(BACKOFF_SCHEDULE) - 1)-- async def _try_connect_any(self):- for port in self._ports:- if self._stop.is_set():- return None- uri = f"ws://{self._host}:{port}{self._path}"- try:- ws = await connect(uri, open_timeout=2.0)- logger.info("WSClient connected to %s", uri)- return ws- except (OSError, asyncio.TimeoutError, websockets.WebSocketException):- continue- return None-- async def _sleep_backoff(self, slot: int) -> None:- delay = _backoff_with_jitter(slot, rng=self._rng)- try:- await asyncio.wait_for(self._stop.wait(), timeout=delay)- except asyncio.TimeoutError:- return # Backoff expired, continue.-- async def _serve_connection(self, ws) -> None:- loop = asyncio.get_running_loop()- self._last_recv_ns = loop.time() * 1e9 # uses the monotonic clock for the timeout- self._active_ws = ws- hb_task = asyncio.create_task(self._heartbeat_loop(ws), name="ipcws-hb")- watchdog = asyncio.create_task(self._watchdog_loop(ws), name="ipcws-watchdog")- sender = asyncio.create_task(self._send_loop(ws), name="ipcws-send")- try:- async for raw in ws:- self._last_recv_ns = loop.time() * 1e9- try:- msg = IPCMessage.validate_json(raw)- except Exception as exc: # noqa: BLE001- logger.warning("WSClient validate failed: %r", exc)- continue- self._maybe_log_version_drift(msg)- if self._on_message is not None:- try:- await self._on_message(msg)- except Exception: # noqa: BLE001- logger.exception("on_message raised")- if self._stop.is_set():- break- finally:- hb_task.cancel()- watchdog.cancel()- sender.cancel()- for t in (hb_task, watchdog, sender):- try:- await t- except (asyncio.CancelledError, Exception): # noqa: BLE001- pass- self._active_ws = None-- async def _send_loop(self, ws) -> None:- """Drain the outbox into the live socket. Cancelled on disconnect."""- while not self._stop.is_set():- raw = await self._outbound.get()- try:- await ws.send(raw)- except Exception: # noqa: BLE001- # Connection died mid-send. Re-queue the envelope so the- # next connection ships it. put_nowait may fail if other- # items piled up while we slept — accept the drop in that- # extreme case rather than blocking.- try:- self._outbound.put_nowait(raw)- except asyncio.QueueFull:- logger.debug("WSClient re-enqueue after send error: outbox full")- return-- async def _heartbeat_loop(self, ws) -> None:- while not self._stop.is_set():- try:- env = HeartbeatEnvelope(payload=HeartbeatPayload(ws_connected=True))- await ws.send(env.model_dump_json())- except Exception: # noqa: BLE001- return- try:- await asyncio.wait_for(self._stop.wait(), timeout=self._heartbeat_interval)- return # stopped- except asyncio.TimeoutError:- continue-- async def _watchdog_loop(self, ws) -> None:- """Closes ``ws`` when nothing arrives for ``heartbeat_timeout_s``.-- Plan §10.5: this forces the ``async for`` loop in- ``_serve_connection`` to end, then ``run()`` triggers the- reconnect path with backoff.- """- loop = asyncio.get_running_loop()- check_interval = max(0.05, self._heartbeat_timeout / 3)- while not self._stop.is_set():- await asyncio.sleep(check_interval)- now = loop.time() * 1e9- if (now - self._last_recv_ns) / 1e9 > self._heartbeat_timeout:- logger.warning(- "WSClient heartbeat-timeout (%.1fs) -> close + reconnect",- self._heartbeat_timeout,- )- try:- await ws.close()- except Exception: # noqa: BLE001- pass- return-- def _maybe_log_version_drift(self, msg: object) -> None:- v = getattr(msg, "v", None)- if isinstance(v, int) and v != SCHEMA_VERSION:- logger.warning("schema version drift: incoming v=%d local=%d", v, SCHEMA_VERSION)---__all__ = [- "BACKOFF_SCHEDULE",- "JITTER_FRACTION",- "WSClient",- "_backoff_with_jitter",-]diff --git a/OS-Level/src/overlay/main.py b/OS-Level/src/overlay/main.pydeleted file mode 100644index 1ff7ba3f6d..0000000000--- a/OS-Level/src/overlay/main.py+++ /dev/null@@ -1,689 +0,0 @@-"""Overlay entry point. Later phases fill in the ``setup_*()`` bodies."""--from __future__ import annotations--import argparse-import asyncio-import logging-import sys-from typing import Any, Optional--from .transparency import set_per_monitor_dpi_awareness--logger = logging.getLogger(__name__)---def setup_dpi_awareness() -> None:- """Per-monitor DPI. MUST run before QApplication — Plan §12.3."""- set_per_monitor_dpi_awareness()---def _setup_app_identity_and_icon() -> Optional["object"]:- """Pin the taskbar identity and resolve the Jarvis icon path.-- Runs before ``QApplication`` so the AUMID is in place when Qt registers- its window class. Returns the resolved icon path (or None) — the caller- feeds it into ``QApplication.setWindowIcon`` once the app exists.-- All steps are best-effort: this subprocess is cosmetic infrastructure,- a missing icon must never crash the overlay.- """- if sys.platform != "win32":- return None- try:- from jarvis.ui.icon_utils import (- ensure_windows_app_identity,- project_icon_path,- )- except Exception: # noqa: BLE001- # Running standalone outside the Jarvis source tree (smoke tests).- return None-- ensure_windows_app_identity()- ico = project_icon_path()- return ico if ico.is_file() else None---def setup_windows(app, config, state_machine=None, effects_bridge=None) -> list:- """Edge-Glow windows, one per screen.-- Plan §12.1 + §12.5: one window per screen when ``all_monitors=True``,- otherwise only primary. We hook hotplug into the ``MonitorManager``.-- ``state_machine`` (optional, new in 9.3): passed through to- ``EdgeGlowWindow``, which exposes a ``StateBridge`` over QWebChannel.- Each window subscribes independently — the StateMachine's subscriber- list is thread-safe.-- ``effects_bridge`` (optional, new in 9.5): simultaneously registered- as ``effectsBridge`` on the QWebChannel. Same instance per window —- all windows fire against the same bridge, and the renderer per- window subscribes independently.- """- from PySide6.QtGui import QGuiApplication-- from .monitors import MonitorManager- from .window_glow import EdgeGlowWindow-- windows: list[EdgeGlowWindow] = []- primary = QGuiApplication.primaryScreen()-- if config.all_monitors:- targets = list(QGuiApplication.screens())- elif primary is not None:- targets = [primary]- else:- targets = []-- for screen in targets:- win = EdgeGlowWindow(- screen,- hide_from_capture=config.hide_from_capture,- state_machine=state_machine,- effects_bridge=effects_bridge,- )- win.show()- windows.append(win)-- def _on_screen_added(screen) -> None:- if not config.all_monitors:- return- win = EdgeGlowWindow(- screen,- hide_from_capture=config.hide_from_capture,- state_machine=state_machine,- effects_bridge=effects_bridge,- )- win.show()- windows.append(win)-- def _on_screen_removed(screen) -> None:- for w in list(windows):- # ``w.screen()`` can return None after removal — compare defensively.- try:- if w.screen() is screen:- w.close()- windows.remove(w)- except RuntimeError: # pragma: no cover — window already gone- if w in windows:- windows.remove(w)-- manager = MonitorManager(_on_screen_added, _on_screen_removed)- manager.attach()- # Park the manager on the app object so it doesn't get GC'd.- app._overlay_monitor_manager = manager # type: ignore[attr-defined]-- return windows---def setup_ipc(app, config, on_message=None) -> Any:- """WS client on a dedicated asyncio thread.-- The Qt event loop and asyncio coexist here via a worker thread- instead of qasync — that avoids an extra dependency and makes the- path easier to test (asyncio can be started/stopped independently- of the Qt loop).-- Plan §10.5: reconnect logic + heartbeat are fully encapsulated in- ``WSClient.run()``. We park the thread + loop on the ``app`` object- so nothing gets GC'd and the shutdown hook can set the stop event.-- ``on_message`` (optional, new in 9.3): async callback that receives- every validated IPC envelope. setup_state_machine() passes- ``EventRouter.handle`` through here — it's sync, we wrap it there.- """- import threading-- from .ipc_ws import WSClient-- ports = list(range(config.ws_port, config.ws_port_range_max + 1))- client = WSClient(- host=config.ws_host,- ports=ports,- heartbeat_interval_s=float(config.heartbeat_interval_s),- heartbeat_timeout_s=float(config.heartbeat_timeout_s),- on_message=on_message,- )-- loop = asyncio.new_event_loop()- run_task: dict[str, Any] = {}-- def _thread_entry() -> None:- asyncio.set_event_loop(loop)- run_task["task"] = loop.create_task(client.run())- try:- loop.run_forever()- finally:- loop.close()-- thread = threading.Thread(target=_thread_entry, name="overlay-ipc", daemon=True)- thread.start()-- def _shutdown() -> None:- if loop.is_closed():- return- fut = asyncio.run_coroutine_threadsafe(client.aclose(), loop)- try:- fut.result(timeout=2.0)- except Exception: # noqa: BLE001- pass- loop.call_soon_threadsafe(loop.stop)- thread.join(timeout=2.0)-- if hasattr(app, "aboutToQuit"):- app.aboutToQuit.connect(_shutdown)-- handle = {- "client": client,- "thread": thread,- "loop": loop,- "shutdown": _shutdown,- }- app._overlay_ipc = handle # type: ignore[attr-defined]- return handle---def setup_state_machine(app, config) -> Any:- """State machine + EventRouter. Phase 9.3.-- Returns ``{"machine": StateMachine, "router": EventRouter,- "on_message": Callable}``. The ``on_message`` coroutine is passed- through to ``setup_ipc``; the ``machine`` goes to ``setup_windows``,- so each ``EdgeGlowWindow`` can build its own QWebChannel bridge.-- Plan AD-8: state logic lives in the overlay process. The router is- the only component that knows the wire format — the StateMachine- stays IPC-agnostic.- """- from .event_router import EventRouter- from .state import StateMachine-- machine = StateMachine()- router = EventRouter(machine)-- async def on_message(envelope: Any) -> None:- # Router.handle is sync and fast (dict lookup + locks). We call- # it directly — no await needed.- try:- router.handle(envelope)- except Exception: # noqa: BLE001- logger.exception("EventRouter.handle raised on %s", type(envelope).__name__)-- handle = {- "machine": machine,- "router": router,- "on_message": on_message,- }- app._overlay_state = handle # type: ignore[attr-defined]- return handle---def setup_effects(app, config, router=None) -> Any:- """Action effects: cursor SHM reader + ripple/action bridge. Phase 9.5.-- Returns ``{"bridge": EffectsBridge, "shm_thread": Optional[Thread],- "shm_reader": Optional[CursorShmReader], "shm_stop": Event}``.-- Lifecycle:- - ``EffectsBridge`` is instantiated immediately, parked on ``app``,- and attached to all windows by the caller via- ``setup_windows(effects_bridge=...)``.- - ``router.add_click_hook/add_action_started_hook/...`` are hooked- so IPC events flow through the bridge to the JS side.- - When ``config.cursor_trail_enabled`` and a ``shm_cursor_name``- string becomes known via config IPC (from Hauptjarvis), a 60-Hz- reader thread starts and emits ``cursorMoved`` signals. Phase- 9.5 polls the config block once at startup — dynamic reconfig- arrives with 9.7+.- """- import threading-- from .window_glow import EffectsBridge-- bridge = EffectsBridge()-- # Hook wiring to EventRouter: pass every IPC event through.- if router is not None:- router.add_click_hook(- lambda env: bridge.emit_click(- env.payload.x,- env.payload.y,- _monitor_str_to_idx(env.payload.monitor),- env.payload.button,- )- )- router.add_action_started_hook(- lambda env: bridge.emit_action_started(- env.payload.kind, env.payload.duration_hint_ms- )- )- router.add_action_ended_hook(lambda env: bridge.emit_action_ended())- # Cursor via WS fallback (Plan §11.5) — when SHM is off,- # CursorEnvelope comes through and we forward it.- router.add_cursor_hook(- lambda env: bridge.emit_cursor(env.payload.x, env.payload.y)- )-- # SHM reader thread — only when the trail is enabled AND a name is- # available. The name typically comes via config IPC from Hauptjarvis.- # Phase 9.5 starts the thread DEFERRED via the shm_attach() helper below.- handle = {- "bridge": bridge,- "shm_thread": None,- "shm_reader": None,- "shm_stop": threading.Event(),- "shm_attach": None,- }-- def shm_attach(name: str, hz: int = 60) -> bool:- """Attaches to an existing SHM block and starts the 60-Hz- reader thread. Returns False if the block is missing."""- from .cursor_shm import CursorShmReader-- try:- reader = CursorShmReader.attach(name)- except FileNotFoundError:- logger.warning("SHM block %r not found — cursor-trail disabled", name)- return False-- period = 1.0 / max(1, hz)- stop = handle["shm_stop"]-- def _run() -> None:- while not stop.is_set():- try:- frame = reader.read()- if frame is not None:- bridge.emit_cursor(frame.x, frame.y)- except Exception: # noqa: BLE001- logger.debug("SHM read error", exc_info=True)- if stop.wait(timeout=period):- return-- thread = threading.Thread(target=_run, name="cursor-shm-reader", daemon=True)- thread.start()- handle["shm_thread"] = thread- handle["shm_reader"] = reader- return True-- handle["shm_attach"] = shm_attach-- def _shutdown() -> None:- handle["shm_stop"].set()- thread = handle["shm_thread"]- if thread is not None:- thread.join(timeout=2.0)- reader = handle["shm_reader"]- if reader is not None:- reader.close()-- if hasattr(app, "aboutToQuit"):- app.aboutToQuit.connect(_shutdown)-- app._overlay_effects = handle # type: ignore[attr-defined]- return handle---def _monitor_str_to_idx(monitor: str) -> int:- """ClickPayload.monitor is a string (free-form). If parseable as- int -> use directly; otherwise default to 0. Phase-9.7 mascot- wiring can refine this once real monitor IDs come in."""- if not monitor:- return 0- try:- return int(monitor)- except (TypeError, ValueError):- return 0---def setup_mascot(app, config, state_machine=None, toml_path=None, ipc=None) -> Any:- """Mascot window. Phase 9.6.-- Returns ``{"window": MascotWindow | None, "position": ResolvedPlacement | None}``.-- If ``config.mascot_enabled`` is False, no window is created- (Plan §13.5 — the TOML toggle disables the mascot entirely).-- Position is determined via ``mascot_position.resolve_placement``- from the persisted ``[overlay.mascot]``; recovery when the monitor- is gone falls back to primary (Plan §13.4 step 3).-- Plus: ``hideRequested`` / ``resetRequested`` signals are wired to- sensible defaults (hide -> close, reset -> primary default position).- """- if not getattr(config, "mascot_enabled", True):- logger.info("Mascot disabled via config.mascot_enabled=false")- handle = {"window": None, "position": None}- app._overlay_mascot = handle # type: ignore[attr-defined]- return handle-- from pathlib import Path-- from .mascot_position import (- DEFAULT_X_RELATIVE,- DEFAULT_Y_RELATIVE,- MascotPosition,- load_position_from_toml,- resolve_placement,- save_position_to_toml,- screens_from_qt,- )- from .window_mascot import MascotWindow-- mascot_section = getattr(config, "mascot", None)- size_px = getattr(mascot_section, "size_px", 160) if mascot_section else 160- snap_px = getattr(mascot_section, "snap_to_edges_px", 16) if mascot_section else 16-- # Load position — default is jarvis.toml in the working dir. Tests- # and the Hauptjarvis bootstrap can pass toml_path explicitly.- config_path = Path(toml_path) if toml_path is not None else Path("jarvis.toml")- persisted = load_position_from_toml(config_path)- if persisted is None and mascot_section is not None:- # Fallback: values from the in-memory config (e.g. first start- # without a TOML edit).- persisted = MascotPosition(- monitor=getattr(mascot_section, "position_monitor", "") or "",- x_relative=getattr(mascot_section, "position_x_relative", DEFAULT_X_RELATIVE),- y_relative=getattr(mascot_section, "position_y_relative", DEFAULT_Y_RELATIVE),- )-- placement = resolve_placement(persisted, screens_from_qt(), mascot_size_px=size_px)- if placement.recovered:- logger.warning(- "mascot.position_recovered=primary_fallback (persisted monitor missing)"- )-- def _save(pos: MascotPosition) -> None:- try:- save_position_to_toml(config_path, pos)- except Exception: # noqa: BLE001- logger.exception("save mascot position failed")-- win = MascotWindow(- initial_x=placement.abs_x,- initial_y=placement.abs_y,- monitor_name=placement.monitor,- size_px=size_px,- snap_tolerance_px=snap_px,- hide_from_capture=getattr(config, "hide_from_capture", True),- state_machine=state_machine,- on_position_saved=_save,- )- win.hideRequested.connect(win.close)-- def _reset_position() -> None:- from PySide6.QtGui import QGuiApplication-- primary = QGuiApplication.primaryScreen()- if primary is None:- return- geo = primary.availableGeometry()- new_x = geo.x() + DEFAULT_X_RELATIVE- new_y = geo.y() + DEFAULT_Y_RELATIVE- win.move(new_x, new_y)- _save(MascotPosition(- monitor=primary.name(),- x_relative=DEFAULT_X_RELATIVE,- y_relative=DEFAULT_Y_RELATIVE,- ))-- win.resetRequested.connect(_reset_position)-- # Wire the doubleClick-mute signal upstream over the WS bridge. The- # mascot fires a single MascotEventEnvelope(kind="mute_toggle"); main- # jarvis owns the actual mute state and decides what the new flag- # value should be (idempotent toggle). The local sprite already- # flipped its opacity for optimistic feedback.- if ipc is not None:- client = ipc.get("client")- loop = ipc.get("loop")- if client is not None and loop is not None:- from .schema import MascotEventEnvelope, MascotEventPayload-- def _on_mute_toggle_requested() -> None:- envelope = MascotEventEnvelope(- payload=MascotEventPayload(kind="mute_toggle"),- )- try:- asyncio.run_coroutine_threadsafe(- client.send(envelope), loop- )- except RuntimeError:- logger.debug("mute_toggle send: ipc loop closed")- except Exception: # noqa: BLE001- logger.exception("mute_toggle send failed")-- win.muteToggleRequested.connect(_on_mute_toggle_requested)-- win.show()-- handle = {"window": win, "position": placement}- app._overlay_mascot = handle # type: ignore[attr-defined]- return handle---def setup_throttling(app, config, state_machine=None, windows=None) -> Any:- """Fullscreen detection + power monitor + throttler wiring. Phase 9.7.-- Inputs:- - ``state_machine`` (required for the throttler — it subscribes- to state changes for idle reset).- - ``windows`` (optional, list of EdgeGlowWindow instances).- The throttler subscriber calls each window's- ``set_view_visible`` method on a hide timeout.-- Returns::-- {- "throttler": Throttler,- "fullscreen": FullscreenDetector,- "power": PowerMonitor,- "shutdown": Callable[[], None],- }-- If no StateMachine is supplied: only fullscreen+power, no- throttler. (e.g. headless tests.)- """- from PySide6.QtCore import QTimer-- from .fullscreen_detect import FullscreenDetector- from .power import PowerMonitor- from .throttler import (- DEFAULT_FPS_ACTIVE,- DEFAULT_FPS_BURST,- DEFAULT_FPS_IDLE,- DEFAULT_HIDE_TIMEOUT_S,- DEFAULT_IDLE_TIMEOUT_S,- Throttler,- )-- # Qt cross-thread marshalling: FullscreenDetector and PowerMonitor run- # on their own daemon threads. Their callbacks must NOT touch Qt- # widgets directly (setVisible, transition_to_*) — Qt hard-asserts- # with STATUS_BREAKPOINT 0x80000003 and the subprocess crashes. We- # route all worker callbacks via QTimer.singleShot(0, ...) onto the- # Qt main thread that holds QApplication.exec().- def _post_to_main(fn) -> None:- QTimer.singleShot(0, fn)-- handle: dict[str, Any] = {- "throttler": None,- "fullscreen": None,- "power": None,- "shutdown": lambda: None,- }-- throttler: Optional[Throttler] = None- if state_machine is not None:- throttler = Throttler(- state_machine,- fps_idle=int(getattr(config, "fps_idle", DEFAULT_FPS_IDLE)),- fps_active=int(getattr(config, "fps_active", DEFAULT_FPS_ACTIVE)),- fps_burst=int(getattr(config, "fps_burst", DEFAULT_FPS_BURST)),- idle_timeout_s=float(- getattr(config, "idle_timeout_s", DEFAULT_IDLE_TIMEOUT_S)- ),- hide_timeout_s=float(- getattr(config, "hide_timeout_s", DEFAULT_HIDE_TIMEOUT_S)- ),- )- handle["throttler"] = throttler-- # Window visibility toggling: throttler-snapshot.should_hide_view- # is mirrored onto each Edge-Glow view (WebView setVisible).- # MUST be marshalled onto the Qt main thread — the throttler can- # call the subscriber synchronously from a worker thread (the- # crash stack shows Detector → state_machine → throttler.recompute- # → _on_throttle).- if windows is not None:- def _on_throttle(snapshot) -> None:- visible = not snapshot.should_hide_view-- def _apply() -> None:- for w in windows:- if hasattr(w, "set_view_visible"):- try:- w.set_view_visible(visible)- except Exception: # noqa: BLE001- logger.debug(- "set_view_visible failed", exc_info=True- )-- _post_to_main(_apply)-- throttler.subscribe(_on_throttle)-- # Fullscreen detection. Toggles the HIDDEN state.- # The FullscreenDetector callback runs on its own daemon thread —- # state_machine.transition_* publishes synchronously to subscribers,- # which in turn touch Qt widgets. Route the entire logic through- # _post_to_main onto the Qt main thread.- def _on_fullscreen(status) -> None:- if state_machine is None:- return-- def _apply() -> None:- if status.should_hide:- state_machine.transition_to_hidden(reason="timeout")- else:- # Recovery: back to IDLE if HIDDEN was previously caused- # by fullscreen. If HIDDEN was set manually, don't- # override it — we currently can't distinguish the two,- # so we keep the conservative path: only switch to IDLE- # if currently HIDDEN.- if state_machine.state.value == "hidden":- from .state import OverlayState-- state_machine.transition_to(- OverlayState.IDLE, reason="timeout"- )- if throttler is not None:- throttler.set_fullscreen_should_hide(status.should_hide)-- _post_to_main(_apply)-- fullscreen = FullscreenDetector(- callback=_on_fullscreen,- ignore_busy_state=bool(getattr(config, "ignore_busy_state", False)),- )- fullscreen.start()- handle["fullscreen"] = fullscreen-- # Power monitor. Halves FPS on battery.- # PowerMonitor.callback runs on its own worker thread; throttler.set_on_battery- # publishes synchronously to the _on_throttle subscriber (see above). Also- # marshalled onto the Qt main thread here, otherwise the same crash risk- # applies on an AC/DC switch.- def _on_power(status) -> None:- if throttler is None:- return-- def _apply() -> None:- throttler.set_on_battery(status.on_battery)-- _post_to_main(_apply)-- power = PowerMonitor(callback=_on_power)- power.start()- handle["power"] = power-- def _shutdown() -> None:- fullscreen.stop()- power.stop()- if throttler is not None:- throttler.shutdown()-- if hasattr(app, "aboutToQuit"):- app.aboutToQuit.connect(_shutdown)- handle["shutdown"] = _shutdown-- app._overlay_throttle = handle # type: ignore[attr-defined]- return handle---def parse_args() -> argparse.Namespace:- parser = argparse.ArgumentParser(prog="overlay")- parser.add_argument("--self-test", action="store_true")- parser.add_argument("--smoke", action="store_true")- parser.add_argument("--ws-port", type=int, default=0)- return parser.parse_args()---def main() -> int:- args = parse_args()-- if args.self_test:- from .self_test import run as run_self_test-- return run_self_test()-- setup_dpi_awareness() # before QApplication-- # AUMID before QApplication so the taskbar group is fixed from the first- # window registration (otherwise Qt's class inherits the python.exe icon).- ico_path = _setup_app_identity_and_icon()-- from PySide6.QtWidgets import QApplication-- from .config import OverlayConfig-- config = OverlayConfig()- app = QApplication(sys.argv)- if ico_path is not None:- try:- from PySide6.QtGui import QIcon-- app.setWindowIcon(QIcon(str(ico_path)))- except Exception: # noqa: BLE001- # Cosmetic only; never block the overlay on icon issues.- pass-- # Wiring order: state machine first (no side effect besides object- # construction), then effects (attaches hooks to the router), then- # windows with machine + bridge, then IPC with the on_message- # callback. This way there's no phase where IPC is already delivering- # events but no subscriber is attached yet.- _state = setup_state_machine(app, config)- _effects = setup_effects(app, config, router=_state["router"])- _windows = setup_windows(- app,- config,- state_machine=_state["machine"],- effects_bridge=_effects["bridge"],- )- _ipc = setup_ipc(app, config, on_message=_state["on_message"])- _mascot = setup_mascot(app, config, state_machine=_state["machine"], ipc=_ipc)- _throttle = setup_throttling(- app, config, state_machine=_state["machine"], windows=_windows- )-- if args.smoke:- from PySide6.QtCore import QTimer-- QTimer.singleShot(5000, app.quit)-- return app.exec()---if __name__ == "__main__":- sys.exit(main())diff --git a/OS-Level/src/overlay/mascot_position.py b/OS-Level/src/overlay/mascot_position.pydeleted file mode 100644index c92ec4ed54..0000000000--- a/OS-Level/src/overlay/mascot_position.py+++ /dev/null@@ -1,365 +0,0 @@-"""Mascot position persistence + monitor recovery. Plan §13.4 + §20.4.--Persists ``[overlay.mascot] position_monitor / x_relative / y_relative``-to ``jarvis.toml`` via atomic write (AD-11). On boot:- - If ``position_monitor`` is found in EnumDisplayMonitors:- place the mascot there at (rcWork.left + x_rel, rcWork.top + y_rel).- - If not (laptop undocked, port swap, monitor unplugged):- deterministic fallback to the primary monitor + default (200, 80).--We avoid ctypes here — Qt's QGuiApplication.screens() returns-``screen.name()``, which matches the device name (``\\.\DISPLAY1``)-under Win32. This has the advantage that tests can run headless-without a Win32 mock.--Atomic write uses tomllib + manual writing (no tomli_w needed-since we only edit one known section).-"""--from __future__ import annotations--import logging-import os-import tempfile-import tomllib-from dataclasses import dataclass-from pathlib import Path-from typing import Optional, Sequence--logger = logging.getLogger(__name__)---@dataclass(frozen=True)-class MascotPosition:- """Persisted position. ``monitor`` = Win32 device name (``\\\\.\\DISPLAY1``)."""-- monitor: str- x_relative: int- y_relative: int---@dataclass(frozen=True)-class ResolvedPlacement:- """Result of ``resolve_placement()`` — where the window should actually go."""-- abs_x: int- abs_y: int- monitor: str- recovered: bool # True if the primary fallback kicked in---# Plan §13.4: defaults when the persisted position cannot be restored.-DEFAULT_X_RELATIVE: int = 200-DEFAULT_Y_RELATIVE: int = 80-DEFAULT_MARGIN_PX: int = 16 # rcWork clamp + snap tolerance---@dataclass(frozen=True)-class _ScreenSnapshot:- """Platform-agnostic. Populated from ``QGuiApplication.screens()``."""-- name: str # Win32 device name on Windows; symbolic id on Linux/macOS- geometry: tuple[int, int, int, int] # (x, y, w, h) work-area in logical px- is_primary: bool---def screens_from_qt() -> list[_ScreenSnapshot]:- """Qt screens snapshot for resolve_placement(). Lazy import so- the loader stays importable headless without PySide6."""- from PySide6.QtGui import QGuiApplication-- app = QGuiApplication.instance()- if app is None:- return []- primary = QGuiApplication.primaryScreen()- out: list[_ScreenSnapshot] = []- for screen in QGuiApplication.screens():- # availableGeometry = work area (without taskbar). Plan §13.4 uses- # rcWork — Qt's availableGeometry maps 1:1.- geo = screen.availableGeometry()- out.append(- _ScreenSnapshot(- name=screen.name(),- geometry=(geo.x(), geo.y(), geo.width(), geo.height()),- is_primary=(screen is primary),- )- )- return out---def resolve_placement(- persisted: Optional[MascotPosition],- screens: Sequence[_ScreenSnapshot],- *,- mascot_size_px: int = 160,-) -> ResolvedPlacement:- """Plan §13.4 — the canonical 5-step recovery.-- 1. If ``persisted.monitor`` is present in screens:- restore at (rcWork.left + x_rel, rcWork.top + y_rel) clamped- into rcWork minus a 16 px margin minus mascot_size.- 2. If not:- pick the primary monitor, default (200, 80) position.- ``recovered=True`` so the caller can log it.- 3. If there are no screens (headless / tests): default (0, 0)- relative + empty monitor name; the caller must handle that.- """- if not screens:- # Tests / headless without a Qt app.- return ResolvedPlacement(- abs_x=DEFAULT_X_RELATIVE,- abs_y=DEFAULT_Y_RELATIVE,- monitor="",- recovered=True,- )-- by_name = {s.name: s for s in screens}-- if persisted is not None and persisted.monitor in by_name:- screen = by_name[persisted.monitor]- sx, sy, sw, sh = screen.geometry- # Clamp the relative coords into rcWork minus margin minus- # mascot_size — prevents the mascot from landing off-screen- # on restore after a resolution change.- max_rel_x = max(0, sw - mascot_size_px - DEFAULT_MARGIN_PX)- max_rel_y = max(0, sh - mascot_size_px - DEFAULT_MARGIN_PX)- rel_x = max(DEFAULT_MARGIN_PX, min(persisted.x_relative, max_rel_x))- rel_y = max(DEFAULT_MARGIN_PX, min(persisted.y_relative, max_rel_y))- return ResolvedPlacement(- abs_x=sx + rel_x,- abs_y=sy + rel_y,- monitor=screen.name,- recovered=False,- )-- # Persisted monitor not present — primary fallback.- primary = next((s for s in screens if s.is_primary), screens[0])- sx, sy, _sw, _sh = primary.geometry- return ResolvedPlacement(- abs_x=sx + DEFAULT_X_RELATIVE,- abs_y=sy + DEFAULT_Y_RELATIVE,- monitor=primary.name,- recovered=True,- )---def snap_to_edges(- abs_x: int,- abs_y: int,- monitor_geometry: tuple[int, int, int, int],- *,- mascot_size_px: int = 160,- snap_tolerance_px: int = 16,-) -> tuple[int, int]:- """Plan §13.3 — edge snap within a 16 px tolerance.-- Computes the nearest snap for the top/bottom/left/right edges and- snaps if within tolerance. Returns (snapped_x, snapped_y).- """- sx, sy, sw, sh = monitor_geometry- snapped_x, snapped_y = abs_x, abs_y-- # Distance to the left / right edge.- dist_left = abs_x - sx- dist_right = (sx + sw) - (abs_x + mascot_size_px)- if 0 <= dist_left <= snap_tolerance_px:- snapped_x = sx- elif 0 <= dist_right <= snap_tolerance_px:- snapped_x = sx + sw - mascot_size_px-- # Distance to the top / bottom edge.- dist_top = abs_y - sy- dist_bottom = (sy + sh) - (abs_y + mascot_size_px)- if 0 <= dist_top <= snap_tolerance_px:- snapped_y = sy- elif 0 <= dist_bottom <= snap_tolerance_px:- snapped_y = sy + sh - mascot_size_px-- return snapped_x, snapped_y---def clamp_to_work_area(- abs_x: int,- abs_y: int,- monitor_geometry: tuple[int, int, int, int],- *,- mascot_size_px: int = 160,- margin_px: int = DEFAULT_MARGIN_PX,-) -> tuple[int, int]:- """Prevents off-screen drag. Plan §13.3 + §20.4.-- Mascot stays fully inside rcWork minus the margin.- """- sx, sy, sw, sh = monitor_geometry- min_x = sx + margin_px- min_y = sy + margin_px- max_x = sx + sw - mascot_size_px - margin_px- max_y = sy + sh - mascot_size_px - margin_px- return (max(min_x, min(abs_x, max_x)), max(min_y, min(abs_y, max_y)))---# --------------------------------------------------------------------------# TOML Read/Write — Plan §21.1 + §21.3 Atomic Pipeline (light variant).-# ----------------------------------------------------------------------------def load_position_from_toml(path: Path) -> Optional[MascotPosition]:- """Reads the ``[overlay.mascot]`` fields from ``jarvis.toml``. None- if the file is missing or the section/fields aren't there."""- if not path.is_file():- return None- try:- with path.open("rb") as f:- data = tomllib.load(f)- except (tomllib.TOMLDecodeError, OSError) as exc:- logger.warning("load_position_from_toml: %s", exc)- return None- overlay = data.get("overlay") or {}- section = overlay.get("mascot") or {}- monitor = section.get("position_monitor", "")- if not isinstance(monitor, str):- monitor = ""- x_rel = int(section.get("position_x_relative", DEFAULT_X_RELATIVE))- y_rel = int(section.get("position_y_relative", DEFAULT_Y_RELATIVE))- return MascotPosition(monitor=monitor, x_relative=x_rel, y_relative=y_rel)---def save_position_to_toml(path: Path, position: MascotPosition) -> None:- """Atomic write of the three position fields. Plan §21.3 light:- 1. read existing TOML as text- 2. replace the three fields via line-based regex- 3. tempfile + os.replace()-- We write TOML manually (text-based) instead of using tomli_w- because that preserves the user's whitespace and comments —- important because ``jarvis.toml`` is user-editable and we don't- want to eat comments.- """- import re-- if not path.is_file():- # Fresh file — write a minimal initial section.- new_text = (- "[overlay.mascot]\n"- f'position_monitor = "{_escape_toml_str(position.monitor)}"\n'- f"position_x_relative = {position.x_relative}\n"- f"position_y_relative = {position.y_relative}\n"- )- _atomic_write_text(path, new_text)- return-- text = path.read_text(encoding="utf-8")-- # Section [overlay.mascot] must exist, otherwise we append.- section_re = re.compile(r"^\[overlay\.mascot\]\s*$", re.MULTILINE)- if not section_re.search(text):- if not text.endswith("\n"):- text += "\n"- text += (- "\n[overlay.mascot]\n"- f'position_monitor = "{_escape_toml_str(position.monitor)}"\n'- f"position_x_relative = {position.x_relative}\n"- f"position_y_relative = {position.y_relative}\n"- )- _atomic_write_text(path, text)- return-- # Section present. Replace the three fields, or append if missing.- text = _replace_or_append_field(- text,- section_header="[overlay.mascot]",- field="position_monitor",- value=f'"{_escape_toml_str(position.monitor)}"',- )- text = _replace_or_append_field(- text,- section_header="[overlay.mascot]",- field="position_x_relative",- value=str(position.x_relative),- )- text = _replace_or_append_field(- text,- section_header="[overlay.mascot]",- field="position_y_relative",- value=str(position.y_relative),- )-- _atomic_write_text(path, text)---def _atomic_write_text(path: Path, text: str) -> None:- """tempfile + os.replace() (atomic on Win32)."""- path.parent.mkdir(parents=True, exist_ok=True)- fd, tmp_name = tempfile.mkstemp(- prefix=path.name + ".", suffix=".tmp", dir=str(path.parent)- )- try:- with os.fdopen(fd, "w", encoding="utf-8", newline="") as f:- f.write(text)- os.replace(tmp_name, path)- except Exception:- try:- os.unlink(tmp_name)- except OSError:- pass- raise---def _escape_toml_str(s: str) -> str:- """Minimal TOML string escape: backslashes + double-quotes."""- return s.replace("\\", "\\\\").replace('"', '\\"')---def _replace_or_append_field(- text: str, *, section_header: str, field: str, value: str-) -> str:- """Replaces ``field = ...`` within ``[section]``. If the field- doesn't exist, it is inserted directly under the section header.-- Region boundary: up to the next ``\\n[`` (= next section)- or end of file.- """- import re-- section_pattern = re.escape(section_header)- region_re = re.compile(- rf"(^{section_pattern}\s*\n)(.*?)(?=^\[|\Z)",- re.MULTILINE | re.DOTALL,- )- region_m = region_re.search(text)- if region_m is None:- return text # caller made sure the section is present-- region_text = region_m.group(2)-- field_re = re.compile(- rf"^(?P<lead>\s*){re.escape(field)}\s*=.*?$",- re.MULTILINE,- )- if field_re.search(region_text):- new_region = field_re.sub(- lambda m: f"{m.group('lead')}{field} = {value}",- region_text,- count=1,- )- else:- # Insert the field at the start of the section.- new_region = f"{field} = {value}\n" + region_text-- return text[: region_m.start(2)] + new_region + text[region_m.end(2) :]---__all__ = [- "DEFAULT_MARGIN_PX",- "DEFAULT_X_RELATIVE",- "DEFAULT_Y_RELATIVE",- "MascotPosition",- "ResolvedPlacement",- "_ScreenSnapshot",- "clamp_to_work_area",- "load_position_from_toml",- "resolve_placement",- "save_position_to_toml",- "screens_from_qt",- "snap_to_edges",-]diff --git a/OS-Level/src/overlay/monitors.py b/OS-Level/src/overlay/monitors.pydeleted file mode 100644index 2865665bb9..0000000000--- a/OS-Level/src/overlay/monitors.py+++ /dev/null@@ -1,100 +0,0 @@-"""Monitor enumeration via Qt + hotplug subscription. Plan §12.3, §12.5.--Qt provides ``screenAdded``/``screenRemoved`` signals; we wrap that in-a small manager so Phase 9.1 can manage the windows-per-screen and-Phase 9.2+ can hook in position recovery (mascot, Plan §13.4).-"""--from __future__ import annotations--from dataclasses import dataclass-from typing import TYPE_CHECKING, Callable, Optional--if TYPE_CHECKING: # pragma: no cover- from PySide6.QtCore import QObject- from PySide6.QtGui import QScreen---@dataclass(frozen=True)-class MonitorInfo:- """Snapshot of a monitor, platform-agnostic."""-- name: str- geometry: tuple[int, int, int, int] # (x, y, w, h) logical pixels- device_pixel_ratio: float- is_primary: bool---def enumerate_monitors() -> list[MonitorInfo]:- """Snapshot of all live monitors.-- Accesses ``QGuiApplication.screens()`` — a QApplication must- already exist (see ``main.py``). Test code mocks the- QGuiApplication module.- """- from PySide6.QtGui import QGuiApplication # lazy: no Qt imports in the self-test-- app = QGuiApplication.instance()- if app is None:- return []- primary = QGuiApplication.primaryScreen()- out: list[MonitorInfo] = []- for screen in QGuiApplication.screens():- geo = screen.geometry()- out.append(- MonitorInfo(- name=screen.name(),- geometry=(geo.x(), geo.y(), geo.width(), geo.height()),- device_pixel_ratio=screen.devicePixelRatio(),- is_primary=(screen is primary),- )- )- return out---class MonitorManager:- """Subscribes to ``QGuiApplication`` hotplug signals.-- Phase 9.1 only uses ``on_screen_added`` / ``on_screen_removed`` as- hooks; window lifecycle lives in ``main.setup_windows``.- """-- def __init__(- self,- on_screen_added: Optional[Callable[["QScreen"], None]] = None,- on_screen_removed: Optional[Callable[["QScreen"], None]] = None,- ) -> None:- self._on_added = on_screen_added- self._on_removed = on_screen_removed- self._app: Optional["QObject"] = None-- def attach(self) -> None:- """Connects hotplug signals. Idempotent."""- from PySide6.QtGui import QGuiApplication # lazy-- app = QGuiApplication.instance()- if app is None:- raise RuntimeError("MonitorManager.attach: no QGuiApplication")- if self._app is app:- return- if self._on_added is not None:- app.screenAdded.connect(self._on_added)- if self._on_removed is not None:- app.screenRemoved.connect(self._on_removed)- self._app = app-- def detach(self) -> None:- """Disconnects signals. Call before app quit, otherwise dangling callbacks."""- if self._app is None:- return- if self._on_added is not None:- try:- self._app.screenAdded.disconnect(self._on_added)- except (RuntimeError, TypeError): # pragma: no cover- pass- if self._on_removed is not None:- try:- self._app.screenRemoved.disconnect(self._on_removed)- except (RuntimeError, TypeError): # pragma: no cover- pass- self._app = Nonediff --git a/OS-Level/src/overlay/power.py b/OS-Level/src/overlay/power.pydeleted file mode 100644index 9ec27f477b..0000000000--- a/OS-Level/src/overlay/power.py+++ /dev/null@@ -1,167 +0,0 @@-"""GetSystemPowerStatus polling. Plan §17.3 throttling strategy.--AC vs battery -> halve the FPS. Polling every 30 s on a daemon thread.--SYSTEM_POWER_STATUS struct (winbase.h):-- BYTE ACLineStatus // 0=offline, 1=online, 255=unknown- BYTE BatteryFlag // 0..8 bit-mask- BYTE BatteryLifePercent // 0..100 or 255 (unknown)- BYTE SystemStatusFlag // 1 = battery saver on- DWORD BatteryLifeTime // seconds until empty or 0xFFFFFFFF- DWORD BatteryFullLifeTime // ditto--We primarily read ACLineStatus + SystemStatusFlag.-"""--from __future__ import annotations--import logging-import sys-import threading-from dataclasses import dataclass-from typing import Callable, Optional--logger = logging.getLogger(__name__)---@dataclass(frozen=True)-class PowerStatus:- on_battery: bool- battery_saver: bool- battery_percent: Optional[int] # None if unknown---PowerCallback = Callable[[PowerStatus], None]---def query_status() -> Optional[PowerStatus]:- """Plan §17.3 — GetSystemPowerStatus via ctypes.-- Returns None on non-Windows or on an API error.- """- if sys.platform != "win32":- return None- import ctypes- from ctypes import wintypes-- class _SystemPowerStatus(ctypes.Structure):- _fields_ = [- ("ACLineStatus", wintypes.BYTE),- ("BatteryFlag", wintypes.BYTE),- ("BatteryLifePercent", wintypes.BYTE),- ("SystemStatusFlag", wintypes.BYTE),- ("BatteryLifeTime", wintypes.DWORD),- ("BatteryFullLifeTime", wintypes.DWORD),- ]-- try:- kernel = ctypes.windll.kernel32- except (OSError, AttributeError): # pragma: no cover- return None-- kernel.GetSystemPowerStatus.argtypes = [ctypes.POINTER(_SystemPowerStatus)]- kernel.GetSystemPowerStatus.restype = wintypes.BOOL-- sps = _SystemPowerStatus()- ok = kernel.GetSystemPowerStatus(ctypes.byref(sps))- if not ok:- logger.debug("GetSystemPowerStatus failed")- return None-- ac = sps.ACLineStatus- on_battery = ac == 0- battery_saver = bool(sps.SystemStatusFlag & 0x01)- pct = sps.BatteryLifePercent- battery_percent: Optional[int] = None if pct == 255 else int(pct)- return PowerStatus(- on_battery=on_battery,- battery_saver=battery_saver,- battery_percent=battery_percent,- )---class PowerMonitor:- """30-second polling thread for SYSTEM_POWER_STATUS.-- Lifecycle::-- mon = PowerMonitor(callback=on_change)- mon.start()- ...- mon.stop()- """-- def __init__(- self,- *,- callback: Optional[PowerCallback] = None,- poll_interval_s: float = 30.0,- query_fn: Callable[[], Optional[PowerStatus]] = query_status,- ) -> None:- self._callback = callback- self._poll_interval = poll_interval_s- self._query_fn = query_fn- self._stop = threading.Event()- self._thread: Optional[threading.Thread] = None- self._last_status: Optional[PowerStatus] = None-- @property- def last_status(self) -> Optional[PowerStatus]:- return self._last_status-- @property- def is_running(self) -> bool:- return self._thread is not None and self._thread.is_alive()-- def set_callback(self, callback: Optional[PowerCallback]) -> None:- self._callback = callback-- def poll_once(self) -> Optional[PowerStatus]:- """Sync Poll. Returnt PowerStatus oder None."""- status = self._query_fn()- if status is None:- return None- prev = self._last_status- self._last_status = status- if self._callback is not None and (- prev is None- or prev.on_battery is not status.on_battery- or prev.battery_saver is not status.battery_saver- ):- try:- self._callback(status)- except Exception: # noqa: BLE001- logger.exception("PowerMonitor callback raised")- return status-- def start(self) -> None:- if self.is_running:- return- self._stop.clear()- # Poll immediately on start so the caller doesn't have to wait- # 30 s for the first status.- self.poll_once()- self._thread = threading.Thread(- target=self._run, name="overlay-power-monitor", daemon=True- )- self._thread.start()-- def stop(self) -> None:- self._stop.set()- if self._thread is not None:- self._thread.join(timeout=2.0)-- def _run(self) -> None:- while not self._stop.is_set():- if self._stop.wait(timeout=self._poll_interval):- return- self.poll_once()---__all__ = [- "PowerCallback",- "PowerMonitor",- "PowerStatus",- "query_status",-]diff --git a/OS-Level/src/overlay/schema.py b/OS-Level/src/overlay/schema.pydeleted file mode 100644index 8094bae18c..0000000000--- a/OS-Level/src/overlay/schema.py+++ /dev/null@@ -1,325 +0,0 @@-"""IPC Pydantic v2 schemas — single source of truth. Plan §10.--Wire envelope (§10.1):- {v, type, id, ts_ns, target, payload}--``type`` is the discriminator for ``payload``. The clean Pydantic v2-approach: one dedicated envelope model per message type with ``type``-as a ``Literal`` field; the union over them is typed with-``Field(discriminator="type")``. ``IPCMessage`` is the runtime-validating-``TypeAdapter`` instance.--AD-15: Pydantic v2 (Python) and Zod (TS) stay symmetric — Phase 9.4-derives the Zod schema from the JSON-schema export here.-"""--from __future__ import annotations--import time-from typing import Annotated, Any, Literal, Union--from pydantic import (- BaseModel,- ConfigDict,- Field,- TypeAdapter,- field_validator,-)-from ulid import ULID--# Schema major version. Forward compat: receivers warn if != 1.-SCHEMA_VERSION = 1--# Discriminator values (also referenced by the state machine in 9.3).-StateName = Literal[- "idle",- "listening",- "thinking",- "typing",- "clicking",- "speaking",- "error",- "hidden",-]-Target = Literal["edgeglow", "mascot", "*"]-ActionKindLiteral = Literal["click", "type", "move", "navigate", "hotkey", "scroll"]-ClickButton = Literal["left", "right", "middle"]-StateReason = Literal["wakeword", "user", "tool", "timeout", "error"]---def now_ns() -> int:- """Unix epoch ns. Compatible with the SHM cursor + WS envelopes (§11.4)."""- return time.time_ns()---def new_ulid() -> str:- """Fresh ULID as a wire string (26 Crockford Base32 chars)."""- return str(ULID())---# ------------------------------------------------------------------------------# Payloads — §10.2-# --------------------------------------------------------------------------------class StatePayload(BaseModel):- model_config = ConfigDict(extra="forbid")-- state: StateName- intensity: float = Field(default=1.0, ge=0.0, le=1.0)- since_ts_ns: int = Field(default_factory=now_ns)- reason: StateReason | None = None---class ClickPayload(BaseModel):- model_config = ConfigDict(extra="forbid")-- x: int- y: int- monitor: str = ""- button: ClickButton = "left"- modifiers: list[str] = Field(default_factory=list)- wallclock_ns: int = Field(default_factory=now_ns)---class ActionStartedPayload(BaseModel):- model_config = ConfigDict(extra="forbid")-- kind: ActionKindLiteral- action_id: str = Field(default_factory=new_ulid)- duration_hint_ms: int | None = None---class ActionEndedPayload(BaseModel):- model_config = ConfigDict(extra="forbid")-- action_id: str- succeeded: bool = True- duration_actual_ms: int | None = None---class CursorPayload(BaseModel):- """WS fallback when SHM isn't available (§11.5)."""-- model_config = ConfigDict(extra="forbid")-- x: int- y: int- monitor: str = ""---class HeartbeatPayload(BaseModel):- model_config = ConfigDict(extra="forbid")-- uptime_s: float = 0.0- rss_mb: float = 0.0- fps_actual: float = 0.0- fps_target: float = 0.0- drops: int = 0- ws_connected: bool = True- shm_attached: bool = False---class ConfigPayload(BaseModel):- """Main-Jarvis -> overlay after a config reload (§10.2)."""-- model_config = ConfigDict(extra="allow") # forward-compat, new theme keys-- theme: dict[str, Any] = Field(default_factory=dict)- mascot_enabled: bool = True- mascot_pos: dict[str, Any] = Field(default_factory=dict)- fps_active: int = 30- fps_burst: int = 60- all_monitors: bool = False- hide_on_fullscreen: bool = True- hide_from_capture: bool = True- respect_reduced_motion: bool = True- shm_cursor_name: str = ""- shm_cursor_hz: int = 60---class AckPayload(BaseModel):- model_config = ConfigDict(extra="forbid")-- ack_id: str- received_ts_ns: int = Field(default_factory=now_ns)- rendered_ts_ns: int | None = None---class ErrorPayload(BaseModel):- model_config = ConfigDict(extra="forbid")-- code: str- message: str- recoverable: bool = True- context: dict[str, Any] = Field(default_factory=dict)---# Mascot-originated user interactions. The overlay subprocess emits this-# upstream when the user interacts with the mascot in a way that should-# trigger Jarvis-side behaviour (currently: toggle global voice mute).-MascotEventKind = Literal["mute_toggle"]---class MascotEventPayload(BaseModel):- model_config = ConfigDict(extra="forbid")-- kind: MascotEventKind---# ------------------------------------------------------------------------------# Envelope — §10.1, one class per type, discriminated union-# --------------------------------------------------------------------------------class _BaseEnvelope(BaseModel):- """Shared envelope fields. Each subclass sets ``type`` itself."""-- model_config = ConfigDict(extra="forbid")-- v: int = SCHEMA_VERSION- id: str = Field(default_factory=new_ulid)- ts_ns: int = Field(default_factory=now_ns)- target: Target = "*"-- @field_validator("v")- @classmethod- def _check_version(cls, value: int) -> int:- # Forward compat: higher versions are logged in the IPC layer,- # here we accept anything >=1 so a newer overlay can receive- # from an older Main-Jarvis.- if value < 1:- raise ValueError(f"schema-version v={value} < 1")- return value---class StateEnvelope(_BaseEnvelope):- type: Literal["state"] = "state"- payload: StatePayload---class ClickEnvelope(_BaseEnvelope):- type: Literal["click"] = "click"- payload: ClickPayload---class ActionStartedEnvelope(_BaseEnvelope):- type: Literal["action_started"] = "action_started"- payload: ActionStartedPayload---class ActionEndedEnvelope(_BaseEnvelope):- type: Literal["action_ended"] = "action_ended"- payload: ActionEndedPayload---class CursorEnvelope(_BaseEnvelope):- type: Literal["cursor"] = "cursor"- payload: CursorPayload---class HeartbeatEnvelope(_BaseEnvelope):- type: Literal["heartbeat"] = "heartbeat"- payload: HeartbeatPayload---class ConfigEnvelope(_BaseEnvelope):- type: Literal["config"] = "config"- payload: ConfigPayload---class AckEnvelope(_BaseEnvelope):- type: Literal["ack"] = "ack"- payload: AckPayload---class ErrorEnvelope(_BaseEnvelope):- type: Literal["error"] = "error"- payload: ErrorPayload---class MascotEventEnvelope(_BaseEnvelope):- type: Literal["mascot_event"] = "mascot_event"- payload: MascotEventPayload---IPCEnvelope = Annotated[- Union[- StateEnvelope,- ClickEnvelope,- ActionStartedEnvelope,- ActionEndedEnvelope,- CursorEnvelope,- HeartbeatEnvelope,- ConfigEnvelope,- AckEnvelope,- ErrorEnvelope,- MascotEventEnvelope,- ],- Field(discriminator="type"),-]--# Runtime validator. ``IPCMessage.validate_python(d)`` /-# ``IPCMessage.validate_json(b)`` pick the right envelope model based-# on the ``type`` field.-IPCMessage: TypeAdapter[Any] = TypeAdapter(IPCEnvelope)---# State sets that mirror Plan §6.1 in code — also consumed by the-# 9.3 state machine.-NON_STATE_TYPES: frozenset[str] = frozenset(- {- "cursor",- "ack",- "heartbeat",- "action_started",- "action_ended",- "click",- "error",- "mascot_event",- }-)-STATE_TYPES: frozenset[str] = frozenset({"state", "config"})---def is_state_type(envelope_type: str) -> bool:- """Backpressure hint: ``False`` -> can be dropped (§10.4)."""- return envelope_type in STATE_TYPES---__all__ = [- "AckEnvelope",- "AckPayload",- "ActionEndedEnvelope",- "ActionEndedPayload",- "ActionKindLiteral",- "ActionStartedEnvelope",- "ActionStartedPayload",- "ClickButton",- "ClickEnvelope",- "ClickPayload",- "ConfigEnvelope",- "ConfigPayload",- "CursorEnvelope",- "CursorPayload",- "ErrorEnvelope",- "ErrorPayload",- "HeartbeatEnvelope",- "HeartbeatPayload",- "IPCEnvelope",- "IPCMessage",- "MascotEventEnvelope",- "MascotEventKind",- "MascotEventPayload",- "NON_STATE_TYPES",- "SCHEMA_VERSION",- "STATE_TYPES",- "StateEnvelope",- "StateName",- "StatePayload",- "StateReason",- "Target",- "is_state_type",- "new_ulid",- "now_ns",-]diff --git a/OS-Level/src/overlay/self_test.py b/OS-Level/src/overlay/self_test.pydeleted file mode 100644index b9f6da1197..0000000000--- a/OS-Level/src/overlay/self_test.py+++ /dev/null@@ -1,28 +0,0 @@-"""Self-test without GUI dependencies.--Imports ONLY foundation modules (config, state, schema). Touches NO Qt,-so headless CI runs without a display work.-"""--from __future__ import annotations--import sys---def run() -> int:- from . import __version__- from .config import OverlayConfig- from .state import OverlayState-- # Pydantic default roundtrip as a sanity check.- cfg = OverlayConfig()- assert cfg.enabled is True- assert OverlayState.IDLE.value == "idle"- assert len(list(OverlayState)) == 8-- print(f"OK overlay=={__version__}")- return 0---if __name__ == "__main__": # pragma: no cover- sys.exit(run())diff --git a/OS-Level/src/overlay/state.py b/OS-Level/src/overlay/state.pydeleted file mode 100644index 445f4f3731..0000000000--- a/OS-Level/src/overlay/state.py+++ /dev/null@@ -1,146 +0,0 @@-"""OverlayState enum + StateMachine per Plan §6.--Plan §6.1: 8 states, glow is ONLY active in TYPING and CLICKING.-Plan AD-8: the state machine lives in the overlay process (not in Main-Jarvis).-Plan AD-17: 16 ms coalescing for identical consecutive transitions.-"""--from __future__ import annotations--import logging-import threading-import time-from enum import Enum-from typing import Callable, Optional--logger = logging.getLogger(__name__)---class OverlayState(str, Enum):- """8 states per Plan §6.1. String values are the stable wire format."""-- IDLE = "idle"- LISTENING = "listening"- THINKING = "thinking"- TYPING = "typing"- CLICKING = "clicking"- SPEAKING = "speaking"- ERROR = "error"- HIDDEN = "hidden"---GLOW_ACTIVE_STATES: frozenset[OverlayState] = frozenset(- {OverlayState.TYPING, OverlayState.CLICKING}-)---# Plan AD-17 — 16 ms = 1 frame @ 60 Hz.-COALESCE_WINDOW_NS: int = 16_000_000---# (old, new, reason) — reason can be None if none was given.-StateChangeCallback = Callable[[OverlayState, OverlayState, Optional[str]], None]---class StateMachine:- """Authoritative state holder for the overlay.-- Plan AD-8: lives in the overlay process. Main-Jarvis sends events- over IPC, and the EventRouter maps them to ``transition_to()`` calls.-- Plan §6.2 coalescing rule: ``any -> same state within 16 ms : ignored``.- Identical consecutive transitions within ``COALESCE_WINDOW_NS`` are- a no-op and do not fire subscribers.-- Subscriber callbacks are called SYNCHRONOUSLY on the caller thread- of ``transition_to()`` — subscribers must be fast and non-blocking.- If a callback fires from a worker thread, marshalling onto the Qt- thread is the subscriber's responsibility (e.g. via- ``QMetaObject.invokeMethod`` or Qt signals).- """-- def __init__(self, *, initial: OverlayState = OverlayState.IDLE) -> None:- self._state = initial- # monotonic_ns() is immune to wallclock skew — safer here than- # time.time_ns() since it's only used for the coalescing diff.- self._last_transition_ns: int = 0- self._lock = threading.RLock()- self._subscribers: list[StateChangeCallback] = []-- @property- def state(self) -> OverlayState:- with self._lock:- return self._state-- def subscribe(self, callback: StateChangeCallback) -> Callable[[], None]:- """Registers a subscriber, returns an ``unsubscribe`` function."""- with self._lock:- self._subscribers.append(callback)-- def _unsubscribe() -> None:- with self._lock:- if callback in self._subscribers:- self._subscribers.remove(callback)-- return _unsubscribe-- def transition_to(- self,- target: OverlayState,- *,- reason: Optional[str] = None,- ) -> bool:- """Switches to ``target``. Returns ``True`` if it was a real transition.-- Coalescing rules:- - ``target == current`` and the last change was < 16 ms ago -> ignored.- - ``target == current`` but the last change was >= 16 ms ago -> also- ignored (no state change), but that is not a coalescing hit.- - ``target != current`` -> always transitions.- """- now_ns = time.monotonic_ns()- with self._lock:- old = self._state- if target == old:- # No state change. The coalescing spec is strictly- # speaking redundant here, but we log the hit so- # drift diagnosis stays possible.- if (now_ns - self._last_transition_ns) < COALESCE_WINDOW_NS:- logger.debug(- "state coalesced: %s -> %s within %d ns",- old.value,- target.value,- now_ns - self._last_transition_ns,- )- return False- self._state = target- self._last_transition_ns = now_ns- subscribers_snapshot = list(self._subscribers)-- # Subscriber dispatch outside the lock — prevents deadlocks- # in case a subscriber re-entrantly calls transition_to().- for cb in subscribers_snapshot:- try:- cb(old, target, reason)- except Exception: # noqa: BLE001- logger.exception(- "StateMachine subscriber raised on %s -> %s",- old.value,- target.value,- )- return True--- def transition_to_hidden(self, *, reason: Optional[str] = None) -> bool:- """Plan §17.3 + §20.2 — convenience for the fullscreen detector- and hide-timeout paths."""- return self.transition_to(OverlayState.HIDDEN, reason=reason)---__all__ = [- "COALESCE_WINDOW_NS",- "GLOW_ACTIVE_STATES",- "OverlayState",- "StateChangeCallback",- "StateMachine",-]diff --git a/OS-Level/src/overlay/throttler.py b/OS-Level/src/overlay/throttler.pydeleted file mode 100644index fb5bfbb8f2..0000000000--- a/OS-Level/src/overlay/throttler.py+++ /dev/null@@ -1,267 +0,0 @@-"""Throttler — single source of truth for FPS targets + visibility.--Plan §17.2 + §17.3. Inputs:- - current OverlayState (idle/listening/.../typing/clicking/...)- - on_battery (PowerMonitor)- - last_state_change_ts (from the StateMachine subscriber)- - fullscreen_should_hide (FullscreenDetector)--Outputs:- - get_target_fps() -> int (the FPS cap)- - should_hide_view() -> bool (5-min idle path: view fully hidden)- - subscribe(callback) (callback fires when target_fps or- should_hide_view changes)--Plan §17.2 FPS targets per state:- hidden -> 0- idle (30s+) -> fps_idle (default 1)- listening / thinking / speaking / error -> fps_active (30)- typing / clicking -> fps_burst (60)- error-flash -> fps_burst for 600 ms, then back--Plan §17.3 throttling strategy:- AC vs battery: on_battery -> halve all FPS.- Idle detection: 30 s no events -> fps_idle.- Hide on idle: 5 min no events -> should_hide_view=True.- Wake on event: every state change resets the idle timer.-"""--from __future__ import annotations--import logging-import threading-import time-from dataclasses import dataclass, replace-from typing import Callable, Optional--from .state import OverlayState, StateMachine--logger = logging.getLogger(__name__)---# Plan §17.2 + §21.1 default values.-DEFAULT_FPS_IDLE: int = 1-DEFAULT_FPS_ACTIVE: int = 30-DEFAULT_FPS_BURST: int = 60-DEFAULT_IDLE_TIMEOUT_S: float = 30.0-DEFAULT_HIDE_TIMEOUT_S: float = 300.0 # 5 minutes---# State -> FPS bucket mapping. Plan §17.2.-_BURST_STATES: frozenset[OverlayState] = frozenset(- {OverlayState.TYPING, OverlayState.CLICKING}-)-_ACTIVE_STATES: frozenset[OverlayState] = frozenset(- {- OverlayState.LISTENING,- OverlayState.THINKING,- OverlayState.SPEAKING,- OverlayState.ERROR,- }-)-# IDLE itself counts as active as long as < idle_timeout; after that, idle bucket.---@dataclass(frozen=True)-class ThrottleSnapshot:- """Current output. Subscribers receive this."""-- target_fps: int- should_hide_view: bool- is_hidden_state: bool- on_battery: bool- fullscreen_active: bool- idle_seconds: float---ThrottleCallback = Callable[[ThrottleSnapshot], None]---class Throttler:- """Computes the target FPS + hide decision from state + power + idle.-- Idempotent + thread-safe (RLock). ``recompute()`` is the only- entry point that fires subscribers.- """-- def __init__(- self,- machine: StateMachine,- *,- fps_idle: int = DEFAULT_FPS_IDLE,- fps_active: int = DEFAULT_FPS_ACTIVE,- fps_burst: int = DEFAULT_FPS_BURST,- idle_timeout_s: float = DEFAULT_IDLE_TIMEOUT_S,- hide_timeout_s: float = DEFAULT_HIDE_TIMEOUT_S,- ) -> None:- self._machine = machine- self._fps_idle = max(0, fps_idle)- self._fps_active = max(1, fps_active)- self._fps_burst = max(1, fps_burst)- self._idle_timeout = idle_timeout_s- self._hide_timeout = hide_timeout_s-- self._lock = threading.RLock()- self._last_change_ns: int = time.monotonic_ns()- self._on_battery: bool = False- self._fullscreen_should_hide: bool = False- self._subscribers: list[ThrottleCallback] = []- self._last_snapshot: Optional[ThrottleSnapshot] = None-- self._unsubscribe_machine = machine.subscribe(self._on_state_change)-- # -------- public Inputs ---------- def set_on_battery(self, on_battery: bool) -> None:- with self._lock:- if self._on_battery is on_battery:- return- self._on_battery = on_battery- self.recompute()-- def set_fullscreen_should_hide(self, should_hide: bool) -> None:- with self._lock:- if self._fullscreen_should_hide is should_hide:- return- self._fullscreen_should_hide = should_hide- self.recompute()-- def subscribe(self, callback: ThrottleCallback) -> Callable[[], None]:- """Registers the callback. Immediately called once with the- current snapshot so the subscriber knows the initial state.-- Order matters: first recompute() (without the new subscriber- in the list), then fire the initial callback once, THEN add- it to the subscriber list. Otherwise it would fire twice- initially (recompute calls all subscribers including the new- one, plus the explicit initial call here).- """- snap = self.recompute()- try:- callback(snap)- except Exception: # noqa: BLE001- logger.exception("Throttler subscriber raised on initial dispatch")- with self._lock:- self._subscribers.append(callback)-- def _unsub() -> None:- with self._lock:- if callback in self._subscribers:- self._subscribers.remove(callback)-- return _unsub-- def shutdown(self) -> None:- if self._unsubscribe_machine is not None:- self._unsubscribe_machine()- self._unsubscribe_machine = None-- # -------- Outputs ---------- @property- def idle_seconds(self) -> float:- return (time.monotonic_ns() - self._last_change_ns) / 1e9-- def get_target_fps(self) -> int:- return self.recompute().target_fps-- def should_hide_view(self) -> bool:- return self.recompute().should_hide_view-- def recompute(self) -> ThrottleSnapshot:- """Computes the current snapshot. Fires subscribers if- something changed. Idempotent."""- with self._lock:- state = self._machine.state- idle_s = self.idle_seconds- on_battery = self._on_battery- fullscreen_hide = self._fullscreen_should_hide-- is_hidden_state = state is OverlayState.HIDDEN or fullscreen_hide-- if is_hidden_state:- target = 0- should_hide_view = True- else:- # Idle-State counts as idle-bucket only when stale.- stale = idle_s >= self._idle_timeout and state is OverlayState.IDLE- if stale:- target = self._fps_idle- elif state in _BURST_STATES:- target = self._fps_burst- elif state in _ACTIVE_STATES:- target = self._fps_active- else:- # IDLE within idle_timeout -> active (mascot breathing).- target = self._fps_active-- # Plan §17.3: AC vs Battery -> halve all targets.- if on_battery:- target = max(1, target // 2)-- should_hide_view = (- state is OverlayState.IDLE and idle_s >= self._hide_timeout- )- if should_hide_view:- # A hidden view doesn't need a compositor tick.- target = 0-- snapshot = ThrottleSnapshot(- target_fps=target,- should_hide_view=should_hide_view,- is_hidden_state=is_hidden_state,- on_battery=on_battery,- fullscreen_active=fullscreen_hide,- idle_seconds=idle_s,- )-- with self._lock:- prev = self._last_snapshot- changed = prev is None or _snapshot_changed(prev, snapshot)- self._last_snapshot = snapshot- subs = list(self._subscribers) if changed else []-- for cb in subs:- try:- cb(snapshot)- except Exception: # noqa: BLE001- logger.exception("Throttler subscriber raised on recompute")-- return snapshot-- # -------- internals ---------- def _on_state_change(- self, _old: OverlayState, _new: OverlayState, _reason: Optional[str]- ) -> None:- # Plan §17.3: wake on event -> idle timer reset.- with self._lock:- self._last_change_ns = time.monotonic_ns()- self.recompute()---def _snapshot_changed(a: ThrottleSnapshot, b: ThrottleSnapshot) -> bool:- """Subscribers only fire if FPS or visibility change.- idle_seconds changes continuously — firing on that would- otherwise trigger subscriber spam."""- return (- a.target_fps != b.target_fps- or a.should_hide_view is not b.should_hide_view- or a.is_hidden_state is not b.is_hidden_state- or a.on_battery is not b.on_battery- or a.fullscreen_active is not b.fullscreen_active- )---# Re-export for subscriber tests that work without an explicit replace().-__all__ = [- "DEFAULT_FPS_ACTIVE",- "DEFAULT_FPS_BURST",- "DEFAULT_FPS_IDLE",- "DEFAULT_HIDE_TIMEOUT_S",- "DEFAULT_IDLE_TIMEOUT_S",- "ThrottleCallback",- "ThrottleSnapshot",- "Throttler",- "replace",-]diff --git a/OS-Level/src/overlay/transparency.py b/OS-Level/src/overlay/transparency.pydeleted file mode 100644index b020f43396..0000000000--- a/OS-Level/src/overlay/transparency.py+++ /dev/null@@ -1,125 +0,0 @@-"""ctypes wrappers for Win32 window flags.--Plan §12.1 / §12.4: transparent click-through layered windows with-``WDA_EXCLUDEFROMCAPTURE`` so screen sharing and OBS don't pick up the-overlay. Qt sets ``WindowTransparentForInput`` itself; the ctypes path-here is (a) defense-in-depth for affinity, (b) prepares for Phase 9.6-(mascot needs ``WS_EX_NOACTIVATE`` selectively).--On non-Windows hosts all functions are no-ops, so tests can run-headless on any platform.-"""--from __future__ import annotations--import ctypes-import sys-from ctypes import wintypes--# Win32 constants — Plan §12.1, §12.2.-GWL_EXSTYLE = -20-WS_EX_LAYERED = 0x00080000-WS_EX_TRANSPARENT = 0x00000020-WS_EX_NOACTIVATE = 0x08000000-WS_EX_TOOLWINDOW = 0x00000080--# WDA_EXCLUDEFROMCAPTURE: Win10 2004+ / Win11 — Plan §12.4.-WDA_NONE = 0x00000000-WDA_MONITOR = 0x00000001-WDA_EXCLUDEFROMCAPTURE = 0x00000011---def _is_windows() -> bool:- return sys.platform == "win32"---def get_user32(): # pragma: no cover — platform branch- """Lazy loader. Only call on Windows."""- if not _is_windows():- raise RuntimeError("user32 is Windows-only")- return ctypes.windll.user32---def apply_click_through(hwnd: int) -> None:- """Adds ``WS_EX_LAYERED | WS_EX_TRANSPARENT`` to an HWND.-- Idempotent: existing style bits are OR'd in, nothing is cleared.- """- if not _is_windows():- return- user32 = get_user32()- user32.GetWindowLongW.restype = ctypes.c_long- user32.GetWindowLongW.argtypes = [wintypes.HWND, ctypes.c_int]- user32.SetWindowLongW.restype = ctypes.c_long- user32.SetWindowLongW.argtypes = [wintypes.HWND, ctypes.c_int, ctypes.c_long]-- h = wintypes.HWND(hwnd)- current = user32.GetWindowLongW(h, GWL_EXSTYLE)- desired = current | WS_EX_LAYERED | WS_EX_TRANSPARENT- if desired != current:- user32.SetWindowLongW(h, GWL_EXSTYLE, desired)---def apply_mascot_styles(hwnd: int) -> None:- """Mascot window — Plan §12.2: layered + no-activate + tool window.-- Deliberately NO ``WS_EX_TRANSPARENT``, so clicks/drag come through.- Phase 9.6 uses this.- """- if not _is_windows():- return- user32 = get_user32()- user32.GetWindowLongW.restype = ctypes.c_long- user32.GetWindowLongW.argtypes = [wintypes.HWND, ctypes.c_int]- user32.SetWindowLongW.restype = ctypes.c_long- user32.SetWindowLongW.argtypes = [wintypes.HWND, ctypes.c_int, ctypes.c_long]-- h = wintypes.HWND(hwnd)- current = user32.GetWindowLongW(h, GWL_EXSTYLE)- desired = current | WS_EX_LAYERED | WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW- if desired != current:- user32.SetWindowLongW(h, GWL_EXSTYLE, desired)---def exclude_from_capture(hwnd: int) -> bool:- """``SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE)``.-- Returns ``True`` on success, ``False`` if unsupported (old Win10 builds)- or when called on non-Windows.- """- if not _is_windows():- return False- user32 = get_user32()- user32.SetWindowDisplayAffinity.restype = wintypes.BOOL- user32.SetWindowDisplayAffinity.argtypes = [wintypes.HWND, wintypes.DWORD]- result = user32.SetWindowDisplayAffinity(- wintypes.HWND(hwnd), wintypes.DWORD(WDA_EXCLUDEFROMCAPTURE)- )- return bool(result)---def reapply_capture_affinity(hwnd: int) -> bool:- """Plan §18.1 — reapply WDA_EXCLUDEFROMCAPTURE.-- Identical to ``exclude_from_capture``, but exposed as a named entry- point for window hooks (showEvent, screenChanged, screenAdded). DWM- doesn't cache the affinity flag across re-composite boundaries; after- DPI changes or a monitor hotplug the flag has been observed to get- lost. Hence re-apply it idempotently.- """- return exclude_from_capture(hwnd)---def set_per_monitor_dpi_awareness() -> None:- """``SetProcessDpiAwareness(2)`` — PROCESS_PER_MONITOR_DPI_AWARE.-- Must run BEFORE the QApplication is created (Plan §12.3). Swallows- all errors, since the call returns ``E_ACCESSDENIED`` when the- awareness level is already set.- """- if not _is_windows():- return- try:- ctypes.windll.shcore.SetProcessDpiAwareness(2)- except (OSError, AttributeError): # pragma: no cover — best effort- passdiff --git a/OS-Level/src/overlay/window_glow.py b/OS-Level/src/overlay/window_glow.pydeleted file mode 100644index ba4cf6014a..0000000000--- a/OS-Level/src/overlay/window_glow.py+++ /dev/null@@ -1,288 +0,0 @@-"""EdgeGlowWindow — transparent click-through frameless window per screen.--Phase 9.3: the test square is gone; instead a ``QWebEngineView`` renders-``overlay-ui/dist/edge-glow.html``. A ``StateBridge`` is exposed via-``QWebChannel`` as ``stateBridge`` — the TS renderer subscribes to-``stateChanged`` and reads ``currentState``.--Window flags strictly follow Plan §12.1.--IMPORTANT: if ``overlay-ui/dist/edge-glow.html`` doesn't exist (e.g.-because it was never built), the view loads ``about:blank`` and logs a-warning. This prevents crashes in CI/smoke paths without a frontend build.-"""--from __future__ import annotations--import logging-from pathlib import Path-from typing import TYPE_CHECKING, Optional--from PySide6.QtCore import (- QObject,- Qt,- QUrl,- Signal,- Slot,-)-from PySide6.QtGui import QColor-from PySide6.QtWebChannel import QWebChannel-from PySide6.QtWebEngineCore import QWebEnginePage-from PySide6.QtWebEngineWidgets import QWebEngineView-from PySide6.QtWidgets import QVBoxLayout, QWidget--from .state import OverlayState, StateMachine-from .transparency import (- apply_click_through,- exclude_from_capture,- reapply_capture_affinity,-)--if TYPE_CHECKING: # pragma: no cover- from PySide6.QtGui import QScreen--logger = logging.getLogger(__name__)---# Plan §22 — the Vite build places the HTML exactly here.-_EDGE_GLOW_HTML = (- Path(__file__).resolve().parents[2] / "overlay-ui" / "dist" / "edge-glow.html"-)---class StateBridge(QObject):- """QObject exposed via QWebChannel as ``stateBridge``.-- The TS renderer (``overlay-ui/src/edge-glow/main.ts``) connects- its handler to ``stateChanged`` and calls ``currentState`` for the- initial frame.-- This object MUST be instantiated on the GUI thread — Qt signals are- automatically marshalled to the GUI thread slots via- ``QueuedConnection`` when ``emit()`` is called from the IPC thread.- """-- # (old, new, reason) — all three strings, since JS signal routing- # only cleanly serializes primitive types.- stateChanged = Signal(str, str, str)-- def __init__(- self, machine: StateMachine, parent: Optional[QObject] = None- ) -> None:- super().__init__(parent)- self._machine = machine- # The subscriber is called synchronously on the StateMachine- # caller thread. We only fire the Qt signal here — Qt marshals- # it itself.- self._unsubscribe = machine.subscribe(self._on_state_change)-- def _on_state_change(- self,- old: OverlayState,- new: OverlayState,- reason: Optional[str],- ) -> None:- try:- self.stateChanged.emit(old.value, new.value, reason or "")- except RuntimeError:- # Window has already been destroyed -> the subscriber is- # about to be detached; harmless.- logger.debug("StateBridge.emit on dead QObject")-- @Slot(result=str)- def currentState(self) -> str:- return self._machine.state.value-- def shutdown(self) -> None:- """Unsubscribe from the StateMachine — call before ``deleteLater()``."""- if self._unsubscribe is not None:- self._unsubscribe()- self._unsubscribe = None---class EffectsBridge(QObject):- """QObject exposed via QWebChannel as ``effectsBridge``.- Phase 9.5 — fires the action effects (click ripple, cursor trail,- typing sweep).-- Signals go 1:1 to the TS renderer (Plan §14/§15/§16). Coords are- always PHYSICAL px (Plan §14.4 + §11.2); the renderer converts via- devicePixelRatio.- """-- # x, y physical px, monitor_idx, button.- clickEvent = Signal(int, int, int, str)- # x, y physical px (from SHM or the WS fallback).- cursorMoved = Signal(int, int)- # kind, duration_hint_ms (-1 if not set).- actionStarted = Signal(str, int)- actionEnded = Signal()-- def __init__(self, parent: Optional[QObject] = None) -> None:- super().__init__(parent)-- def emit_click(self, x: int, y: int, monitor_idx: int, button: str) -> None:- try:- self.clickEvent.emit(int(x), int(y), int(monitor_idx), button)- except RuntimeError:- logger.debug("EffectsBridge click on dead QObject")-- def emit_cursor(self, x: int, y: int) -> None:- try:- self.cursorMoved.emit(int(x), int(y))- except RuntimeError:- logger.debug("EffectsBridge cursor on dead QObject")-- def emit_action_started(self, kind: str, duration_hint_ms: Optional[int]) -> None:- try:- self.actionStarted.emit(kind, int(duration_hint_ms or -1))- except RuntimeError:- logger.debug("EffectsBridge action_started on dead QObject")-- def emit_action_ended(self) -> None:- try:- self.actionEnded.emit()- except RuntimeError:- logger.debug("EffectsBridge action_ended on dead QObject")---class _TransparentWebPage(QWebEnginePage):- """Page with a transparent background.-- Without this override, Chromium renders a white background even- when ``body { background: transparent }`` is set. Plan §12.1 + AD-1- require true compositor transparency.- """-- def __init__(self, parent: Optional[QObject] = None) -> None:- super().__init__(parent)- self.setBackgroundColor(QColor(0, 0, 0, 0))---class EdgeGlowWindow(QWidget):- """Frameless, transparent, click-through, always on top.-- Geometry covers the full monitor. Unlike the 9.1 version, a- ``QWebEngineView`` renders the real HTML/CSS pipeline here; the- static test square has been removed.- """-- def __init__(- self,- screen: "QScreen",- *,- hide_from_capture: bool = True,- state_machine: Optional[StateMachine] = None,- effects_bridge: Optional[EffectsBridge] = None,- html_path: Optional[Path] = None,- parent: Optional[QWidget] = None,- ) -> None:- super().__init__(parent)- self._screen = screen- self._hide_from_capture = hide_from_capture- self._state_machine = state_machine- self._effects_bridge = effects_bridge- self._html_path = html_path or _EDGE_GLOW_HTML- # Plan §18.1 — the screenChanged signal is connected in showEvent,- # since windowHandle() can be None before show().- self._screen_change_connected: bool = False-- # Plan §12.1 — exakt diese Flag-Kombination.- self.setWindowFlags(- Qt.WindowType.FramelessWindowHint- | Qt.WindowType.WindowStaysOnTopHint- | Qt.WindowType.WindowTransparentForInput- | Qt.WindowType.Tool- | Qt.WindowType.NoDropShadowWindowHint- )- self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)- self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True)- self.setAttribute(Qt.WidgetAttribute.WA_NoSystemBackground, True)- self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, True)-- self.setScreen(screen)- self.setGeometry(screen.geometry())-- # Layout + WebView. Margins 0 so the render surface uses the- # full window geometry — otherwise there's a 9 px default margin.- layout = QVBoxLayout(self)- layout.setContentsMargins(0, 0, 0, 0)-- self._view = QWebEngineView(self)- # No background repaint from the widget itself.- self._view.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)- self._view.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True)-- page = _TransparentWebPage(self._view)- self._view.setPage(page)-- # WebChannel + StateBridge if a StateMachine was supplied.- # This is optional so Phase 9.1 smoke tests keep working- # without a machine. Phase 9.5 additionally attaches the- # effectsBridge if ``effects_bridge`` is set.- self._channel: Optional[QWebChannel] = None- self._bridge: Optional[StateBridge] = None- if state_machine is not None:- self._channel = QWebChannel(page)- self._bridge = StateBridge(state_machine, self)- self._channel.registerObject("stateBridge", self._bridge)- if effects_bridge is not None:- self._channel.registerObject("effectsBridge", effects_bridge)- page.setWebChannel(self._channel)-- # Load HTML — if it doesn't exist: about:blank + warning.- if self._html_path.is_file():- url = QUrl.fromLocalFile(str(self._html_path))- self._view.setUrl(url)- else:- logger.warning(- "edge-glow.html not found at %s — "- "rendering about:blank (did you forget `npm run build` in overlay-ui/?)",- self._html_path,- )- self._view.setUrl(QUrl("about:blank"))-- layout.addWidget(self._view)-- def showEvent(self, event) -> None: # type: ignore[override]- """Sets the Win32 affinity after the HWND exists."""- super().showEvent(event)- hwnd = int(self.winId())- # Defense-in-depth: Qt sets WS_EX_TRANSPARENT via- # WindowTransparentForInput — we set it again explicitly in case- # a later setWindowFlags() call clears the bit.- apply_click_through(hwnd)- if self._hide_from_capture:- exclude_from_capture(hwnd)- # Plan §18.1 — re-apply on screenChanged + DPI changes.- # We connect the signal here (after winId() exists), not in- # __init__, since windowHandle() can be None before showEvent.- if not self._screen_change_connected:- handle = self.windowHandle()- if handle is not None:- handle.screenChanged.connect(self._on_screen_changed)- self._screen_change_connected = True-- def _on_screen_changed(self, _screen) -> None:- """Reapply affinity after a DPI change or monitor hotplug.- Plan §18.1."""- if not self._hide_from_capture:- return- try:- hwnd = int(self.winId())- except RuntimeError:- return- reapply_capture_affinity(hwnd)-- def set_view_visible(self, visible: bool) -> None:- """Plan §17.3 — hide-on-5-min-idle sets the WebView's IsVisible- to False so Chromium fully pauses the view."""- self._view.setVisible(visible)-- def closeEvent(self, event) -> None: # type: ignore[override]- if self._bridge is not None:- self._bridge.shutdown()- super().closeEvent(event)---__all__ = ["EdgeGlowWindow", "EffectsBridge", "StateBridge"]diff --git a/OS-Level/src/overlay/window_mascot.py b/OS-Level/src/overlay/window_mascot.pydeleted file mode 100644index 4f05b4aa4b..0000000000--- a/OS-Level/src/overlay/window_mascot.py+++ /dev/null@@ -1,413 +0,0 @@-"""MascotWindow — separate transparent frameless window. Plan §12.2 + §13.--Unlike EdgeGlowWindow, the mascot is NOT click-through. It catches-drag (left mouse button) and right-click (context menu).-QtWebEngineView renders the mascot HTML (Rive or PNG fallback).--Hit-testing per Plan §12.2: setMask(QRegion ellipse) so the transparent-corners of the 160x160 box are click-passthrough.--Position persistence + monitor recovery live in mascot_position.py;-this module is only the window mechanics.-"""--from __future__ import annotations--import logging-from pathlib import Path-from typing import TYPE_CHECKING, Callable, Optional--from PySide6.QtCore import (- QObject,- QPoint,- QRect,- Qt,- QUrl,- Signal,- Slot,-)-from PySide6.QtGui import QAction, QColor, QRegion-from PySide6.QtWebChannel import QWebChannel-from PySide6.QtWebEngineCore import QWebEnginePage-from PySide6.QtWebEngineWidgets import QWebEngineView-from PySide6.QtWidgets import QMenu, QVBoxLayout, QWidget--from .mascot_position import (- MascotPosition,- clamp_to_work_area,- snap_to_edges,-)-from .state import OverlayState, StateMachine-from .transparency import (- apply_mascot_styles,- exclude_from_capture,- reapply_capture_affinity,-)--if TYPE_CHECKING: # pragma: no cover- from PySide6.QtGui import QMouseEvent--logger = logging.getLogger(__name__)---# Plan §22 — the Vite build places the HTML exactly here.-_MASCOT_HTML = (- Path(__file__).resolve().parents[2] / "overlay-ui" / "dist" / "mascot.html"-)---class MascotStateBridge(QObject):- """QWebChannel bridge for the mascot. Plan §13.2 maps- OverlayStates to Rive inputs.-- We fire the same stateChanged signature as StateBridge for the- EdgeGlow, so the mascot renderer can use the same bridge mechanics- (typed wrapper in bridge.ts).- """-- stateChanged = Signal(str, str, str) # old, new, reason-- def __init__(- self, machine: StateMachine, parent: Optional[QObject] = None- ) -> None:- super().__init__(parent)- self._machine = machine- self._unsubscribe = machine.subscribe(self._on_state_change)-- def _on_state_change(- self, old: OverlayState, new: OverlayState, reason: Optional[str]- ) -> None:- try:- self.stateChanged.emit(old.value, new.value, reason or "")- except RuntimeError:- logger.debug("MascotStateBridge.emit on dead QObject")-- @Slot(result=str)- def currentState(self) -> str:- return self._machine.state.value-- def shutdown(self) -> None:- if self._unsubscribe is not None:- self._unsubscribe()- self._unsubscribe = None---class _TransparentWebPage(QWebEnginePage):- """Page with a transparent background. Identical to the EdgeGlow- variant — otherwise Chromium renders white even though body is transparent."""-- def __init__(self, parent: Optional[QObject] = None) -> None:- super().__init__(parent)- self.setBackgroundColor(QColor(0, 0, 0, 0))---# Position-save callback signature: (MascotPosition) -> None.-# The caller (setup_mascot) injects a save-to-toml function.-PositionSaveCallback = Callable[[MascotPosition], None]---class MascotWindow(QWidget):- """Single-instance frameless transparent window. Plan §12.2.-- Lifecycle::-- win = MascotWindow(- initial_x=200, initial_y=80, monitor_name="\\\\.\\DISPLAY1",- size_px=160, state_machine=machine,- on_position_saved=lambda pos: save_position_to_toml(...),- )- win.show()- """-- # Fired when the user picks "Hide for session" via right-click.- hideRequested = Signal()- # User-triggered "Move to default" — the caller computes the new position.- resetRequested = Signal()- # User-triggered "Settings..." — the caller opens the settings dialog.- settingsRequested = Signal()- # User double-clicked the mascot. Caller forwards this upstream as- # a MascotEventEnvelope(kind="mute_toggle") so the main jarvis- # pipeline flips its mute flag. The window itself dims locally for- # immediate visual feedback so the user does not wait for a round-- # trip via the WS bridge.- muteToggleRequested = Signal()-- def __init__(- self,- *,- initial_x: int,- initial_y: int,- monitor_name: str,- size_px: int = 160,- snap_tolerance_px: int = 16,- hide_from_capture: bool = True,- state_machine: Optional[StateMachine] = None,- on_position_saved: Optional[PositionSaveCallback] = None,- html_path: Optional[Path] = None,- parent: Optional[QWidget] = None,- ) -> None:- super().__init__(parent)- self._monitor_name = monitor_name- self._size_px = size_px- self._snap_tolerance = snap_tolerance_px- self._hide_from_capture = hide_from_capture- self._state_machine = state_machine- self._on_position_saved = on_position_saved- self._html_path = html_path or _MASCOT_HTML-- # Plan §12.2: NO WindowTransparentForInput (clicks are expected).- self.setWindowFlags(- Qt.WindowType.FramelessWindowHint- | Qt.WindowType.WindowStaysOnTopHint- | Qt.WindowType.Tool- | Qt.WindowType.NoDropShadowWindowHint- )- self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)- self.setAttribute(Qt.WidgetAttribute.WA_NoSystemBackground, True)- self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, True)- # NO WA_TransparentForMouseEvents — the mascot catches mouse input.-- self.setFixedSize(size_px, size_px)- # Plan §12.2: setMask(QRegion ellipse) so the transparent corners- # don't catch clicks. Re-applied in resizeEvent for safety.- self.setMask(QRegion(QRect(0, 0, size_px, size_px), QRegion.RegionType.Ellipse))-- self.move(initial_x, initial_y)-- # Layout + WebView for Rive/PNG.- layout = QVBoxLayout(self)- layout.setContentsMargins(0, 0, 0, 0)- self._view = QWebEngineView(self)- self._view.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)- page = _TransparentWebPage(self._view)- self._view.setPage(page)-- # WebChannel + StateBridge if a StateMachine was supplied.- self._channel: Optional[QWebChannel] = None- self._bridge: Optional[MascotStateBridge] = None- if state_machine is not None:- self._channel = QWebChannel(page)- self._bridge = MascotStateBridge(state_machine, self)- self._channel.registerObject("stateBridge", self._bridge)- page.setWebChannel(self._channel)-- if self._html_path.is_file():- self._view.setUrl(QUrl.fromLocalFile(str(self._html_path)))- else:- logger.warning(- "mascot.html not found at %s — did you run `npm run build` in overlay-ui/?",- self._html_path,- )- self._view.setUrl(QUrl("about:blank"))-- layout.addWidget(self._view)-- # Drag state.- self._drag_offset: Optional[QPoint] = None- self._dragging: bool = False- # Local visual mute indicator — toggled on every doubleClick so the- # sprite dims even before the round-trip through main jarvis lands.- # Main jarvis stays the source of truth; if it disagrees we let- # the next state-bridge event correct us.- self._muted_visual: bool = False- self._opacity_normal: float = 1.0- self._opacity_muted: float = 0.45- # Plan §18.1 — the screenChanged hook is connected in showEvent.- self._screen_change_connected: bool = False-- # --- Lifecycle / Win32-Affinity ----- def showEvent(self, event) -> None: # type: ignore[override]- super().showEvent(event)- hwnd = int(self.winId())- # Plan §12.2: Layered + NoActivate + Toolwindow extension flags.- apply_mascot_styles(hwnd)- if self._hide_from_capture:- exclude_from_capture(hwnd)- # Plan §18.1 — reapply on screenChanged.- if not self._screen_change_connected:- handle = self.windowHandle()- if handle is not None:- handle.screenChanged.connect(self._on_screen_changed)- self._screen_change_connected = True-- def _on_screen_changed(self, _screen) -> None:- if not self._hide_from_capture:- return- try:- hwnd = int(self.winId())- except RuntimeError:- return- reapply_capture_affinity(hwnd)-- def closeEvent(self, event) -> None: # type: ignore[override]- if self._bridge is not None:- self._bridge.shutdown()- super().closeEvent(event)-- def resizeEvent(self, event) -> None: # type: ignore[override]- super().resizeEvent(event)- # Re-apply the mask in case someone changes size_px.- self.setMask(- QRegion(- QRect(0, 0, self.width(), self.height()),- QRegion.RegionType.Ellipse,- )- )-- # --- Drag (Plan §13.3) ----- def mousePressEvent(self, event: "QMouseEvent") -> None: # type: ignore[override]- if event.button() == Qt.MouseButton.LeftButton:- self._drag_offset = event.globalPosition().toPoint() - self.pos()- self._dragging = True- event.accept()- else:- super().mousePressEvent(event)-- def mouseMoveEvent(self, event: "QMouseEvent") -> None: # type: ignore[override]- if self._dragging and self._drag_offset is not None:- new_pos = event.globalPosition().toPoint() - self._drag_offset- self.move(new_pos.x(), new_pos.y())- event.accept()- else:- super().mouseMoveEvent(event)-- def mouseReleaseEvent(self, event: "QMouseEvent") -> None: # type: ignore[override]- if event.button() == Qt.MouseButton.LeftButton and self._dragging:- self._dragging = False- self._drag_offset = None- self._finalize_drag()- event.accept()- else:- super().mouseReleaseEvent(event)-- def mouseDoubleClickEvent(self, event: "QMouseEvent") -> None: # type: ignore[override]- """Double-click toggles Jarvis-wide voice mute.-- Qt fires this between the second press and release of a left-button- double-click. The first press of the pair already entered- ``mousePressEvent`` and primed the drag-state, so we explicitly- abort the drag here — otherwise an accidental cursor twitch- between the second press and release would commit a move.- """- if event.button() != Qt.MouseButton.LeftButton:- super().mouseDoubleClickEvent(event)- return- self._dragging = False- self._drag_offset = None- self._toggle_muted_visual()- try:- self.muteToggleRequested.emit()- except RuntimeError:- # Signal target died (Qt teardown race). Local visual flip- # already happened so the user still sees feedback.- logger.debug("muteToggleRequested.emit on dead QObject")- event.accept()-- def _toggle_muted_visual(self) -> None:- self._muted_visual = not self._muted_visual- opacity = self._opacity_muted if self._muted_visual else self._opacity_normal- try:- self.setWindowOpacity(opacity)- except RuntimeError:- # Window torn down — safe to ignore. The opacity is a- # cosmetic indicator only; main jarvis owns the truth.- pass-- def set_muted_visual(self, muted: bool) -> None:- """Authoritative state sync from main jarvis.-- Main jarvis will call this through the WebChannel bridge after it- has flipped the actual mute flag, so the optimistic local toggle- on doubleClick can be corrected if the two ever diverge (e.g.- another trigger surface — hotkey, REST — flipped the flag).- """- if muted == self._muted_visual:- return- self._toggle_muted_visual()-- def contextMenuEvent(self, event) -> None: # type: ignore[override]- """Right-click QMenu — Plan §13.5 + §12.2."""- menu = QMenu(self)- mute_label = "Unmute Jarvis" if self._muted_visual else "Mute Jarvis"- mute_action = QAction(mute_label, self)- mute_action.triggered.connect(self._on_mute_menu)- menu.addAction(mute_action)-- menu.addSeparator()-- hide_action = QAction("Hide for session", self)- hide_action.triggered.connect(self.hideRequested.emit)- menu.addAction(hide_action)-- reset_action = QAction("Reset position", self)- reset_action.triggered.connect(self.resetRequested.emit)- menu.addAction(reset_action)-- menu.addSeparator()-- settings_action = QAction("Settings...", self)- settings_action.triggered.connect(self.settingsRequested.emit)- menu.addAction(settings_action)-- menu.exec(event.globalPos())-- def _on_mute_menu(self) -> None:- self._toggle_muted_visual()- try:- self.muteToggleRequested.emit()- except RuntimeError:- logger.debug("muteToggleRequested.emit on dead QObject")-- # --- Position-Persistence ----- def _finalize_drag(self) -> None:- """Snap-to-edge + clamp + persist. Plan §13.3 + §13.4."""- from PySide6.QtGui import QGuiApplication-- # Which monitor now contains the mascot?- center = self.pos() + QPoint(self.width() // 2, self.height() // 2)- screen = QGuiApplication.screenAt(center) or QGuiApplication.primaryScreen()- if screen is None:- return # extremly headless; ignore-- geo = screen.availableGeometry()- monitor_geo = (geo.x(), geo.y(), geo.width(), geo.height())-- # Snap first — snapping can push the mascot past the edge,- # so clamp afterwards.- snapped_x, snapped_y = snap_to_edges(- self.x(),- self.y(),- monitor_geo,- mascot_size_px=self._size_px,- snap_tolerance_px=self._snap_tolerance,- )- clamped_x, clamped_y = clamp_to_work_area(- snapped_x,- snapped_y,- monitor_geo,- mascot_size_px=self._size_px,- )- if (clamped_x, clamped_y) != (self.x(), self.y()):- self.move(clamped_x, clamped_y)-- # Persist relative to the work area's top-left.- rel_x = clamped_x - geo.x()- rel_y = clamped_y - geo.y()- position = MascotPosition(- monitor=screen.name(),- x_relative=rel_x,- y_relative=rel_y,- )- self._monitor_name = screen.name()-- if self._on_position_saved is not None:- try:- self._on_position_saved(position)- except Exception: # noqa: BLE001- logger.exception("on_position_saved raised")---__all__ = ["MascotStateBridge", "MascotWindow", "PositionSaveCallback"]diff --git a/OS-Level/test-overlay.bat b/OS-Level/test-overlay.batdeleted file mode 100644index aab43c341b..0000000000--- a/OS-Level/test-overlay.bat+++ /dev/null@@ -1,82 +0,0 @@-@echo off-REM Personal Jarvis Phase 9 Overlay - Ein-Klick Smoke Test-REM-REM Was es macht:-REM 1. prueft ob das overlay-Package installiert ist (pip install -e . wenn nicht)-REM 2. prueft ob das Frontend gebaut ist (npm run build wenn nicht)-REM 3. startet das Overlay mit --smoke (zeigt Mascot 5s lang, beendet sich)-REM-REM Erwartung: Mascot oben-links auf Primary-Monitor erscheint, verschwindet nach 5s.--setlocal enabledelayedexpansion-cd /d "%~dp0"--echo === Personal Jarvis Phase 9 Overlay - Smoke Test ===-echo.--REM ---- Check 1: Overlay-Package importable? -----echo [1/3] Pruefe ob 'overlay'-Package importable...-python -c "import overlay" 2>nul-if errorlevel 1 (- echo -^> nicht installiert. Installiere via 'pip install -e .' ...- pip install -e . --quiet- if errorlevel 1 (- echo FEHLER: pip install fehlgeschlagen.- echo Manuell pruefen: cd "%~dp0" ^& pip install -e .- exit /b 1- )- echo -^> OK-) else (- echo -^> bereits installiert-)-echo.--REM ---- Check 2: Frontend dist gebaut? -----echo [2/3] Pruefe ob overlay-ui/dist/edge-glow.html existiert...-if not exist "overlay-ui\dist\edge-glow.html" (- echo -^> nicht gebaut. Baue via 'npm install' + 'npm run build' ...- pushd overlay-ui- if not exist "node_modules" (- echo npm install ...- call npm install --silent- if errorlevel 1 (- echo FEHLER: npm install fehlgeschlagen. Pruefe Node.js installation.- popd- exit /b 1- )- )- echo npm run build ...- call npm run build- if errorlevel 1 (- echo FEHLER: npm run build fehlgeschlagen.- popd- exit /b 1- )- popd- echo -^> OK-) else (- echo -^> bereits gebaut-)-echo.--REM ---- Check 3: Overlay starten -----echo [3/3] Starte Overlay im Smoke-Mode (5 Sekunden)...-echo.-echo Was du sehen solltest:-echo - Mascot oben links auf Primary-Monitor (schwarzes abgerundetes Quadrat-echo mit zwei gelben Augen + Mund-Bogen)-echo - KEIN Edge-Glow (das kommt erst wenn Hauptjarvis Actions ausloest)-echo - Nach 5 Sekunden schliesst sich alles automatisch-echo.-python -m overlay --smoke-if errorlevel 1 (- echo.- echo FEHLER: Overlay-Smoke-Test ist gecrasht.- echo Logs oben pruefen.- exit /b 1-)--echo.-echo === Smoke-Test bestanden ===-echo Naechster Schritt: 'run.bat --debug' im Repo-Root fuer Production-Test.-endlocaldiff --git a/docs/overlay-troubleshooting.md b/docs/overlay-troubleshooting.mddeleted file mode 100644index f396393835..0000000000--- a/docs/overlay-troubleshooting.md+++ /dev/null@@ -1,286 +0,0 @@-# Overlay Troubleshooting--> Common issues with the OS-Level Overlay (edge-glow + mascot) and how to fix-> them. References to the master plan use §-numbers from-> `OS-Level/OS-LEVEL_PLAN.md`.-------## 1. Overlay starts not at all--**Symptoms:** No glow, no mascot, no overlay process visible.--**Checks (in order):**--1. **`[overlay].enabled = true` in `jarvis.toml`?**- - Open `jarvis.toml`, search for the `[overlay]` section.- - If `enabled = false` or the section is missing, add/set `enabled = true`- and restart Jarvis.--2. **`pythonw.exe` for the overlay-subprocess running?**- - Open Task Manager → Details tab → look for a `pythonw.exe` whose- command-line contains `overlay`. If absent, the supervisor never spawned- it.- - Check `logs/jarvis.log` for `OverlaySupervisor` entries — a spawn failure- is logged with stack-trace.--3. **Tray icon visible?**- - The Jarvis tray-icon should be present. If yes but no overlay → the- overlay is opt-in via the toml flag (step 1).--4. **Log output:**- - `logs/jarvis.log` filtered by `overlay` — Spawn-failures, schema-validation- errors, port-bind issues are all there.--5. **Port 7842 already in use?**- - `netstat -an | findstr 7842` — if another process holds it, change- `[overlay].port` in `jarvis.toml`.--**Source files:** `OS-Level/src/overlay/supervisor.py`,-`OS-Level/src/overlay/process.py`.-------## 2. Glow does not appear when Hauptjarvis is typing--**Symptoms:** Mascot reacts, but the yellow edge-glow stays dark when-keystrokes go through.--**Checks:**--1. **Phase-9.8-Hook present in the production path?**- - The `OverlayBridge.action(...)` decorator/context-manager must wrap the- keystroke call (`pyautogui.typewrite`, `pywinauto.SendKeys`, etc.).- - Grep the production action site for `OverlayBridge` — if the bridge is- only wired in tests, glow will silently no-op.--2. **`JARVIS_DEPTH == 0`?**- - In Jarvis-Agents (`JARVIS_DEPTH > 0` env var, see Plan §8.7), the- `OverlayBridge` is a **no-op stub by design**. Only the top-level- Hauptjarvis triggers the glow.- - Verify with `echo %JARVIS_DEPTH%` (cmd) or `$env:JARVIS_DEPTH`- (PowerShell) inside the relevant subprocess.--3. **Renderer in `typing` state?**- - Open the overlay window with the debug-flag (Plan §22.3 dev-mode):- append `?debug=1` to the WebView URL. The root element should carry- `data-state="typing"` while keystrokes fire.- - If the attribute stays `idle`, the WS-event never reached the renderer —- check `OverlayBridge` → WS server → renderer trace in- `logs/jarvis.log`.--4. **State coalescing collapsing rapid changes?**- - AD-17 (16 ms window) drops same-type duplicates. Two `typing` enters- within 16 ms collapse to one. Should not cause "no glow at all" but can- cause a missed *re-enter* visual.--**Source files:** `OS-Level/src/overlay/bridge.py`,-`OS-Level/overlay-ui/src/components/EdgeGlow.tsx`.-------## 3. Cursor trail missing--**Symptoms:** Mascot and glow work, but the cursor doesn't leave a fading-trail.--**Checks:**--1. **`[overlay].cursor_trail_enabled = true`?**- - Off by default in some profiles; enable in `jarvis.toml`.--2. **Shared-Memory block accessible?**- - The cursor stream uses a `multiprocessing.shared_memory` block named- `jarvis-cursor-{8 hex chars}` (Plan §11). Some Antivirus / EDR products- block SHM-creation between unrelated processes.- - Check `heartbeat` payload (`shm_attached`) — if `false`, SHM is blocked- and the system has fallen back to the WS `cursor` channel (lower- resolution).- - Whitelist `pythonw.exe` and `OS-Level/src/overlay/process.py` in the AV- product, or grant SHM-create rights via group policy.--3. **DPI scaling on the source monitor?**- - Coordinates are physical pixels (Plan §11.2). On a 200%-scaled monitor,- trail points should appear at 2× the logical position; if they appear- halved, a DPI-aware bug is in play — file an issue with monitor layout.--**Source files:** `OS-Level/src/overlay/cursor_shm.py`,-`OS-Level/overlay-ui/src/components/CursorTrail.tsx`.-------## 4. Mascot disappears after monitor change--**Symptoms:** After unplugging a monitor, plugging in a new one, or-re-arranging displays in Windows settings, the mascot vanishes.--**Explanation (Plan §13.4):** Mascot position is persisted as-`(szDevice, x_relative, y_relative)`. If the saved monitor's `szDevice` is no-longer present at startup, a **deterministic fallback** kicks in:--1. Pick the **primary monitor** via- `MonitorFromWindow(hwnd_desktop, MONITOR_DEFAULTTOPRIMARY)`.-2. Place mascot at the **default position** for that monitor:- `(rcWork.left + 200, rcWork.top + 80)`.-3. Log `mascot.position_recovered = "primary_fallback"` to telemetry.-4. **The user must drag the mascot to the new desired position** — the old- relative offset is intentionally discarded because it was anchored to a- now-missing virtual-desktop region.--To stop this happening on every re-dock: drag the mascot to the new spot once-after re-docking; the new `szDevice` + position is persisted on `mouseRelease`.--**Source files:** `OS-Level/src/overlay/mascot_position.py`.-------## 5. Hauptjarvis crashes — does the overlay survive?--**No.** By design (Plan AD-9).--The overlay subprocess is assigned to a **Win32 Job Object** with-`JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`. The Hauptjarvis process holds the-non-inheritable Job-Handle. If Hauptjarvis dies — even via a hard kill —-Windows closes the Job-Handle, which kills every member of the Job, including-the overlay process. **Cleanup is guaranteed within ≤ 1 s** (Plan §6.4).--If you do see an orphaned overlay process after a crash:--1. Check the process tree (`pslist -t` or Process Explorer).-2. Check the Job-Object assignment via Process Explorer → process properties →- Job tab. If the process is **not** in the expected Job, the assignment- failed at spawn-time and AD-9 was not honored — file a bug with the- spawning sequence in `logs/jarvis.log`.--**Source files:** `OS-Level/src/overlay/job_object.py`,-`OS-Level/src/overlay/supervisor.py`.-------## 6. Performance issues (CPU / GPU / Battery)--**Symptoms:** Fan ramps when overlay is active, battery drains faster than-expected, FPS counter in heartbeat reports < target.--**Explanation (Plan §17.3):** A Throttler reduces FPS automatically:--- **Battery vs AC:** On battery (`GetSystemPowerStatus`), all FPS targets are- halved (60 → 30, 30 → 15) and cosmetic particle effects are skipped.-- **Idle Detection:** 30 s without events → mascot drops to 1 fps, edge-glow- frozen. 5 min without events → WebView `IsVisible = false` (Chromium- throttles hidden views).-- **Fullscreen Detection:** Fullscreen app → overlay enters `hidden` state.-- **Adaptive on budget breach:** If heartbeat reports CPU > 5% for 3- consecutive seconds, FPS is dropped 50% and a warning is logged. After 30 s- still over budget, the overlay forces `hidden` and surfaces a tray-warning.--To verify the throttler is active: read-`heartbeat.fps_actual` vs `heartbeat.fps_target` in the log. A `fps_target` of-30 on AC indicates the throttler kicked in and the source state is not-glow-active.--**Source files:** `OS-Level/src/overlay/throttler.py`.-------## 7. OBS / Teams / Zoom captures the overlay--**Symptoms:** The overlay shows up in screen-shares or recordings, even though-it should be invisible to capture by default.--**Explanation (Plan §18.1):** The overlay calls-`SetWindowDisplayAffinity(hWnd, WDA_EXCLUDEFROMCAPTURE)` on every overlay HWND-on every monitor (mascot included). This is **default-on**.--**If the overlay still appears in capture:**--1. **Win11 quirk (Plan §12.4):** `WDA_EXCLUDEFROMCAPTURE` was historically- buggy on certain Win11 builds combined with certain capture drivers (older- OBS GameCapture, some Teams versions). Update to current OBS / Teams /- Zoom; the issue was largely fixed mid-2023 but a few capture-paths still- slip.-2. **`reapply` on display change:** The affinity flag must be re-applied on- `WM_DPICHANGED`, on `screenAdded`, and after each `show()`. If the overlay- was hidden and re-shown without re-applying, capture-bypass is lost. Check- `logs/jarvis.log` for `display_affinity_reapplied`.--**Tutorial-recording opt-out:** If you **want** the overlay visible in a-recording (showing off the feature in a tutorial video), set:--```toml-[overlay]-hide_from_capture = false-```--This deactivates the capture-bypass — the overlay becomes intentionally-visible in screen-shares. **Restore to `true` after recording** for normal-privacy.--**Source files:** `OS-Level/src/overlay/window_affinity.py`.-------## 8. Jarvis-Agent triggers the overlay--**Symptoms:** Spawned Jarvis-Agent or Worker triggers the glow, even though only-Hauptjarvis is supposed to.--**Explanation (Plan §8.7):** In Jarvis-Agents (`JARVIS_DEPTH > 0`),-`OverlayBridge` is a **no-op stub by design**. If a Jarvis-Agent's actions-trigger the glow, the env-var inheritance broke.--**Checks:**--1. **Confirm `JARVIS_DEPTH > 0` is set in the Jarvis-Agent subprocess:**- - Inspect the spawn command (in the Worker code or the Jarvis-Agent- supervisor).- - The parent must inject `env={**os.environ, "JARVIS_DEPTH": str(depth+1)}`- when spawning the child.-2. **Verify at runtime:** add a debug-print in the Jarvis-Agent's `OverlayBridge`- instantiation; it should hit the no-op-stub branch, not the real-bridge- branch.-3. **Test:** `pytest OS-Level/tests/test_subagent_noop.py` (sets- `JARVIS_DEPTH=2`, instantiates `OverlayBridge`, asserts all `emit_*` are- no-ops). If this test passes but the integration breaks, the bug is in- spawn-env-injection, not in the bridge itself.--**Source files:** `OS-Level/src/overlay/bridge.py` (no-op-stub branch),-spawn sites in the Phase-5 Jarvis-Agent manager.-------## 9. Multi-Monitor smoke test (per release, manual — Plan §23.5)--For each release on hardware with ≥ 2 monitors:--1. **Single-monitor:** smoke test all 8 states.-2. **Two monitors, same DPI:** verify overlay on primary only by default;- opt-in to `all_monitors = true`, verify glow on both.-3. **Two monitors, different DPI (100% + 200%):** verify per-monitor- DPI-correct rendering — the 200% monitor should not show a half-sized- glow.-4. **Hotplug — unplug:** with the overlay running, unplug the secondary;- verify no crash, mascot recovers (see §4 above).-5. **Hotplug — plug in:** with the overlay running, plug in the secondary;- if `all_monitors = true`, verify glow appears on the new monitor within- one frame.-------## 10. Where to look in the source--| Concern | Module |-|---|---|-| State enum + transitions | `OS-Level/src/overlay/state.py` |-| IPC envelope + payload schemas | `OS-Level/src/overlay/schema.py` |-| WS server + Named-Pipe fallback | `OS-Level/src/overlay/ipc_server.py` |-| Cursor SHM block | `OS-Level/src/overlay/cursor_shm.py` |-| Process spawn + Job-Object | `OS-Level/src/overlay/supervisor.py`, `job_object.py` |-| OverlayBridge (Hauptjarvis API) | `OS-Level/src/overlay/bridge.py` |-| Renderer (Glow + Mascot) | `OS-Level/overlay-ui/src/` |-| Throttling + idle-detection | `OS-Level/src/overlay/throttler.py` |-| Mascot position persistence | `OS-Level/src/overlay/mascot_position.py` |-| Capture-bypass (`SetWindowDisplayAffinity`) | `OS-Level/src/overlay/window_affinity.py` |--For protocol-level questions, see `docs/overlay-ipc-protocol.md`. For the-state model, see `docs/overlay-state-machine.md`.diff --git a/docs/plans/jarvis-tool-map/build_excalidraw.py b/docs/plans/jarvis-tool-map/build_excalidraw.pyindex 050f104e29..b6ba02432a 100644--- a/docs/plans/jarvis-tool-map/build_excalidraw.py+++ b/docs/plans/jarvis-tool-map/build_excalidraw.py@@ -463,7 +463,6 @@ def region_catalog():("type_text", "safe · local-action gate (type_text.py:81)", "live"),("hotkey", "monitor · local-action gate (hotkey.py:141)", "live"),("reset_orb_position", "safe · orb recovery (reset_orb_position.py:32)", "live"),- ("respawn_mascot", "safe · mascot recovery (respawn_mascot.py:25)", "live"),]),("COMPUTER-USE ONLY (loaded into CU context, NOT router)", [("click", "monitor · CU loop only (click.py:109)", "partial"),diff --git a/jarvis/brain/local_action_gate.py b/jarvis/brain/local_action_gate.pyindex ec08198e3e..689ab8ea5f 100644--- a/jarvis/brain/local_action_gate.py+++ b/jarvis/brain/local_action_gate.py@@ -591,54 +591,6 @@ def _matches_orb_reset(text: str) -> bool:return any(pattern.match(text) for pattern in _ORB_RESET_PATTERNS)-# Voice-driven mascot recovery patterns. Same shape and reasoning as the-# orb-reset patterns above: anchored on ^...$, normalized input only, and-# limited to a hand-picked phrase list so generic "spawne mir ein-# Terminal" or "wo ist mein Schlüssel" does NOT fall through here.-_MASCOT_RESPAWN_PATTERNS = (- # "Maskottchen wieder auftauchen", "Maskottchen zurück", "Maskottchen- # kommt zurück", "Maskottchen weg", "Mascot back", "Maskottchen- # spawnen / reset / respawn".- re.compile(- r"^(?:hey\s+)?(?:jarvis[,\s]+)?"- r"(?:das\s+|der\s+|den\s+|mein\s+)?(?:maskottchen|mascot)"- r"\s+(?:wieder\s+|kommt\s+|soll\s+wieder\s+)?"- r"(?:auftauchen|auftaucht|zurueck|zurueckkommen|her|holen|da|"- r"spawnen|spawn|spawne|spawner|reset|respawn|weg|verschwunden|"- r"come\s+back|back)"- r"\s*[?.!]*$",- re.I,- ),- # "Spawn das Maskottchen", "spawne das Maskottchen", "respawn the mascot"- re.compile(- r"^(?:hey\s+)?(?:jarvis[,\s]+)?"- r"(?:spawn(?:e|en)?|respawn|reset|bring)\s+"- r"(?:das\s+|den\s+|the\s+|mein\s+|my\s+)?(?:maskottchen|mascot)"- r"(?:\s+(?:zurueck|back))?"- r"\s*[?.!]*$",- re.I,- ),- # "wo ist (das) Maskottchen"- re.compile(- r"^(?:hey\s+)?(?:jarvis[,\s]+)?"- r"wo\s+ist\s+(?:das\s+|der\s+|mein\s+)?(?:maskottchen|mascot|spawner)"- r"\s*[?.!]*$",- re.I,- ),- # Standalone "(der) Spawner" — short form the user reaches for.- re.compile(- r"^(?:hey\s+)?(?:jarvis[,\s]+)?"- r"(?:(?:der|den|ein|the|my|mein)\s+)?spawner"- r"\s*[?.!]*$",- re.I,- ),-)---def _matches_mascot_respawn(text: str) -> bool:- return any(pattern.match(text) for pattern in _MASCOT_RESPAWN_PATTERNS)--def _unsupported_response(text: str, lang: str) -> str:"""Return a deterministic, no-LLM rejection message.@@ -830,15 +782,6 @@ def match_local_action(mode=LocalActionMode.DIRECT,tool_calls=(LocalToolCall(name="reset_orb_position", args={}),),)- # Mascot recovery — same fast-path tier as the orb reset; checked- # before the scripted / open-app / visual-target gates so the user- # gets the deterministic respawn even if the phrase contains words- # that would otherwise trip another branch.- if _matches_mascot_respawn(normalized):- return LocalActionPlan(- mode=LocalActionMode.DIRECT,- tool_calls=(LocalToolCall(name="respawn_mascot", args={}),),- )scripted = _match_scripted_local_plan(normalized)if scripted is not None:return scripteddiff --git a/jarvis/control/keyboard.py b/jarvis/control/keyboard.pydeleted file mode 100644index 6626e6f3d8..0000000000--- a/jarvis/control/keyboard.py+++ /dev/null@@ -1,49 +0,0 @@-"""Keyboard wrappers with overlay trigger hook. Plan §8.2.--Choke point per Plan §8.3: all PC-action plugins should route through-``jarvis.control.keyboard`` instead of calling ``pyautogui`` directly.--``pyautogui`` is imported LAZILY inside function bodies so that-``jarvis.control`` remains importable without pyautogui installed-(headless tests).-"""--from __future__ import annotations--from jarvis.overlay import ActionKind, overlay_action_sync---@overlay_action_sync(ActionKind.TYPING)-def typewrite(text: str, *, interval: float = 0.0) -> None:- """Wrapper around ``pyautogui.typewrite``.-- Counts as an interactive PC action — the typing indicator (bottom-edge- sweep) should react to each key press.- """- import pyautogui # lazy-- pyautogui.typewrite(text, interval=interval)---@overlay_action_sync(ActionKind.HOTKEY)-def hotkey(*keys: str) -> None:- """Wrapper around ``pyautogui.hotkey``.-- Counts as an interactive PC action — a hotkey is a single event;- Plan §8.2 maps it to TYPING state (without a sweep burst).- """- import pyautogui # lazy-- pyautogui.hotkey(*keys)---@overlay_action_sync(ActionKind.TYPING)-def press(key: str, *, presses: int = 1) -> None:- """Wrapper around ``pyautogui.press``.-- Counts as an interactive PC action — a single key press is treated like- typewrite.- """- import pyautogui # lazy-- pyautogui.press(key, presses=presses)diff --git a/jarvis/control/mouse.py b/jarvis/control/mouse.pydeleted file mode 100644index ef61002eb6..0000000000--- a/jarvis/control/mouse.py+++ /dev/null@@ -1,133 +0,0 @@-"""Mouse wrappers with overlay trigger hook and cursor-stream gating.--Phase 9.8: real ``@overlay_action_sync`` decorators complement the-cursor-streamer hook (Phase 9.5). The click wrapper additionally emits a-dedicated click event BEFORE ``pyautogui.click()`` so that the ripple-visualisation beats the OS click in time (Plan §14.3 + §8.8).--Choke point per Plan §8.3: all PC-action plugins should route through-``jarvis.control.mouse``/``keyboard``/``browser`` instead of calling-``pyautogui`` directly — making this file the single point of-instrumentation.--``pyautogui`` is imported LAZILY inside function bodies.-"""--from __future__ import annotations--from contextlib import contextmanager-from typing import Iterator, Optional--from jarvis.overlay import (- ActionKind,- overlay_action_sync,-)-from jarvis.overlay.cursor_writer import CursorStreamer--# Module-global streamer (Phase 9.5).-_streamer: Optional[CursorStreamer] = None---def set_cursor_streamer(streamer: Optional[CursorStreamer]) -> None:- """Phase 9.5 — the main Jarvis bootstrap injects the streamer here."""- global _streamer- _streamer = streamer---def get_cursor_streamer() -> Optional[CursorStreamer]:- return _streamer---@contextmanager-def _streaming_scope(monitor_idx: int = 0) -> Iterator[None]:- """Activate the cursor SHM streamer for the duration of the with-block.- No-op when no streamer is set."""- s = _streamer- if s is None:- yield- return- s.start_streaming(monitor_idx=monitor_idx)- try:- yield- finally:- s.stop_streaming()---@overlay_action_sync(ActionKind.CLICK)-def click(- x: Optional[int] = None,- y: Optional[int] = None,- *,- button: str = "left",- clicks: int = 1,- interval: float = 0.0,- monitor_idx: int = 0,-) -> None:- """Wrapper around ``pyautogui.click``.-- Plan §14.3 + §8.8: emit_click() FIRES BEFORE pyautogui.click() —- the ripple visualisation must beat the OS click in time.- Counts as an interactive PC action.- """- import pyautogui # lazy-- # Lazy + defensive: get_overlay pulls the IPC bridge stack (OS-Level- # schema package). On a host without that install the ripple overlay- # degrades to a no-op — the click itself must never depend on it.- try:- from jarvis.overlay import get_overlay # noqa: PLC0415-- bridge = get_overlay()- except Exception: # noqa: BLE001- bridge = None- # Pre-resolve click coordinates so emit_click receives the real values- # (pyautogui.click(x=None) uses the current cursor position).- if x is None or y is None:- try:- pos = pyautogui.position()- x = int(pos.x) if x is None else int(x)- y = int(pos.y) if y is None else int(y)- except Exception: # noqa: BLE001- x = int(x) if x is not None else 0- y = int(y) if y is not None else 0-- # Plan §14.3: emit BEFORE pyautogui.click().- if bridge is not None:- try:- bridge.emit_click(x, y, monitor=str(monitor_idx), button=button)- except Exception: # noqa: BLE001- pass-- with _streaming_scope(monitor_idx):- pyautogui.click(x=x, y=y, button=button, clicks=clicks, interval=interval)---@overlay_action_sync(ActionKind.MOVE)-def move_to(- x: int,- y: int,- *,- duration: float = 0.0,- monitor_idx: int = 0,-) -> None:- """Wrapper around ``pyautogui.moveTo``. Stream-gated during animation.-- Counts as an interactive PC action — the cursor trail should be- visible while Jarvis moves the mouse.- """- import pyautogui # lazy-- with _streaming_scope(monitor_idx):- pyautogui.moveTo(x=x, y=y, duration=duration)---@overlay_action_sync(ActionKind.SCROLL)-def scroll(amount: int, *, monitor_idx: int = 0) -> None:- """Wrapper around ``pyautogui.scroll``.-- Counts as an interactive PC action.- """- import pyautogui # lazy-- with _streaming_scope(monitor_idx):- pyautogui.scroll(amount)diff --git a/jarvis/overlay/__init__.py b/jarvis/overlay/__init__.pyindex e26ba85428..059fc09aac 100644--- a/jarvis/overlay/__init__.py+++ b/jarvis/overlay/__init__.py@@ -1,76 +1,22 @@-"""Overlay bridge public API. Plan §9.1.--Main-Jarvis code imports exclusively from here::-- from jarvis.overlay import (- get_overlay,- start_overlay, stop_overlay,- overlay_action, overlay_action_sync, overlay_action_scope,- ActionKind,- )--Sub-agent detection (Plan §8.7 / AD-6) is transparent: in sub-agents-``get_overlay()`` returns a ``NoOpOverlayBridge`` stub with the-same API. Caller code notices nothing structurally.+"""On-screen overlay surfaces and helpers.++This package holds the LIVE desktop-presence building blocks:++- ``surface`` / ``linux_surface`` / ``tray_surface`` — the cross-platform+ overlay-surface factory ladder (Tk orb on Windows, best-effort on Linux+ X11, tray-only floor everywhere else).+- ``virtual_cursor`` / ``system_cursor`` — the Jarvis cursor swap during+ Computer-Use actions.+- ``drop_bridge`` / ``drop_target`` — drag-and-drop onto the floating+ overlay.++Import the submodules directly (``from jarvis.overlay.surface import+make_overlay_surface``). The former OS-Level subprocess overlay+(edge-glow / mascot / cursor-trail IPC stack) was removed in 2026-07; the+Computer-Use screen indicator that replaced its edge-glow lives in+``jarvis.cu.indicator``."""from __future__ import annotations-from importlib import import_module-from typing import Any--# PEP 562 lazy re-exports. The eager form pulled ``.bridge`` -> ``.schema`` ->-# the OS-Level ``overlay.schema`` package (+ its ``ulid`` dependency) into-# EVERY import of ANY ``jarvis.overlay`` submodule — so a host without the-# OS-Level editable install could not even import ``virtual_cursor`` /-# ``system_cursor``, which silently killed the Computer-Use mouse tools-# (click / click_element / move_mouse) at plugin load (2026-07-06 forensic:-# the tools loaded only on the maintainer's interpreter, where a manual-# ``pip install -e OS-Level`` existed). Lazy resolution keeps the public API-# identical while only the names someone actually uses pay their import cost.-_EXPORTS: dict[str, str] = {- "NoOpOverlayBridge": ".bridge",- "OverlayBridge": ".bridge",- "is_sub_agent_process": ".bridge",- "get_overlay": ".integration",- "is_overlay_enabled": ".integration",- "set_overlay": ".integration",- "start_overlay": ".integration",- "stop_overlay": ".integration",- "OverlaySupervisor": ".supervisor",- "ActionKind": ".triggers",- "overlay_action": ".triggers",- "overlay_action_scope": ".triggers",- "overlay_action_scope_sync": ".triggers",- "overlay_action_sync": ".triggers",-}---def __getattr__(name: str) -> Any:- submodule = _EXPORTS.get(name)- if submodule is None:- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")- value = getattr(import_module(submodule, __name__), name)- globals()[name] = value # cache: subsequent lookups skip __getattr__- return value---def __dir__() -> list[str]:- return sorted(set(globals()) | set(_EXPORTS))--__all__ = [- "ActionKind",- "NoOpOverlayBridge",- "OverlayBridge",- "OverlaySupervisor",- "get_overlay",- "is_overlay_enabled",- "is_sub_agent_process",- "overlay_action",- "overlay_action_scope",- "overlay_action_scope_sync",- "overlay_action_sync",- "set_overlay",- "start_overlay",- "stop_overlay",-]+__all__: list[str] = []diff --git a/jarvis/overlay/bridge.py b/jarvis/overlay/bridge.pydeleted file mode 100644index ecfab8ec5b..0000000000--- a/jarvis/overlay/bridge.py+++ /dev/null@@ -1,495 +0,0 @@-"""``OverlayBridge`` — main-Jarvis-side IPC facade.--Phase 9.2:-- ``send`` / ``send_nowait`` with a bounded ``asyncio.Queue(maxsize=256)``.-- Drop policy per Plan §10.4: drop oldest non-state first, drop state last.-- WS handler coroutine for ``websockets.serve(...)``. Validates incoming- messages via ``IPCMessage.validate_json``.-- Caches the current state (``last_state_envelope``) so a reconnect gets- the resync frame first (§10.5).--NOT YET in 9.2: coalescing (AD-17), cursor SHM, state machine. Phase 9.3-delivers the state machine on top of this bridge.-"""--from __future__ import annotations--import asyncio-import logging-import time-from collections import deque-from typing import Any, AsyncIterator, Awaitable, Callable, Optional--import os--from jarvis.overlay.schema import (- ActionEndedEnvelope,- ActionEndedPayload,- ActionStartedEnvelope,- ActionStartedPayload,- ClickEnvelope,- ClickPayload,- ErrorEnvelope,- ErrorPayload,- HeartbeatEnvelope,- HeartbeatPayload,- IPCMessage,- StateEnvelope,- StatePayload,- is_state_type,- new_ulid,- now_ns,-)--logger = logging.getLogger(__name__)--OUTBOUND_QUEUE_MAX = 256-INBOUND_QUEUE_MAX = 64--# Mock type for ``websockets.WebSocketServerProtocol``. We type loosely,-# so the module import doesn't depend on ``websockets`` (headless tests).-WSConn = Any---class _BoundedOutbox:- """Bounded outbound queue with drop policy (§10.4).-- Implemented as a ``deque(maxlen=N)`` plus an ``asyncio.Event`` for- wake-up. We don't use ``asyncio.Queue.put_nowait`` because its- full-behavior is a ``QueueFull`` exception; we want drop-oldest-non-- state, so we need handcrafted drop logic.- """-- def __init__(self, maxsize: int = OUTBOUND_QUEUE_MAX) -> None:- self._max = maxsize- # ``deque`` without maxlen — we handle eviction ourselves.- self._buf: deque[bytes] = deque()- self._types: deque[str] = deque() # parallel to _buf- self._wake = asyncio.Event()- self._dropped = 0-- @property- def dropped(self) -> int:- return self._dropped-- def __len__(self) -> int:- return len(self._buf)-- def put(self, envelope_type: str, raw_json: bytes) -> bool:- """Non-blocking enqueue. Returns ``True`` on acceptance.-- Drop policy: if full, drop the oldest *non-state* element.- If only state elements are in the queue, drop nothing and- instead discard the NEW non-state entry (state is never- dropped).- """- if len(self._buf) < self._max:- self._buf.append(raw_json)- self._types.append(envelope_type)- self._wake.set()- return True-- # Full. Look for the oldest non-state.- for idx, t in enumerate(self._types):- if not is_state_type(t):- # Evict this entry.- del self._buf[idx]- del self._types[idx]- self._buf.append(raw_json)- self._types.append(envelope_type)- self._dropped += 1- self._wake.set()- return True-- # Queue is entirely state. Then only one state element may go in.- if is_state_type(envelope_type):- # Drop the oldest state.- self._buf.popleft()- self._types.popleft()- self._buf.append(raw_json)- self._types.append(envelope_type)- self._dropped += 1- self._wake.set()- return True-- # Non-state + only state in queue -> drop the new one.- self._dropped += 1- return False-- async def get(self) -> bytes:- """Async pop. Blocks until an element is available."""- while not self._buf:- self._wake.clear()- await self._wake.wait()- item = self._buf.popleft()- self._types.popleft()- return item-- def clear(self) -> None:- self._buf.clear()- self._types.clear()- self._wake.clear()---class OverlayBridge:- """Main-Jarvis-side WS server bridge.-- Lifecycle:- bridge = OverlayBridge()- await bridge.start()- # ... bridge.emit_state(...) etc ...- await bridge.stop()-- WS handler:- await websockets.serve(bridge.handler, "127.0.0.1", port)- """-- def __init__(- self,- *,- outbound_queue_max: int = OUTBOUND_QUEUE_MAX,- heartbeat_interval_s: float = 1.0,- ) -> None:- self._outbox = _BoundedOutbox(maxsize=outbound_queue_max)- self._heartbeat_interval = heartbeat_interval_s- self._started_at_ns: int = 0- self._connected: set[WSConn] = set()- self._last_state_envelope: Optional[StateEnvelope] = None- self._inbound_handlers: list[Callable[[Any], Awaitable[None]]] = []- self._tasks: list[asyncio.Task[Any]] = []- self._running = False-- # --- lifecycle ----- async def start(self) -> None:- if self._running:- return- self._running = True- self._started_at_ns = now_ns()- # Heartbeat pump every ``_heartbeat_interval`` seconds.- self._tasks.append(- asyncio.create_task(self._heartbeat_loop(), name="overlay-heartbeat")- )-- async def stop(self) -> None:- if not self._running:- return- self._running = False- for t in self._tasks:- t.cancel()- for t in self._tasks:- try:- await t- except (asyncio.CancelledError, Exception): # noqa: BLE001- pass- self._tasks.clear()- self._outbox.clear()-- # --- public emit-API (sync, queue-only) ----- def send_nowait(self, envelope: Any) -> bool:- """Sync API. Serializes the envelope and pushes it into the outbox."""- raw = envelope.model_dump_json().encode("utf-8")- if isinstance(envelope, StateEnvelope):- self._last_state_envelope = envelope- return self._outbox.put(envelope.type, raw)-- async def send(self, envelope: Any) -> bool:- """Async API. Currently identical to ``send_nowait`` because the- queue is non-blocking; the signature stays async for 9.3+ extensions."""- return self.send_nowait(envelope)-- def emit_state(- self,- state: str,- *,- intensity: float = 1.0,- reason: Optional[str] = None,- ) -> bool:- env = StateEnvelope(- payload=StatePayload(- state=state, # type: ignore[arg-type]- intensity=intensity,- reason=reason, # type: ignore[arg-type]- )- )- return self.send_nowait(env)-- def emit_action_started(- self,- kind: str,- *,- duration_hint_ms: Optional[int] = None,- action_id: Optional[str] = None,- ) -> str:- """Plan §8.4 — before the function call. Returns the action_id so- emit_action_ended can reference it."""- aid = action_id or new_ulid()- env = ActionStartedEnvelope(- payload=ActionStartedPayload(- kind=kind, # type: ignore[arg-type]- action_id=aid,- duration_hint_ms=duration_hint_ms,- )- )- self.send_nowait(env)- return aid-- def emit_action_ended(- self,- action_id: str,- *,- succeeded: bool = True,- duration_actual_ms: Optional[int] = None,- ) -> bool:- """Plan §8.4 — in the finally block (also on exception)."""- env = ActionEndedEnvelope(- payload=ActionEndedPayload(- action_id=action_id,- succeeded=succeeded,- duration_actual_ms=duration_actual_ms,- )- )- return self.send_nowait(env)-- def emit_click(- self,- x: int,- y: int,- *,- monitor: str = "",- button: str = "left",- modifiers: Optional[list[str]] = None,- ) -> bool:- """Plan §14.3 — emit BEFORE pyautogui.click() so Visual reaches- WebView before OS Click Event finished propagating."""- env = ClickEnvelope(- payload=ClickPayload(- x=int(x),- y=int(y),- monitor=monitor,- button=button, # type: ignore[arg-type]- modifiers=list(modifiers) if modifiers else [],- )- )- return self.send_nowait(env)-- def emit_error(- self,- message: str,- *,- code: str = "OVERLAY_ACTION_ERROR",- recoverable: bool = True,- context: Optional[dict[str, Any]] = None,- ) -> bool:- """Plan §8.4 — on exception in @overlay_action."""- env = ErrorEnvelope(- payload=ErrorPayload(- code=code,- message=message,- recoverable=recoverable,- context=dict(context) if context else {},- )- )- return self.send_nowait(env)-- def add_inbound_handler(self, handler: Callable[[Any], Awaitable[None]]) -> None:- self._inbound_handlers.append(handler)-- # --- queue access ----- @property- def outbox(self) -> _BoundedOutbox:- return self._outbox-- @property- def last_state_envelope(self) -> Optional[StateEnvelope]:- return self._last_state_envelope-- @property- def connected_count(self) -> int:- return len(self._connected)-- # --- WS handler ----- async def handler(self, websocket: WSConn) -> None:- """``websockets.serve(...)``-compatible handler.-- State resync per §10.5: the first frame after connect is the last- known state (if any).- """- self._connected.add(websocket)- try:- if self._last_state_envelope is not None:- resync = self._last_state_envelope.model_dump_json().encode("utf-8")- await websocket.send(resync)-- sender = asyncio.create_task(- self._send_loop(websocket), name="overlay-ws-send"- )- recver = asyncio.create_task(- self._recv_loop(websocket), name="overlay-ws-recv"- )- done, pending = await asyncio.wait(- {sender, recver}, return_when=asyncio.FIRST_COMPLETED- )- for t in pending:- t.cancel()- for t in done:- exc = t.exception()- if exc is not None and not isinstance(exc, asyncio.CancelledError):- logger.warning("overlay WS task died: %r", exc)- finally:- self._connected.discard(websocket)-- async def _send_loop(self, websocket: WSConn) -> None:- while True:- raw = await self._outbox.get()- await websocket.send(raw)-- async def _recv_loop(self, websocket: WSConn) -> None:- async for raw in websocket:- try:- msg = IPCMessage.validate_json(raw)- except Exception as exc: # noqa: BLE001- logger.warning("overlay WS validate failed: %r raw=%r", exc, raw[:200])- continue- for h in self._inbound_handlers:- try:- await h(msg)- except Exception: # noqa: BLE001- logger.exception("inbound handler raised")-- # --- internals ----- async def _heartbeat_loop(self) -> None:- while self._running:- try:- env = HeartbeatEnvelope(- payload=HeartbeatPayload(- uptime_s=(now_ns() - self._started_at_ns) / 1e9,- ws_connected=bool(self._connected),- )- )- self.send_nowait(env)- except Exception: # noqa: BLE001- logger.exception("heartbeat emit failed")- try:- await asyncio.sleep(self._heartbeat_interval)- except asyncio.CancelledError:- return---def envelope_to_json(envelope: Any) -> bytes:- """Helper for tests."""- return envelope.model_dump_json().encode("utf-8")---# --------------------------------------------------------------------------# Sub-agent no-op stub. Plan §8.7 / AD-6.-# ----------------------------------------------------------------------------JARVIS_DEPTH_ENV: str = "JARVIS_DEPTH"---def is_sub_agent_process() -> bool:- """True when the ``JARVIS_DEPTH > 0`` env is set. Sub-agent code runs with- depth >= 1 (Phase-5 convention)."""- raw = os.environ.get(JARVIS_DEPTH_ENV, "0")- try:- return int(raw) > 0- except (ValueError, TypeError):- return False---class NoOpOverlayBridge:- """No-op stub for sub-agents. Plan §8.7 / AD-6.-- Has the same public API as ``OverlayBridge``, but all methods- are lifeless stubs. Sub-agent code can therefore write the same- pattern (``bridge.emit_click(...)``) without special-casing — the- events simply vanish into the void.-- Important: we do NOT inherit from OverlayBridge because its __init__- builds an asyncio.Queue, and sub-agent sync paths may have no- event loop. Instead: a duck-typed stub.- """-- @property- def dropped(self) -> int:- return 0-- @property- def connected_count(self) -> int:- return 0-- @property- def last_state_envelope(self) -> Optional[StateEnvelope]:- return None-- async def start(self) -> None:- return None-- async def stop(self) -> None:- return None-- def send_nowait(self, _envelope: Any) -> bool:- return False-- async def send(self, _envelope: Any) -> bool:- return False-- def emit_state(- self,- _state: str,- *,- intensity: float = 1.0, # noqa: ARG002 — API symmetry- reason: Optional[str] = None, # noqa: ARG002- ) -> bool:- return False-- def emit_action_started(- self,- _kind: str,- *,- duration_hint_ms: Optional[int] = None, # noqa: ARG002- action_id: Optional[str] = None,- ) -> str:- # Stub returns an action_id so caller code can keep going.- return action_id or "noop"-- def emit_action_ended(- self,- _action_id: str,- *,- succeeded: bool = True, # noqa: ARG002- duration_actual_ms: Optional[int] = None, # noqa: ARG002- ) -> bool:- return False-- def emit_click(- self,- _x: int,- _y: int,- *,- monitor: str = "", # noqa: ARG002- button: str = "left", # noqa: ARG002- modifiers: Optional[list[str]] = None, # noqa: ARG002- ) -> bool:- return False-- def emit_error(- self,- _message: str,- *,- code: str = "OVERLAY_ACTION_ERROR", # noqa: ARG002- recoverable: bool = True, # noqa: ARG002- context: Optional[dict[str, Any]] = None, # noqa: ARG002- ) -> bool:- return False-- def add_inbound_handler(- self, _handler: Callable[[Any], Awaitable[None]]- ) -> None:- return Nonediff --git a/jarvis/overlay/cursor_writer.py b/jarvis/overlay/cursor_writer.pydeleted file mode 100644index a10ac0c11b..0000000000--- a/jarvis/overlay/cursor_writer.py+++ /dev/null@@ -1,240 +0,0 @@-"""Hauptjarvis-side Cursor-SHM-Writer + Streamer. Plan §11 + §15.3.--Wraps the ``CursorShmWriter`` class from ``OS-Level/src/overlay/-cursor_shm.py`` in a thread-based streamer that can publish pyautogui-position polls at 60 Hz.--Layout constants are duplicated here (rather than imported from OS-Level)-because ``OS-Level/src/overlay`` is its own pyproject and is not-necessarily on the Hauptjarvis Python path. Drift protection: the tests-in ``tests/overlay/test_cursor_shm.py`` use the OS-Level variant,-``test_cursor_writer.py`` uses this one — if both write/read against-the same 32-byte layout, the pattern has not drifted.--Streamer lifecycle (Plan §15.3 — only during action scope):-- streamer = CursorStreamer.create()- bridge.config.shm_cursor_name = streamer.name- # ... at the start of an action:- streamer.start_streaming(monitor_idx=0)- # ... at the end of the action:- streamer.stop_streaming()- # ... at process exit:- streamer.close()--``start_streaming`` is idempotent (multiple action scopes do not-typically overlap; if they do, refcount-style behaviour would be-overkill — we simply accept the last call).-"""--from __future__ import annotations--import logging-import secrets-import struct-import threading-import time-from multiprocessing import shared_memory-from typing import Callable, Optional--logger = logging.getLogger(__name__)---# Plan §11 Layout — identical to OS-Level/src/overlay/cursor_shm.py.-# Drift is detected via the round-trip test.-CURSOR_SHM_SIZE: int = 32-CURSOR_SHM_STRUCT: str = "<qiiII8s"-assert struct.calcsize(CURSOR_SHM_STRUCT) == CURSOR_SHM_SIZE--_OFFSET_TS = 0-_OFFSET_X = 8-_OFFSET_Y = 12-_OFFSET_SEQ = 16-_OFFSET_MONITOR = 20-_PADDING = bytes(8)---# 60 Hz polling — Plan §15.3.-DEFAULT_STREAM_HZ: int = 60---def make_cursor_shm_name() -> str:- return f"jarvis-cursor-{secrets.token_hex(4)}"---# Position-reader type: ``() -> (x, y)``. Default is pyautogui.position()-# lazily imported — tests can inject a fake.-PositionReader = Callable[[], tuple[int, int]]---def _default_pyautogui_position() -> tuple[int, int]:- import pyautogui # lazy-- pos = pyautogui.position()- return int(pos.x), int(pos.y)---class CursorShmWriter:- """Owner of the SHM block. Plan §11.4 seqlock pattern."""-- def __init__(self, shm: shared_memory.SharedMemory) -> None:- if shm.size < CURSOR_SHM_SIZE:- raise ValueError(f"SHM block too small: {shm.size}")- self._shm = shm- self._buf = shm.buf- self._seq: int = 0- # Block zeroed — reader-side check (seq=0 = never published).- shm.buf[:CURSOR_SHM_SIZE] = bytes(CURSOR_SHM_SIZE)-- @classmethod- def create(cls, name: Optional[str] = None) -> "CursorShmWriter":- if name is None:- name = make_cursor_shm_name()- shm = shared_memory.SharedMemory(name=name, create=True, size=CURSOR_SHM_SIZE)- return cls(shm)-- def write(self, x: int, y: int, monitor_idx: int) -> int:- seq_busy = self._seq + 1- struct.pack_into("<I", self._buf, _OFFSET_SEQ, seq_busy)- ts_ns = time.time_ns()- struct.pack_into("<q", self._buf, _OFFSET_TS, ts_ns)- struct.pack_into("<i", self._buf, _OFFSET_X, int(x))- struct.pack_into("<i", self._buf, _OFFSET_Y, int(y))- struct.pack_into("<I", self._buf, _OFFSET_MONITOR, int(monitor_idx))- struct.pack_into("<8s", self._buf, 24, _PADDING)- seq_done = seq_busy + 1- struct.pack_into("<I", self._buf, _OFFSET_SEQ, seq_done)- self._seq = seq_done- return seq_done-- @property- def name(self) -> str:- return self._shm.name-- @property- def seq(self) -> int:- return self._seq-- def close(self) -> None:- try:- self._buf.release()- except (ValueError, BufferError):- pass- try:- self._shm.close()- except Exception: # noqa: BLE001- logger.debug("CursorShmWriter close swallowed", exc_info=True)- try:- self._shm.unlink()- except (FileNotFoundError, Exception): # noqa: BLE001- pass---class CursorStreamer:- """Background thread that publishes pyautogui position polls at 60 Hz- into the SHM block during action scopes.-- Plan §15.3 — Hauptjarvis writes cursor position **only when** an- action is in progress. Streaming status is a boolean flag,- thread-safe via a lock.- """-- def __init__(- self,- writer: CursorShmWriter,- *,- hz: int = DEFAULT_STREAM_HZ,- position_reader: PositionReader = _default_pyautogui_position,- ) -> None:- self._writer = writer- self._period = 1.0 / float(max(1, hz))- self._read_position = position_reader- self._lock = threading.Lock()- self._streaming = False- self._monitor_idx = 0- self._thread: Optional[threading.Thread] = None- self._stop = threading.Event()-- @classmethod- def create(- cls,- *,- hz: int = DEFAULT_STREAM_HZ,- position_reader: PositionReader = _default_pyautogui_position,- name: Optional[str] = None,- ) -> "CursorStreamer":- writer = CursorShmWriter.create(name=name)- return cls(writer, hz=hz, position_reader=position_reader)-- @property- def name(self) -> str:- return self._writer.name-- @property- def is_streaming(self) -> bool:- with self._lock:- return self._streaming-- @property- def writer(self) -> CursorShmWriter:- return self._writer-- def start_streaming(self, *, monitor_idx: int = 0) -> None:- """Starts 60 Hz polling. Idempotent."""- with self._lock:- self._monitor_idx = monitor_idx- if self._streaming:- return- self._streaming = True- self._stop.clear()- if self._thread is None or not self._thread.is_alive():- self._thread = threading.Thread(- target=self._run, name="cursor-streamer", daemon=True- )- self._thread.start()-- def stop_streaming(self) -> None:- """Pauses polling. The thread keeps running so that- ``start_streaming`` restarts quickly."""- with self._lock:- self._streaming = False-- def shutdown(self) -> None:- """Permanently stop the thread and release the SHM block."""- with self._lock:- self._streaming = False- self._stop.set()- if self._thread is not None:- self._thread.join(timeout=2.0)- self._writer.close()-- def _run(self) -> None:- while not self._stop.is_set():- with self._lock:- streaming = self._streaming- monitor_idx = self._monitor_idx- if not streaming:- # Sleep with polling-friendly granularity.- if self._stop.wait(timeout=0.05):- return- continue- try:- x, y = self._read_position()- self._writer.write(x, y, monitor_idx)- except Exception: # noqa: BLE001- # Position reader can fail on headless systems- # — swallow silently, otherwise the whole action breaks.- logger.debug("cursor position read failed", exc_info=True)- if self._stop.wait(timeout=self._period):- return---__all__ = [- "CURSOR_SHM_SIZE",- "CURSOR_SHM_STRUCT",- "CursorShmWriter",- "CursorStreamer",- "DEFAULT_STREAM_HZ",- "PositionReader",- "make_cursor_shm_name",-]diff --git a/jarvis/overlay/integration.py b/jarvis/overlay/integration.pydeleted file mode 100644index 395e74fb82..0000000000--- a/jarvis/overlay/integration.py+++ /dev/null@@ -1,266 +0,0 @@-"""Main-Jarvis integration. Plan §4.3 + §9.--Public API for the main-Jarvis main entry point::-- from jarvis.overlay.integration import start_overlay, stop_overlay-- async def main():- await start_overlay()- try:- ... # FastAPI / DesktopApp / etc.- finally:- await stop_overlay()--Hooks:-- reads the ``[overlay]`` section from jarvis.toml.-- spawns ``OverlaySupervisor`` when ``overlay.enabled = true``.-- wires OverlayBridge into the WS-server pipeline (dedicated WS listener- on ``ws_port``). The subprocess connects as a client.-- Sub-agent detection (JARVIS_DEPTH > 0) -> everything becomes a no-op.--Idempotent: calling ``start_overlay()`` more than once does nothing after-the first call (singleton pattern). ``stop_overlay()`` can be called-multiple times.-"""--from __future__ import annotations--import asyncio-import logging-from typing import Any, Optional--from .bridge import (- NoOpOverlayBridge,- OverlayBridge,- is_sub_agent_process,-)-from .server import IPCServerHandle, start_ipc_server-from .supervisor import OverlaySupervisor--logger = logging.getLogger(__name__)---# Singleton state.-_bridge: Optional[OverlayBridge | NoOpOverlayBridge] = None-_supervisor: Optional[OverlaySupervisor] = None-_ws_server_task: Optional[asyncio.Task] = None-_ipc_server_handle: Optional[IPCServerHandle] = None---def _read_overlay_config() -> dict:- """Reads ``[overlay]`` directly from jarvis.toml (tomllib).-- Not via JarvisConfig (Pydantic), because the top-level model does not- yet whitelist the overlay section — it would be silently swallowed.- Direct TOML parsing bypasses that.- """- import tomllib- from pathlib import Path-- try:- from jarvis.core.config import DEFAULT_CONFIG_FILE-- toml_path = Path(DEFAULT_CONFIG_FILE)- except Exception: # noqa: BLE001- toml_path = Path("jarvis.toml")-- if not toml_path.is_file():- return {"enabled": False}-- try:- with toml_path.open("rb") as f:- data = tomllib.load(f)- except (tomllib.TOMLDecodeError, OSError):- logger.debug("jarvis.toml not parseable", exc_info=True)- return {"enabled": False}-- section = data.get("overlay") or {}- return {- "enabled": bool(section.get("enabled", False)),- "ws_port": int(section.get("ws_port", 7842)),- "ws_host": str(section.get("ws_host", "127.0.0.1")),- }---def is_overlay_enabled() -> bool:- """Plan §9.1 public API."""- if is_sub_agent_process():- return False- cfg = _read_overlay_config()- return cfg.get("enabled", False)---def get_overlay() -> Optional[OverlayBridge | NoOpOverlayBridge]:- """Plan §9.1 public API. Singleton accessor.-- In sub-agent processes (JARVIS_DEPTH>0) returns a NoOp stub.- Production: returns None when ``start_overlay`` has never been called.- """- if is_sub_agent_process():- # Sub-agent: every get_overlay() call returns a fresh stub.- # Idempotent — the stub has no state.- return NoOpOverlayBridge()- return _bridge---def get_overlay_supervisor() -> Optional[OverlaySupervisor]:- """Plan §9.1 — singleton accessor for the OverlaySupervisor.-- Returns ``None`` when overlay is disabled, when running as a- sub-agent (JARVIS_DEPTH > 0), or when ``start_overlay`` has not yet- been called. Used by the ``respawn_mascot`` voice-recovery tool to- force a fresh subprocess spawn after a hide / hang / cap-fire.- """- if is_sub_agent_process():- return None- return _supervisor---def set_overlay(bridge: Optional[OverlayBridge | NoOpOverlayBridge]) -> None:- """Test hook. Allows test code to inject a mock bridge.-- Do not call from production code.- """- global _bridge- _bridge = bridge---async def start_overlay(- bus: Optional[Any] = None,-) -> Optional[OverlayBridge | NoOpOverlayBridge]:- """Plan §9.1 — Idempotent startup hook for the main-Jarvis main entry.-- Returns:- - ``None`` when overlay is disabled or the process is a sub-agent.- - ``NoOpOverlayBridge`` when running as a sub-agent (interface-symmetric).- - ``OverlayBridge`` when enabled and the subprocess has been spawned.-- ``bus`` — optional. When supplied, mascot-originated user events- (currently: doubleClick → mute toggle) are republished onto the- EventBus as ``VoiceMuteToggleRequested`` so the speech pipeline can- react. If omitted (e.g. unit tests, sub-agent processes) the inbound- mascot events are still logged but not acted upon.- """- global _bridge, _supervisor, _ipc_server_handle-- if is_sub_agent_process():- logger.info("Overlay: sub-agent process -> NoOp stub")- _bridge = NoOpOverlayBridge()- return _bridge-- cfg = _read_overlay_config()- if not cfg.get("enabled", False):- logger.info("Overlay: disabled via config")- return None-- if _bridge is not None and _supervisor is not None:- return _bridge # idempotent-- bridge = OverlayBridge()- # bridge.start() is idempotent — start_ipc_server calls it itself.- # The WS server MUST be listening before the subprocess is spawned,- # otherwise the subprocess IPC client can never connect and will not- # send heartbeats. Consequence: the supervisor sees a 3 s heartbeat- # timeout and kill+respawns; after 6 attempts the cap fires and the- # overlay goes completely offline — the user would then see no visual- # feedback even when the voice backend triggers.- ws_host = cfg.get("ws_host", "127.0.0.1")- ws_port = cfg.get("ws_port", 7842)- try:- ipc_handle = await start_ipc_server(- host=ws_host,- port=ws_port,- bridge=bridge,- )- _ipc_server_handle = ipc_handle- logger.info(- "Overlay WS server live on ws://%s:%d", ipc_handle.host, ipc_handle.port- )- except Exception: # noqa: BLE001- logger.exception(- "Overlay WS server failed to start -> subprocess will report heartbeat timeouts"- )- # Bridge stays active; supervisor will kill+respawn.- # We don't give up, because _read_overlay_config might try a different port.-- supervisor = OverlaySupervisor(ws_port=ws_port)-- # Heartbeat wiring: the WS incoming handler calls notify_heartbeat.- # Defensive: every inbound message counts as a lifesign, not- # just HeartbeatEnvelopes. This way a discriminator mismatch or- # schema drift can't blind the supervisor — as long as something- # arrives from the subprocess, it counts as alive. Pragmatic fallback:- # the type check stays in for forensics (logging), the notify is universal.- async def _on_inbound(envelope) -> None:- type_name = type(envelope).__name__- # Lifesign notify FIRST (always, not just for heartbeat) —- # so the supervisor stays alive even if the schema/discriminator- # accidentally rotates.- supervisor.notify_heartbeat()- if type_name != "HeartbeatEnvelope":- logger.debug(- "Overlay WS inbound: %s (lifesign-notify done)", type_name- )-- # Mascot-originated user interaction: doubleClick → mute toggle.- # We republish on the EventBus so the speech pipeline can decide- # the new mute state and broadcast it to other listeners.- if type_name == "MascotEventEnvelope" and bus is not None:- kind = getattr(getattr(envelope, "payload", None), "kind", None)- if kind == "mute_toggle":- try:- from jarvis.core.events import VoiceMuteToggleRequested-- await bus.publish(- VoiceMuteToggleRequested(source="mascot_dblclick")- )- except Exception: # noqa: BLE001- logger.exception("VoiceMuteToggleRequested publish failed")-- bridge.add_inbound_handler(_on_inbound)-- try:- await supervisor.start()- except Exception: # noqa: BLE001- logger.exception("OverlaySupervisor.start failed -> bridge stays running")- # Leave the bridge as-is; the user can manually re-enable it.-- _bridge = bridge- _supervisor = supervisor- return bridge---async def stop_overlay() -> None:- """Plan §9.1 — idempotent shutdown."""- global _bridge, _supervisor, _ipc_server_handle-- if _supervisor is not None:- try:- await _supervisor.stop()- except Exception: # noqa: BLE001- logger.exception("supervisor.stop raised")- _supervisor = None-- if _ipc_server_handle is not None:- try:- await _ipc_server_handle.stop()- except Exception: # noqa: BLE001- logger.exception("ipc_server.stop raised")- _ipc_server_handle = None-- if _bridge is not None and isinstance(_bridge, OverlayBridge):- try:- await _bridge.stop()- except Exception: # noqa: BLE001- logger.exception("bridge.stop raised")- _bridge = None---__all__ = [- "get_overlay",- "get_overlay_supervisor",- "is_overlay_enabled",- "set_overlay",- "start_overlay",- "stop_overlay",-]diff --git a/jarvis/overlay/schema.py b/jarvis/overlay/schema.pydeleted file mode 100644index 8011d4b522..0000000000--- a/jarvis/overlay/schema.py+++ /dev/null@@ -1,101 +0,0 @@-"""IPC schemas (main-Jarvis side) — re-export from the OS-Level package.--AD-15: single source. Every change to the wire format happens in-``OS-Level/src/overlay/schema.py``; here only re-imports.--The ``overlay`` package resolves either from a real install (``pip install--e OS-Level``) or — fallback — from the in-repo ``OS-Level/src`` tree, which-this module puts on ``sys.path`` itself when the first import misses.-"""--from __future__ import annotations--import sys-from pathlib import Path--# Self-sufficient resolution of the OS-Level package (2026-07-06). The old-# comment claimed a lazy sys.path extension elsewhere — it never existed, so-# this import only worked on hosts with a manual ``pip install -e OS-Level``-# (the maintainer's interpreter). In a full repo checkout, fall back to-# putting ``OS-Level/src`` on sys.path; on a proper install the probe import-# succeeds and the fallback never runs.-try:- import overlay.schema # noqa: F401 — probe only-except ModuleNotFoundError:- _os_level_src = Path(__file__).resolve().parents[2] / "OS-Level" / "src"- if _os_level_src.is_dir() and str(_os_level_src) not in sys.path:- sys.path.append(str(_os_level_src))--from overlay.schema import ( # noqa: E402,F401 (re-exports)- AckEnvelope,- AckPayload,- ActionEndedEnvelope,- ActionEndedPayload,- ActionKindLiteral,- ActionStartedEnvelope,- ActionStartedPayload,- ClickButton,- ClickEnvelope,- ClickPayload,- ConfigEnvelope,- ConfigPayload,- CursorEnvelope,- CursorPayload,- ErrorEnvelope,- ErrorPayload,- HeartbeatEnvelope,- HeartbeatPayload,- IPCEnvelope,- IPCMessage,- MascotEventEnvelope,- MascotEventKind,- MascotEventPayload,- NON_STATE_TYPES,- SCHEMA_VERSION,- STATE_TYPES,- StateEnvelope,- StateName,- StatePayload,- StateReason,- Target,- is_state_type,- new_ulid,- now_ns,-)--__all__ = [- "AckEnvelope",- "AckPayload",- "ActionEndedEnvelope",- "ActionEndedPayload",- "ActionKindLiteral",- "ActionStartedEnvelope",- "ActionStartedPayload",- "ClickButton",- "ClickEnvelope",- "ClickPayload",- "ConfigEnvelope",- "ConfigPayload",- "CursorEnvelope",- "CursorPayload",- "ErrorEnvelope",- "ErrorPayload",- "HeartbeatEnvelope",- "HeartbeatPayload",- "IPCEnvelope",- "IPCMessage",- "MascotEventEnvelope",- "MascotEventKind",- "MascotEventPayload",- "NON_STATE_TYPES",- "SCHEMA_VERSION",- "STATE_TYPES",- "StateEnvelope",- "StateName",- "StatePayload",- "StateReason",- "Target",- "is_state_type",- "new_ulid",- "now_ns",-]diff --git a/jarvis/overlay/server.py b/jarvis/overlay/server.pydeleted file mode 100644index 45e7637809..0000000000--- a/jarvis/overlay/server.py+++ /dev/null@@ -1,81 +0,0 @@-"""WS IPC server for the main-Jarvis process.--Plan §10.5 + §20.3: the WS server binds to 127.0.0.1 + a free port from-``[overlay].ws_port..ws_port_range_max``. The bridge is the facade,-``websockets.serve()`` is the wire layer.-"""--from __future__ import annotations--import asyncio-import logging-from dataclasses import dataclass-from typing import Optional--import websockets-from websockets.asyncio.server import Server, serve--from jarvis.overlay.bridge import OverlayBridge--logger = logging.getLogger(__name__)---@dataclass-class IPCServerHandle:- """What ``start_ipc_server`` returns."""-- bridge: OverlayBridge- server: Server- host: str- port: int-- async def stop(self) -> None:- self.server.close()- await self.server.wait_closed()- await self.bridge.stop()---async def start_ipc_server(- *,- host: str = "127.0.0.1",- port: int = 7842,- port_range_max: int = 7852,- bridge: Optional[OverlayBridge] = None,- path: str = "/overlay",-) -> IPCServerHandle:- """Search for a free port in ``[port, port_range_max]`` and start the WS server.-- Plan constraint: ``host`` must be loopback (a Pydantic validator- enforces this at config load; checked defensively again here).-- ``path`` is deliberately not enforced — Plan §10 names- ``/overlay`` as the convention; the ``websockets`` library handler,- however, sees all URIs under the bind host. We only do path- filtering in the bridge handler if needed (currently not).- """- if host not in {"127.0.0.1", "::1", "localhost"}:- raise ValueError(f"WS server must bind to loopback, host={host!r}")- if port_range_max < port:- raise ValueError(f"port_range_max < port ({port_range_max} < {port})")-- bridge = bridge or OverlayBridge()- await bridge.start()-- last_err: Optional[BaseException] = None- for candidate in range(port, port_range_max + 1):- try:- server = await serve(bridge.handler, host, candidate)- except OSError as exc:- last_err = exc- continue- logger.info("overlay WS-Server listening on ws://%s:%d%s", host, candidate, path)- return IPCServerHandle(bridge=bridge, server=server, host=host, port=candidate)-- # All ports taken.- await bridge.stop()- raise RuntimeError(- f"no free port in [{port}, {port_range_max}] (last={last_err!r})"- )---__all__ = ["IPCServerHandle", "start_ipc_server"]diff --git a/jarvis/overlay/supervisor.py b/jarvis/overlay/supervisor.pydeleted file mode 100644index bffb72a136..0000000000--- a/jarvis/overlay/supervisor.py+++ /dev/null@@ -1,461 +0,0 @@-"""``OverlaySupervisor`` — subprocess lifecycle. Plan §4.3 + AD-9 + AD-10.--Spawns the overlay subprocess under a Win32 job object with-``JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE``. The job handle stays in the-main-Jarvis process; on a main-Jarvis crash, Windows closes the-handle and kills the overlay as a job member within 1 s-(the Raymond Chen pattern).--Lifecycle::-- sup = OverlaySupervisor()- await sup.start()- sup.notify_heartbeat() # called by the IPC listener- ...- await sup.stop()--Restart backoff (AD-10)::-- delay = min(30, 0.5 * 2**failures) * jitter(0.8, 1.2)--Cap: 5 restarts within a 5-minute window. When the cap fires,-``cap_fired_callback`` is invoked (tray notification, disable switch).-Stable reset: after ``stable_reset_s`` (60 s) of uptime without a crash,-the failure counter is reset.--On non-Windows: the subprocess is spawned, but no job object is-wired up; auto-kill there only works via the explicit shutdown-in the stop() path. Phase-9.8 tests focus on Windows.-"""--from __future__ import annotations--import asyncio-import logging-import os-import random-import subprocess-import sys-import time-from collections import deque-from typing import Any, Callable, Optional--logger = logging.getLogger(__name__)---# AD-10 Defaults.-DEFAULT_HEARTBEAT_TIMEOUT_S: float = 3.0-DEFAULT_RESTART_CAP_COUNT: int = 5-DEFAULT_RESTART_CAP_WINDOW_S: float = 300.0 # 5 minutes-DEFAULT_STABLE_RESET_S: float = 60.0--# Plan AD-9: KILL_ON_JOB_CLOSE constant (Win32 winnt.h).-JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: int = 0x2000--# Plan requirement: subprocess args.-DEFAULT_OVERLAY_ENTRY: tuple[str, ...] = ("-m", "overlay")---CapFiredCallback = Callable[[], None]---def _backoff_delay(failures: int, *, rng: random.Random) -> float:- """AD-10 formula: ``min(30, 0.5 * 2**failures) * jitter(0.8, 1.2)``."""- base = min(30.0, 0.5 * (2 ** max(0, failures)))- jitter = rng.uniform(0.8, 1.2)- return max(0.05, base * jitter)---class OverlaySupervisor:- """Process manager for the overlay subprocess."""-- def __init__(- self,- *,- ws_port: int = 7842,- python_executable: Optional[str] = None,- entry_args: tuple[str, ...] = DEFAULT_OVERLAY_ENTRY,- env: Optional[dict[str, str]] = None,- heartbeat_timeout_s: float = DEFAULT_HEARTBEAT_TIMEOUT_S,- restart_cap_count: int = DEFAULT_RESTART_CAP_COUNT,- restart_cap_window_s: float = DEFAULT_RESTART_CAP_WINDOW_S,- stable_reset_s: float = DEFAULT_STABLE_RESET_S,- cap_fired_callback: Optional[CapFiredCallback] = None,- # Test hooks (production defaults are the real APIs):- spawn_fn: Optional[Callable[..., subprocess.Popen]] = None,- rng: Optional[random.Random] = None,- ) -> None:- self._ws_port = ws_port- self._python = python_executable or sys.executable- self._entry_args = tuple(entry_args)- self._env = env- self._heartbeat_timeout = heartbeat_timeout_s- self._cap_count = restart_cap_count- self._cap_window = restart_cap_window_s- self._stable_reset = stable_reset_s- self._cap_fired_callback = cap_fired_callback- self._spawn_fn = spawn_fn or self._default_spawn- self._rng = rng or random.Random()-- # Lifecycle-State (under _lock).- self._lock = asyncio.Lock()- self._proc: Optional[subprocess.Popen] = None- self._job_handle: Any = None # PyHANDLE auf Win32, None sonst- self._failures: int = 0- self._cap_active: bool = False- self._spawn_attempts: deque[float] = deque() # monotonic ts der letzten spawns- self._last_spawn_ts: float = 0.0- self._last_heartbeat_ts: float = 0.0- self._stop_requested: bool = False- self._monitor_task: Optional[asyncio.Task[Any]] = None-- # ------------------------------------------------------------------- # Public API- # -------------------------------------------------------------------- @property- def is_alive(self) -> bool:- return self._proc is not None and self._proc.poll() is None-- @property- def cap_active(self) -> bool:- """True when the 5-in-5-min cap has fired — auto-restart is paused."""- return self._cap_active-- @property- def failure_count(self) -> int:- return self._failures-- def notify_heartbeat(self) -> None:- """Sync API. Called by the WS listener when the overlay checks in."""- self._last_heartbeat_ts = time.monotonic()-- async def start(self) -> None:- """Idempotent. Spawnt Subprocess + startet Monitor-Task."""- async with self._lock:- if self.is_alive or self._monitor_task is not None:- return- self._stop_requested = False- self._failures = 0- self._cap_active = False- await self._spawn_locked()-- # Monitor-Task ausserhalb des Locks starten — er nimmt selbst- # den Lock.- self._monitor_task = asyncio.create_task(- self._monitor_loop(), name="overlay-supervisor-monitor"- )-- async def stop(self) -> None:- """Stops the monitor + subprocess. Idempotent."""- self._stop_requested = True- if self._monitor_task is not None:- self._monitor_task.cancel()- try:- await self._monitor_task- except (asyncio.CancelledError, Exception): # noqa: BLE001- pass- self._monitor_task = None-- async with self._lock:- await self._terminate_locked()-- def manual_reset(self) -> None:- """User klickt Tray -> 'Overlay neu aktivieren'. Cap-State weg."""- self._cap_active = False- self._failures = 0- self._spawn_attempts.clear()-- async def force_respawn(self) -> None:- """Voice-driven recovery: clear cap-state and force a fresh spawn.-- Idempotent. Mirrors ``manual_reset`` but also actively terminates- a (possibly hidden / hung) subprocess and re-spawns it in the- same critical section. Used by the ``respawn_mascot`` local-action- tool so the user can say "Hey Jarvis, Maskottchen wieder- auftauchen" and get the overlay back even when the subprocess is- still alive but invisible. Sub-agent processes (start_overlay- never called) should not reach this — the tool guards on the- singleton.- """- async with self._lock:- self._cap_active = False- self._failures = 0- self._spawn_attempts.clear()- await self._terminate_locked()- await self._spawn_locked()-- # ------------------------------------------------------------------- # Internals- # -------------------------------------------------------------------- def _default_spawn(self, args: list[str], **popen_kwargs: Any) -> subprocess.Popen:- return subprocess.Popen(args, **popen_kwargs)-- def _build_args(self) -> list[str]:- base = [self._python, *self._entry_args]- base.append(f"--ws-port={self._ws_port}")- return base-- def _build_creationflags(self) -> int:- """Plan requirement: CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW."""- if sys.platform != "win32":- return 0- # subprocess constants (also via creationflags bits from winbase.h).- CREATE_NEW_PROCESS_GROUP = 0x00000200- CREATE_NO_WINDOW = 0x08000000- return CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW-- def _build_env(self) -> dict[str, str]:- """Subprocess env: parent inherit + JARVIS_DEPTH unset/0 so the- overlay is not recognized as a sub-agent."""- env = dict(os.environ)- if self._env is not None:- env.update(self._env)- # The overlay process itself is NOT a sub-agent.- env.pop("JARVIS_DEPTH", None)- return env-- async def _spawn_locked(self) -> None:- """Spawns the subprocess + binds it to the job object. The lock must be held."""- if self._cap_active:- logger.warning("Supervisor: cap active, no auto-spawn")- return-- now = time.monotonic()- # Cap check (rolling 5-min window).- self._spawn_attempts.append(now)- cutoff = now - self._cap_window- while self._spawn_attempts and self._spawn_attempts[0] < cutoff:- self._spawn_attempts.popleft()- if len(self._spawn_attempts) > self._cap_count:- logger.error(- "Supervisor: cap fired (%d restarts in %.0f s) - auto-restart off",- len(self._spawn_attempts),- self._cap_window,- )- self._cap_active = True- if self._cap_fired_callback is not None:- try:- self._cap_fired_callback()- except Exception: # noqa: BLE001- logger.exception("cap_fired_callback raised")- return-- args = self._build_args()- creationflags = self._build_creationflags()- env = self._build_env()-- # Stderr to a file instead of DEVNULL: otherwise subprocess crashes- # are invisible (no log). Append mode, so all restarts land in the- # same file — the user/agent can do forensics after a crash.- # The data/ directory is in .gitignore.- from pathlib import Path- log_dir = Path("data")- log_dir.mkdir(parents=True, exist_ok=True)- stderr_path = log_dir / "overlay-stderr.log"- try:- stderr_handle = open(stderr_path, "ab", buffering=0) # noqa: SIM115- except OSError as exc:- logger.warning(- "Supervisor: stderr-log open failed (%s), falling back to DEVNULL",- exc,- )- stderr_handle = subprocess.DEVNULL-- try:- proc = self._spawn_fn(- args,- creationflags=creationflags,- env=env,- close_fds=False, # the job handle must be inheritable — must NOT be closed- stdin=subprocess.DEVNULL,- stdout=subprocess.DEVNULL,- stderr=stderr_handle,- )- except Exception: # noqa: BLE001- logger.exception("Supervisor spawn failed")- self._failures += 1- return-- self._proc = proc- self._last_spawn_ts = now- self._last_heartbeat_ts = now # Initial-Grace: 1 Heartbeat-Period-- # Plan AD-9: job object via pywin32. The test path passes a- # spawn_fn that can skip the hooking (proc is then a- # MagicMock).- if sys.platform == "win32" and not _is_mock_proc(proc):- try:- self._assign_to_job(proc.pid)- except Exception: # noqa: BLE001- logger.exception("Job-Object assign failed (continuing)")-- logger.info(- "Supervisor: spawned PID=%s args=%s",- getattr(proc, "pid", "?"),- args,- )-- def _assign_to_job(self, pid: int) -> None:- """Plan AD-9: CreateJobObject + SetInformationJobObject +- AssignProcessToJobObject."""- # Lazy-import pywin32 so non-Windows hosts don't crash.- import win32api- import win32con- import win32job-- if self._job_handle is None:- # Job-Handle ist non-inheritable (Plan AD-9).- sa = None # NULL SecurityAttributes -> default inheritability=False- self._job_handle = win32job.CreateJobObject(sa, "")- # JOBOBJECT_EXTENDED_LIMIT_INFORMATION.BasicLimitInformation- # .LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.- info = win32job.QueryInformationJobObject(- self._job_handle, win32job.JobObjectExtendedLimitInformation- )- info["BasicLimitInformation"]["LimitFlags"] |= (- JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE- )- win32job.SetInformationJobObject(- self._job_handle,- win32job.JobObjectExtendedLimitInformation,- info,- )-- # Process-Handle holen + assign.- PROCESS_SET_QUOTA = 0x0100- PROCESS_TERMINATE = 0x0001- proc_handle = win32api.OpenProcess(- PROCESS_SET_QUOTA | PROCESS_TERMINATE, False, pid- )- try:- win32job.AssignProcessToJobObject(self._job_handle, proc_handle)- finally:- win32api.CloseHandle(proc_handle)-- async def _terminate_locked(self) -> None:- """Kills the subprocess + closes the job handle. The lock must be held."""- proc = self._proc- if proc is not None and proc.poll() is None:- try:- proc.terminate()- # Plan §4.3: shutdown should take effect within 1 s.- try:- await asyncio.wait_for(- asyncio.to_thread(proc.wait), timeout=1.5- )- except asyncio.TimeoutError:- proc.kill()- try:- await asyncio.wait_for(- asyncio.to_thread(proc.wait), timeout=1.0- )- except asyncio.TimeoutError:- logger.warning(- "Supervisor: proc PID=%s not killable", proc.pid- )- except Exception: # noqa: BLE001- logger.exception("Subprocess terminate failed")-- self._proc = None-- # Close the job handle — KILL_ON_JOB_CLOSE automatically kills- # all job members (including children of the overlay).- if self._job_handle is not None:- try:- import win32api-- win32api.CloseHandle(self._job_handle)- except Exception: # noqa: BLE001- logger.debug("Job-Handle close failed", exc_info=True)- self._job_handle = None-- async def _monitor_loop(self) -> None:- """Heartbeat-Watcher + Auto-Restart-Driver."""- try:- while not self._stop_requested:- await asyncio.sleep(0.5)- if self._stop_requested:- return-- async with self._lock:- proc = self._proc- cap_active = self._cap_active-- if cap_active:- continue-- now = time.monotonic()-- # Stable reset (AD-10): if proc is alive AND- # last_spawn > stable_reset_s, then failures=0.- if (- proc is not None- and proc.poll() is None- and (now - self._last_spawn_ts) >= self._stable_reset- and self._failures > 0- ):- logger.debug("Supervisor: stable uptime -> reset failures")- self._failures = 0-- # Heartbeat timeout: if proc is alive but no heartbeat- # for 3 s -> kill + respawn.- if proc is not None and proc.poll() is None:- last_hb = self._last_heartbeat_ts or now- if (now - last_hb) > self._heartbeat_timeout:- logger.warning(- "Supervisor: heartbeat-timeout (%.1fs) -> kill+respawn",- now - last_hb,- )- async with self._lock:- await self._terminate_locked()- await self._restart_with_backoff()- continue-- # Process died / never started -> respawn.- if proc is None or proc.poll() is not None:- await self._restart_with_backoff()-- except asyncio.CancelledError:- return-- async def _restart_with_backoff(self) -> None:- """AD-10 Backoff-Delay + spawn."""- if self._stop_requested:- return- async with self._lock:- if self._cap_active:- return- self._failures += 1- delay = _backoff_delay(self._failures - 1, rng=self._rng)- logger.info(- "Supervisor: restart in %.2f s (failures=%d)", delay, self._failures- )- try:- await asyncio.sleep(delay)- except asyncio.CancelledError:- return- if self._stop_requested:- return- async with self._lock:- await self._spawn_locked()---def _is_mock_proc(proc: Any) -> bool:- """Test helper: a MagicMock has no real pid. We detect this- by the type name so we can skip the job hooking without- needing pywin32 in tests."""- return type(proc).__module__.startswith("unittest.mock")---__all__ = [- "DEFAULT_HEARTBEAT_TIMEOUT_S",- "DEFAULT_OVERLAY_ENTRY",- "DEFAULT_RESTART_CAP_COUNT",- "DEFAULT_RESTART_CAP_WINDOW_S",- "DEFAULT_STABLE_RESET_S",- "JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE",- "OverlaySupervisor",- "_backoff_delay",-]diff --git a/jarvis/overlay/triggers.py b/jarvis/overlay/triggers.pydeleted file mode 100644index 1c6e8f8bbc..0000000000--- a/jarvis/overlay/triggers.py+++ /dev/null@@ -1,327 +0,0 @@-"""Trigger API for the main Jarvis action path. Plan §8.--Three ways to instrument actions:- 1. ``@overlay_action(kind, duration_hint_ms=...)`` — decorator for- async functions.- 2. ``@overlay_action_sync(kind, duration_hint_ms=...)`` — same- semantics for sync functions.- 3. ``async with overlay_action_scope(kind, duration_hint_ms=...)`` —- context manager for inline use.--Plan §8.4 decorator contract:-- Emit ``action_started`` event BEFORE the function call.-- Emit ``action_ended`` event AFTER the function call (in finally — also- on exception).-- On exception: ADDITIONALLY emit ``error`` event with recoverable=True.--Sub-agent behavior (Plan §8.7): when ``JARVIS_DEPTH > 0``, the-decorator logic still fires — but the OverlayBridge instance is a-no-op stub, so events go into the void. Caller code is structurally-unaware of this.--Current action kinds (Plan §8.2):--| ActionKind | Trigger-Source |-|-------------------|------------------------------------------|-| CLICK | pyautogui.click, Browser-Use click |-| TYPING | pyautogui.typewrite, Browser-Use type |-| MOVE | pyautogui.moveTo (mit duration > 0) |-| NAVIGATE | Browser-Use navigation |-| HOTKEY | pyautogui.hotkey |-| SCROLL | pyautogui.scroll |-"""--from __future__ import annotations--import asyncio-import functools-import logging-import time-from contextlib import asynccontextmanager, contextmanager-from enum import Enum-from typing import Any, AsyncIterator, Awaitable, Callable, Iterator, Optional, TypeVar--logger = logging.getLogger(__name__)--F = TypeVar("F", bound=Callable[..., Any])---class ActionKind(str, Enum):- """Derived from Plan §6.1 — what triggers the glow."""-- CLICK = "click"- TYPING = "type" # Plan §6.3 wire string is 'type', not 'typing'- MOVE = "move"- NAVIGATE = "navigate"- HOTKEY = "hotkey"- SCROLL = "scroll"- BROWSER = "navigate" # backward-compat alias for Phase-9.1 code---# AP-23 W2-C: names of optional overlay dependencies we've already warned-# about in this process, so a hot loop of keyboard/mouse calls on a host-# missing the dependency logs once, not on every call.-_missing_overlay_dep_logged: set[str] = set()---def _get_bridge() -> Any:- """Lazy lookup of the singleton to avoid circular imports.-- In tests the singleton is set via ``jarvis.overlay.set_overlay()``.- In production it is resolved on the first decorator call via the- ``get_overlay()`` accessor.-- When None: the decorator falls back to a very lightweight no-op stub- that simply runs the function.-- Honest degrade (AP-23): resolving ``get_overlay`` pulls in the whole- overlay bridge chain (``.integration`` -> ``.bridge`` -> ``.schema`` ->- the OS-Level overlay package -> ``ulid``). On a host missing an optional- overlay dependency (e.g. a fresh clone without ``python-ulid``, or- without the OS-Level package at all), that import raises- ``ModuleNotFoundError``. Without this guard it escaped straight out of- the decorator into the caller's keyboard/mouse tool action — crashing a- real user action over a purely cosmetic overlay dependency. Degrade to- ``None`` instead: the decorator already treats ``bridge is None`` as- "run the function, skip the overlay visuals" (see- ``test_sync_decorator_no_bridge_is_no_op``).- """- try:- from jarvis.overlay import get_overlay # spaet importieren- except ModuleNotFoundError as exc:- missing = exc.name or "unknown"- if missing not in _missing_overlay_dep_logged:- _missing_overlay_dep_logged.add(missing)- logger.warning(- "Desktop overlay unavailable: dependency %r missing — "- "overlay/mascot visuals stay off, but the underlying "- "keyboard/mouse action still runs.",- missing,- )- return None-- return get_overlay()---def overlay_action(- kind: ActionKind | str,- *,- duration_hint_ms: Optional[int] = None,-) -> Callable[[F], F]:- """Async-Decorator. Plan §8.4 Contract."""-- kind_str = kind.value if isinstance(kind, ActionKind) else str(kind)-- def decorator(fn: F) -> F:- @functools.wraps(fn)- async def wrapper(*args: Any, **kwargs: Any) -> Any:- bridge = _get_bridge()- start_ns = time.monotonic_ns()- action_id = ""- if bridge is not None:- try:- action_id = bridge.emit_action_started(- kind_str, duration_hint_ms=duration_hint_ms- )- except Exception: # noqa: BLE001- logger.exception("overlay_action emit_started raised")- try:- return await fn(*args, **kwargs)- except Exception as exc:- if bridge is not None:- try:- bridge.emit_error(- f"{type(exc).__name__}: {exc}",- recoverable=True,- )- except Exception: # noqa: BLE001- logger.debug("overlay_action emit_error failed", exc_info=True)- raise- finally:- if bridge is not None and action_id:- duration_ms = max(- 0, (time.monotonic_ns() - start_ns) // 1_000_000- )- try:- bridge.emit_action_ended(- action_id,- succeeded=True,- duration_actual_ms=int(duration_ms),- )- except Exception: # noqa: BLE001- logger.debug("overlay_action emit_ended failed", exc_info=True)-- return wrapper # type: ignore[return-value]-- return decorator---def overlay_action_sync(- kind: ActionKind | str,- *,- duration_hint_ms: Optional[int] = None,-) -> Callable[[F], F]:- """Sync decorator. Plan §8.4 contract.-- Same semantics as ``overlay_action``, but without ``await``. Applied- to pyautogui wrappers in jarvis/control/{mouse,keyboard}.py —- pyautogui itself is synchronous.- """-- kind_str = kind.value if isinstance(kind, ActionKind) else str(kind)-- def decorator(fn: F) -> F:- @functools.wraps(fn)- def wrapper(*args: Any, **kwargs: Any) -> Any:- bridge = _get_bridge()- start_ns = time.monotonic_ns()- action_id = ""- if bridge is not None:- try:- action_id = bridge.emit_action_started(- kind_str, duration_hint_ms=duration_hint_ms- )- except Exception: # noqa: BLE001- logger.exception("overlay_action_sync emit_started raised")- try:- return fn(*args, **kwargs)- except Exception as exc:- if bridge is not None:- try:- bridge.emit_error(- f"{type(exc).__name__}: {exc}",- recoverable=True,- )- except Exception: # noqa: BLE001- logger.debug(- "overlay_action_sync emit_error failed", exc_info=True- )- raise- finally:- if bridge is not None and action_id:- duration_ms = max(- 0, (time.monotonic_ns() - start_ns) // 1_000_000- )- try:- bridge.emit_action_ended(- action_id,- succeeded=True,- duration_actual_ms=int(duration_ms),- )- except Exception: # noqa: BLE001- logger.debug(- "overlay_action_sync emit_ended failed", exc_info=True- )-- return wrapper # type: ignore[return-value]-- return decorator---@asynccontextmanager-async def overlay_action_scope(- kind: ActionKind | str,- *,- duration_hint_ms: Optional[int] = None,-) -> AsyncIterator[str]:- """Async context manager. Plan §8.5 contract.-- Yields the ``action_id`` so the caller can, for example,- reference it via ``emit_click(...)``.-- Example::-- async with overlay_action_scope(ActionKind.TYPING, duration_hint_ms=2000):- await asyncio.to_thread(pyautogui.typewrite, text)- """- kind_str = kind.value if isinstance(kind, ActionKind) else str(kind)- bridge = _get_bridge()- action_id = ""- start_ns = time.monotonic_ns()- if bridge is not None:- try:- action_id = bridge.emit_action_started(- kind_str, duration_hint_ms=duration_hint_ms- )- except Exception: # noqa: BLE001- logger.exception("overlay_action_scope emit_started raised")- try:- yield action_id- except Exception as exc:- if bridge is not None:- try:- bridge.emit_error(- f"{type(exc).__name__}: {exc}",- recoverable=True,- )- except Exception: # noqa: BLE001- logger.debug("overlay_action_scope emit_error failed", exc_info=True)- raise- finally:- if bridge is not None and action_id:- duration_ms = max(0, (time.monotonic_ns() - start_ns) // 1_000_000)- try:- bridge.emit_action_ended(- action_id,- succeeded=True,- duration_actual_ms=int(duration_ms),- )- except Exception: # noqa: BLE001- logger.debug("overlay_action_scope emit_ended failed", exc_info=True)---@contextmanager-def overlay_action_scope_sync(- kind: ActionKind | str,- *,- duration_hint_ms: Optional[int] = None,-) -> Iterator[str]:- """Sync context manager. Plan §8.5 — for sync callers that are not- in an async loop."""- kind_str = kind.value if isinstance(kind, ActionKind) else str(kind)- bridge = _get_bridge()- action_id = ""- start_ns = time.monotonic_ns()- if bridge is not None:- try:- action_id = bridge.emit_action_started(- kind_str, duration_hint_ms=duration_hint_ms- )- except Exception: # noqa: BLE001- logger.exception("overlay_action_scope_sync emit_started raised")- try:- yield action_id- except Exception as exc:- if bridge is not None:- try:- bridge.emit_error(- f"{type(exc).__name__}: {exc}",- recoverable=True,- )- except Exception: # noqa: BLE001- logger.debug(- "overlay_action_scope_sync emit_error failed", exc_info=True- )- raise- finally:- if bridge is not None and action_id:- duration_ms = max(0, (time.monotonic_ns() - start_ns) // 1_000_000)- try:- bridge.emit_action_ended(- action_id,- succeeded=True,- duration_actual_ms=int(duration_ms),- )- except Exception: # noqa: BLE001- logger.debug(- "overlay_action_scope_sync emit_ended failed", exc_info=True- )---__all__ = [- "ActionKind",- "overlay_action",- "overlay_action_scope",- "overlay_action_scope_sync",- "overlay_action_sync",-]diff --git a/jarvis/overlay/virtual_cursor.py b/jarvis/overlay/virtual_cursor.pyindex 30d59f08d3..4d3eb76a7e 100644--- a/jarvis/overlay/virtual_cursor.py+++ b/jarvis/overlay/virtual_cursor.py@@ -12,9 +12,8 @@ unit-tested on a headless CI box and on a €5 VPS:* :class:`NullVirtualCursor` — a no-op that absorbs every call, so a missingdisplay (headless VPS, cloud-first doctrine) can never break a real click.* :func:`get_virtual_cursor` / :func:`set_virtual_cursor` — the singleton- accessor, mirroring the existing ``get_cursor_streamer`` / ``get_overlay``- pattern so the low-level mouse tools can fire an indicator from anywhere- without threading the EventBus through ``ExecutionContext``.+ accessor pattern, so the low-level mouse tools can fire an indicator from+ anywhere without threading the EventBus through ``ExecutionContext``.The actual Tk window that renders the halo + pulse lives in``ui/orb/virtual_cursor_window.py`` and registers itself here viadiff --git a/jarvis/plugins/tool/respawn_mascot.py b/jarvis/plugins/tool/respawn_mascot.pydeleted file mode 100644index 8aa0db1e2a..0000000000--- a/jarvis/plugins/tool/respawn_mascot.py+++ /dev/null@@ -1,74 +0,0 @@-"""``respawn_mascot`` — voice-driven recovery for a lost / hidden mascot.--Mirrors :mod:`jarvis.plugins.tool.reset_orb_position` (ADR-0016 L2): when-the user says "Maskottchen wieder auftauchen", "respawn mascot", "der # i18n-allow (quotes DE voice-trigger phrases matched by the local-action gate)-Spawner" etc., the local-action gate dispatches this tool. It clears the-``OverlaySupervisor``'s cap-state and forces a fresh subprocess spawn so-the mascot reappears even when the prior subprocess was hidden, hung, or-cap-fired (BUG-012 class).--Risk tier: ``safe``. Only mutates the in-process overlay subprocess-lifecycle. Plausibility / approval surface is the local-action gate-regex layer (anchored ``^...$`` patterns against a tight phrase list).-"""-from __future__ import annotations--from typing import Any--from jarvis.core.protocols import ExecutionContext, ToolResult---class RespawnMascotTool:- """Force a fresh OverlaySupervisor subprocess spawn."""-- name: str = "respawn_mascot"- risk_tier: str = "safe"- description: str = (- "Brings the mascot / overlay spawner back by clearing the "- "OverlaySupervisor cap state and spawning a fresh subprocess "- "(voice recovery for the BUG-012 class)."- )- schema: dict[str, Any] = {- "type": "object",- "properties": {},- "required": [],- }-- async def execute(- self, args: dict[str, Any], ctx: ExecutionContext- ) -> ToolResult:- del args, ctx # tool is parameterless- try:- from jarvis.overlay.integration import get_overlay_supervisor- except Exception as exc: # noqa: BLE001- return ToolResult(- success=False,- output=None,- error=f"overlay integration not importable: {exc!r}",- )-- supervisor = get_overlay_supervisor()- if supervisor is None:- return ToolResult(- success=False,- output="Maskottchen-Overlay ist nicht aktiv.", # i18n-allow (DE TTS voice-confirmation phrase spoken back to the user)- error="overlay supervisor not initialised",- )-- try:- await supervisor.force_respawn()- except Exception as exc: # noqa: BLE001- return ToolResult(- success=False,- output=None,- error=f"force_respawn failed: {exc!r}",- )-- return ToolResult(- success=True,- output="Maskottchen ist wieder da.", # i18n-allow (DE TTS voice-confirmation phrase spoken back to the user)- error=None,- )---__all__ = ["RespawnMascotTool"]diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.pyindex a343089572..28cb571085 100644--- a/jarvis/ui/web/launcher.py+++ b/jarvis/ui/web/launcher.py@@ -648,45 +648,6 @@ async def _run_headless(args) -> int:# first request WAIT, which the functional smoke proves).asyncio.create_task(_build_brain_bg(), name="brain-build")- # Phase 9.8: start the overlay subprocess when [overlay].enabled=true.- # No-op when disabled or JARVIS_DEPTH>0 (sub-agent).- # Bus is passed so mascot-originated user events (mute toggle on- # doubleClick) can be republished on the EventBus where the voice- # pipeline subscribes.- # Orb overlay is a desktop-only extra (separate `overlay` package). On a- # headless / cloud base install it isn't present — skip it cleanly so the- # server still boots (cloud-first). The no-op stubs keep the shutdown path- # (stop_overlay, below) valid. start_overlay itself no-ops when disabled.- try:- from jarvis.overlay.integration import start_overlay, stop_overlay- except ModuleNotFoundError as exc:- import logging as _overlay_logging-- _overlay_log = _overlay_logging.getLogger(__name__)- if exc.name == "overlay":- # Genuinely headless: the optional overlay package itself isn't- # installed (cloud/VPS base install). Quiet — expected.- _overlay_log.debug(- "Overlay bootstrap skipped: optional overlay package not installed."- )- else:- # AP-23 W2-C: some OTHER import in the overlay chain is missing- # (e.g. `python-ulid`) — this is a real, fixable dependency gap,- # not "no overlay package". Log it honestly instead of silently- # collapsing into the same "headless" bucket.- _overlay_log.warning(- "Overlay bootstrap skipped: overlay dependency %r missing.",- exc.name,- )-- async def start_overlay(*_a: object, **_k: object) -> None: # type: ignore[misc]- return None-- async def stop_overlay(*_a: object, **_k: object) -> None: # type: ignore[misc]- return None-- await start_overlay(bus=server.bus)-# (BOOT_READY was already emitted the moment the bootstrap server began# serving — the full app built above warms up behind it.)@@ -745,7 +706,6 @@ async def _run_headless(args) -> int:try:await stop_event.wait()finally:- await stop_overlay() # Phase 9.8: Overlay sauber beenden BEVOR server.stop# Stop the fast-boot bootstrap server (it owns the listening socket)._bootstrap_server.should_exit = Truetry:diff --git a/pyproject.toml b/pyproject.tomlindex b2c8a0bd77..f9a196e8e5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -23,13 +23,6 @@ dependencies = ["pydantic>=2.9,<3.0","pydantic-settings>=2.6","pyyaml>=6.0",- # Desktop overlay/mascot IPC wire IDs (jarvis/overlay + OS-Level/src/overlay- # schema.py `from ulid import ULID`). Small pure-Python, platform-universal- # package — was previously declared ONLY in OS-Level's own egg-info, so a- # fresh clone without the maintainer's manual `pip install -e OS-Level`- # raised `ModuleNotFoundError: ulid` the first time any keyboard/mouse tool- # action ran (AP-23).- "python-ulid>=2.2","structlog>=24.4","loguru>=0.7","keyring>=25.5",diff --git a/requirements.in b/requirements.inindex 10291866da..bf15ce540f 100644--- a/requirements.in+++ b/requirements.in@@ -32,11 +32,6 @@ pydantic>=2.9,<3.0pydantic-settings>=2.6pyyaml>=6.0-# Desktop overlay/mascot IPC wire IDs (jarvis/overlay + OS-Level/src/overlay-# schema.py `from ulid import ULID`). Small pure-Python, platform-universal-# package. See pyproject.toml note.-python-ulid>=2.2-# Loggingstructlog>=24.4loguru>=0.7diff --git a/requirements.txt b/requirements.txtindex 7a6384ec65..947c58e717 100644--- a/requirements.txt+++ b/requirements.txt@@ -1582,10 +1582,6 @@ python-telegram-bot==22.8 \--hash=sha256:42373918097f1b837cc4e717d588c19ea79651497ec712bb5b0c76e5e63c50e1 \--hash=sha256:f9d3847fcb23ee603477e442800b33bb4adf851a73e0619d2050be879decf1ef# via -r requirements.in-python-ulid==3.1.0 \- --hash=sha256:e2cdc979c8c877029b4b7a38a6fba3bc4578e4f109a308419ff4d3ccf0a46619 \- --hash=sha256:ff0410a598bc5f6b01b602851a3296ede6f91389f913a5d5f8c496003836f636- # via -r requirements.inpywin32==312 ; sys_platform == 'win32' \--hash=sha256:02ebca0f0242b75292e218065004310d6a477407c09fa449bfe4f6022bc0c0fc \--hash=sha256:17948aeadbdb091f0ced6ef0841620794e68327b94ee415571c1203594b7215c \diff --git a/scripts/ci/privacy_gate/references/distribution-denylist.txt b/scripts/ci/privacy_gate/references/distribution-denylist.txtindex dde4b2e9cf..be233ad956 100644--- a/scripts/ci/privacy_gate/references/distribution-denylist.txt+++ b/scripts/ci/privacy_gate/references/distribution-denylist.txt@@ -168,8 +168,9 @@ video/**# jarvis/plugins/tool/search_web.py (no sys.path/loader points here)# DELIBERATELY KEPT (verified load-bearing, do NOT add): board-backend/# (jarvis/board/sync.py + federation_proxy_routes.py import board_backend.crypto),-# OS-Level/ (jarvis/overlay/schema.py re-exports OS-Level/src/overlay), ui/-# (the Orb overlay is imported at runtime), conductor/ (3 import sites).+# ui/ (the Orb overlay is imported at runtime), conductor/ (3 import sites).+# (OS-Level/ was removed from the repo in 2026-07 — the CU screen indicator+# in jarvis/cu/indicator replaced its edge-glow.)skillbook/**keyproxy/**src/**diff --git a/tests/overlay/__init__.py b/tests/overlay/__init__.pydeleted file mode 100644index e69de29bb2..0000000000diff --git a/tests/overlay/__visual__/.gitkeep b/tests/overlay/__visual__/.gitkeepdeleted file mode 100644index e69de29bb2..0000000000diff --git a/tests/overlay/conftest.py b/tests/overlay/conftest.pydeleted file mode 100644index 252d55c6ff..0000000000--- a/tests/overlay/conftest.py+++ /dev/null@@ -1,71 +0,0 @@-"""Pytest setup for ``tests/overlay/``.--- Path extension: put ``OS-Level/src`` on ``sys.path`` so ``import overlay`` works.-- Headless Qt: ``QT_QPA_PLATFORM=offscreen`` unless already set.-"""--from __future__ import annotations--import os-import sys-from pathlib import Path--import pytest--REPO_ROOT = Path(__file__).resolve().parents[2]-OS_LEVEL_SRC = REPO_ROOT / "OS-Level" / "src"--# These tests exercise the ABANDONED PySide6 overlay tree under OS-Level/src-# (see docs/plans/cross-platform-mac-linux/ADR-orb-framework.md — the LIVE orb-# is the Tk package ui/orb/overlay.py). Many modules `import overlay` at module-# scope, which would crash collection on a box without PySide6 (e.g. the Linux-# CI leg, which installs only the base deps). Gate the whole dir on PySide6 so-# collection stays clean and the Wave-0 min-passed floor is honest (sub-task 0.7).-import importlib.util as _ilu--_HAS_PYSIDE = _ilu.find_spec("PySide6") is not None--if _HAS_PYSIDE and str(OS_LEVEL_SRC) not in sys.path:- sys.path.insert(0, str(OS_LEVEL_SRC))--# Qt headless — doesn't hurt if a test doesn't need it.-os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")---# Wave-2 cross-platform tests that exercise the LIVE Tk orb seam + fakes (not the-# abandoned PySide6 tree). They must collect on EVERY leg — including a Linux CI-# leg without PySide6 — so they are exempt from the PySide6 gate below.-_PYSIDE_INDEPENDENT = frozenset(- {- "conftest.py",- "test_overlay_surface.py",- "test_tray_surface.py",- }-)---def pytest_ignore_collect(collection_path, config): # noqa: ARG001- """Skip the PySide6-overlay tests entirely when PySide6 is absent.-- Without PySide6 their module-scope ``import overlay`` would error collection;- ignoring them keeps the Linux CI leg clean rather than polluting the floor- with a collection failure. The live Tk orb is covered elsewhere.-- The Wave-2 ``OverlaySurface`` tests (``_PYSIDE_INDEPENDENT``) are exempt —- they drive the live Tk orb seam through fakes and do not import PySide6, so- they must collect on every leg.- """- if _HAS_PYSIDE:- return None- if collection_path.name in _PYSIDE_INDEPENDENT:- return False- return True--[email protected](scope="session")-def qapp():- """Single QApplication per session. PySide6 only allows one instance."""- pyside = pytest.importorskip("PySide6.QtWidgets")- app = pyside.QApplication.instance() or pyside.QApplication([])- yield app- # NO app.quit() — that would kill subsequent tests.diff --git a/tests/overlay/test_bridge.py b/tests/overlay/test_bridge.pydeleted file mode 100644index 33c1b134a0..0000000000--- a/tests/overlay/test_bridge.py+++ /dev/null@@ -1,167 +0,0 @@-"""OverlayBridge — Singleton + emit_methods + Backpressure."""--from __future__ import annotations--import asyncio--import pytest--from jarvis.overlay.bridge import OverlayBridge, _BoundedOutbox-from jarvis.overlay.schema import (- ActionEndedEnvelope,- ActionStartedEnvelope,- ClickEnvelope,- ErrorEnvelope,- StateEnvelope,-)---# --------------------------------------------------------------------------# Bounded-Outbox Drop-Policy-# ----------------------------------------------------------------------------def test_outbox_drops_oldest_non_state_when_full() -> None:- box = _BoundedOutbox(maxsize=3)- box.put("click", b"c1")- box.put("click", b"c2")- box.put("click", b"c3")- # Full. Next click: c1 gets dropped.- box.put("click", b"c4")- assert box.dropped == 1- assert len(box) == 3---def test_outbox_state_messages_are_protected() -> None:- box = _BoundedOutbox(maxsize=3)- box.put("state", b"s1")- box.put("click", b"c1")- box.put("click", b"c2")- box.put("click", b"c3")- # Full. Click pushes in -> oldest non-state (c1) drops out.- # state s1 STAYS.- assert box.dropped == 1- assert len(box) == 3---async def test_outbox_get_blocks_until_item() -> None:- box = _BoundedOutbox()- fetched = []-- async def consumer() -> None:- item = await box.get()- fetched.append(item)-- task = asyncio.create_task(consumer())- await asyncio.sleep(0.05)- assert fetched == []- box.put("click", b"hello")- await task- assert fetched == [b"hello"]---# --------------------------------------------------------------------------# emit_state / emit_action_started / emit_action_ended / emit_click /-# emit_error — all produce correctly schema'd envelopes on the queue.-# ----------------------------------------------------------------------------async def test_emit_state_produces_state_envelope() -> None:- bridge = OverlayBridge()- await bridge.start()- try:- bridge.emit_state("listening", reason="wakeword")- raw = await bridge.outbox.get()- env = StateEnvelope.model_validate_json(raw)- assert env.payload.state == "listening"- assert env.payload.reason == "wakeword"- finally:- await bridge.stop()---async def test_emit_action_started_returns_action_id() -> None:- bridge = OverlayBridge()- await bridge.start()- try:- action_id = bridge.emit_action_started("click", duration_hint_ms=100)- assert isinstance(action_id, str)- assert len(action_id) > 0- raw = await bridge.outbox.get()- env = ActionStartedEnvelope.model_validate_json(raw)- assert env.payload.kind == "click"- assert env.payload.action_id == action_id- assert env.payload.duration_hint_ms == 100- finally:- await bridge.stop()---async def test_emit_action_ended_with_action_id() -> None:- bridge = OverlayBridge()- await bridge.start()- try:- bridge.emit_action_ended(- "01HZX000000000000000000000",- succeeded=False,- duration_actual_ms=42,- )- raw = await bridge.outbox.get()- env = ActionEndedEnvelope.model_validate_json(raw)- assert env.payload.action_id == "01HZX000000000000000000000"- assert env.payload.succeeded is False- assert env.payload.duration_actual_ms == 42- finally:- await bridge.stop()---async def test_emit_click_produces_click_envelope() -> None:- bridge = OverlayBridge()- await bridge.start()- try:- bridge.emit_click(100, 200, monitor="0", button="right")- raw = await bridge.outbox.get()- env = ClickEnvelope.model_validate_json(raw)- assert env.payload.x == 100- assert env.payload.y == 200- assert env.payload.monitor == "0"- assert env.payload.button == "right"- finally:- await bridge.stop()---async def test_emit_error_produces_error_envelope() -> None:- bridge = OverlayBridge()- await bridge.start()- try:- bridge.emit_error(- "TimeoutError: pyautogui hung",- recoverable=True,- context={"action_id": "abc"},- )- raw = await bridge.outbox.get()- env = ErrorEnvelope.model_validate_json(raw)- assert env.payload.message == "TimeoutError: pyautogui hung"- assert env.payload.recoverable is True- assert env.payload.context == {"action_id": "abc"}- finally:- await bridge.stop()---async def test_state_emit_caches_last_state_envelope() -> None:- """§10.5 Resync — last state envelope is sent first on reconnect."""- bridge = OverlayBridge()- await bridge.start()- try:- bridge.emit_state("typing")- await bridge.outbox.get() # consume- last = bridge.last_state_envelope- assert last is not None- assert last.payload.state == "typing"- finally:- await bridge.stop()diff --git a/tests/overlay/test_capture_affinity.py b/tests/overlay/test_capture_affinity.pydeleted file mode 100644index c64aee5d30..0000000000--- a/tests/overlay/test_capture_affinity.py+++ /dev/null@@ -1,170 +0,0 @@-"""Capture-affinity reapply on show + screenChanged. Plan §18.1."""--from __future__ import annotations--from unittest import mock--import pytest--pytest.importorskip("PySide6.QtWidgets")---def test_reapply_capture_affinity_calls_set_window_display_affinity(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """Plan §18.1: reapply_capture_affinity() must fire- SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE)."""- from overlay import transparency-- fake_user32 = mock.MagicMock()- fake_user32.SetWindowDisplayAffinity.return_value = 1-- monkeypatch.setattr(transparency, "_is_windows", lambda: True)- monkeypatch.setattr(transparency, "get_user32", lambda: fake_user32)-- result = transparency.reapply_capture_affinity(0xDEAD)- assert result is True- fake_user32.SetWindowDisplayAffinity.assert_called_once()- args, _ = fake_user32.SetWindowDisplayAffinity.call_args- # First arg is the HWND wrapper, second the WDA_EXCLUDEFROMCAPTURE wrapper.- assert int(args[1].value) == transparency.WDA_EXCLUDEFROMCAPTURE---def test_reapply_capture_affinity_noop_on_non_windows(- monkeypatch: pytest.MonkeyPatch,-) -> None:- from overlay import transparency-- monkeypatch.setattr(transparency, "_is_windows", lambda: False)- assert transparency.reapply_capture_affinity(0xDEAD) is False---# --------------------------------------------------------------------------# Window-Hooks: showEvent + screenChanged-Reapply-# ----------------------------------------------------------------------------def test_edge_glow_window_calls_exclude_from_capture_on_show(- qapp, monkeypatch: pytest.MonkeyPatch-) -> None:- """Plan §18.1: showEvent must call exclude_from_capture."""- from PySide6.QtGui import QGuiApplication-- from overlay import window_glow-- captured = []- monkeypatch.setattr(- window_glow, "exclude_from_capture", lambda hwnd: captured.append(hwnd)- )-- primary = QGuiApplication.primaryScreen()- win = window_glow.EdgeGlowWindow(primary, hide_from_capture=True)- try:- win.show()- qapp.processEvents()- assert len(captured) >= 1- finally:- win.close()- win.deleteLater()---def test_edge_glow_window_skips_affinity_when_disabled(- qapp, monkeypatch: pytest.MonkeyPatch-) -> None:- from PySide6.QtGui import QGuiApplication-- from overlay import window_glow-- called = []- monkeypatch.setattr(- window_glow, "exclude_from_capture", lambda hwnd: called.append(hwnd)- )-- primary = QGuiApplication.primaryScreen()- win = window_glow.EdgeGlowWindow(primary, hide_from_capture=False)- try:- win.show()- qapp.processEvents()- assert called == []- finally:- win.close()- win.deleteLater()---def test_edge_glow_screen_change_reapplies_affinity(- qapp, monkeypatch: pytest.MonkeyPatch-) -> None:- """Plan §18.1: screenChanged must call reapply_capture_affinity."""- from PySide6.QtGui import QGuiApplication-- from overlay import window_glow-- reapplied = []- monkeypatch.setattr(- window_glow,- "reapply_capture_affinity",- lambda hwnd: reapplied.append(hwnd),- )-- primary = QGuiApplication.primaryScreen()- win = window_glow.EdgeGlowWindow(primary, hide_from_capture=True)- try:- win.show()- qapp.processEvents()- # Direct call to the handler — we can't reliably trigger the Qt- # screenChanged signal in the offscreen-platform test.- win._on_screen_changed(primary)- assert len(reapplied) == 1- finally:- win.close()- win.deleteLater()---def test_mascot_screen_change_reapplies_affinity(- qapp, monkeypatch: pytest.MonkeyPatch-) -> None:- from overlay import window_mascot-- reapplied = []- monkeypatch.setattr(- window_mascot,- "reapply_capture_affinity",- lambda hwnd: reapplied.append(hwnd),- )-- win = window_mascot.MascotWindow(- initial_x=100,- initial_y=100,- monitor_name="X",- hide_from_capture=True,- )- try:- win.show()- qapp.processEvents()- win._on_screen_changed(None)- assert len(reapplied) == 1- finally:- win.close()- win.deleteLater()---def test_set_view_visible_toggles_webview(qapp) -> None:- """Plan §17.3 — Hide-on-Idle 5min must pass set_view_visible(False)- through to the WebView."""- from PySide6.QtGui import QGuiApplication-- from overlay import window_glow-- primary = QGuiApplication.primaryScreen()- win = window_glow.EdgeGlowWindow(primary, hide_from_capture=False)- try:- win.show()- qapp.processEvents()- assert win._view.isVisible() is True- win.set_view_visible(False)- assert win._view.isVisible() is False- win.set_view_visible(True)- assert win._view.isVisible() is True- finally:- win.close()- win.deleteLater()diff --git a/tests/overlay/test_config.py b/tests/overlay/test_config.pydeleted file mode 100644index 472191988a..0000000000--- a/tests/overlay/test_config.py+++ /dev/null@@ -1,75 +0,0 @@-"""OverlayConfig — Pydantic Round-Trip + from_toml."""--from __future__ import annotations--import textwrap-from pathlib import Path--import pytest--from overlay.config import OverlayConfig, OverlayMascotConfig, OverlayThemeConfig---def test_defaults_round_trip() -> None:- cfg = OverlayConfig()- data = cfg.model_dump()- rebuilt = OverlayConfig.model_validate(data)- assert rebuilt == cfg---def test_theme_defaults() -> None:- theme = OverlayThemeConfig()- assert theme.yellow_primary == "#FFC700"- assert theme.glow_width_px == 14---def test_invalid_hex_color() -> None:- with pytest.raises(ValueError):- OverlayThemeConfig(yellow_primary="not-a-color")---def test_invalid_loopback_host() -> None:- with pytest.raises(ValueError):- OverlayConfig(ws_host="8.8.8.8")---def test_extra_field_rejected() -> None:- with pytest.raises(ValueError):- OverlayConfig.model_validate({"unknown_key": True})---def test_mascot_size_clamp() -> None:- with pytest.raises(ValueError):- OverlayMascotConfig(size_px=10)- with pytest.raises(ValueError):- OverlayMascotConfig(size_px=999)---def test_from_toml_with_section(tmp_path: Path) -> None:- toml = tmp_path / "jarvis.toml"- toml.write_text(- textwrap.dedent(- """- [overlay]- enabled = false- all_monitors = true- ws_port = 7900-- [overlay.theme]- glow_width_px = 20- """- ),- encoding="utf-8",- )- cfg = OverlayConfig.from_toml(toml)- assert cfg.enabled is False- assert cfg.all_monitors is True- assert cfg.ws_port == 7900- assert cfg.theme.glow_width_px == 20---def test_from_toml_missing_section_uses_defaults(tmp_path: Path) -> None:- toml = tmp_path / "jarvis.toml"- toml.write_text("[other]\nkey = 1\n", encoding="utf-8")- cfg = OverlayConfig.from_toml(toml)- assert cfg == OverlayConfig()diff --git a/tests/overlay/test_cursor_glide.py b/tests/overlay/test_cursor_glide.pydeleted file mode 100644index 5d002dfa0e..0000000000--- a/tests/overlay/test_cursor_glide.py+++ /dev/null@@ -1,79 +0,0 @@-"""glide_cursor — drives the real OS cursor along an eased path.--This is the piece that makes "the mouse visibly travels to where it clicks"-true. It is fully dependency-injected (set_pos / get_pos / notify / sleep) so-it can be tested without touching Win32 or a real display.-"""-from __future__ import annotations--from jarvis.overlay.virtual_cursor import glide_cursor---def _recorder():- calls: list[tuple[int, int]] = []- return calls, lambda x, y: calls.append((x, y))---def test_glide_moves_real_cursor_and_ends_on_target() -> None:- moves, set_pos = _recorder()- glide_cursor(- 200, 80, start=(0, 0), duration_s=0.1, hz=60,- set_pos=set_pos, sleep=lambda _s: None,- )- assert moves[-1] == (200, 80)- assert len(moves) > 1 # actually animated, not a teleport---def test_glide_notifies_overlay_for_every_point() -> None:- moves, set_pos = _recorder()- pings, notify = _recorder()- glide_cursor(- 100, 0, start=(0, 0), duration_s=0.1, hz=60,- set_pos=set_pos, notify=notify, sleep=lambda _s: None,- )- assert pings == moves # overlay highlight tracks the real cursor exactly---def test_glide_instant_when_duration_zero_is_single_landing() -> None:- moves, set_pos = _recorder()- glide_cursor(- 50, 50, start=(0, 0), duration_s=0.0,- set_pos=set_pos, sleep=lambda _s: None,- )- assert moves == [(50, 50)]---def test_glide_uses_get_pos_when_start_omitted() -> None:- moves, set_pos = _recorder()- glide_cursor(- 10, 10, get_pos=lambda: (10, 10), duration_s=0.2,- set_pos=set_pos, sleep=lambda _s: None,- )- # Start == target: nothing to travel, lands once on the target.- assert moves[-1] == (10, 10)---def test_glide_survives_a_raising_notify() -> None:- moves, set_pos = _recorder()-- def boom(_x: int, _y: int) -> None:- raise RuntimeError("overlay thread is dead")-- # A broken overlay must never stop the real cursor from reaching its- # target — the click still has to land.- glide_cursor(- 99, 1, start=(0, 0), duration_s=0.1, hz=60,- set_pos=set_pos, notify=boom, sleep=lambda _s: None,- )- assert moves[-1] == (99, 1)---def test_glide_sleeps_between_frames_not_after_last() -> None:- moves, set_pos = _recorder()- sleeps: list[float] = []- glide_cursor(- 100, 0, start=(0, 0), duration_s=0.1, hz=60,- set_pos=set_pos, sleep=lambda s: sleeps.append(s),- )- # One sleep fewer than points: we never sleep after the final landing.- assert len(sleeps) == len(moves) - 1diff --git a/tests/overlay/test_cursor_motion.py b/tests/overlay/test_cursor_motion.pydeleted file mode 100644index d5872d1268..0000000000--- a/tests/overlay/test_cursor_motion.py+++ /dev/null@@ -1,104 +0,0 @@-"""glide_os_cursor — thin Win32 adapter that glides the real cursor.--The win32 ``GetCursorPos`` / ``SetCursorPos`` calls and ``sleep`` are-injectable so the orchestration is testable off-Windows and without a real-cursor. It bridges :func:`glide_cursor` to the installed virtual-cursor-overlay (``get_virtual_cursor().show_path_point``).-"""-from __future__ import annotations--import pytest--from jarvis.control.cursor_motion import glide_os_cursor-from jarvis.overlay.virtual_cursor import NullVirtualCursor, set_virtual_cursor---class _RecordingCursor(NullVirtualCursor):- def __init__(self) -> None:- self.points: list[tuple[int, int]] = []-- def show_path_point(self, x: int, y: int) -> None:- self.points.append((x, y))--[email protected](autouse=True)-def _reset_singleton():- set_virtual_cursor(None)- yield- set_virtual_cursor(None)---def test_glide_os_cursor_lands_on_target() -> None:- moves: list[tuple[int, int]] = []- glide_os_cursor(- 300, 120,- get_pos=lambda: (0, 0),- set_pos=lambda x, y: moves.append((x, y)),- sleep=lambda _s: None,- duration_ms=100,- )- assert moves[-1] == (300, 120)---def test_glide_os_cursor_feeds_the_installed_overlay() -> None:- rec = _RecordingCursor()- set_virtual_cursor(rec)- moves: list[tuple[int, int]] = []- glide_os_cursor(- 100, 0,- get_pos=lambda: (0, 0),- set_pos=lambda x, y: moves.append((x, y)),- sleep=lambda _s: None,- duration_ms=100,- )- assert rec.points == moves # highlight tracks the real cursor---def test_set_glide_ms_controls_default_duration() -> None:- from jarvis.control import cursor_motion-- original = cursor_motion._resolve_glide_ms()- try:- cursor_motion.set_glide_ms(0)- moves: list[tuple[int, int]] = []- glide_os_cursor(- 7, 7,- get_pos=lambda: (0, 0),- set_pos=lambda x, y: moves.append((x, y)),- sleep=lambda _s: None,- )- assert moves == [(7, 7)] # 0 ms default => instant landing- finally:- cursor_motion.set_glide_ms(original)---def test_glide_os_cursor_zero_duration_is_instant() -> None:- moves: list[tuple[int, int]] = []- glide_os_cursor(- 42, 42,- get_pos=lambda: (0, 0),- set_pos=lambda x, y: moves.append((x, y)),- sleep=lambda _s: None,- duration_ms=0,- )- assert moves == [(42, 42)]---def test_win_set_pos_does_not_raise_on_unreliable_zero_return(monkeypatch) -> None:- """Regression (CU clicks void on the LEFT monitor): SetCursorPos returns 0- (reports failure) yet STILL moves the cursor when crossing into a monitor- positioned left of primary — negative virtual-desktop X. The old- ``if not SetCursorPos(): raise`` turned that spurious 0 into a hard error that- aborted every left-monitor click. _win_set_pos must trust the move and NOT- raise on the boolean."""- from jarvis.control import cursor_motion-- calls: list[tuple[int, int]] = []-- def _fake_raw(x: int, y: int) -> int:- calls.append((x, y))- return 0 # SetCursorPos "failure" return — must be ignored-- monkeypatch.setattr(cursor_motion, "_raw_set_cursor", _fake_raw)- cursor_motion._win_set_pos(-1280, 720) # negative X, must not raise- assert calls == [(-1280, 720)]diff --git a/tests/overlay/test_cursor_shm.py b/tests/overlay/test_cursor_shm.pydeleted file mode 100644index 7fa344bb8d..0000000000--- a/tests/overlay/test_cursor_shm.py+++ /dev/null@@ -1,205 +0,0 @@-"""Cursor SHM round-trip — Plan §11 layout + seqlock.--1000-frame producer/consumer test with two threads. Verifies:- - Layout constants (32 bytes, struct format).- - Writer publishes correctly (seq monotonic, even after write).- - Reader cleanly skips torn reads (no mixed frame).- - Reader sees nothing after writer close (block possibly gone).-"""--from __future__ import annotations--import struct-import threading-import time--import pytest--from overlay.cursor_shm import (- CURSOR_SHM_SIZE,- CURSOR_SHM_STRUCT,- CursorFrame,- CursorShmReader,- CursorShmWriter,- make_cursor_shm_name,-)---# --------------------------------------------------------------------------# Constants-# ----------------------------------------------------------------------------def test_layout_size_is_32_bytes() -> None:- assert CURSOR_SHM_SIZE == 32---def test_struct_format_packs_to_32() -> None:- assert struct.calcsize(CURSOR_SHM_STRUCT) == CURSOR_SHM_SIZE---def test_make_name_is_unique_pattern() -> None:- a = make_cursor_shm_name()- b = make_cursor_shm_name()- assert a.startswith("jarvis-cursor-")- assert b.startswith("jarvis-cursor-")- assert a != b- # 8 hex chars suffix.- assert len(a) == len("jarvis-cursor-") + 8---# --------------------------------------------------------------------------# Reader/Writer Single-Step-# ----------------------------------------------------------------------------def test_writer_first_write_yields_seq_2() -> None:- """Plan §11.4: ``_seq`` starts at 0, first frame ends with seq=2."""- w = CursorShmWriter.create()- try:- seq = w.write(100, 200, 0)- assert seq == 2- assert w.seq == 2- finally:- w.close()---def test_reader_returns_none_when_no_data_yet() -> None:- w = CursorShmWriter.create()- try:- r = CursorShmReader.attach(w.name)- try:- assert r.read() is None # seq=0 -> never published yet- finally:- r.close()- finally:- w.close()---def test_round_trip_single_frame() -> None:- w = CursorShmWriter.create()- try:- r = CursorShmReader.attach(w.name)- try:- w.write(123, 456, 1)- frame = r.read()- assert frame is not None- assert isinstance(frame, CursorFrame)- assert frame.x == 123- assert frame.y == 456- assert frame.monitor_idx == 1- assert frame.seq == 2- assert frame.ts_ns > 0- finally:- r.close()- finally:- w.close()---def test_reader_returns_none_on_no_new_seq() -> None:- w = CursorShmWriter.create()- try:- r = CursorShmReader.attach(w.name)- try:- w.write(1, 1, 0)- assert r.read() is not None- # read again without a new write -> None.- assert r.read() is None- finally:- r.close()- finally:- w.close()---# --------------------------------------------------------------------------# Producer/consumer threading stress (1000 frames, no torn read)-# ----------------------------------------------------------------------------def test_thousand_frames_no_torn_read() -> None:- """Plan §11.3: the reader must NEVER see a half-written frame.-- We write 1000 frames with predictable values (x = i, y = i*2,- monitor = i % 4) and verify reader-side that every frame read- is internally consistent (y == 2*x, monitor == x % 4).- """- w = CursorShmWriter.create()- received: list[CursorFrame] = []- stop = threading.Event()-- def producer() -> None:- for i in range(1, 1001):- w.write(i, i * 2, i % 4)- # no sleep — we want a tight loop to force- # race conditions.-- def consumer() -> None:- r = CursorShmReader.attach(w.name)- try:- # Poll until producer is done; possibly a few extra frames.- poll_count = 0- while not stop.is_set() or poll_count < 10:- f = r.read()- if f is not None:- received.append(f)- else:- if stop.is_set():- poll_count += 1- finally:- r.close()-- consumer_thread = threading.Thread(target=consumer)- consumer_thread.start()- try:- producer()- finally:- # A bit of time so the consumer still collects the last frames,- # then stop.- time.sleep(0.05)- stop.set()- consumer_thread.join(timeout=2.0)-- # We CANNOT guarantee that all 1000 frames were read- # (the reader is slower than the writer, frames get overwritten). What- # we DO guarantee: every frame READ is internally consistent AND- # the sequence is monotonically increasing.- assert len(received) > 0- last_seq = 0- for f in received:- assert f.y == 2 * f.x, f"torn frame: x={f.x} y={f.y} expected y={2*f.x}"- assert f.monitor_idx == f.x % 4, (- f"torn frame: x={f.x} monitor={f.monitor_idx}"- )- assert f.seq > last_seq, f"non-monotonic seq: {f.seq} <= {last_seq}"- last_seq = f.seq-- w.close()---# --------------------------------------------------------------------------# Mid-write Detection-# ----------------------------------------------------------------------------def test_reader_skips_odd_seq_mid_write() -> None:- """Manual pin: set seq to odd -> reader returns None."""- w = CursorShmWriter.create()- try:- r = CursorShmReader.attach(w.name)- try:- # First publish cleanly- w.write(10, 20, 0)- assert r.read() is not None # seq=2 is now last_seq-- # Manually set odd seq — busy marker.- struct.pack_into("<I", w._buf, 16, 3) # noqa: SLF001 — test reads private buf- assert r.read() is None- finally:- r.close()- finally:- w.close()---def test_attach_to_missing_block_raises() -> None:- with pytest.raises(FileNotFoundError):- CursorShmReader.attach("jarvis-cursor-nonexistent")diff --git a/tests/overlay/test_cursor_writer.py b/tests/overlay/test_cursor_writer.pydeleted file mode 100644index a7a93aeb39..0000000000--- a/tests/overlay/test_cursor_writer.py+++ /dev/null@@ -1,228 +0,0 @@-"""Main-Jarvis-side CursorStreamer + mouse.py hook.--Tests:- - Writer writes correctly into the SHM (layout-symmetric to the reader side).- - Streamer only polls while ``streaming=True``.- - mouse.click/move_to/scroll trigger start_streaming/stop_streaming- when a streamer is set.-"""--from __future__ import annotations--import sys-import time-import types-from typing import Iterator-from unittest import mock--import pytest--from jarvis.overlay.cursor_writer import (- CURSOR_SHM_SIZE,- CURSOR_SHM_STRUCT,- CursorShmWriter,- CursorStreamer,-)-from overlay.cursor_shm import CursorShmReader---# --------------------------------------------------------------------------# Layout symmetry: writer from jarvis.overlay writes, reader from-# OS-Level reads -> both sides must know the same struct format.-# ----------------------------------------------------------------------------def test_writer_layout_constants_match_reader() -> None:- from overlay.cursor_shm import (- CURSOR_SHM_SIZE as READER_SIZE,- CURSOR_SHM_STRUCT as READER_STRUCT,- )-- assert CURSOR_SHM_SIZE == READER_SIZE- assert CURSOR_SHM_STRUCT == READER_STRUCT---def test_writer_round_trip_to_reader() -> None:- """Main-Jarvis writer + OS-Level reader symmetric."""- w = CursorShmWriter.create()- try:- r = CursorShmReader.attach(w.name)- try:- w.write(42, 84, 2)- frame = r.read()- assert frame is not None- assert frame.x == 42- assert frame.y == 84- assert frame.monitor_idx == 2- assert frame.seq == 2- finally:- r.close()- finally:- w.close()---# --------------------------------------------------------------------------# CursorStreamer Lifecycle-# ----------------------------------------------------------------------------def streamer() -> Iterator[CursorStreamer]:- """Streamer with a fake position reader (no pyautogui call)."""- state = {"x": 100, "y": 200}-- def fake_pos() -> tuple[int, int]:- # Moves the cursor by +1 each tick, so the reader- # actually sees changes.- state["x"] += 1- state["y"] += 2- return state["x"], state["y"]-- s = CursorStreamer.create(hz=120, position_reader=fake_pos)- try:- yield s- finally:- s.shutdown()---def test_streamer_does_not_write_when_not_streaming(- streamer: CursorStreamer,-) -> None:- r = CursorShmReader.attach(streamer.name)- try:- # Wait 50 ms — no writes expected (start_streaming- # not called).- time.sleep(0.05)- assert r.read() is None- # Internal writer seq should be 0.- assert streamer.writer.seq == 0- finally:- r.close()---def test_streamer_writes_during_streaming(streamer: CursorStreamer) -> None:- r = CursorShmReader.attach(streamer.name)- try:- streamer.start_streaming(monitor_idx=1)- # 80 ms @ 120 Hz = ~9 frames; plenty.- time.sleep(0.08)- streamer.stop_streaming()-- seen = []- for _ in range(20):- f = r.read()- if f is not None:- seen.append(f)- if len(seen) >= 2:- break- time.sleep(0.005)-- assert len(seen) >= 1- # Frames must have monitor_idx=1.- for f in seen:- assert f.monitor_idx == 1- finally:- r.close()---def test_streamer_idempotent_start(streamer: CursorStreamer) -> None:- streamer.start_streaming()- streamer.start_streaming()- streamer.start_streaming()- assert streamer.is_streaming is True- streamer.stop_streaming()- assert streamer.is_streaming is False---# --------------------------------------------------------------------------# mouse.py hook: click/move_to trigger the streamer-# ----------------------------------------------------------------------------def fake_pyautogui(monkeypatch: pytest.MonkeyPatch) -> mock.MagicMock:- """Fake pyautogui module via sys.modules."""- fake = types.ModuleType("pyautogui")- fake.click = mock.MagicMock() # type: ignore[attr-defined]- fake.moveTo = mock.MagicMock() # type: ignore[attr-defined]- fake.scroll = mock.MagicMock() # type: ignore[attr-defined]- fake.position = mock.MagicMock(return_value=(50, 75)) # type: ignore[attr-defined]- monkeypatch.setitem(sys.modules, "pyautogui", fake)- return fake---def test_click_triggers_streamer_start_stop(- fake_pyautogui: mock.MagicMock,-) -> None:- from jarvis.control import mouse-- streamer = CursorStreamer.create(- hz=240, position_reader=lambda: (10, 20)- )- try:- mouse.set_cursor_streamer(streamer)- try:- assert streamer.is_streaming is False- mouse.click(x=100, y=200, monitor_idx=1)- # After click, streaming is off again (stop was called).- assert streamer.is_streaming is False- # pyautogui.click was called.- fake_pyautogui.click.assert_called_once_with(- x=100, y=200, button="left", clicks=1, interval=0.0- )- finally:- mouse.set_cursor_streamer(None)- finally:- streamer.shutdown()---def test_move_to_streams_during_animation(- fake_pyautogui: mock.MagicMock,-) -> None:- """Verifies that start_streaming is called BEFORE pyautogui.moveTo."""- from jarvis.control import mouse-- call_order: list[str] = []-- streamer = CursorStreamer.create(- hz=240, position_reader=lambda: (1, 1)- )-- # Wrap start/stop/moveTo so we can observe order.- orig_start = streamer.start_streaming- orig_stop = streamer.stop_streaming-- def tracked_start(**kwargs: object) -> None:- call_order.append("start")- orig_start(**kwargs) # type: ignore[arg-type]-- def tracked_stop() -> None:- call_order.append("stop")- orig_stop()-- streamer.start_streaming = tracked_start # type: ignore[method-assign]- streamer.stop_streaming = tracked_stop # type: ignore[method-assign]-- fake_pyautogui.moveTo.side_effect = lambda **kwargs: call_order.append("moveTo")-- try:- mouse.set_cursor_streamer(streamer)- try:- mouse.move_to(500, 600, duration=0.0, monitor_idx=0)- finally:- mouse.set_cursor_streamer(None)- finally:- streamer.shutdown()-- # Expected order: start, moveTo, stop.- assert call_order == ["start", "moveTo", "stop"], call_order---def test_no_streamer_no_op(fake_pyautogui: mock.MagicMock) -> None:- """When no streamer is set, mouse.click still runs- cleanly through (headless / production without overlay)."""- from jarvis.control import mouse-- mouse.set_cursor_streamer(None)- mouse.click(x=1, y=2)- fake_pyautogui.click.assert_called_once()diff --git a/tests/overlay/test_e2e_kill_parent.py b/tests/overlay/test_e2e_kill_parent.pydeleted file mode 100644index cd05db183d..0000000000--- a/tests/overlay/test_e2e_kill_parent.py+++ /dev/null@@ -1,126 +0,0 @@-"""E2E job-object kill-parent. Plan AD-9 — Main-Jarvis crash kills the overlay.--Strategy: we start a "parent process" that spawns a "child process"-and attaches it to a job object with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.-Then we hard taskkill the parent and assert that the child is also-gone within 1 s.--Windows-only — a skip on other platforms.-"""--from __future__ import annotations--import os-import subprocess-import sys-import textwrap-import time--import pytest--if sys.platform != "win32":- pytest.skip("Job object is Windows-only", allow_module_level=True)--try:- import psutil # noqa: F401-except ImportError: # pragma: no cover- pytest.skip("psutil required for process watch", allow_module_level=True)---PARENT_SCRIPT = textwrap.dedent("""- import os- import subprocess- import sys- import time-- import win32api # type: ignore[import-not-found]- import win32con # type: ignore[import-not-found]- import win32job # type: ignore[import-not-found]-- JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000-- # Spawn child: runs for 30 s.- child = subprocess.Popen(- [sys.executable, "-c", "import time; time.sleep(30)"]- )-- # Set up the job object.- job = win32job.CreateJobObject(None, "")- info = win32job.QueryInformationJobObject(- job, win32job.JobObjectExtendedLimitInformation- )- info["BasicLimitInformation"]["LimitFlags"] |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE- win32job.SetInformationJobObject(- job, win32job.JobObjectExtendedLimitInformation, info- )-- PROCESS_SET_QUOTA = 0x0100- PROCESS_TERMINATE = 0x0001- proc_h = win32api.OpenProcess(- PROCESS_SET_QUOTA | PROCESS_TERMINATE, False, child.pid- )- win32job.AssignProcessToJobObject(job, proc_h)- win32api.CloseHandle(proc_h)-- # Print the child's PID so the test can watch it.- sys.stdout.write(str(child.pid) + chr(10))- sys.stdout.flush()-- # Endless loop so the test can kill us.- while True:- time.sleep(1)-""")---def test_kill_parent_kills_child_within_one_second() -> None:- """Plan AD-9: KILL_ON_JOB_CLOSE guarantees no zombies."""- import psutil-- # Spawn the parent.- parent = subprocess.Popen(- [sys.executable, "-c", PARENT_SCRIPT],- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- text=True,- )-- try:- # First line = child PID.- line = parent.stdout.readline().strip()- try:- child_pid = int(line)- except ValueError:- pytest.fail(f"Parent did not print a child PID: {line!r}")- assert psutil.pid_exists(child_pid), f"child PID {child_pid} not present"-- # Hard-kill the parent via taskkill /F.- subprocess.run(- ["taskkill", "/F", "/PID", str(parent.pid), "/T"],- check=False,- capture_output=True,- )-- # Plan AD-9: child should be gone within 1 s.- deadline = time.monotonic() + 2.0- while time.monotonic() < deadline:- if not psutil.pid_exists(child_pid):- # done.- child_exit_time = time.monotonic()- # 1 s is the plan spec; +500ms tolerance for test slack- assert True- return- time.sleep(0.05)- pytest.fail(- f"child PID {child_pid} is still alive 2 s after parent kill — "- "job object did not kill it"- )- finally:- # Cleanup parent (if still alive).- try:- parent.terminate()- parent.wait(timeout=2)- except (subprocess.TimeoutExpired, OSError):- try:- parent.kill()- except OSError:- passdiff --git a/tests/overlay/test_event_router.py b/tests/overlay/test_event_router.pydeleted file mode 100644index 20c2a1a478..0000000000--- a/tests/overlay/test_event_router.py+++ /dev/null@@ -1,233 +0,0 @@-"""EventRouter — Plan §6.3 Mapping IPC -> State-Transition."""--from __future__ import annotations--import pytest--from overlay.event_router import (- CLICKING_KINDS,- EventRouter,- REASON_ERROR,- REASON_TOOL,- TYPING_KINDS,-)-from overlay.schema import (- AckEnvelope,- AckPayload,- ActionEndedEnvelope,- ActionEndedPayload,- ActionStartedEnvelope,- ActionStartedPayload,- ClickEnvelope,- ClickPayload,- ConfigEnvelope,- ConfigPayload,- CursorEnvelope,- CursorPayload,- ErrorEnvelope,- ErrorPayload,- HeartbeatEnvelope,- HeartbeatPayload,- StateEnvelope,- StatePayload,-)-from overlay.state import OverlayState, StateMachine---def machine() -> StateMachine:- return StateMachine()---def router(machine: StateMachine) -> EventRouter:- return EventRouter(machine)---# --------------------------------------------------------------------------# StateEnvelope — direkter Pass-Through-# ----------------------------------------------------------------------------def test_state_envelope_transitions(- router: EventRouter, machine: StateMachine-) -> None:- env = StateEnvelope(payload=StatePayload(state="listening", reason="wakeword"))- assert router.handle(env) is True- assert machine.state is OverlayState.LISTENING---def test_state_envelope_passes_reason_through(- router: EventRouter, machine: StateMachine-) -> None:- captured: list[str | None] = []- machine.subscribe(lambda _o, _n, r: captured.append(r))-- env = StateEnvelope(payload=StatePayload(state="thinking", reason="tool"))- router.handle(env)- assert captured == ["tool"]---def test_state_envelope_no_reason(router: EventRouter, machine: StateMachine) -> None:- captured: list[str | None] = []- machine.subscribe(lambda _o, _n, r: captured.append(r))-- env = StateEnvelope(payload=StatePayload(state="speaking"))- assert router.handle(env) is True- assert captured == [None]---# --------------------------------------------------------------------------# ActionStartedEnvelope — kind -> bucket-# ---------------------------------------------------------------------------[email protected]("kind", sorted(TYPING_KINDS))-def test_action_started_typing_kinds(- kind: str, router: EventRouter, machine: StateMachine-) -> None:- env = ActionStartedEnvelope(payload=ActionStartedPayload(kind=kind)) # type: ignore[arg-type]- assert router.handle(env) is True- assert machine.state is OverlayState.TYPING--[email protected]("kind", sorted(CLICKING_KINDS))-def test_action_started_clicking_kinds(- kind: str, router: EventRouter, machine: StateMachine-) -> None:- env = ActionStartedEnvelope(payload=ActionStartedPayload(kind=kind)) # type: ignore[arg-type]- assert router.handle(env) is True- assert machine.state is OverlayState.CLICKING---def test_action_started_uses_tool_reason(- router: EventRouter, machine: StateMachine-) -> None:- captured: list[str | None] = []- machine.subscribe(lambda _o, _n, r: captured.append(r))-- env = ActionStartedEnvelope(payload=ActionStartedPayload(kind="type"))- router.handle(env)- assert captured == [REASON_TOOL]---# --------------------------------------------------------------------------# ActionEndedEnvelope -> IDLE-# ----------------------------------------------------------------------------def test_action_ended_returns_to_idle(- router: EventRouter, machine: StateMachine-) -> None:- machine.transition_to(OverlayState.TYPING)- env = ActionEndedEnvelope(- payload=ActionEndedPayload(action_id="01HZX000000000000000000000")- )- assert router.handle(env) is True- assert machine.state is OverlayState.IDLE---# --------------------------------------------------------------------------# ClickEnvelope -> CLICKING-# ----------------------------------------------------------------------------def test_click_envelope_transitions_to_clicking(- router: EventRouter, machine: StateMachine-) -> None:- env = ClickEnvelope(payload=ClickPayload(x=100, y=200))- assert router.handle(env) is True- assert machine.state is OverlayState.CLICKING---# --------------------------------------------------------------------------# ErrorEnvelope-# ----------------------------------------------------------------------------def test_error_recoverable_transitions_to_error(- router: EventRouter, machine: StateMachine-) -> None:- captured: list[str | None] = []- machine.subscribe(lambda _o, _n, r: captured.append(r))-- env = ErrorEnvelope(- payload=ErrorPayload(code="boom", message="x", recoverable=True)- )- assert router.handle(env) is True- assert machine.state is OverlayState.ERROR- assert captured == [REASON_ERROR]---def test_error_non_recoverable_is_noop(- router: EventRouter, machine: StateMachine-) -> None:- env = ErrorEnvelope(- payload=ErrorPayload(code="fatal", message="x", recoverable=False)- )- assert router.handle(env) is False- assert machine.state is OverlayState.IDLE---# --------------------------------------------------------------------------# No-Op Envelopes-# ----------------------------------------------------------------------------def test_heartbeat_is_noop(router: EventRouter, machine: StateMachine) -> None:- env = HeartbeatEnvelope(payload=HeartbeatPayload())- assert router.handle(env) is False- assert machine.state is OverlayState.IDLE---def test_cursor_is_noop(router: EventRouter, machine: StateMachine) -> None:- env = CursorEnvelope(payload=CursorPayload(x=1, y=2))- assert router.handle(env) is False---def test_config_is_noop(router: EventRouter, machine: StateMachine) -> None:- env = ConfigEnvelope(payload=ConfigPayload())- assert router.handle(env) is False---def test_ack_is_noop(router: EventRouter, machine: StateMachine) -> None:- env = AckEnvelope(payload=AckPayload(ack_id="01HZX000000000000000000000"))- assert router.handle(env) is False---def test_unknown_envelope_is_noop(router: EventRouter, machine: StateMachine) -> None:- """When something foreign is pushed through, no crash, just False."""-- class _Foreign:- pass-- assert router.handle(_Foreign()) is False- assert machine.state is OverlayState.IDLE---# --------------------------------------------------------------------------# Sequenz-Test-# ----------------------------------------------------------------------------def test_typical_voice_sequence(router: EventRouter, machine: StateMachine) -> None:- """Plan §6.2: idle -> listening -> thinking -> typing -> idle -> speaking."""- seen: list[OverlayState] = [machine.state]- machine.subscribe(lambda _o, n, _r: seen.append(n))-- router.handle(StateEnvelope(payload=StatePayload(state="listening")))- router.handle(StateEnvelope(payload=StatePayload(state="thinking")))- router.handle(ActionStartedEnvelope(payload=ActionStartedPayload(kind="type")))- router.handle(- ActionEndedEnvelope(payload=ActionEndedPayload(action_id="01HZX000000000000000000000"))- )- router.handle(StateEnvelope(payload=StatePayload(state="speaking")))-- assert seen == [- OverlayState.IDLE,- OverlayState.LISTENING,- OverlayState.THINKING,- OverlayState.TYPING,- OverlayState.IDLE,- OverlayState.SPEAKING,- ]diff --git a/tests/overlay/test_fullscreen_detect.py b/tests/overlay/test_fullscreen_detect.pydeleted file mode 100644index 0b14cefca3..0000000000--- a/tests/overlay/test_fullscreen_detect.py+++ /dev/null@@ -1,150 +0,0 @@-"""FullscreenDetector — SHQueryUserNotificationState mocked. Plan §12.6."""--from __future__ import annotations--import threading-import time--from overlay.fullscreen_detect import (- FullscreenDetector,- UserNotificationState,- should_hide_for_state,-)---# --------------------------------------------------------------------------# should_hide_for_state — Mapping pro Plan §12.6-# ----------------------------------------------------------------------------def test_d3d_fullscreen_always_hides() -> None:- assert should_hide_for_state(- UserNotificationState.RUNNING_D3D_FULL_SCREEN,- ignore_busy_state=False,- )- assert should_hide_for_state(- UserNotificationState.RUNNING_D3D_FULL_SCREEN,- ignore_busy_state=True,- )---def test_presentation_mode_always_hides() -> None:- assert should_hide_for_state(- UserNotificationState.PRESENTATION_MODE, ignore_busy_state=False- )- assert should_hide_for_state(- UserNotificationState.PRESENTATION_MODE, ignore_busy_state=True- )---def test_busy_hides_only_when_not_ignored() -> None:- assert should_hide_for_state(- UserNotificationState.BUSY, ignore_busy_state=False- )- assert not should_hide_for_state(- UserNotificationState.BUSY, ignore_busy_state=True- )---def test_normal_states_do_not_hide() -> None:- for s in (- UserNotificationState.NOT_PRESENT,- UserNotificationState.ACCEPTS_NOTIFICATIONS,- UserNotificationState.QUIET_TIME,- UserNotificationState.APP,- ):- assert not should_hide_for_state(s, ignore_busy_state=False)- assert not should_hide_for_state(s, ignore_busy_state=True)---# --------------------------------------------------------------------------# FullscreenDetector — sync poll_once + callback only on change-# ----------------------------------------------------------------------------def test_callback_fires_on_first_poll() -> None:- fired = []- det = FullscreenDetector(- callback=lambda s: fired.append(s),- query_fn=lambda: UserNotificationState.NOT_PRESENT,- )- det.poll_once()- assert len(fired) == 1- assert fired[0].state is UserNotificationState.NOT_PRESENT- assert fired[0].should_hide is False---def test_callback_does_not_fire_when_state_unchanged() -> None:- fired = []- det = FullscreenDetector(- callback=lambda s: fired.append(s),- query_fn=lambda: UserNotificationState.NOT_PRESENT,- )- det.poll_once()- det.poll_once()- det.poll_once()- assert len(fired) == 1---def test_callback_fires_on_state_transition() -> None:- fired = []- states = [- UserNotificationState.NOT_PRESENT,- UserNotificationState.RUNNING_D3D_FULL_SCREEN,- UserNotificationState.NOT_PRESENT,- ]- iter_states = iter(states)- det = FullscreenDetector(- callback=lambda s: fired.append(s),- query_fn=lambda: next(iter_states),- )- det.poll_once()- det.poll_once()- det.poll_once()- assert len(fired) == 3- assert fired[0].should_hide is False- assert fired[1].should_hide is True- assert fired[2].should_hide is False---def test_query_returning_none_does_not_crash() -> None:- fired = []- det = FullscreenDetector(- callback=lambda s: fired.append(s),- query_fn=lambda: None,- )- assert det.poll_once() is None- assert fired == []---def test_thread_starts_and_stops_cleanly() -> None:- """2-second polling-thread shutdown must be fast (<200 ms)."""- states = [UserNotificationState.NOT_PRESENT]-- det = FullscreenDetector(- poll_interval_s=0.05,- query_fn=lambda: states[0],- )- det.start()- time.sleep(0.02)- assert det.is_running- t0 = time.monotonic()- det.stop()- assert (time.monotonic() - t0) < 0.5- assert not det.is_running---def test_set_ignore_busy_state_runtime_toggle() -> None:- fired = []- det = FullscreenDetector(- callback=lambda s: fired.append(s),- query_fn=lambda: UserNotificationState.BUSY,- ignore_busy_state=False,- )- det.poll_once()- assert fired[-1].should_hide is True-- det.set_ignore_busy_state(True)- det.poll_once()- # Wechsel der Hide-Decision -> Callback fires.- assert fired[-1].should_hide is Falsediff --git a/tests/overlay/test_ipc_pipe.py b/tests/overlay/test_ipc_pipe.pydeleted file mode 100644index 5805b65fc2..0000000000--- a/tests/overlay/test_ipc_pipe.py+++ /dev/null@@ -1,75 +0,0 @@-"""Named-Pipe-Roundtrip — Windows-only, sonst skip."""--from __future__ import annotations--import sys-import threading-import time--import pytest--from overlay import ipc_pipe---pytestmark = pytest.mark.skipif(- not sys.platform.startswith("win"),- reason="Named-Pipe-Fallback ist Windows-only (pywin32)",-)---def test_capable_flag_matches_platform() -> None:- assert ipc_pipe.CAPABLE is sys.platform.startswith("win")---def test_default_pipe_name() -> None:- assert ipc_pipe.DEFAULT_PIPE_NAME == r"\\.\pipe\jarvis-overlay"---def test_send_recv_roundtrip() -> None:- """Server in a thread, client in the main thread: sends JSON, receives it back.-- The pipe is created in the main thread (CreateNamedPipe), only then does- the server thread start on ConnectNamedPipe. That way there's no race before- WaitNamedPipe.- """- pytest.importorskip("win32pipe")- pytest.importorskip("win32file")-- pipe = r"\\.\pipe\jarvis-overlay-test-" + str(time.time_ns())- handle = ipc_pipe.create_server_pipe(pipe)-- server_payload: dict[str, bytes] = {}- server_err: list[BaseException] = []-- def server_thread() -> None:- try:- ipc_pipe.accept_server_connection(handle)- data = ipc_pipe.recv(handle)- ipc_pipe.send(handle, b"echo:" + data)- server_payload["data"] = data- except BaseException as exc: # noqa: BLE001- server_err.append(exc)-- t = threading.Thread(target=server_thread, daemon=True)- t.start()-- try:- with ipc_pipe.open_client(pipe, timeout_ms=2000) as h:- sent = b'{"type":"state","payload":{"state":"idle"}}'- ipc_pipe.send(h, sent)- reply = ipc_pipe.recv(h)- assert reply == b"echo:" + sent- t.join(timeout=2.0)- finally:- ipc_pipe.close_server_pipe(handle)-- assert not server_err, server_err- assert server_payload.get("data", b"") != b""---def test_open_client_raises_when_pipe_missing() -> None:- pytest.importorskip("win32pipe")- bogus = r"\\.\pipe\definitely-not-running-" + str(time.time_ns())- with pytest.raises(RuntimeError):- with ipc_pipe.open_client(bogus, timeout_ms=200):- passdiff --git a/tests/overlay/test_ipc_ws.py b/tests/overlay/test_ipc_ws.pydeleted file mode 100644index 993d8452b1..0000000000--- a/tests/overlay/test_ipc_ws.py+++ /dev/null@@ -1,314 +0,0 @@-"""WS server (jarvis.overlay.server + bridge) and WS client (overlay.ipc_ws).--End-to-end round-trip over 127.0.0.1, plus backpressure/drop-policy-tests directly against the bridge outbox.-"""--from __future__ import annotations--import asyncio-import random--import pytest--from overlay.ipc_ws import (- BACKOFF_SCHEDULE,- JITTER_FRACTION,- WSClient,- _backoff_with_jitter,-)-from overlay.schema import (- ClickEnvelope,- ClickPayload,- HeartbeatEnvelope,- HeartbeatPayload,- IPCMessage,- StateEnvelope,- StatePayload,-)-from jarvis.overlay.bridge import OverlayBridge, _BoundedOutbox-from jarvis.overlay.server import IPCServerHandle, start_ipc_server--# pytest-asyncio ``asyncio_mode = "auto"`` (in pyproject.toml) marks-# async functions automatically — no module pytestmark needed.---# ------------------------------------------------------------------------------# Backoff-# --------------------------------------------------------------------------------def test_backoff_slot_progression() -> None:- rng = random.Random(0)- delays = [_backoff_with_jitter(i, rng=rng) for i in range(10)]- assert len(delays) == 10- # Slot 0..5 ramps up linearly, from 6 on capped at 30.- assert all(d > 0 for d in delays)- cap_band = (30 * (1 - JITTER_FRACTION), 30 * (1 + JITTER_FRACTION))- assert cap_band[0] <= delays[-1] <= cap_band[1]---def test_backoff_jitter_within_bounds() -> None:- rng = random.Random(42)- for slot, base in enumerate(BACKOFF_SCHEDULE):- for _ in range(20):- d = _backoff_with_jitter(slot, rng=rng)- assert base * (1 - JITTER_FRACTION) - 1e-9 <= d <= base * (1 + JITTER_FRACTION) + 1e-9---# ------------------------------------------------------------------------------# Bounded outbox / drop policy (§10.4)-# --------------------------------------------------------------------------------async def test_outbox_accepts_under_limit() -> None:- box = _BoundedOutbox(maxsize=4)- for i in range(4):- assert box.put("click", f'{{"i":{i}}}'.encode()) is True- assert len(box) == 4- assert box.dropped == 0---async def test_outbox_drops_oldest_non_state_first() -> None:- box = _BoundedOutbox(maxsize=3)- box.put("state", b"S0") # state- box.put("cursor", b"C1") # non-state, oldest non-state- box.put("heartbeat", b"H2") # non-state- # Full. A new entry (regardless of type) must drop C1 first.- assert box.put("click", b"X3") is True- out = []- while len(box):- out.append(await box.get())- assert b"S0" in out- assert b"H2" in out- assert b"X3" in out- assert b"C1" not in out- assert box.dropped == 1---async def test_outbox_drops_state_only_if_no_non_state() -> None:- box = _BoundedOutbox(maxsize=2)- box.put("state", b"S0")- box.put("state", b"S1")- # Full, all state. New state -> drop the oldest state.- assert box.put("state", b"S2") is True- out = [await box.get(), await box.get()]- assert b"S0" not in out- assert b"S1" in out and b"S2" in out---async def test_outbox_rejects_new_non_state_when_only_state_in_buf() -> None:- box = _BoundedOutbox(maxsize=2)- box.put("state", b"S0")- box.put("state", b"S1")- # Full, all state. New non-state -> gets dropped itself.- assert box.put("cursor", b"C2") is False- assert box.dropped == 1- out = [await box.get(), await box.get()]- assert b"S0" in out and b"S1" in out---# ------------------------------------------------------------------------------# Bridge: Outbox + State-Cache-# --------------------------------------------------------------------------------async def test_bridge_caches_last_state_for_resync() -> None:- bridge = OverlayBridge()- await bridge.start()- try:- bridge.emit_state("typing", intensity=0.7)- assert bridge.last_state_envelope is not None- assert bridge.last_state_envelope.payload.state == "typing"- bridge.emit_state("idle")- assert bridge.last_state_envelope.payload.state == "idle"- finally:- await bridge.stop()---async def test_bridge_send_nowait_returns_bool() -> None:- bridge = OverlayBridge(outbound_queue_max=2)- await bridge.start()- try:- # Two state frames fit in.- e1 = StateEnvelope(payload=StatePayload(state="idle"))- e2 = StateEnvelope(payload=StatePayload(state="typing"))- assert bridge.send_nowait(e1) is True- assert bridge.send_nowait(e2) is True- # Third state -> evicts the oldest state, accepted.- assert bridge.send_nowait(e1) is True- finally:- await bridge.stop()---# ------------------------------------------------------------------------------# E2E: Server + Client-# --------------------------------------------------------------------------------async def _start_test_server(port: int = 0) -> IPCServerHandle:- return await start_ipc_server(- host="127.0.0.1",- port=18000,- port_range_max=18020,- )---async def test_server_picks_free_port() -> None:- handle = await _start_test_server()- try:- assert 18000 <= handle.port <= 18020- finally:- await handle.stop()---async def test_server_raises_when_no_port_free() -> None:- """When port_range_max < port -> immediate ValueError."""- with pytest.raises(ValueError):- await start_ipc_server(host="127.0.0.1", port=18100, port_range_max=18099)---async def test_client_connects_and_receives_state_resync() -> None:- """Plan §10.5: first frame after connect is the last known state."""- handle = await _start_test_server()- handle.bridge.emit_state("clicking", intensity=1.0, reason="tool")- try:- received: list = []- recv_event = asyncio.Event()-- async def on_msg(m: object) -> None:- received.append(m)- recv_event.set()-- client = WSClient(- host="127.0.0.1",- ports=[handle.port],- heartbeat_interval_s=0.5,- heartbeat_timeout_s=5.0,- on_message=on_msg,- )- run_task = asyncio.create_task(client.run())- try:- connected = await client.wait_connected(timeout=3.0)- assert connected, "client did not connect"- await asyncio.wait_for(recv_event.wait(), timeout=3.0)- assert any(- isinstance(m, StateEnvelope) and m.payload.state == "clicking"- for m in received- )- finally:- await client.aclose()- try:- await asyncio.wait_for(run_task, timeout=2.0)- except asyncio.TimeoutError:- run_task.cancel()- finally:- await handle.stop()---async def test_client_reconnects_after_server_restart() -> None:- """Server dies -> client reconnects with backoff (§10.5)."""- handle1 = await _start_test_server()- port = handle1.port-- async def on_msg(_m: object) -> None:- pass-- client = WSClient(- host="127.0.0.1",- ports=[port],- heartbeat_interval_s=0.2,- heartbeat_timeout_s=2.0,- on_message=on_msg,- rng=random.Random(0),- )- run_task = asyncio.create_task(client.run())- try:- assert await client.wait_connected(timeout=3.0)- first_count = client.connection_count- # Stop the server.- await handle1.stop()- # Bring it back up with the same port.- await asyncio.sleep(0.3)- handle2 = await start_ipc_server(- host="127.0.0.1", port=port, port_range_max=port- )- try:- # Give the client time to reconnect (backoff <= 1.2s + jitter).- for _ in range(40):- await asyncio.sleep(0.1)- if client.connection_count > first_count:- break- assert client.connection_count > first_count- finally:- await handle2.stop()- finally:- await client.aclose()- try:- await asyncio.wait_for(run_task, timeout=2.0)- except asyncio.TimeoutError:- run_task.cancel()---async def test_invalid_json_dropped_and_logged(caplog) -> None:- """Server must log + drop invalid JSON, not crash.-- We send garbage and still expect at least one valid- StateEnvelope afterward (pushed after the garbage). Other frames- (heartbeat, resync) may occur in between.- """- import websockets-- handle = await _start_test_server()- try:- async with websockets.connect(f"ws://127.0.0.1:{handle.port}/overlay") as ws:- await ws.send("definitely-not-json")- handle.bridge.emit_state("idle")- # Drain until the next StateEnvelope (max ~3s of heartbeats).- seen_state = False- for _ in range(30):- try:- frame = await asyncio.wait_for(ws.recv(), timeout=2.0)- except asyncio.TimeoutError:- break- msg = IPCMessage.validate_json(frame)- if isinstance(msg, StateEnvelope) and msg.payload.state == "idle":- seen_state = True- break- assert seen_state, "no StateEnvelope received after the garbage frame"- finally:- await handle.stop()---async def test_client_sends_heartbeats() -> None:- """Client sends heartbeats that the server validates."""- received_types: list[str] = []- handle = await _start_test_server()-- async def collect(msg: object) -> None:- received_types.append(getattr(msg, "type", "?"))-- handle.bridge.add_inbound_handler(collect)-- client = WSClient(- host="127.0.0.1",- ports=[handle.port],- heartbeat_interval_s=0.1,- heartbeat_timeout_s=5.0,- )- run_task = asyncio.create_task(client.run())- try:- assert await client.wait_connected(timeout=3.0)- # Wait until at least one heartbeat has been received.- for _ in range(40):- await asyncio.sleep(0.05)- if "heartbeat" in received_types:- break- assert "heartbeat" in received_types- finally:- await client.aclose()- try:- await asyncio.wait_for(run_task, timeout=2.0)- except asyncio.TimeoutError:- run_task.cancel()- await handle.stop()diff --git a/tests/overlay/test_jarvis_agent_noop.py b/tests/overlay/test_jarvis_agent_noop.pydeleted file mode 100644index ca11f8cde4..0000000000--- a/tests/overlay/test_jarvis_agent_noop.py+++ /dev/null@@ -1,135 +0,0 @@-"""Sub-agent no-op path. Plan §8.7 + AD-6.--When the ``JARVIS_DEPTH > 0`` env var is set, the OverlayBridge is a no-op-stub. Caller code sees the same interface, but events are not sent-anywhere.-"""--from __future__ import annotations--import asyncio--import pytest--from jarvis.overlay import (- NoOpOverlayBridge,- get_overlay,- is_sub_agent_process,- start_overlay,- stop_overlay,-)---# --------------------------------------------------------------------------# is_sub_agent_process Detection-# ----------------------------------------------------------------------------def test_no_jarvis_depth_is_main_process(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.delenv("JARVIS_DEPTH", raising=False)- assert is_sub_agent_process() is False---def test_jarvis_depth_zero_is_main_process(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setenv("JARVIS_DEPTH", "0")- assert is_sub_agent_process() is False--[email protected]("depth", ["1", "2", "5"])-def test_jarvis_depth_positive_is_sub_agent(- depth: str, monkeypatch: pytest.MonkeyPatch-) -> None:- monkeypatch.setenv("JARVIS_DEPTH", depth)- assert is_sub_agent_process() is True---def test_invalid_jarvis_depth_falls_back_to_main(- monkeypatch: pytest.MonkeyPatch,-) -> None:- monkeypatch.setenv("JARVIS_DEPTH", "garbage")- assert is_sub_agent_process() is False---# --------------------------------------------------------------------------# get_overlay liefert NoOp-Stub in Sub-Agents-# ----------------------------------------------------------------------------def test_get_overlay_returns_noop_stub_in_sub_agent(- monkeypatch: pytest.MonkeyPatch,-) -> None:- monkeypatch.setenv("JARVIS_DEPTH", "2")- bridge = get_overlay()- assert bridge is not None- assert isinstance(bridge, NoOpOverlayBridge)---# --------------------------------------------------------------------------# NoOpOverlayBridge — all emit methods are no-ops, no IPC traffic-# ----------------------------------------------------------------------------def test_noop_emit_state_returns_false() -> None:- bridge = NoOpOverlayBridge()- assert bridge.emit_state("listening") is False---def test_noop_emit_action_started_returns_action_id() -> None:- bridge = NoOpOverlayBridge()- aid = bridge.emit_action_started("click", duration_hint_ms=100)- assert isinstance(aid, str)---def test_noop_emit_action_ended_returns_false() -> None:- bridge = NoOpOverlayBridge()- assert bridge.emit_action_ended("noop") is False---def test_noop_emit_click_returns_false() -> None:- bridge = NoOpOverlayBridge()- assert bridge.emit_click(100, 200, button="left") is False---def test_noop_emit_error_returns_false() -> None:- bridge = NoOpOverlayBridge()- assert bridge.emit_error("test") is False---def test_noop_send_nowait_returns_false() -> None:- bridge = NoOpOverlayBridge()- assert bridge.send_nowait(object()) is False---def test_noop_dropped_count_is_zero() -> None:- bridge = NoOpOverlayBridge()- bridge.emit_state("listening")- bridge.emit_state("typing")- bridge.emit_state("idle")- assert bridge.dropped == 0- assert bridge.connected_count == 0---async def test_noop_start_stop_lifecycle() -> None:- bridge = NoOpOverlayBridge()- await bridge.start()- await bridge.stop()- # No exception. No state.---# --------------------------------------------------------------------------# start_overlay() im Sub-Agent-# ----------------------------------------------------------------------------async def test_start_overlay_in_sub_agent_returns_noop_stub(- monkeypatch: pytest.MonkeyPatch,-) -> None:- monkeypatch.setenv("JARVIS_DEPTH", "2")- try:- bridge = await start_overlay()- assert isinstance(bridge, NoOpOverlayBridge)- finally:- await stop_overlay()- monkeypatch.delenv("JARVIS_DEPTH", raising=False)diff --git a/tests/overlay/test_mascot_event_schema.py b/tests/overlay/test_mascot_event_schema.pydeleted file mode 100644index a1d3e02b66..0000000000--- a/tests/overlay/test_mascot_event_schema.py+++ /dev/null@@ -1,48 +0,0 @@-"""Schema coverage for the mascot → main jarvis interaction envelope.--The mascot subprocess sends ``MascotEventEnvelope`` upstream when the-user interacts with the sprite in a way that should drive Jarvis state-(currently: doubleClick → mute toggle). The envelope is part of the-discriminated IPC union, so we round-trip it through ``IPCMessage`` to-catch any drift in the validator.-"""--from __future__ import annotations--import pytest-from pydantic import ValidationError--from overlay.schema import (- IPCMessage,- MascotEventEnvelope,- MascotEventPayload,- NON_STATE_TYPES,- STATE_TYPES,- is_state_type,-)---def test_mascot_event_round_trip() -> None:- e = MascotEventEnvelope(payload=MascotEventPayload(kind="mute_toggle"))- raw = e.model_dump_json()- back = IPCMessage.validate_json(raw)- assert isinstance(back, MascotEventEnvelope)- assert back.payload.kind == "mute_toggle"- assert back.type == "mascot_event"---def test_mascot_event_rejects_unknown_kind() -> None:- with pytest.raises(ValidationError):- MascotEventPayload(kind="hover") # type: ignore[arg-type]---def test_mascot_event_is_non_state_type() -> None:- assert "mascot_event" in NON_STATE_TYPES- assert "mascot_event" not in STATE_TYPES- assert is_state_type("mascot_event") is False---def test_mascot_event_payload_forbids_extras() -> None:- """User-driven payload must reject unknown keys to surface protocol drift."""- with pytest.raises(ValidationError):- MascotEventPayload.model_validate({"kind": "mute_toggle", "stray": 1})diff --git a/tests/overlay/test_mascot_mute_integration.py b/tests/overlay/test_mascot_mute_integration.pydeleted file mode 100644index 64bd969431..0000000000--- a/tests/overlay/test_mascot_mute_integration.py+++ /dev/null@@ -1,107 +0,0 @@-"""Integration coverage: mascot dblclick → main-side mute toggle.--This stitches the three layers together that the unit tests cover in-isolation:-- Mascot subprocess (sending the envelope) is simulated by feeding a- ``MascotEventEnvelope`` directly into ``OverlayBridge``'s inbound- handler queue, exactly as the WS recv-loop would once a real frame- arrives. The integration.py glue then publishes- ``VoiceMuteToggleRequested`` on the supplied bus; the pipeline- subscribes and flips its mute flag.--The point is to catch wiring drift — if integration.py is ever-refactored to drop the mascot_event branch, this test fails fast.-"""--from __future__ import annotations--from collections.abc import AsyncIterator-from dataclasses import dataclass, field--import pytest--from jarvis.core.bus import EventBus-from jarvis.core.events import VoiceMuteToggleRequested-from jarvis.core.protocols import AudioChunk-from jarvis.overlay.schema import MascotEventEnvelope, MascotEventPayload-from jarvis.speech.pipeline import SpeechPipeline---@dataclass-class FakeTTS:- name: str = "fake-tts"- supports_streaming: bool = True- calls: list[tuple[str, str | None]] = field(default_factory=list)-- async def synthesize(- self, text: str, voice: str | None = None,- language_code: str | None = None,- ) -> AsyncIterator[AudioChunk]:- self.calls.append((text, language_code))- if False: # pragma: no cover- yield # type: ignore[unreachable]---@dataclass-class FakePlayer:- stop_calls: int = 0-- async def play_chunks(self, chunks: AsyncIterator[AudioChunk]) -> None:- async for _ in chunks:- pass-- def stop(self) -> None:- self.stop_calls += 1---async def test_mascot_dblclick_envelope_drives_pipeline_mute() -> None:- """End-to-end: an inbound mascot_event publishes on the bus and the- pipeline flips its mute flag.-- We avoid spinning up the full OverlayBridge/WS server — instead we- invoke the exact handler ``start_overlay`` installs (mirroring its- logic) so the wiring is verified without I/O.- """- bus = EventBus()- tts = FakeTTS()- player = FakePlayer()- pipeline = SpeechPipeline(tts=tts, bus=bus, enable_whisper_wake=False)- pipeline._player = player # type: ignore[assignment]-- # This is the same predicate integration.py runs in its inbound- # handler. We assert the contract by name+kind so any rename of the- # envelope class or payload kind surfaces here.- envelope = MascotEventEnvelope(payload=MascotEventPayload(kind="mute_toggle"))- type_name = type(envelope).__name__- assert type_name == "MascotEventEnvelope"- assert envelope.payload.kind == "mute_toggle"-- await bus.publish(VoiceMuteToggleRequested(source="mascot_dblclick"))-- assert pipeline.is_muted is True- assert pipeline._activation_allowed() is False- # player.stop() is intentionally NOT called on mute (input-only mute,- # 2026-06-29 forensic): stopping playback mid-write wedged the WASAPI- # device so subsequent wake-mic opens silently failed. Jarvis finishes- # the current sentence; new _speak() calls are suppressed while muted.- assert player.stop_calls == 0---async def test_pipeline_ignores_request_without_subscriber() -> None:- """A pipeline that never wired the subscriber stays unmuted.-- Defensive: confirms the subscription itself does the work, not some- accidental module-level side effect.- """- bus = EventBus()- tts = FakeTTS()- pipeline = SpeechPipeline(tts=tts, bus=None, enable_whisper_wake=False)- pipeline._player = FakePlayer() # type: ignore[assignment]-- # No bus → no subscription → publish on a foreign bus is a no-op- # for THIS pipeline.- await bus.publish(VoiceMuteToggleRequested(source="mascot_dblclick"))- assert pipeline.is_muted is Falsediff --git a/tests/overlay/test_mascot_position.py b/tests/overlay/test_mascot_position.pydeleted file mode 100644index ff89e29809..0000000000--- a/tests/overlay/test_mascot_position.py+++ /dev/null@@ -1,210 +0,0 @@-"""Mascot Position-Persistence + Monitor-Recovery — Plan §13.4 + §20.4."""--from __future__ import annotations--from pathlib import Path--import pytest--from overlay.mascot_position import (- DEFAULT_X_RELATIVE,- DEFAULT_Y_RELATIVE,- MascotPosition,- ResolvedPlacement,- _ScreenSnapshot,- clamp_to_work_area,- load_position_from_toml,- resolve_placement,- save_position_to_toml,- snap_to_edges,-)---def _screen(- name: str,- *,- x: int = 0,- y: int = 0,- w: int = 1920,- h: int = 1080,- primary: bool = False,-) -> _ScreenSnapshot:- return _ScreenSnapshot(- name=name, geometry=(x, y, w, h), is_primary=primary- )---# --------------------------------------------------------------------------# resolve_placement — Plan §13.4 5-Schritt-Recovery-# ----------------------------------------------------------------------------def test_resolve_when_persisted_monitor_present() -> None:- screens = [_screen("\\\\.\\DISPLAY1", primary=True)]- persisted = MascotPosition(- monitor="\\\\.\\DISPLAY1", x_relative=300, y_relative=100- )- placement = resolve_placement(persisted, screens)- assert placement.abs_x == 300- assert placement.abs_y == 100- assert placement.monitor == "\\\\.\\DISPLAY1"- assert placement.recovered is False---def test_resolve_falls_back_to_primary_when_monitor_missing() -> None:- """Plan §13.4 step 3: primary fallback wenn persisted monitor weg."""- screens = [_screen("\\\\.\\DISPLAY2", primary=True, x=100, y=200)]- persisted = MascotPosition(- monitor="\\\\.\\DISPLAY99", x_relative=500, y_relative=400- )- placement = resolve_placement(persisted, screens)- # Default position on primary, NOT the stored offset.- assert placement.abs_x == 100 + DEFAULT_X_RELATIVE- assert placement.abs_y == 200 + DEFAULT_Y_RELATIVE- assert placement.monitor == "\\\\.\\DISPLAY2"- assert placement.recovered is True---def test_resolve_with_no_persisted_uses_primary_default() -> None:- screens = [_screen("\\\\.\\DISPLAY1", primary=True)]- placement = resolve_placement(None, screens)- assert placement.abs_x == DEFAULT_X_RELATIVE- assert placement.abs_y == DEFAULT_Y_RELATIVE- assert placement.recovered is True---def test_resolve_with_no_screens_returns_default() -> None:- persisted = MascotPosition(monitor="X", x_relative=10, y_relative=20)- placement = resolve_placement(persisted, [])- assert placement.recovered is True- assert placement.monitor == ""---def test_resolve_clamps_when_relative_offset_off_screen() -> None:- """Resolution-Change: monitor schrumpft, persisted x_rel ist nun ausserhalb."""- screens = [_screen("\\\\.\\DISPLAY1", primary=True, w=800, h=600)]- persisted = MascotPosition(- monitor="\\\\.\\DISPLAY1", x_relative=2000, y_relative=2000- )- placement = resolve_placement(persisted, screens, mascot_size_px=160)- # Clamped in 800-160-16=624 max.- assert placement.abs_x <= 800 - 160 - 16- assert placement.abs_y <= 600 - 160 - 16- assert placement.recovered is False # gleicher Monitor, nur clamped---def test_resolve_picks_first_screen_when_no_primary_flagged() -> None:- screens = [_screen("a"), _screen("b")]- placement = resolve_placement(None, screens)- assert placement.monitor == "a"---# --------------------------------------------------------------------------# Snap + Clamp-# ----------------------------------------------------------------------------def test_snap_to_left_edge_when_within_tolerance() -> None:- geo = (0, 0, 1920, 1080)- sx, sy = snap_to_edges(8, 100, geo, mascot_size_px=160, snap_tolerance_px=16)- assert sx == 0- assert sy == 100---def test_snap_to_right_edge_when_within_tolerance() -> None:- geo = (0, 0, 1920, 1080)- # Mascot 160 wide, right edge at 1920. Position 1755 -> right gap 5px.- sx, _sy = snap_to_edges(1755, 100, geo, mascot_size_px=160, snap_tolerance_px=16)- assert sx == 1920 - 160---def test_snap_no_op_outside_tolerance() -> None:- geo = (0, 0, 1920, 1080)- sx, sy = snap_to_edges(50, 50, geo, mascot_size_px=160, snap_tolerance_px=16)- assert (sx, sy) == (50, 50)---def test_clamp_keeps_mascot_in_work_area() -> None:- geo = (0, 0, 1920, 1080)- cx, cy = clamp_to_work_area(-100, -100, geo, mascot_size_px=160, margin_px=16)- assert cx == 16- assert cy == 16- cx2, cy2 = clamp_to_work_area(5000, 5000, geo, mascot_size_px=160, margin_px=16)- assert cx2 == 1920 - 160 - 16- assert cy2 == 1080 - 160 - 16---# --------------------------------------------------------------------------# TOML Round-Trip-# ----------------------------------------------------------------------------def test_save_and_load_round_trip(tmp_path: Path) -> None:- p = tmp_path / "jarvis.toml"- pos = MascotPosition(- monitor="\\\\.\\DISPLAY1", x_relative=300, y_relative=400- )- save_position_to_toml(p, pos)- loaded = load_position_from_toml(p)- assert loaded == pos---def test_load_missing_file_returns_none(tmp_path: Path) -> None:- p = tmp_path / "no-such.toml"- assert load_position_from_toml(p) is None---def test_load_section_missing_returns_defaults_with_empty_monitor(- tmp_path: Path,-) -> None:- p = tmp_path / "jarvis.toml"- p.write_text("[other.section]\nfoo = 1\n", encoding="utf-8")- loaded = load_position_from_toml(p)- assert loaded is not None- assert loaded.monitor == ""- assert loaded.x_relative == DEFAULT_X_RELATIVE- assert loaded.y_relative == DEFAULT_Y_RELATIVE---def test_save_preserves_existing_other_sections(tmp_path: Path) -> None:- p = tmp_path / "jarvis.toml"- p.write_text(- "# user comment\n"- "[other.section]\n"- 'foo = "bar"\n'- "\n"- "[overlay.mascot]\n"- 'position_monitor = "OLD"\n'- "position_x_relative = 1\n"- "position_y_relative = 2\n",- encoding="utf-8",- )- pos = MascotPosition(- monitor="\\\\.\\DISPLAY3", x_relative=500, y_relative=600- )- save_position_to_toml(p, pos)- text = p.read_text(encoding="utf-8")- assert "[other.section]" in text- assert "# user comment" in text # Comments bleiben- assert 'foo = "bar"' in text- loaded = load_position_from_toml(p)- assert loaded == pos---def test_save_appends_section_when_missing(tmp_path: Path) -> None:- p = tmp_path / "jarvis.toml"- p.write_text("[other]\nbaz = 3\n", encoding="utf-8")- pos = MascotPosition(monitor="X", x_relative=10, y_relative=20)- save_position_to_toml(p, pos)- loaded = load_position_from_toml(p)- assert loaded == pos- assert "[other]" in p.read_text(encoding="utf-8")---def test_save_to_nonexistent_file_creates_minimal(tmp_path: Path) -> None:- p = tmp_path / "fresh.toml"- pos = MascotPosition(monitor="X", x_relative=1, y_relative=2)- save_position_to_toml(p, pos)- assert p.is_file()- loaded = load_position_from_toml(p)- assert loaded == posdiff --git a/tests/overlay/test_monitors.py b/tests/overlay/test_monitors.pydeleted file mode 100644index da79dc96c5..0000000000--- a/tests/overlay/test_monitors.py+++ /dev/null@@ -1,87 +0,0 @@-"""Monitor-Enumeration + Hotplug — mit gemockter QGuiApplication."""--from __future__ import annotations--from unittest.mock import MagicMock--import pytest--pytest.importorskip("PySide6.QtGui")---def _make_screen(name: str, x: int, y: int, w: int, h: int, dpr: float = 1.0) -> MagicMock:- screen = MagicMock()- screen.name.return_value = name- geo = MagicMock()- geo.x.return_value = x- geo.y.return_value = y- geo.width.return_value = w- geo.height.return_value = h- screen.geometry.return_value = geo- screen.devicePixelRatio.return_value = dpr- return screen---def test_enumerate_monitors_with_qapp(qapp) -> None:- """Echte Qt-Headless-Enumeration: liefert mindestens den Offscreen-Default."""- from overlay.monitors import enumerate_monitors-- monitors = enumerate_monitors()- # offscreen-Plattform liefert mindestens einen virtuellen Screen,- # dessen ``name`` aber leer sein darf.- assert isinstance(monitors, list)- assert len(monitors) >= 1- m = monitors[0]- assert isinstance(m.name, str)- assert len(m.geometry) == 4- assert m.device_pixel_ratio > 0---def test_enumerate_monitors_without_qapp(monkeypatch) -> None:- """Ohne QGuiApplication.instance() → leere Liste."""- from overlay import monitors as mod-- fake_qgui = MagicMock()- fake_qgui.instance.return_value = None- monkeypatch.setattr("PySide6.QtGui.QGuiApplication", fake_qgui, raising=False)- # Re-Import verschonen wir uns; enumerate_monitors prueft instance() selbst.- assert mod.enumerate_monitors() == []---def test_monitor_manager_attach_requires_qapp(monkeypatch) -> None:- from overlay.monitors import MonitorManager-- fake_qgui = MagicMock()- fake_qgui.instance.return_value = None- monkeypatch.setattr("PySide6.QtGui.QGuiApplication", fake_qgui, raising=False)-- mgr = MonitorManager()- with pytest.raises(RuntimeError):- mgr.attach()---def test_monitor_manager_connects_callbacks(qapp) -> None:- """Mit echter QApplication: attach + detach binden/loesen Signals."""- from overlay.monitors import MonitorManager-- added_calls: list = []- removed_calls: list = []-- mgr = MonitorManager(- on_screen_added=added_calls.append,- on_screen_removed=removed_calls.append,- )- mgr.attach()- # Idempotent — a second attach() must not connect twice.- mgr.attach()- mgr.detach()- # Detach idempotent.- mgr.detach()---def test_monitor_info_dataclass() -> None:- from overlay.monitors import MonitorInfo-- m = MonitorInfo(name="\\\\.\\DISPLAY1", geometry=(0, 0, 1920, 1080), device_pixel_ratio=1.0, is_primary=True)- assert m.is_primary is True- assert m.geometry == (0, 0, 1920, 1080)diff --git a/tests/overlay/test_overlay_surface.py b/tests/overlay/test_overlay_surface.pydeleted file mode 100644index 37fcce5bdb..0000000000--- a/tests/overlay/test_overlay_surface.py+++ /dev/null@@ -1,205 +0,0 @@-"""Tests for the Wave-2 ``OverlaySurface`` seam + factory (sub-task 2.5; AD-6/7/11).--These run headless on every CI leg (Windows/macOS/Linux) under-``QT_QPA_PLATFORM=offscreen`` (set by ``tests/overlay/conftest.py``). They do-**not** create a real ``tk.Tk()`` window or a pystray thread — ``TkColorKeyOverlay``-is driven against a :class:`FakeOrb`, and factory selection is asserted purely on-the returned class via faked capabilities. Anything needing a real transparent-window / live tray is deferred to Wave 4's one-time live sign-off (AD-3).-"""--from __future__ import annotations--import pytest--from jarvis.overlay.surface import (- OverlaySurface,- TkColorKeyOverlay,- make_overlay_surface,-)-from tests.fakes.fake_capabilities import (- fake_headless_capabilities,- fake_linux_capabilities,- fake_macos_capabilities,- fake_windows_capabilities,-)-from tests.fakes.fake_overlay_surface import FakeOrb--# -----------------------------------------------------------------------# Protocol conformance + lifecycle (TkColorKeyOverlay wrapping a fake orb).-# -------------------------------------------------------------------------def test_tk_overlay_satisfies_protocol():- surface = TkColorKeyOverlay(inner=FakeOrb())- assert isinstance(surface, OverlaySurface)---def test_tk_overlay_start_delegates_to_inner_orb():- orb = FakeOrb()- surface = TkColorKeyOverlay(inner=orb)-- surface.start()-- assert orb.started is True---def test_tk_overlay_start_is_idempotent():- orb = FakeOrb()- surface = TkColorKeyOverlay(inner=orb)-- surface.start()- surface.start()-- # FakeOrb only records a bool, so prove the second start did not crash and the- # wrapper stayed started by exercising a state change afterwards.- surface.set_state("listening")- assert orb.visible is True--- "state,expected_mode",- [- ("listening", "listen"),- ("thinking", "think"),- ("speaking", "speak"),- ],-)-def test_tk_overlay_visible_states_show_correct_mode(state, expected_mode):- orb = FakeOrb()- surface = TkColorKeyOverlay(inner=orb)- surface.start()-- surface.set_state(state)-- assert orb.visible is True- assert orb.mode == expected_mode- assert surface.is_visible() is True--[email protected]("state", ["idle", "paused", "error"])-def test_tk_overlay_non_visible_states_hide(state):- orb = FakeOrb()- surface = TkColorKeyOverlay(inner=orb)- surface.start()- surface.set_state("listening") # become visible first-- surface.set_state(state)-- assert orb.visible is False- assert surface.is_visible() is False---def test_tk_overlay_set_state_before_start_is_noop():- orb = FakeOrb()- surface = TkColorKeyOverlay(inner=orb)-- surface.set_state("listening") # no start yet-- assert orb.visible is False- assert surface.is_visible() is False---def test_tk_overlay_stop_hides_and_resets_visibility():- orb = FakeOrb()- surface = TkColorKeyOverlay(inner=orb)- surface.start()- surface.set_state("speaking")-- surface.stop()-- assert orb.hide_calls >= 1- assert surface.is_visible() is False---def test_tk_overlay_stop_without_start_never_raises():- surface = TkColorKeyOverlay(inner=FakeOrb())- surface.stop() # must be a safe no-op- assert surface.is_visible() is False---# -----------------------------------------------------------------------# Factory selection (AD-11) — pure logic, runs on every OS leg.-# -------------------------------------------------------------------------def test_factory_selects_tk_on_windows():- surface = make_overlay_surface(capabilities=fake_windows_capabilities())- assert isinstance(surface, TkColorKeyOverlay)- assert isinstance(surface, OverlaySurface)---def test_factory_selects_tray_floor_on_macos():- # NOT TkColorKeyOverlay: the factory's surfaces run Tk on a worker- # thread, and Aqua-Tk is main-thread-only on macOS — a Tk root there- # aborts the process natively (BUG-057). The tray floor is the degrade.- from jarvis.overlay.tray_surface import TrayOnlySurface-- surface = make_overlay_surface(capabilities=fake_macos_capabilities())- assert isinstance(surface, TrayOnlySurface)- assert not isinstance(surface, TkColorKeyOverlay)---def test_factory_selects_linux_best_effort_on_x11():- from jarvis.overlay.linux_surface import LinuxBestEffortOverlay-- surface = make_overlay_surface(- capabilities=fake_linux_capabilities(is_wayland=False, display_present=True)- )- assert isinstance(surface, LinuxBestEffortOverlay)- assert not isinstance(surface, TkColorKeyOverlay)---def test_factory_selects_tray_on_wayland():- from jarvis.overlay.tray_surface import TrayOnlySurface-- surface = make_overlay_surface(- capabilities=fake_linux_capabilities(is_wayland=True, display_present=True)- )- assert isinstance(surface, TrayOnlySurface)---def test_factory_selects_tray_when_no_overlay_capability():- from jarvis.overlay.tray_surface import TrayOnlySurface-- # has_overlay False on every platform → tray floor.- surface = make_overlay_surface(capabilities=fake_headless_capabilities())- assert isinstance(surface, TrayOnlySurface)---def test_factory_selects_tray_on_windows_without_overlay():- from jarvis.overlay.tray_surface import TrayOnlySurface-- surface = make_overlay_surface(- capabilities=fake_windows_capabilities(has_overlay=False)- )- assert isinstance(surface, TrayOnlySurface)---def test_factory_selects_tray_on_linux_no_display():- from jarvis.overlay.tray_surface import TrayOnlySurface-- surface = make_overlay_surface(- capabilities=fake_linux_capabilities(display_present=False)- )- assert isinstance(surface, TrayOnlySurface)---def test_factory_never_raises_and_returns_protocol_on_every_capability_shape():- for caps in (- fake_windows_capabilities(),- fake_macos_capabilities(),- fake_linux_capabilities(),- fake_linux_capabilities(is_wayland=True),- fake_headless_capabilities(),- fake_windows_capabilities(has_overlay=False),- ):- surface = make_overlay_surface(capabilities=caps)- assert isinstance(surface, OverlaySurface)---def test_factory_with_real_capabilities_returns_protocol():- """No-arg call uses the real host snapshot; on this Windows box that is- ``TkColorKeyOverlay``. Must never raise (AD-6)."""- surface = make_overlay_surface()- assert isinstance(surface, OverlaySurface)diff --git a/tests/overlay/test_power.py b/tests/overlay/test_power.pydeleted file mode 100644index 72e4775492..0000000000--- a/tests/overlay/test_power.py+++ /dev/null@@ -1,87 +0,0 @@-"""PowerMonitor — GetSystemPowerStatus mocked. Plan §17.3."""--from __future__ import annotations--import time--from overlay.power import PowerMonitor, PowerStatus---def _ac() -> PowerStatus:- return PowerStatus(on_battery=False, battery_saver=False, battery_percent=80)---def _battery() -> PowerStatus:- return PowerStatus(on_battery=True, battery_saver=False, battery_percent=40)---def _battery_saver() -> PowerStatus:- return PowerStatus(on_battery=True, battery_saver=True, battery_percent=20)---def test_callback_fires_on_first_poll() -> None:- fired = []- mon = PowerMonitor(callback=lambda s: fired.append(s), query_fn=_ac)- mon.poll_once()- assert len(fired) == 1- assert fired[0].on_battery is False---def test_callback_does_not_fire_when_unchanged() -> None:- fired = []- mon = PowerMonitor(callback=lambda s: fired.append(s), query_fn=_ac)- mon.poll_once()- mon.poll_once()- mon.poll_once()- assert len(fired) == 1---def test_callback_fires_on_ac_to_battery_transition() -> None:- fired = []- sequence = [_ac, _battery]- idx = [0]-- def q():- s = sequence[idx[0]]()- idx[0] = min(idx[0] + 1, len(sequence) - 1)- return s-- mon = PowerMonitor(callback=lambda s: fired.append(s), query_fn=q)- mon.poll_once()- mon.poll_once()- assert len(fired) == 2- assert fired[0].on_battery is False- assert fired[1].on_battery is True---def test_battery_saver_change_triggers_callback() -> None:- fired = []- sequence = [_battery, _battery_saver]- idx = [0]-- def q():- s = sequence[idx[0]]()- idx[0] = min(idx[0] + 1, len(sequence) - 1)- return s-- mon = PowerMonitor(callback=lambda s: fired.append(s), query_fn=q)- mon.poll_once()- mon.poll_once()- assert len(fired) == 2- assert fired[1].battery_saver is True---def test_thread_lifecycle() -> None:- mon = PowerMonitor(poll_interval_s=0.05, query_fn=_ac)- mon.start()- time.sleep(0.02)- assert mon.is_running- mon.stop()- assert not mon.is_running---def test_query_returning_none_does_not_crash() -> None:- fired = []- mon = PowerMonitor(callback=lambda s: fired.append(s), query_fn=lambda: None)- assert mon.poll_once() is None- assert fired == []diff --git a/tests/overlay/test_ripple_e2e.py b/tests/overlay/test_ripple_e2e.pydeleted file mode 100644index b21d761b89..0000000000--- a/tests/overlay/test_ripple_e2e.py+++ /dev/null@@ -1,191 +0,0 @@-"""Ripple E2E. Plan §14.3 — click event ⇒ DOM update ≤ 50 ms.--We can't easily start the real EffectsBridge without the whole-QtWebEngine app, so we simulate the bridge path by calling the-``triggerRipple`` export directly from the built JS bundle.--Tests:- - Pool builds up (8 slots).- - triggerRipple adds an .active CSS class.- - Animation starts ≤ 50 ms after the JS call.- - Reduced-motion path: no animation.-"""--from __future__ import annotations--import http.server-import socketserver-import threading-from pathlib import Path--import pytest--playwright_sync = pytest.importorskip("playwright.sync_api")-sync_playwright = playwright_sync.sync_playwright---REPO_ROOT = Path(__file__).resolve().parents[2]-DIST_DIR = REPO_ROOT / "OS-Level" / "overlay-ui" / "dist"-EDGE_GLOW_HTML = DIST_DIR / "edge-glow.html"---def _skip_if_no_build() -> None:- if not EDGE_GLOW_HTML.is_file():- pytest.skip(f"edge-glow.html not found — npm run build?")---class _SilentHandler(http.server.SimpleHTTPRequestHandler):- def log_message(self, format: str, *args: object) -> None: # noqa: A002- return--[email protected](scope="module")-def http_server():- _skip_if_no_build()- cwd = str(DIST_DIR)-- class _RootedHandler(_SilentHandler):- def __init__(self, *args, **kwargs) -> None:- super().__init__(*args, directory=cwd, **kwargs)-- httpd = socketserver.TCPServer(("127.0.0.1", 0), _RootedHandler)- port = httpd.server_address[1]- thread = threading.Thread(target=httpd.serve_forever, daemon=True)- thread.start()- try:- yield f"http://127.0.0.1:{port}"- finally:- httpd.shutdown()- httpd.server_close()- thread.join(timeout=2)--[email protected](scope="module")-def page_url(http_server: str) -> str:- return f"{http_server}/edge-glow.html"--[email protected](scope="module")-def browser_ctx():- try:- with sync_playwright() as p:- browser = p.chromium.launch(headless=True)- yield browser- browser.close()- except Exception as exc: # noqa: BLE001- pytest.skip(f"Playwright browser not available: {exc!r}")---def test_ripple_pool_built(browser_ctx, page_url: str) -> None:- page = browser_ctx.new_page()- try:- page.goto(page_url)- page.wait_for_function(- "document.querySelectorAll('.ripple-layer .ripple').length === 8",- timeout=2000,- )- count = page.evaluate(- "document.querySelectorAll('.ripple-layer .ripple').length"- )- assert count == 8- finally:- page.close()---def test_ripple_triggers_within_50ms(browser_ctx, page_url: str) -> None:- """Plan §14.3: click event -> ripple visible in DOM ≤ 50 ms."""- page = browser_ctx.new_page()- try:- page.goto(page_url)- page.wait_for_function(- "document.querySelectorAll('.ripple-layer .ripple').length === 8",- timeout=2000,- )- # Measure time between JS trigger and the visible ".active" slot.- elapsed_ms = page.evaluate(- """async () => {- const { triggerRipple } = await import('/assets/edge-glow-DPwwKrEp.js')- .catch(() => ({ triggerRipple: null }));- // Fallback: via global helpers — not exposed, so- // we use direct DOM manipulation to simulate the effect.- const t0 = performance.now();- // Trigger via the pool CSS pattern: first empty slot- // gets the .active class.- const slot = document.querySelector('.ripple-layer .ripple');- if (!slot) return -1;- slot.classList.add('active');- slot.style.transform = 'translate(100px, 100px) scale(0)';- slot.style.opacity = '1';- // Forced reflow + wait one frame.- void slot.offsetWidth;- await new Promise(r => requestAnimationFrame(r));- const t1 = performance.now();- const isActive = slot.classList.contains('active');- return isActive ? (t1 - t0) : -1;- }"""- )- assert elapsed_ms >= 0, "active class never set"- assert elapsed_ms < 50, f"Ripple-Activation {elapsed_ms} ms > 50 ms"- finally:- page.close()---def test_ripple_reduced_motion_no_animation(browser_ctx, page_url: str) -> None:- """Plan §19.1: prefers-reduced-motion -> ripple opacity 0."""- page = browser_ctx.new_page()- page.emulate_media(reduced_motion="reduce")- try:- page.goto(page_url)- page.wait_for_function(- "document.querySelectorAll('.ripple-layer .ripple').length === 8",- timeout=2000,- )- # Set .active manually and check whether computed opacity is 0.- opacity = page.evaluate(- """() => {- const slot = document.querySelector('.ripple-layer .ripple');- slot.classList.add('active');- return getComputedStyle(slot).opacity;- }"""- )- assert float(opacity) <= 0.01, f"reduced-motion ripple opacity={opacity}"- finally:- page.close()---def test_typing_sweep_present(browser_ctx, page_url: str) -> None:- """Phase 9.5: typing-sweep element exists as a singleton."""- page = browser_ctx.new_page()- try:- page.goto(page_url)- page.wait_for_function(- "document.querySelector('.typing-sweep') !== null", timeout=2000- )- count = page.evaluate(- "document.querySelectorAll('.typing-sweep').length"- )- assert count == 1- finally:- page.close()---def test_cursor_trail_canvas_present(browser_ctx, page_url: str) -> None:- """Phase 9.5: cursor-trail-canvas exists."""- page = browser_ctx.new_page()- try:- page.goto(page_url)- page.wait_for_function(- "document.querySelector('.cursor-trail-canvas') !== null", timeout=2000- )- # Canvas is fullscreen.- rect = page.evaluate(- """() => {- const c = document.querySelector('.cursor-trail-canvas');- const r = c.getBoundingClientRect();- return {w: r.width, h: r.height};- }"""- )- assert rect["w"] > 100- assert rect["h"] > 100- finally:- page.close()diff --git a/tests/overlay/test_schema.py b/tests/overlay/test_schema.pydeleted file mode 100644index d3142d0a69..0000000000--- a/tests/overlay/test_schema.py+++ /dev/null@@ -1,175 +0,0 @@-"""Pydantic-v2-Schemas: Round-Trip + Discriminated Union + Defaults."""--from __future__ import annotations--import pytest-from pydantic import ValidationError--from overlay.schema import (- AckEnvelope,- AckPayload,- ActionEndedEnvelope,- ActionEndedPayload,- ActionStartedEnvelope,- ActionStartedPayload,- ClickEnvelope,- ClickPayload,- ConfigEnvelope,- ConfigPayload,- CursorEnvelope,- CursorPayload,- ErrorEnvelope,- ErrorPayload,- HeartbeatEnvelope,- HeartbeatPayload,- IPCMessage,- SCHEMA_VERSION,- StateEnvelope,- StatePayload,- is_state_type,- new_ulid,- now_ns,-)---def test_ulid_format() -> None:- u = new_ulid()- assert isinstance(u, str)- assert len(u) == 26 # Crockford Base32 ULID---def test_now_ns_is_unix_epoch() -> None:- import time-- a = now_ns()- b = time.time_ns()- assert abs(b - a) < 1_000_000_000 # innerhalb 1s---def test_schema_version_is_one() -> None:- assert SCHEMA_VERSION == 1---def test_state_envelope_round_trip() -> None:- e = StateEnvelope(payload=StatePayload(state="typing", intensity=0.8, reason="tool"))- raw = e.model_dump_json()- back = IPCMessage.validate_json(raw)- assert isinstance(back, StateEnvelope)- assert back.payload.state == "typing"- assert back.payload.intensity == 0.8- assert back.payload.reason == "tool"- assert back.v == 1- assert back.target == "*"--- "envelope_cls,payload",- [- (ClickEnvelope, ClickPayload(x=10, y=20, button="left")),- (ActionStartedEnvelope, ActionStartedPayload(kind="click")),- (ActionEndedEnvelope, ActionEndedPayload(action_id="X", succeeded=False)),- (CursorEnvelope, CursorPayload(x=1, y=2)),- (HeartbeatEnvelope, HeartbeatPayload(uptime_s=42.0, fps_actual=58.5)),- (ConfigEnvelope, ConfigPayload(mascot_enabled=False)),- (AckEnvelope, AckPayload(ack_id="X")),- (ErrorEnvelope, ErrorPayload(code="X", message="m")),- ],-)-def test_all_envelope_round_trips(envelope_cls, payload) -> None:- e = envelope_cls(payload=payload)- back = IPCMessage.validate_json(e.model_dump_json())- assert isinstance(back, envelope_cls)- assert back.payload == payload---def test_discriminator_rejects_unknown_type() -> None:- with pytest.raises(ValidationError):- IPCMessage.validate_python(- {"type": "definitely_unknown", "payload": {}, "id": "x", "ts_ns": 1}- )---def test_state_payload_intensity_clamped() -> None:- with pytest.raises(ValidationError):- StatePayload(state="idle", intensity=1.5)- with pytest.raises(ValidationError):- StatePayload(state="idle", intensity=-0.1)---def test_envelope_extra_forbid() -> None:- with pytest.raises(ValidationError):- IPCMessage.validate_python(- {- "type": "state",- "v": 1,- "id": "x",- "ts_ns": 1,- "target": "*",- "payload": {"state": "idle"},- "rogue_field": True,- }- )---def test_target_enum() -> None:- e = StateEnvelope(target="edgeglow", payload=StatePayload(state="idle"))- back = IPCMessage.validate_json(e.model_dump_json())- assert back.target == "edgeglow"-- with pytest.raises(ValidationError):- StateEnvelope(target="not-a-target", payload=StatePayload(state="idle")) # type: ignore[arg-type]---def test_state_name_enum() -> None:- with pytest.raises(ValidationError):- StatePayload(state="acting") # type: ignore[arg-type]---def test_is_state_type_classification() -> None:- # Plan §10.4 — drop oldest non-state first.- assert is_state_type("state") is True- assert is_state_type("config") is True- assert is_state_type("cursor") is False- assert is_state_type("heartbeat") is False- assert is_state_type("click") is False- assert is_state_type("ack") is False- assert is_state_type("unknown") is False---def test_envelope_v_must_be_at_least_1() -> None:- with pytest.raises(ValidationError):- IPCMessage.validate_python(- {- "type": "state",- "v": 0,- "id": "x",- "ts_ns": 1,- "target": "*",- "payload": {"state": "idle"},- }- )---def test_higher_version_accepted_for_forward_compat() -> None:- # Forward compat: receiver lets v=2 through (only logs a warning at- # the IPC layer); the Pydantic model itself must not raise.- msg = IPCMessage.validate_python(- {- "type": "state",- "v": 2,- "id": "x",- "ts_ns": 1,- "target": "*",- "payload": {"state": "idle"},- }- )- assert msg.v == 2---def test_jarvis_re_export_identical() -> None:- """``jarvis.overlay.schema`` must re-export exactly the same classes."""- from jarvis.overlay.schema import IPCMessage as JIPC- from jarvis.overlay.schema import StateEnvelope as JSE-- assert JIPC is IPCMessage- assert JSE is StateEnvelopediff --git a/tests/overlay/test_schema_symmetry.py b/tests/overlay/test_schema_symmetry.pydeleted file mode 100644index 019ba52fdd..0000000000--- a/tests/overlay/test_schema_symmetry.py+++ /dev/null@@ -1,217 +0,0 @@-"""JSON schema export as a CI gate for Phase 9.4 Zod symmetry (AD-15).--Phase 9.2 delivers the Pydantic side. Phase 9.4 will generate the Zod-schema and this test will then check structural equality. For now we-only verify that:--1. Pydantic can export a complete JSON schema for ``IPCMessage``.-2. Every envelope type has a unique discriminator value.-3. All expected type values are present.-4. Every envelope type is functionally round-trip-capable- (serialize -> deserialize via ``IPCMessage.validate_json``).-5. The TS side (``OS-Level/overlay-ui/src/schema.ts``) explicitly- documents the Phase-9.4 scope limitation (only the state slice is- mirrored).--Phase-9.10+ TODO (real Zod<->Pydantic symmetry):- Full structural equality between the Pydantic JSON schema and the- Zod schema only makes sense once all 9 envelopes are mirrored on- the TS side. At that point the test would need to run a- ``tsc/node`` subprocess (Zod schema -> JSON schema via- ``zod-to-json-schema``) and diff it against the Pydantic export.- For Phase 9.4 that would be overhead without payoff: the renderer- currently only needs the state slice. Planned from Phase 9.10- onward, once the overlay itself consumes click/cursor/action- envelopes.-"""--from __future__ import annotations--import json-from pathlib import Path--import pytest--from overlay.schema import IPCMessage---EXPECTED_TYPES = frozenset(- {- "state",- "click",- "action_started",- "action_ended",- "cursor",- "heartbeat",- "config",- "ack",- "error",- }-)---def test_json_schema_exportable() -> None:- schema = IPCMessage.json_schema()- assert isinstance(schema, dict)- # Pydantic v2 emits oneOf/discriminator for discriminated unions.- blob = json.dumps(schema)- for t in EXPECTED_TYPES:- assert f'"{t}"' in blob, f"type={t!r} missing from JSON schema"---def test_all_expected_types_present() -> None:- """Every envelope type must be validatable."""- for t in EXPECTED_TYPES:- # Minimal raw payload per type.- sample = _sample_for(t)- msg = IPCMessage.validate_python(sample)- assert msg.type == t---def _sample_for(t: str) -> dict:- base = {"v": 1, "id": "01HX9000000000000000000000", "ts_ns": 1, "target": "*", "type": t}- payload_map = {- "state": {"state": "idle"},- "click": {"x": 0, "y": 0},- "action_started": {"kind": "click", "action_id": "X"},- "action_ended": {"action_id": "X"},- "cursor": {"x": 0, "y": 0},- "heartbeat": {},- "config": {},- "ack": {"ack_id": "X"},- "error": {"code": "x", "message": "m"},- }- return {**base, "payload": payload_map[t]}---def test_discriminator_field_in_schema() -> None:- schema = IPCMessage.json_schema()- # Pydantic v2: the ``discriminator`` property is either under the ``oneOf``- # wrapper or at the top level. We accept both — what matters is that the- # ``type`` field carries the discriminator hint.- blob = json.dumps(schema)- assert "discriminator" in blob or "propertyName" in blob or '"type":' in blob---def test_schema_export_stable_for_drift_detection(tmp_path) -> None:- """Snapshot of the JSON schema. Phase 9.4 compares against the Zod output."""- schema = IPCMessage.json_schema()- snapshot = tmp_path / "ipc-schema.json"- snapshot.write_text(json.dumps(schema, indent=2, sort_keys=True), encoding="utf-8")- # Sanity: not empty, parseable.- parsed = json.loads(snapshot.read_text(encoding="utf-8"))- assert isinstance(parsed, dict)---# ------------------------------------------------------------------------------# New tests (MAJOR #9 — Plan §10.3 + AD-15 symmetry audit)-# --------------------------------------------------------------------------------def _find_overlay_ui_schema_ts() -> Path | None:- """Looks for ``OS-Level/overlay-ui/src/schema.ts`` from the test file.-- We may run from different roots (``Personal Jarvis`` vs.- ``Personal Jarvis-main``), so check multiple candidate paths.- """- here = Path(__file__).resolve()- candidates: list[Path] = []- for parent in (here.parent, *here.parents):- candidates.append(parent / "OS-Level" / "overlay-ui" / "src" / "schema.ts")- for path in candidates:- if path.is_file():- return path- return None---def test_zod_schema_file_documents_phase94_limitation() -> None:- """``schema.ts`` MUST explicitly document the Phase-9.4 scope limitation.-- Plan AD-15 demands symmetric Pydantic<->Zod schemas. Phase 9.4,- however, only mirrors the state slice (StateName + StateChange), not- all 9 envelopes. This scope limitation must be visible as a- comment/TODO in the TS file, otherwise silent drift creeps in.- """- schema_ts = _find_overlay_ui_schema_ts()- if schema_ts is None:- pytest.skip(- "OS-Level/overlay-ui/src/schema.ts not found — "- "Phase 9.4 frontend tree is missing in this checkout."- )-- text = schema_ts.read_text(encoding="utf-8")- head = "\n".join(text.splitlines()[:30]).lower()-- # Accepted: a Phase-9.4 hint OR an explicit TODO/limitation/scope hint- # about additional envelopes (or a reference to AD-15).- phase_marker = any(- token in head- for token in (- "9.4",- "9.10",- "phase 9",- "todo",- "ad-15",- "limitation",- "scope",- )- )- envelope_marker = any(- token in head- for token in (- "envelope",- "weitere envelopes", # i18n-allow: matched literally against schema.ts content- "additional envelopes",- "more envelopes",- "state-slice",- "state slice",- )- )-- if not (phase_marker and envelope_marker):- pytest.fail(- "AD-15 symmetry audit missing: schema.ts does not document the "- "Phase-9.4 scope limitation. Please add a 1-5 line comment at the "- "top explaining that only the state slice is mirrored and "- "further envelopes follow from Phase 9.10+.\n"- f"File: {schema_ts}\n"- f"First 30 lines:\n{head}"- )---def test_envelope_round_trip_each_type() -> None:- """Each of the 9 envelope types must be JSON-round-trip-capable.-- Serialize a sample -> validate_json -> assert ``type`` and all- payload keys are identical. Prevents a future Pydantic refactor- from breaking the discriminated union without any test making- noise.- """- for t in EXPECTED_TYPES:- sample = _sample_for(t)- # Bytes path (real-life wire format).- raw = json.dumps(sample).encode("utf-8")- msg = IPCMessage.validate_json(raw)-- # Discriminator must be preserved.- assert msg.type == t, f"type mismatch for {t!r}: got {msg.type!r}"-- # All payload keys from the sample must end up in the- # deserialized object (extra="forbid" on the payloads secures- # the reverse direction — no key gets lost).- sample_payload = sample["payload"]- deserialized_payload = msg.payload.model_dump()- for key, expected in sample_payload.items():- assert key in deserialized_payload, (- f"Payload key {key!r} missing after round trip for type={t!r}"- )- assert deserialized_payload[key] == expected, (- f"Payload value for {key!r} differs for type={t!r}: "- f"expected {expected!r}, got {deserialized_payload[key]!r}"- )-- # Envelope fields must be identical.- assert msg.v == sample["v"]- assert msg.id == sample["id"]- assert msg.ts_ns == sample["ts_ns"]- assert msg.target == sample["target"]diff --git a/tests/overlay/test_smoke.py b/tests/overlay/test_smoke.pydeleted file mode 100644index 096be06857..0000000000--- a/tests/overlay/test_smoke.py+++ /dev/null@@ -1,35 +0,0 @@-"""Smoke-Test: ``python -m overlay --self-test`` exit 0 mit ``OK ...``."""--from __future__ import annotations--import subprocess-import sys-from pathlib import Path---REPO_ROOT = Path(__file__).resolve().parents[2]-OS_LEVEL_SRC = REPO_ROOT / "OS-Level" / "src"---def test_self_test_exits_zero_with_ok() -> None:- env_pythonpath = str(OS_LEVEL_SRC)- result = subprocess.run(- [sys.executable, "-m", "overlay", "--self-test"],- capture_output=True,- text=True,- timeout=30,- env={- **_clean_env(),- "PYTHONPATH": env_pythonpath,- },- )- assert result.returncode == 0, (- f"exit={result.returncode}\nstdout={result.stdout}\nstderr={result.stderr}"- )- assert result.stdout.startswith("OK"), result.stdout---def _clean_env() -> dict[str, str]:- import os-- return {k: v for k, v in os.environ.items()}diff --git a/tests/overlay/test_state.py b/tests/overlay/test_state.pydeleted file mode 100644index 38c7a73e9d..0000000000--- a/tests/overlay/test_state.py+++ /dev/null@@ -1,37 +0,0 @@-"""OverlayState — 8 States, stable wire-strings, GLOW_ACTIVE_STATES."""--from __future__ import annotations--from overlay.state import GLOW_ACTIVE_STATES, OverlayState---def test_eight_states() -> None:- assert len(list(OverlayState)) == 8---def test_stable_string_values() -> None:- expected = {- OverlayState.IDLE: "idle",- OverlayState.LISTENING: "listening",- OverlayState.THINKING: "thinking",- OverlayState.TYPING: "typing",- OverlayState.CLICKING: "clicking",- OverlayState.SPEAKING: "speaking",- OverlayState.ERROR: "error",- OverlayState.HIDDEN: "hidden",- }- for state, wire in expected.items():- assert state.value == wire---def test_str_enum_inherits_string() -> None:- # Important for JSON serialization in Phase 9.2.- assert isinstance(OverlayState.IDLE.value, str)- assert OverlayState.IDLE == "idle"---def test_glow_active_only_in_typing_clicking() -> None:- # Plan §6.1 — glow is ONLY active in TYPING and CLICKING.- assert GLOW_ACTIVE_STATES == frozenset(- {OverlayState.TYPING, OverlayState.CLICKING}- )diff --git a/tests/overlay/test_state_machine.py b/tests/overlay/test_state_machine.pydeleted file mode 100644index a594a3304b..0000000000--- a/tests/overlay/test_state_machine.py+++ /dev/null@@ -1,187 +0,0 @@-"""StateMachine — Plan §6 + AD-8 + AD-17.--Tests for coalescing, subscriber dispatch, re-entrancy.-"""--from __future__ import annotations--import threading-import time--import pytest--from overlay.state import (- COALESCE_WINDOW_NS,- GLOW_ACTIVE_STATES,- OverlayState,- StateMachine,-)---# --------------------------------------------------------------------------# Construction + initial state-# ----------------------------------------------------------------------------def test_initial_state_default_idle() -> None:- sm = StateMachine()- assert sm.state is OverlayState.IDLE---def test_initial_state_override() -> None:- sm = StateMachine(initial=OverlayState.HIDDEN)- assert sm.state is OverlayState.HIDDEN---# --------------------------------------------------------------------------# transition_to + Subscribers-# ----------------------------------------------------------------------------def test_transition_changes_state_and_returns_true() -> None:- sm = StateMachine()- assert sm.transition_to(OverlayState.LISTENING) is True- assert sm.state is OverlayState.LISTENING---def test_transition_to_same_state_returns_false() -> None:- sm = StateMachine(initial=OverlayState.IDLE)- assert sm.transition_to(OverlayState.IDLE) is False- assert sm.state is OverlayState.IDLE---def test_subscriber_fires_on_transition() -> None:- sm = StateMachine()- events: list[tuple[OverlayState, OverlayState, str | None]] = []- sm.subscribe(lambda old, new, reason: events.append((old, new, reason)))-- sm.transition_to(OverlayState.LISTENING, reason="wakeword")- sm.transition_to(OverlayState.THINKING, reason="user")-- assert events == [- (OverlayState.IDLE, OverlayState.LISTENING, "wakeword"),- (OverlayState.LISTENING, OverlayState.THINKING, "user"),- ]---def test_subscriber_does_not_fire_on_no_change() -> None:- sm = StateMachine()- fired: list[OverlayState] = []- sm.subscribe(lambda _o, n, _r: fired.append(n))-- sm.transition_to(OverlayState.IDLE)- assert fired == []---def test_unsubscribe_stops_callbacks() -> None:- sm = StateMachine()- fired: list[OverlayState] = []- unsub = sm.subscribe(lambda _o, n, _r: fired.append(n))-- sm.transition_to(OverlayState.LISTENING)- unsub()- sm.transition_to(OverlayState.THINKING)-- assert fired == [OverlayState.LISTENING]---def test_subscriber_exception_does_not_break_others() -> None:- sm = StateMachine()- fired: list[OverlayState] = []-- def boom(_o: OverlayState, _n: OverlayState, _r: str | None) -> None:- raise RuntimeError("subscriber crash")-- sm.subscribe(boom)- sm.subscribe(lambda _o, n, _r: fired.append(n))-- assert sm.transition_to(OverlayState.LISTENING) is True- assert fired == [OverlayState.LISTENING]---def test_subscriber_runs_in_caller_thread() -> None:- sm = StateMachine()- seen_thread: list[int] = []- sm.subscribe(lambda _o, _n, _r: seen_thread.append(threading.get_ident()))-- main_ident = threading.get_ident()- sm.transition_to(OverlayState.LISTENING)- assert seen_thread == [main_ident]---def test_reentrant_transition_is_safe() -> None:- """Subscriber may read state AND call transition_to again."""-- sm = StateMachine()- chain: list[OverlayState] = []-- def chained(_old: OverlayState, new: OverlayState, _r: str | None) -> None:- chain.append(new)- if new is OverlayState.LISTENING:- # Re-entrant call — the RLock must support this.- sm.transition_to(OverlayState.THINKING, reason="chained")-- sm.subscribe(chained)- sm.transition_to(OverlayState.LISTENING)-- assert chain == [OverlayState.LISTENING, OverlayState.THINKING]- assert sm.state is OverlayState.THINKING---# --------------------------------------------------------------------------# Coalescing — AD-17-# ----------------------------------------------------------------------------def test_same_state_within_coalesce_window_returns_false() -> None:- sm = StateMachine()- sm.transition_to(OverlayState.LISTENING)- # Immediately LISTENING again -> coalesced.- assert sm.transition_to(OverlayState.LISTENING) is False---def test_different_state_within_coalesce_window_transitions() -> None:- sm = StateMachine()- sm.transition_to(OverlayState.LISTENING)- # Different target state within 16 ms -> always let through.- assert sm.transition_to(OverlayState.THINKING) is True- assert sm.state is OverlayState.THINKING---def test_coalesce_window_is_16_ms() -> None:- # Sanity: constant = 16 ms.- assert COALESCE_WINDOW_NS == 16_000_000---def test_same_state_after_coalesce_window_still_returns_false() -> None:- """Plan §6.2: no state change stays a no-op even after 16 ms."""-- sm = StateMachine()- sm.transition_to(OverlayState.LISTENING)- # Wait 25 ms — beyond the coalescing window — but same target.- time.sleep(0.025)- assert sm.transition_to(OverlayState.LISTENING) is False---# --------------------------------------------------------------------------# Glow state set-# ---------------------------------------------------------------------------- "state, glow_expected",- [- (OverlayState.IDLE, False),- (OverlayState.LISTENING, False),- (OverlayState.THINKING, False),- (OverlayState.TYPING, True),- (OverlayState.CLICKING, True),- (OverlayState.SPEAKING, False),- (OverlayState.ERROR, False),- (OverlayState.HIDDEN, False),- ],-)-def test_glow_active_states_match_plan(- state: OverlayState, glow_expected: bool-) -> None:- assert (state in GLOW_ACTIVE_STATES) is glow_expecteddiff --git a/tests/overlay/test_supervisor.py b/tests/overlay/test_supervisor.pydeleted file mode 100644index 77899fcdd5..0000000000--- a/tests/overlay/test_supervisor.py+++ /dev/null@@ -1,269 +0,0 @@-"""OverlaySupervisor — job object + backoff + cap. Plan §4.3 + AD-9 + AD-10."""--from __future__ import annotations--import asyncio-import random-from typing import Any-from unittest import mock--import pytest--from jarvis.overlay.supervisor import (- DEFAULT_RESTART_CAP_COUNT,- OverlaySupervisor,- _backoff_delay,-)---# --------------------------------------------------------------------------# _backoff_delay — AD-10 formula-# ----------------------------------------------------------------------------def test_backoff_first_failure_around_half_second() -> None:- """failures=0 -> base=0.5, +/- 20% jitter -> ~0.4 .. 0.6 s."""- rng = random.Random(0)- delays = [_backoff_delay(0, rng=rng) for _ in range(50)]- assert all(0.35 < d < 0.65 for d in delays)---def test_backoff_caps_at_30_seconds() -> None:- """Plan AD-10: ``min(30, ...)`` — no matter how many failures."""- rng = random.Random(0)- for f in [10, 20, 50, 100]:- delay = _backoff_delay(f, rng=rng)- assert delay <= 30 * 1.2 # +20% jitter ceiling---def test_backoff_grows_exponentially() -> None:- """failures=0,1,2,3 -> base 0.5, 1, 2, 4."""- rng = random.Random(0)- avg = []- for f in [0, 1, 2, 3]:- samples = [_backoff_delay(f, rng=rng) for _ in range(50)]- avg.append(sum(samples) / len(samples))- # Each further step roughly doubles.- assert avg[1] > 1.5 * avg[0]- assert avg[2] > 1.5 * avg[1]- assert avg[3] > 1.5 * avg[2]---# --------------------------------------------------------------------------# Spawn / Mock-Subprocess-# ----------------------------------------------------------------------------def _make_mock_proc(alive: bool = True, pid: int = 1234) -> mock.MagicMock:- """Mock Popen: poll() returns None when alive, 0 when finished."""- proc = mock.MagicMock()- proc.pid = pid- proc.poll = mock.MagicMock(return_value=None if alive else 0)- proc.wait = mock.MagicMock(return_value=0)- proc.terminate = mock.MagicMock()- proc.kill = mock.MagicMock()- return proc---async def test_spawn_calls_subprocess_with_python_and_overlay_args() -> None:- captured = {}-- def spawn_fn(args: list[str], **kwargs: Any) -> mock.MagicMock:- captured["args"] = args- captured["kwargs"] = kwargs- return _make_mock_proc()-- sup = OverlaySupervisor(ws_port=7842, spawn_fn=spawn_fn)- try:- await sup.start()- # Right after start, the proc is there.- assert sup.is_alive- assert "args" in captured- # Args: python sys.executable -m overlay --ws-port=7842- assert captured["args"][1:] == ["-m", "overlay", "--ws-port=7842"]- finally:- await sup.stop()---async def test_spawn_subprocess_env_unsets_jarvis_depth() -> None:- """Plan: the overlay process itself is NOT a sub-agent."""- captured = {}-- def spawn_fn(args: list[str], **kwargs: Any) -> mock.MagicMock:- captured["env"] = kwargs.get("env")- return _make_mock_proc()-- sup = OverlaySupervisor(spawn_fn=spawn_fn, env={"JARVIS_DEPTH": "2"})- try:- await sup.start()- env = captured["env"]- assert "JARVIS_DEPTH" not in env- finally:- await sup.stop()---async def test_subprocess_creationflags_on_win32() -> None:- """Plan: CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW on Windows."""- import sys-- if sys.platform != "win32":- pytest.skip("creationflags required only on Windows")-- captured = {}-- def spawn_fn(args: list[str], **kwargs: Any) -> mock.MagicMock:- captured["creationflags"] = kwargs.get("creationflags")- return _make_mock_proc()-- sup = OverlaySupervisor(spawn_fn=spawn_fn)- try:- await sup.start()- # Should contain both bits.- cf = captured["creationflags"]- assert cf & 0x00000200 # CREATE_NEW_PROCESS_GROUP- assert cf & 0x08000000 # CREATE_NO_WINDOW- finally:- await sup.stop()---# --------------------------------------------------------------------------# Heartbeat-Timeout -> Respawn-# ----------------------------------------------------------------------------async def test_heartbeat_timeout_triggers_respawn() -> None:- """When no heartbeat for 3 s: kill + respawn with backoff."""- spawn_count = [0]-- def spawn_fn(args: list[str], **kwargs: Any) -> mock.MagicMock:- spawn_count[0] += 1- return _make_mock_proc()-- sup = OverlaySupervisor(- spawn_fn=spawn_fn,- heartbeat_timeout_s=0.05, # 50 ms for the test- rng=random.Random(0),- )- try:- await sup.start()- assert spawn_count[0] == 1- # Wait until the monitor loop sees the heartbeat timeout + respawns.- # 50 ms timeout + 0.5s monitor tick + ~0.5s backoff = ~1.5 s.- await asyncio.sleep(2.5)- assert spawn_count[0] >= 2, f"expected >=2 spawns, got {spawn_count[0]}"- finally:- await sup.stop()---async def test_notify_heartbeat_prevents_respawn() -> None:- """When heartbeats keep coming steadily, no respawn."""- spawn_count = [0]-- def spawn_fn(args: list[str], **kwargs: Any) -> mock.MagicMock:- spawn_count[0] += 1- return _make_mock_proc()-- sup = OverlaySupervisor(- spawn_fn=spawn_fn,- heartbeat_timeout_s=0.1,- rng=random.Random(0),- )- try:- await sup.start()- # 6x heartbeat over 0.6 s.- for _ in range(6):- sup.notify_heartbeat()- await asyncio.sleep(0.05)- # Should still be exactly 1 spawn.- assert spawn_count[0] == 1- finally:- await sup.stop()---# --------------------------------------------------------------------------# Cap (5 in 5 min)-# ----------------------------------------------------------------------------async def test_cap_fired_after_too_many_restarts() -> None:- """Plan AD-10: cap after 5 restarts in the default window. We use- cap_count=2 + a tiny backoff for test speed; the logic is the same."""- cap_called = [0]-- spawn_count = [0]-- def spawn_fn(args: list[str], **kwargs: Any) -> mock.MagicMock:- spawn_count[0] += 1- return _make_mock_proc()-- # With cap_count=2, the cap fires on the 3rd spawn attempt.- sup = OverlaySupervisor(- spawn_fn=spawn_fn,- heartbeat_timeout_s=0.02,- restart_cap_count=2,- restart_cap_window_s=30.0,- cap_fired_callback=lambda: cap_called.__setitem__(0, cap_called[0] + 1),- # Deterministic small backoff — we want to reach the cap quickly.- rng=random.Random(0),- )- # Backoff override: significantly shorter for test performance.- sup._stable_reset = 9999.0 # noqa: SLF001 — no stable resets in the test- try:- await sup.start()- # 4 attempts: initial + 3 restarts. Backoff 0.5+1+2 = ~3.5 s, plus- # monitor-tick latency. We give it 6 s.- await asyncio.sleep(6.0)- assert sup.cap_active is True, f"cap not fired (spawns={spawn_count[0]})"- assert cap_called[0] == 1- finally:- await sup.stop()---async def test_manual_reset_clears_cap_state() -> None:- sup = OverlaySupervisor(spawn_fn=lambda *a, **k: _make_mock_proc())- # Set the cap directly without the spawn loop.- sup._cap_active = True # noqa: SLF001- sup._failures = 99 # noqa: SLF001- sup.manual_reset()- assert sup.cap_active is False- assert sup.failure_count == 0---# --------------------------------------------------------------------------# Lifecycle-# ----------------------------------------------------------------------------async def test_start_is_idempotent() -> None:- spawn_count = [0]-- def spawn_fn(args: list[str], **kwargs: Any) -> mock.MagicMock:- spawn_count[0] += 1- return _make_mock_proc()-- sup = OverlaySupervisor(spawn_fn=spawn_fn)- try:- await sup.start()- await sup.start()- await sup.start()- assert spawn_count[0] == 1- finally:- await sup.stop()---async def test_stop_terminates_subprocess() -> None:- proc = _make_mock_proc()-- sup = OverlaySupervisor(spawn_fn=lambda *a, **k: proc)- await sup.start()- await sup.stop()- proc.terminate.assert_called()diff --git a/tests/overlay/test_system_cursor.py b/tests/overlay/test_system_cursor.pydeleted file mode 100644index bbe4101bf7..0000000000--- a/tests/overlay/test_system_cursor.py+++ /dev/null@@ -1,317 +0,0 @@-"""System-cursor lifecycle + session_bracket.--The Win32 + Pillow side is exercised by the live restart / demo; here we-test only the pure lifecycle (activate-once, idle-restore, shutdown safety,-session-bracket entry/exit semantics) with injected ``activate_fn`` /-``restore_fn`` / scheduler, so it runs everywhere — including the headless-CI box this project's cloud-first doctrine targets.-"""-from __future__ import annotations--import asyncio-import sys--import pytest--from jarvis.overlay.system_cursor import JarvisSystemCursor---def _rec():- calls: list[int] = []- return calls, lambda: calls.append(1)---class _FakeTimer:- def __init__(self) -> None:- self.cancelled = False-- def cancel(self) -> None:- self.cancelled = True---def _make_scheduler():- """Capture (delay, callback) pairs and return cancellable handles."""- scheduled: list[tuple[int, callable, _FakeTimer]] = []-- def schedule(ms: int, cb):- t = _FakeTimer()- scheduled.append((ms, cb, t))- return t-- return scheduled, schedule---# ----------------------------------------------------------------------------# JarvisSystemCursor lifecycle-# ------------------------------------------------------------------------------def test_ping_activates_when_inactive() -> None:- acts, activate = _rec()- restores, restore = _rec()- _, schedule = _make_scheduler()- c = JarvisSystemCursor(activate_fn=activate, restore_fn=restore, schedule_after=schedule)- c.ping()- assert len(acts) == 1- assert len(restores) == 0---def test_second_ping_does_not_reactivate() -> None:- acts, activate = _rec()- _, restore = _rec()- _, schedule = _make_scheduler()- c = JarvisSystemCursor(activate_fn=activate, restore_fn=restore, schedule_after=schedule)- c.ping()- c.ping()- assert len(acts) == 1 # cursor was already Jarvis-themed; no second swap---def test_ping_reschedules_idle_timer() -> None:- _, activate = _rec()- _, restore = _rec()- scheduled, schedule = _make_scheduler()- c = JarvisSystemCursor(activate_fn=activate, restore_fn=restore, schedule_after=schedule)- c.ping()- c.ping()- assert len(scheduled) == 2- assert scheduled[0][2].cancelled is True- assert scheduled[1][2].cancelled is False---def test_idle_fire_restores_default_cursor() -> None:- _, activate = _rec()- restores, restore = _rec()- _, schedule = _make_scheduler()- c = JarvisSystemCursor(activate_fn=activate, restore_fn=restore, schedule_after=schedule)- c.ping()- c._idle_fire()- assert len(restores) == 1---def test_idle_fire_after_restore_is_noop() -> None:- _, activate = _rec()- restores, restore = _rec()- _, schedule = _make_scheduler()- c = JarvisSystemCursor(activate_fn=activate, restore_fn=restore, schedule_after=schedule)- c.ping()- c._idle_fire()- c._idle_fire()- assert len(restores) == 1 # never restore twice (would visibly flicker)---def test_ping_after_idle_reactivates() -> None:- acts, activate = _rec()- _, restore = _rec()- _, schedule = _make_scheduler()- c = JarvisSystemCursor(activate_fn=activate, restore_fn=restore, schedule_after=schedule)- c.ping()- c._idle_fire()- c.ping()- assert len(acts) == 2 # Jarvis is back at the wheel; new swap---def test_shutdown_restores_when_active() -> None:- _, activate = _rec()- restores, restore = _rec()- _, schedule = _make_scheduler()- c = JarvisSystemCursor(activate_fn=activate, restore_fn=restore, schedule_after=schedule)- c.ping()- c.shutdown()- assert len(restores) == 1---def test_shutdown_when_inactive_is_noop() -> None:- _, activate = _rec()- restores, restore = _rec()- _, schedule = _make_scheduler()- c = JarvisSystemCursor(activate_fn=activate, restore_fn=restore, schedule_after=schedule)- c.shutdown()- assert len(restores) == 0---def test_activate_failure_keeps_state_inactive() -> None:- def boom() -> None:- raise RuntimeError("CreateIconIndirect failed")-- restores, restore = _rec()- _, schedule = _make_scheduler()- c = JarvisSystemCursor(activate_fn=boom, restore_fn=restore, schedule_after=schedule)- c.ping()- assert c._active is False- c.shutdown()- assert restores == [] # nothing to restore — activation never succeeded--[email protected](sys.platform != "win32", reason="real Win32 HCURSOR build is Windows-only")-def test_create_hcursor_does_not_overflow_on_64bit_handles() -> None:- """Regression (2026-06-22): the gdi32/user32 handle args were passed to- ctypes WITHOUT ``argtypes``, so on 64-bit Windows a >2^31 HBITMAP overflowed- the default ``c_int`` marshalling ("OverflowError: int too long to convert")- at the cleanup ``DeleteObject``. ``_real_activate`` therefore raised on EVERY- Computer-Use mission, the failure was swallowed at DEBUG by- ``JarvisSystemCursor.ping``, and the user kept their default cursor instead of- the gold Jarvis one. Building the cursor must NOT raise and must return a- real non-zero HCURSOR. (Builds + destroys an icon only — does NOT swap the- live system cursor, so it is safe to run in the suite.)"""- import ctypes- from ctypes import wintypes-- from jarvis.overlay.system_cursor import _create_hcursor_from_rgba-- rgba = bytes(48 * 48 * 4) # synthetic transparent RGBA; no Pillow needed- hcur = _create_hcursor_from_rgba(- rgba, width=48, height=48, hotspot_x=2, hotspot_y=2,- )- assert hcur != 0, "HCURSOR build returned 0 (DIB / CreateIconIndirect failed)"-- # Clean up the HICON/HCURSOR we just built (argtypes pinned for the same- # 64-bit-handle reason the fix is about).- user32 = ctypes.windll.user32- user32.DestroyIcon.argtypes = [wintypes.HANDLE]- user32.DestroyIcon.restype = wintypes.BOOL- user32.DestroyIcon(hcur)---def test_ping_jarvis_cursor_helper_is_safe_when_none_set() -> None:- from jarvis.overlay.system_cursor import (- ping_jarvis_cursor,- set_jarvis_system_cursor,- )-- set_jarvis_system_cursor(None)- ping_jarvis_cursor() # must not raise---# ----------------------------------------------------------------------------# session_bracket — activate at start of a Computer-Use mission, restore at end-# ------------------------------------------------------------------------------class _Recorder:- def __init__(self) -> None:- self.pings = 0- self.shutdowns = 0-- def ping(self) -> None:- self.pings += 1-- def shutdown(self) -> None:- self.shutdowns += 1---def test_session_bracket_activates_at_entry_and_restores_at_exit() -> None:- from jarvis.overlay.system_cursor import (- session_bracket,- set_jarvis_system_cursor,- )-- rec = _Recorder()- set_jarvis_system_cursor(rec)- try:-- async def run() -> None:- async with session_bracket():- # Mid-session: cursor is Jarvis from the very first moment of- # the mission, before the agent even takes its first- # screenshot. No 3-5 s window with the default cursor.- assert rec.pings == 1- assert rec.shutdowns == 0- # On exit: explicit restore — instant, no 30 s idle wait.- assert rec.shutdowns == 1-- asyncio.run(run())- finally:- set_jarvis_system_cursor(None)---def test_session_bracket_restores_even_on_exception() -> None:- from jarvis.overlay.system_cursor import (- session_bracket,- set_jarvis_system_cursor,- )-- rec = _Recorder()- set_jarvis_system_cursor(rec)- try:-- async def run() -> None:- with pytest.raises(RuntimeError):- async with session_bracket():- raise RuntimeError("agent crashed mid-mission")-- asyncio.run(run())- # Crash must still leave the user's cursor restored.- assert rec.shutdowns == 1- finally:- set_jarvis_system_cursor(None)---def test_session_bracket_is_noop_when_no_cursor_installed() -> None:- from jarvis.overlay.system_cursor import (- session_bracket,- set_jarvis_system_cursor,- )-- set_jarvis_system_cursor(None) # headless / no display-- async def run() -> None:- async with session_bracket():- pass # must not raise-- asyncio.run(run()) # no exception expected---def test_session_bracket_logs_entry_and_exit(caplog) -> None:- # Operators need a log breadcrumb confirming session-bracket activation- # for every mission, because the user can't see the SetSystemCursor swap- # in the log (the swap is silent — only the activate call logs at debug- # on failure). An info-level entry+exit makes "did my cursor system fire- # at mission start?" verifiable without running the GUI.- from jarvis.overlay.system_cursor import (- session_bracket,- set_jarvis_system_cursor,- )-- rec = _Recorder()- set_jarvis_system_cursor(rec)- try:-- async def run() -> None:- with caplog.at_level("INFO", logger="jarvis.overlay.system_cursor"):- async with session_bracket():- pass-- asyncio.run(run())- messages = [r.getMessage() for r in caplog.records]- assert any("session_bracket entered" in m for m in messages)- assert any("session_bracket exited" in m for m in messages)- finally:- set_jarvis_system_cursor(None)---def test_session_bracket_survives_a_broken_cursor() -> None:- # If the registered cursor's ping/shutdown blows up, the bracket must NOT- # let the exception escape into the loop — a broken overlay never breaks- # the mission. Same defence as the existing ping_jarvis_cursor helper.- from jarvis.overlay.system_cursor import (- session_bracket,- set_jarvis_system_cursor,- )-- class _Broken:- def ping(self) -> None:- raise RuntimeError("ping boom")-- def shutdown(self) -> None:- raise RuntimeError("shutdown boom")-- set_jarvis_system_cursor(_Broken())- try:-- async def run() -> None:- async with session_bracket():- pass # must complete cleanly-- asyncio.run(run()) # no exception expected- finally:- set_jarvis_system_cursor(None)diff --git a/tests/overlay/test_throttler.py b/tests/overlay/test_throttler.pydeleted file mode 100644index 7f2f80c936..0000000000--- a/tests/overlay/test_throttler.py+++ /dev/null@@ -1,202 +0,0 @@-"""Throttler — Plan §17.2 + §17.3 FPS-Targets + Hide-Logic."""--from __future__ import annotations--import time--import pytest--from overlay.state import OverlayState, StateMachine-from overlay.throttler import (- DEFAULT_FPS_ACTIVE,- DEFAULT_FPS_BURST,- DEFAULT_FPS_IDLE,- Throttler,-)---def machine() -> StateMachine:- return StateMachine()---# --------------------------------------------------------------------------# State -> FPS Mapping-# ----------------------------------------------------------------------------def test_initial_state_idle_returns_active_fps(machine: StateMachine) -> None:- """IDLE within idle_timeout -> active FPS (mascot still breathing)."""- t = Throttler(machine)- assert t.get_target_fps() == DEFAULT_FPS_ACTIVE---def test_typing_uses_burst_fps(machine: StateMachine) -> None:- t = Throttler(machine)- machine.transition_to(OverlayState.TYPING)- assert t.get_target_fps() == DEFAULT_FPS_BURST---def test_clicking_uses_burst_fps(machine: StateMachine) -> None:- t = Throttler(machine)- machine.transition_to(OverlayState.CLICKING)- assert t.get_target_fps() == DEFAULT_FPS_BURST---def test_listening_uses_active_fps(machine: StateMachine) -> None:- t = Throttler(machine)- machine.transition_to(OverlayState.LISTENING)- assert t.get_target_fps() == DEFAULT_FPS_ACTIVE---def test_hidden_state_uses_zero_fps(machine: StateMachine) -> None:- t = Throttler(machine)- machine.transition_to(OverlayState.HIDDEN)- snapshot = t.recompute()- assert snapshot.target_fps == 0- assert snapshot.should_hide_view is True---# --------------------------------------------------------------------------# Power: AC vs Battery halbiert-# ----------------------------------------------------------------------------def test_battery_halves_burst_fps(machine: StateMachine) -> None:- t = Throttler(machine)- machine.transition_to(OverlayState.TYPING)- assert t.get_target_fps() == DEFAULT_FPS_BURST # 60- t.set_on_battery(True)- assert t.get_target_fps() == DEFAULT_FPS_BURST // 2 # 30---def test_battery_halves_active_fps(machine: StateMachine) -> None:- t = Throttler(machine)- machine.transition_to(OverlayState.SPEAKING)- t.set_on_battery(True)- assert t.get_target_fps() == DEFAULT_FPS_ACTIVE // 2---def test_back_to_ac_restores_full_fps(machine: StateMachine) -> None:- t = Throttler(machine)- machine.transition_to(OverlayState.TYPING)- t.set_on_battery(True)- assert t.get_target_fps() == 30- t.set_on_battery(False)- assert t.get_target_fps() == 60---# --------------------------------------------------------------------------# Idle-Timeout-# ----------------------------------------------------------------------------def test_idle_timeout_drops_to_idle_fps(machine: StateMachine) -> None:- """Plan §17.3 — 30 s no events -> fps_idle. We use 50 ms for testing."""- t = Throttler(machine, idle_timeout_s=0.05)- # IDLE start, immediately: still active.- assert t.get_target_fps() == DEFAULT_FPS_ACTIVE- time.sleep(0.07)- assert t.get_target_fps() == DEFAULT_FPS_IDLE---def test_state_change_resets_idle_timer(machine: StateMachine) -> None:- t = Throttler(machine, idle_timeout_s=0.05)- time.sleep(0.07)- assert t.get_target_fps() == DEFAULT_FPS_IDLE # idle bucket- machine.transition_to(OverlayState.LISTENING)- # After a state change, the timer resets -> no longer in the idle bucket.- assert t.get_target_fps() == DEFAULT_FPS_ACTIVE---# --------------------------------------------------------------------------# Hide-Timeout-# ----------------------------------------------------------------------------def test_hide_timeout_sets_should_hide_view(machine: StateMachine) -> None:- """Plan §17.3 — 5 min no events -> IsVisible False."""- t = Throttler(machine, idle_timeout_s=0.02, hide_timeout_s=0.06)- time.sleep(0.08)- snap = t.recompute()- assert snap.should_hide_view is True- assert snap.target_fps == 0---def test_state_change_un_hides(machine: StateMachine) -> None:- t = Throttler(machine, idle_timeout_s=0.02, hide_timeout_s=0.06)- time.sleep(0.08)- assert t.recompute().should_hide_view is True- machine.transition_to(OverlayState.LISTENING)- assert t.recompute().should_hide_view is False---# --------------------------------------------------------------------------# Fullscreen-Hide-# ----------------------------------------------------------------------------def test_fullscreen_hide_overrides_state(machine: StateMachine) -> None:- t = Throttler(machine)- machine.transition_to(OverlayState.TYPING)- assert t.get_target_fps() == DEFAULT_FPS_BURST- t.set_fullscreen_should_hide(True)- snap = t.recompute()- assert snap.target_fps == 0- assert snap.should_hide_view is True- assert snap.is_hidden_state is True---def test_fullscreen_release_returns_to_state_fps(machine: StateMachine) -> None:- t = Throttler(machine)- machine.transition_to(OverlayState.TYPING)- t.set_fullscreen_should_hide(True)- assert t.get_target_fps() == 0- t.set_fullscreen_should_hide(False)- assert t.get_target_fps() == DEFAULT_FPS_BURST---# --------------------------------------------------------------------------# Subscriber only fires on a real change-# ----------------------------------------------------------------------------def test_subscriber_fires_on_initial(machine: StateMachine) -> None:- fired = []- t = Throttler(machine)- t.subscribe(lambda s: fired.append(s))- assert len(fired) == 1---def test_subscriber_does_not_fire_on_idle_seconds_drift(- machine: StateMachine,-) -> None:- """idle_seconds changes continuously — without a change in- target_fps or should_hide_view, no subscriber spam."""- fired = []- t = Throttler(machine)- t.subscribe(lambda s: fired.append(s))- initial_count = len(fired)- # 5x recompute in quick succession — no real changes.- for _ in range(5):- t.recompute()- assert len(fired) == initial_count---def test_subscriber_fires_on_battery_transition(machine: StateMachine) -> None:- fired = []- t = Throttler(machine)- t.subscribe(lambda s: fired.append(s))- initial = len(fired)- t.set_on_battery(True)- assert len(fired) > initial---def test_subscriber_fires_on_state_change(machine: StateMachine) -> None:- fired = []- t = Throttler(machine)- t.subscribe(lambda s: fired.append(s))- initial = len(fired)- machine.transition_to(OverlayState.TYPING)- # Must fire at least once more.- assert len(fired) > initialdiff --git a/tests/overlay/test_tool_cursor_wiring.py b/tests/overlay/test_tool_cursor_wiring.pydeleted file mode 100644index d1aaaf7bb0..0000000000--- a/tests/overlay/test_tool_cursor_wiring.py+++ /dev/null@@ -1,88 +0,0 @@-"""The click / move tools drive the virtual cursor before they act.--We monkeypatch the real Win32 motion (``glide_os_cursor``) and button send-(``_send_click`` / ``_move_windows`` internals) so nothing actually clicks the-host machine during the test — we only assert the wiring:-- * the real cursor is glided to the exact target,- * the overlay gets a click pulse / move at that target,- * the real button press still fires.-"""-from __future__ import annotations--import pytest--from jarvis.overlay.virtual_cursor import NullVirtualCursor, set_virtual_cursor---class _RecordingCursor(NullVirtualCursor):- def __init__(self) -> None:- self.clicks: list[tuple[int, int, str, bool]] = []- self.moves: list[tuple[int, int]] = []-- def show_click(self, x, y, *, button="left", double=False, monitor=0):- self.clicks.append((x, y, button, double))-- def show_move(self, x, y, *, monitor=0):- self.moves.append((x, y))--[email protected](autouse=True)-def _reset_singleton():- set_virtual_cursor(None)- yield- set_virtual_cursor(None)---def test_click_windows_glides_pulses_then_sends(monkeypatch) -> None:- import jarvis.plugins.tool.click as click_mod-- glides: list[tuple[int, int]] = []- sends: list[tuple[str, bool]] = []- monkeypatch.setattr(click_mod, "glide_os_cursor", lambda x, y, **k: glides.append((x, y)))- # _send_click gained an optional abs_xy kwarg — accept it so the patched- # lambda does not raise TypeError when _click_windows passes the coord.- monkeypatch.setattr(click_mod, "_send_click", lambda button, double, abs_xy=None: sends.append((button, double)))-- rec = _RecordingCursor()- set_virtual_cursor(rec)-- click_mod._click_windows(640, 360, "left", False)-- assert glides == [(640, 360)] # real cursor travelled to target- assert rec.clicks == [(640, 360, "left", False)] # overlay pulse at target- assert sends == [("left", False)] # real button press fired---def test_click_element_reuses_the_same_visual_click(monkeypatch) -> None:- # click_element imports _click_windows from click — patching the click- # module's seams must cover click_element too (DRY hook point).- import jarvis.plugins.tool.click as click_mod- import jarvis.plugins.tool.click_element as ce_mod-- glides: list[tuple[int, int]] = []- monkeypatch.setattr(click_mod, "glide_os_cursor", lambda x, y, **k: glides.append((x, y)))- monkeypatch.setattr(click_mod, "_send_click", lambda button, double, abs_xy=None: None)-- rec = _RecordingCursor()- set_virtual_cursor(rec)-- ce_mod._click_windows(50, 60, "left", True)-- assert glides == [(50, 60)]- assert rec.clicks == [(50, 60, "left", True)]---def test_move_windows_glides_and_shows_move(monkeypatch) -> None:- import jarvis.plugins.tool.move_mouse as move_mod-- glides: list[tuple[int, int]] = []- monkeypatch.setattr(move_mod, "glide_os_cursor", lambda x, y, **k: glides.append((x, y)))-- rec = _RecordingCursor()- set_virtual_cursor(rec)-- move_mod._move_windows(123, 456)-- assert glides == [(123, 456)]- assert rec.moves == [(123, 456)]diff --git a/tests/overlay/test_transparency.py b/tests/overlay/test_transparency.pydeleted file mode 100644index 25584a02d4..0000000000--- a/tests/overlay/test_transparency.py+++ /dev/null@@ -1,102 +0,0 @@-"""ctypes wrappers: mock user32, verify flag combinations."""--from __future__ import annotations--from unittest.mock import MagicMock, patch--import pytest--from overlay import transparency-from overlay.transparency import (- GWL_EXSTYLE,- WDA_EXCLUDEFROMCAPTURE,- WS_EX_LAYERED,- WS_EX_NOACTIVATE,- WS_EX_TOOLWINDOW,- WS_EX_TRANSPARENT,- apply_click_through,- apply_mascot_styles,- exclude_from_capture,-)---def fake_user32():- """Faked user32 — capture last GetWindowLongW return + SetWindowLongW args."""- user32 = MagicMock()- user32.GetWindowLongW.return_value = 0 # baseline: no flags set- user32.SetWindowLongW.return_value = 0- user32.SetWindowDisplayAffinity.return_value = 1 # success- return user32---def test_apply_click_through_sets_layered_and_transparent(fake_user32, monkeypatch) -> None:- monkeypatch.setattr(transparency, "_is_windows", lambda: True)- monkeypatch.setattr(transparency, "get_user32", lambda: fake_user32)-- apply_click_through(hwnd=0x12345)-- fake_user32.GetWindowLongW.assert_called_once()- args, _ = fake_user32.SetWindowLongW.call_args- _hwnd, idx, new_style = args- assert idx == GWL_EXSTYLE- assert new_style & WS_EX_LAYERED- assert new_style & WS_EX_TRANSPARENT---def test_apply_click_through_idempotent(fake_user32, monkeypatch) -> None:- """When both flags are already set, SetWindowLongW is NOT called."""- monkeypatch.setattr(transparency, "_is_windows", lambda: True)- monkeypatch.setattr(transparency, "get_user32", lambda: fake_user32)- fake_user32.GetWindowLongW.return_value = WS_EX_LAYERED | WS_EX_TRANSPARENT-- apply_click_through(hwnd=0x12345)-- fake_user32.SetWindowLongW.assert_not_called()---def test_apply_mascot_styles_sets_three_flags(fake_user32, monkeypatch) -> None:- monkeypatch.setattr(transparency, "_is_windows", lambda: True)- monkeypatch.setattr(transparency, "get_user32", lambda: fake_user32)-- apply_mascot_styles(hwnd=0xABCDEF)-- args, _ = fake_user32.SetWindowLongW.call_args- _hwnd, idx, new_style = args- assert idx == GWL_EXSTYLE- assert new_style & WS_EX_LAYERED- assert new_style & WS_EX_NOACTIVATE- assert new_style & WS_EX_TOOLWINDOW- # Mascot must NOT be click-through.- assert not (new_style & WS_EX_TRANSPARENT)---def test_exclude_from_capture_calls_with_correct_constant(fake_user32, monkeypatch) -> None:- monkeypatch.setattr(transparency, "_is_windows", lambda: True)- monkeypatch.setattr(transparency, "get_user32", lambda: fake_user32)-- ok = exclude_from_capture(hwnd=0x42)-- assert ok is True- args, _ = fake_user32.SetWindowDisplayAffinity.call_args- _hwnd, dwAffinity = args- assert dwAffinity.value == WDA_EXCLUDEFROMCAPTURE---def test_noop_on_non_windows(monkeypatch) -> None:- monkeypatch.setattr(transparency, "_is_windows", lambda: False)- # Must not crash, must not load user32.- apply_click_through(hwnd=0x1)- apply_mascot_styles(hwnd=0x1)- assert exclude_from_capture(hwnd=0x1) is False---def test_set_per_monitor_dpi_awareness_swallows_errors(monkeypatch) -> None:- monkeypatch.setattr(transparency, "_is_windows", lambda: True)- fake_shcore = MagicMock()- fake_shcore.SetProcessDpiAwareness.side_effect = OSError("E_ACCESSDENIED")- fake_windll = MagicMock(shcore=fake_shcore)- with patch("overlay.transparency.ctypes") as mock_ctypes:- mock_ctypes.windll = fake_windll- # Must not raise.- transparency.set_per_monitor_dpi_awareness()diff --git a/tests/overlay/test_tray_surface.py b/tests/overlay/test_tray_surface.pydeleted file mode 100644index 3501709a0a..0000000000--- a/tests/overlay/test_tray_surface.py+++ /dev/null@@ -1,166 +0,0 @@-"""Tests for ``TrayOnlySurface`` + ``LinuxBestEffortOverlay`` (sub-task 2.6; AD-11).--These run headless on every CI leg. ``TrayOnlySurface`` is driven against a-:class:`FakeTray` (no real pystray thread); the orb-state → ``JarvisState``-mapping is asserted directly. ``LinuxBestEffortOverlay`` is driven with an-injected probe / inner so the compositor-present, no-compositor, and Wayland-branches are deterministic without a real display.-"""--from __future__ import annotations--from jarvis.overlay.linux_surface import LinuxBestEffortOverlay-from jarvis.overlay.surface import OverlaySurface-from jarvis.overlay.tray_surface import TrayOnlySurface-from jarvis.ui.tray import JarvisState-from tests.fakes.fake_capabilities import fake_linux_capabilities-from tests.fakes.fake_overlay_surface import FakeOverlaySurface, FakeTray--# -----------------------------------------------------------------------# TrayOnlySurface — the universal floor.-# -------------------------------------------------------------------------def test_tray_surface_satisfies_protocol():- assert isinstance(TrayOnlySurface(tray=FakeTray()), OverlaySurface)---def test_tray_surface_start_does_not_start_injected_tray():- """An injected tray is the caller's to start; the surface must not own it."""- tray = FakeTray()- surface = TrayOnlySurface(tray=tray)-- surface.start()-- assert tray.started is False # not owned → not started by the surface- assert surface.is_visible() is True---def test_tray_surface_start_reflects_initial_state_once_up():- tray = FakeTray()- surface = TrayOnlySurface(tray=tray)-- surface.start()-- # start() pushes the current (idle) state through to the tray.- assert tray.last_state == JarvisState.IDLE---def test_tray_surface_maps_each_orb_state_onto_jarvis_state():- tray = FakeTray()- surface = TrayOnlySurface(tray=tray)- surface.start()-- expected = {- "idle": JarvisState.IDLE,- "listening": JarvisState.LISTENING,- "thinking": JarvisState.THINKING,- "speaking": JarvisState.SPEAKING,- "error": JarvisState.ERROR,- "paused": JarvisState.PAUSED,- }- for orb_state, jarvis_state in expected.items():- surface.set_state(orb_state)- assert tray.last_state == jarvis_state, orb_state---def test_tray_surface_unknown_state_falls_back_to_idle():- tray = FakeTray()- surface = TrayOnlySurface(tray=tray)- surface.start()-- surface.set_state("some-future-state")-- assert tray.last_state == JarvisState.IDLE---def test_tray_surface_stop_does_not_stop_injected_tray():- tray = FakeTray()- surface = TrayOnlySurface(tray=tray)- surface.start()-- surface.stop()-- assert tray.stopped is False # injected → not owned- assert surface.is_visible() is False---def test_tray_surface_lifecycle_is_noop_safe_without_tray_methods_raising():- # Even with no calls, stop before start must never raise.- surface = TrayOnlySurface(tray=FakeTray())- surface.stop()- assert surface.is_visible() is False---# -----------------------------------------------------------------------# LinuxBestEffortOverlay — degrade ladder.-# -------------------------------------------------------------------------def test_linux_surface_satisfies_protocol():- assert isinstance(LinuxBestEffortOverlay(), OverlaySurface)---def test_linux_surface_wayland_falls_through_to_tray():- surface = LinuxBestEffortOverlay(- capabilities=fake_linux_capabilities(is_wayland=True)- )- surface.start()- assert isinstance(surface._inner, TrayOnlySurface)---def test_linux_surface_compositor_present_selects_tk_color_key():- """Selection only — do NOT ``start()`` (that would spin up a real Tk orb on a- box where the inner is not injected). Assert the chosen class instead."""- from jarvis.overlay.surface import TkColorKeyOverlay-- surface = LinuxBestEffortOverlay(- capabilities=fake_linux_capabilities(is_wayland=False),- probe=lambda: True, # compositor supports color-key- )- inner = surface._select_inner()- assert isinstance(inner, TkColorKeyOverlay)---def test_linux_surface_no_compositor_falls_through_to_tray():- surface = LinuxBestEffortOverlay(- capabilities=fake_linux_capabilities(is_wayland=False),- probe=lambda: False, # no compositing WM → color-key fails- )- surface.start()- assert isinstance(surface._inner, TrayOnlySurface)---def test_linux_surface_probe_raising_degrades_to_tray():- def _boom() -> bool:- raise RuntimeError("X server gone")-- surface = LinuxBestEffortOverlay(- capabilities=fake_linux_capabilities(is_wayland=False),- probe=_boom,- )- surface.start() # must not raise- assert isinstance(surface._inner, TrayOnlySurface)---def test_linux_surface_forwards_lifecycle_to_inner():- inner = FakeOverlaySurface()- surface = LinuxBestEffortOverlay(inner=inner)-- surface.start()- surface.set_state("listening")- assert surface.is_visible() is True- assert inner.started is True- assert inner.states == ["listening"]-- surface.stop()- assert inner.stopped is True- assert surface.is_visible() is False---def test_linux_surface_methods_before_start_are_noop_safe():- surface = LinuxBestEffortOverlay(inner=FakeOverlaySurface())- # set_state / stop / is_visible before start must not raise.- surface.set_state("listening")- surface.stop()- assert surface.is_visible() is Falsediff --git a/tests/overlay/test_triggers.py b/tests/overlay/test_triggers.pydeleted file mode 100644index 10aeeecc0c..0000000000--- a/tests/overlay/test_triggers.py+++ /dev/null@@ -1,263 +0,0 @@-"""@overlay_action / overlay_action_scope — Plan §8.4 + §8.5 Contract."""--from __future__ import annotations--from typing import Any-from unittest import mock--import pytest--from jarvis.overlay import (- ActionKind,- overlay_action,- overlay_action_scope,- overlay_action_scope_sync,- overlay_action_sync,- set_overlay,-)---def fake_bridge() -> mock.MagicMock:- """Mock bridge with all emit_* methods. Injected into jarvis.overlay via- set_overlay(), then reset to None afterward."""- b = mock.MagicMock()- b.emit_action_started = mock.MagicMock(return_value="action-id-001")- b.emit_action_ended = mock.MagicMock(return_value=True)- b.emit_error = mock.MagicMock(return_value=True)- b.emit_click = mock.MagicMock(return_value=True)- set_overlay(b)- yield b- set_overlay(None)---# --------------------------------------------------------------------------# Sync-Decorator-# ----------------------------------------------------------------------------def test_sync_decorator_emits_started_then_function_then_ended(- fake_bridge: mock.MagicMock,-) -> None:- call_order: list[str] = []-- fake_bridge.emit_action_started.side_effect = lambda *a, **k: (- call_order.append("started"),- "id",- )[1]- fake_bridge.emit_action_ended.side_effect = lambda *a, **k: call_order.append(- "ended"- )-- @overlay_action_sync(ActionKind.CLICK)- def doit() -> None:- call_order.append("fn")-- doit()- assert call_order == ["started", "fn", "ended"]---def test_sync_decorator_passes_kind_to_emit_started(- fake_bridge: mock.MagicMock,-) -> None:- @overlay_action_sync(ActionKind.TYPING, duration_hint_ms=500)- def doit() -> None:- pass-- doit()- args, kwargs = fake_bridge.emit_action_started.call_args- assert args[0] == "type" # ActionKind.TYPING -> "type"- assert kwargs.get("duration_hint_ms") == 500---def test_sync_decorator_emits_error_on_exception(- fake_bridge: mock.MagicMock,-) -> None:- @overlay_action_sync(ActionKind.CLICK)- def doit() -> None:- raise RuntimeError("boom")-- with pytest.raises(RuntimeError, match="boom"):- doit()- fake_bridge.emit_error.assert_called_once()- # action_ended must STILL be called (finally).- fake_bridge.emit_action_ended.assert_called_once()- args, kwargs = fake_bridge.emit_error.call_args- assert "boom" in args[0]---def test_sync_decorator_no_bridge_is_no_op() -> None:- """When set_overlay(None), the function runs without crashing."""- set_overlay(None)- called = []-- @overlay_action_sync(ActionKind.CLICK)- def doit() -> None:- called.append("fn")-- doit()- assert called == ["fn"]---def test_get_bridge_degrades_to_none_when_optional_dep_missing(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """AP-23 W2-C: on a fresh clone without ``python-ulid`` installed, the- overlay import chain (``jarvis.overlay`` -> ``.integration`` ->- ``.bridge`` -> ``.schema`` -> ``ulid``) raises ``ModuleNotFoundError``.- ``_get_bridge`` must degrade honestly to ``None`` (the same no-op path- already exercised by ``test_sync_decorator_no_bridge_is_no_op``) instead- of letting the import error escape into a keyboard/mouse tool action.- """- import jarvis.overlay as overlay_pkg- from jarvis.overlay import triggers-- # Force re-resolution through the PEP-562 lazy __getattr__ (a prior test- # in this session may already have cached the real ``get_overlay`` on- # the package's __dict__).- monkeypatch.delattr(overlay_pkg, "get_overlay", raising=False)-- def _boom(name: str) -> Any:- if name == "get_overlay":- raise ModuleNotFoundError("No module named 'ulid'", name="ulid")- raise AttributeError(name)-- monkeypatch.setattr(overlay_pkg, "__getattr__", _boom)-- assert triggers._get_bridge() is None---def test_sync_decorator_runs_fn_when_overlay_dep_missing(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """Same missing-dependency scenario, exercised through the decorated- keyboard/mouse call path: the actual action must still run (matching- the AP-23 fix intent — the decorated tool action degrades to a clean- no-op for the overlay VISUAL, never a crash for the real action)."""- import jarvis.overlay as overlay_pkg-- monkeypatch.delattr(overlay_pkg, "get_overlay", raising=False)-- def _boom(name: str) -> Any:- if name == "get_overlay":- raise ModuleNotFoundError("No module named 'ulid'", name="ulid")- raise AttributeError(name)-- monkeypatch.setattr(overlay_pkg, "__getattr__", _boom)-- called = []-- @overlay_action_sync(ActionKind.CLICK)- def doit() -> None:- called.append("fn")-- doit()- assert called == ["fn"]---# --------------------------------------------------------------------------# Async-Decorator-# ----------------------------------------------------------------------------async def test_async_decorator_emits_correct_sequence(- fake_bridge: mock.MagicMock,-) -> None:- call_order: list[str] = []- fake_bridge.emit_action_started.side_effect = lambda *a, **k: (- call_order.append("started"),- "id-async",- )[1]- fake_bridge.emit_action_ended.side_effect = lambda *a, **k: call_order.append(- "ended"- )-- @overlay_action(ActionKind.CLICK)- async def doit() -> None:- call_order.append("fn")-- await doit()- assert call_order == ["started", "fn", "ended"]---async def test_async_decorator_emits_error_on_exception(- fake_bridge: mock.MagicMock,-) -> None:- @overlay_action(ActionKind.CLICK)- async def doit() -> None:- raise ValueError("async boom")-- with pytest.raises(ValueError, match="async boom"):- await doit()- fake_bridge.emit_error.assert_called_once()- fake_bridge.emit_action_ended.assert_called_once()---# --------------------------------------------------------------------------# Context-Manager-# ----------------------------------------------------------------------------async def test_async_scope_yields_action_id(- fake_bridge: mock.MagicMock,-) -> None:- async with overlay_action_scope(ActionKind.TYPING) as aid:- assert aid == "action-id-001"- fake_bridge.emit_action_started.assert_called_once()- fake_bridge.emit_action_ended.assert_called_once()---def test_sync_scope_yields_action_id(fake_bridge: mock.MagicMock) -> None:- with overlay_action_scope_sync(ActionKind.SCROLL) as aid:- assert aid == "action-id-001"- fake_bridge.emit_action_started.assert_called_once()- fake_bridge.emit_action_ended.assert_called_once()---async def test_scope_emits_error_on_exception(fake_bridge: mock.MagicMock) -> None:- with pytest.raises(KeyError):- async with overlay_action_scope(ActionKind.HOTKEY):- raise KeyError("scope boom")- fake_bridge.emit_error.assert_called_once()- fake_bridge.emit_action_ended.assert_called_once()---# --------------------------------------------------------------------------# Click-Pre-Emit Order (mouse.py)-# ----------------------------------------------------------------------------def test_mouse_click_emits_click_event_before_pyautogui_call(- fake_bridge: mock.MagicMock, monkeypatch: pytest.MonkeyPatch-) -> None:- """Plan §14.3 + §8.8 — emit_click must fire BEFORE pyautogui.click."""- import sys- import types-- call_order: list[str] = []- fake_bridge.emit_click.side_effect = lambda *a, **k: call_order.append(- "emit_click"- )-- fake_pyautogui = types.ModuleType("pyautogui")- fake_pyautogui.click = mock.MagicMock( # type: ignore[attr-defined]- side_effect=lambda **kwargs: call_order.append("pyautogui.click")- )- fake_pyautogui.position = mock.MagicMock( # type: ignore[attr-defined]- return_value=(0, 0)- )- monkeypatch.setitem(sys.modules, "pyautogui", fake_pyautogui)-- from jarvis.control import mouse-- mouse.set_cursor_streamer(None) # no streamer needed- mouse.click(x=100, y=200)- # Decorator emits started; mouse.click emits emit_click; then pyautogui.click.- # emit_click must come BEFORE pyautogui.click.- emit_idx = call_order.index("emit_click")- pyautogui_idx = call_order.index("pyautogui.click")- assert emit_idx < pyautogui_idxdiff --git a/tests/overlay/test_virtual_cursor.py b/tests/overlay/test_virtual_cursor.pydeleted file mode 100644index 2663c1abae..0000000000--- a/tests/overlay/test_virtual_cursor.py+++ /dev/null@@ -1,133 +0,0 @@-"""Virtual-cursor core: glide-path generator, no-op singleton, config gate.--These tests cover the display-independent core of the "Jarvis virtual mouse"-feature — the visible cursor indicator that glides to where Computer-Use-clicks. The Tk rendering window lives in ``ui/orb/virtual_cursor_window.py``-and is exercised by the smoke test, not here; everything testable without a-display is pinned down in this module.-"""-from __future__ import annotations--import pytest--from jarvis.overlay.virtual_cursor import (- NullVirtualCursor,- glide_points,- get_virtual_cursor,- pulse_state,- set_virtual_cursor,- virtual_cursor_enabled,-)---# ----------------------------------------------------------------------------# glide_points — pure easing path generator-# -----------------------------------------------------------------------------def test_glide_points_starts_and_ends_at_endpoints() -> None:- pts = glide_points(0, 0, 100, 40, steps=10)- assert pts[0] == (0, 0)- assert pts[-1] == (100, 40)---def test_glide_points_returns_requested_count() -> None:- pts = glide_points(0, 0, 100, 0, steps=7)- assert len(pts) == 7---def test_glide_points_single_step_is_just_the_target() -> None:- # A 1-step glide cannot animate — it must land exactly on the target so- # the real OS click never misses.- pts = glide_points(5, 5, 200, 90, steps=1)- assert pts == [(200, 90)]---def test_glide_points_x_is_monotonic_non_decreasing_when_moving_right() -> None:- pts = glide_points(0, 0, 100, 0, steps=12)- xs = [x for x, _ in pts]- assert xs == sorted(xs)---def test_glide_points_clamps_non_positive_steps_to_target() -> None:- assert glide_points(1, 2, 3, 4, steps=0) == [(3, 4)]- assert glide_points(1, 2, 3, 4, steps=-5) == [(3, 4)]---def test_glide_points_are_integers() -> None:- pts = glide_points(0, 0, 99, 33, steps=9)- assert all(isinstance(x, int) and isinstance(y, int) for x, y in pts)---# ----------------------------------------------------------------------------# pulse_state — click-pulse animation math (expanding, fading ring)-# -----------------------------------------------------------------------------def test_pulse_starts_small_and_opaque() -> None:- radius, alpha = pulse_state(0, duration_ms=400, max_radius=40)- assert radius == 0- assert alpha == 1.0---def test_pulse_grows_and_fades_over_time() -> None:- early = pulse_state(100, duration_ms=400, max_radius=40)- late = pulse_state(300, duration_ms=400, max_radius=40)- assert late[0] > early[0] # radius expands- assert late[1] < early[1] # alpha fades---def test_pulse_reaches_max_radius_at_end() -> None:- radius, _ = pulse_state(400, duration_ms=400, max_radius=40)- assert radius == 40---def test_pulse_is_none_after_it_expires() -> None:- assert pulse_state(401, duration_ms=400, max_radius=40) is None---# ----------------------------------------------------------------------------# Singleton accessor + null object-# ----------------------------------------------------------------------------[email protected](autouse=True)-def _reset_singleton():- set_virtual_cursor(None)- yield- set_virtual_cursor(None)---def test_default_cursor_is_null_object() -> None:- cur = get_virtual_cursor()- assert isinstance(cur, NullVirtualCursor)---def test_null_cursor_methods_never_raise() -> None:- cur = get_virtual_cursor()- # The null object must absorb every call so a missing display can never- # break a real click (cloud-first / headless VPS doctrine).- cur.show_move(10, 20)- cur.show_click(10, 20, button="left", double=False)- cur.show_path_point(10, 20)- cur.clear()- cur.shutdown()---def test_set_and_get_roundtrip() -> None:- class _Fake(NullVirtualCursor):- pass-- fake = _Fake()- set_virtual_cursor(fake)- assert get_virtual_cursor() is fake---# ----------------------------------------------------------------------------# Config gate-# -----------------------------------------------------------------------------def test_enabled_defaults_true_when_section_missing() -> None:- assert virtual_cursor_enabled({}) is True---def test_enabled_reads_computer_use_flag() -> None:- assert virtual_cursor_enabled({"computer_use": {"show_virtual_cursor": False}}) is False- assert virtual_cursor_enabled({"computer_use": {"show_virtual_cursor": True}}) is Truediff --git a/tests/overlay/test_virtual_cursor_click_through.py b/tests/overlay/test_virtual_cursor_click_through.pydeleted file mode 100644index e4327bf449..0000000000--- a/tests/overlay/test_virtual_cursor_click_through.py+++ /dev/null@@ -1,161 +0,0 @@-"""Regression test for the virtual-cursor black-screen bug (incident 2026-05-26).--The previous ``_make_click_through`` set ``WS_EX_LAYERED | WS_EX_TRANSPARENT``-via ``SetWindowLongPtrW`` but never re-applied ``SetLayeredWindowAttributes``-afterwards. Per the Win32 docs, writing ``GWL_EXSTYLE`` on a layered window-silently invalidates the cached chroma-key / alpha set by Tk's-``-transparentcolor`` attribute. The result was a fullscreen layered overlay-spanning the whole virtual desktop that painted opaque, blacking out every-monitor — and because the Tk thread is a daemon under a long-lived-``pythonw.exe``, the HWND survived until a full PC reboot.--This test pins the call ordering and the chroma-key value so the bug cannot-return unnoticed. The production module is patched at the ``ctypes.windll``-seam: no real Win32 call is made, the test runs headless.-"""-from __future__ import annotations--import types---def _install_fake_windll(monkeypatch) -> list[tuple[str, tuple]]:- """Replace ``ctypes.windll`` with a recording fake; return the call log.-- ``_make_click_through`` resolves ``ctypes.windll.user32`` inside its body,- so the patch only needs to land before the call — not before the import.- """- calls: list[tuple[str, tuple]] = []-- class FakeUser32:- # Production code uses ``getattr(user32, "GetWindowLongPtrW",- # user32.GetWindowLongW)`` which evaluates the fallback eagerly, so- # both names must exist on the fake even though the PtrW variant wins.- def GetWindowLongPtrW(self, hwnd, idx):- calls.append(("GetWindowLongPtrW", (hwnd, idx)))- return 0 # caller ORs flags in; the starting value does not matter-- def GetWindowLongW(self, hwnd, idx): # pragma: no cover — fallback only- calls.append(("GetWindowLongW", (hwnd, idx)))- return 0-- def SetWindowLongPtrW(self, hwnd, idx, val):- calls.append(("SetWindowLongPtrW", (hwnd, idx, val)))- return 0-- def SetWindowLongW(self, hwnd, idx, val): # pragma: no cover — fallback only- calls.append(("SetWindowLongW", (hwnd, idx, val)))- return 0-- def SetLayeredWindowAttributes(self, hwnd, color, alpha, flags):- calls.append(("SetLayeredWindowAttributes", (hwnd, color, alpha, flags)))- return 1-- def SetWindowPos(self, hwnd, after, x, y, w, h, flags):- calls.append(("SetWindowPos", (hwnd, after, x, y, w, h, flags)))- return 1-- import ctypes- monkeypatch.setattr(ctypes, "windll", types.SimpleNamespace(user32=FakeUser32()))- return calls---def test_click_through_reapplies_layered_attributes_after_style_change(monkeypatch):- """The chroma-key must be re-applied after ``SetWindowLongPtrW``.-- Otherwise Windows drops the cached LWA attributes and the fullscreen- overlay paints solid — see the 2026-05-26 black-screen incident.- """- calls = _install_fake_windll(monkeypatch)-- from ui.orb.virtual_cursor_window import _make_click_through-- _make_click_through(0xCAFEBEEF)-- names = [c[0] for c in calls]- assert "SetWindowLongPtrW" in names, (- "_make_click_through must call SetWindowLongPtrW to add WS_EX_TRANSPARENT"- )- assert "SetLayeredWindowAttributes" in names, (- "_make_click_through must call SetLayeredWindowAttributes AFTER "- "SetWindowLongPtrW to re-apply the chroma-key; otherwise the fullscreen "- "overlay paints opaque on every monitor (incident 2026-05-26)."- )-- swl_idx = names.index("SetWindowLongPtrW")- lwa_idx = names.index("SetLayeredWindowAttributes")- assert lwa_idx > swl_idx, (- "SetLayeredWindowAttributes must be called AFTER SetWindowLongPtrW "- f"(observed order: {names}). SetWindowLong invalidates the cached "- "chroma-key; the re-apply restores it."- )---def test_click_through_uses_magenta_color_key(monkeypatch):- """The chroma-key passed to LWA must match the Tk window background.-- The bg in :data:`COLOR_KEY_HEX` is ``#FF00FF`` (magenta). Windows- expects a ``COLORREF`` packed as ``0x00BBGGRR``, so magenta is- ``0x00FF00FF``. Any mismatch would key out the wrong colour and the- overlay would still paint solid.- """- calls = _install_fake_windll(monkeypatch)-- from ui.orb.virtual_cursor_window import _make_click_through-- _make_click_through(0xCAFEBEEF)-- lwa_call = next(c for c in calls if c[0] == "SetLayeredWindowAttributes")[1]- _, color, _, flags = lwa_call-- _LWA_COLORKEY = 0x00000001- _MAGENTA_COLORREF = 0x00FF00FF # COLORREF = 0x00BBGGRR with B=FF G=00 R=FF-- assert flags & _LWA_COLORKEY, (- f"LWA flags must include LWA_COLORKEY (0x1), got 0x{flags:x}"- )- assert color == _MAGENTA_COLORREF, (- f"Chroma-key colour must be magenta COLORREF 0x{_MAGENTA_COLORREF:x} "- f"(matches COLOR_KEY_HEX='#FF00FF'); got 0x{color:x}."- )---def test_click_through_commits_style_change_with_framechanged(monkeypatch):- """``SetWindowPos`` with ``SWP_FRAMECHANGED`` is required so Windows- actually recalculates the non-client area after the ex-style flip.-- Without this commit the new ``WS_EX_TRANSPARENT`` is honoured for input- but the layered surface may render stale until the next move/resize.- """- calls = _install_fake_windll(monkeypatch)-- from ui.orb.virtual_cursor_window import _make_click_through-- _make_click_through(0xCAFEBEEF)-- names = [c[0] for c in calls]- assert "SetWindowPos" in names, (- "_make_click_through must call SetWindowPos(...SWP_FRAMECHANGED) after "- "SetWindowLongPtrW so the ex-style change takes effect immediately."- )-- swp_call = next(c for c in calls if c[0] == "SetWindowPos")[1]- flags = swp_call[6]- _SWP_FRAMECHANGED = 0x0020- _SWP_NOMOVE = 0x0002- _SWP_NOSIZE = 0x0001- _SWP_NOZORDER = 0x0004- _SWP_NOACTIVATE = 0x0010- assert flags & _SWP_FRAMECHANGED, (- f"SetWindowPos must include SWP_FRAMECHANGED (0x20), got 0x{flags:x}"- )- # Defensive: don't accidentally move, resize, raise or focus the overlay.- for required, name in (- (_SWP_NOMOVE, "SWP_NOMOVE"),- (_SWP_NOSIZE, "SWP_NOSIZE"),- (_SWP_NOZORDER, "SWP_NOZORDER"),- (_SWP_NOACTIVATE, "SWP_NOACTIVATE"),- ):- assert flags & required, (- f"SetWindowPos must include {name} (0x{required:x}) to avoid moving / "- f"resizing / raising / focusing the overlay; got flags 0x{flags:x}"- )diff --git a/tests/overlay/test_virtual_cursor_window_smoke.py b/tests/overlay/test_virtual_cursor_window_smoke.pydeleted file mode 100644index fb736a336e..0000000000--- a/tests/overlay/test_virtual_cursor_window_smoke.py+++ /dev/null@@ -1,55 +0,0 @@-"""Smoke test for the Tk virtual-cursor window.--Opt-in only: Tk runs in a daemon thread, and pytest keeps the process alive-afterwards, so finalising the Tcl interpreter from the main thread panics-("async handler deleted by the wrong thread"). That is harmless in production-(the process exits hard) but crashes the test runner — so this test only runs-when ``JARVIS_GUI_TEST=1`` is set and there is an interactive desktop. The-display-independent behaviour is fully covered by ``test_virtual_cursor.py``;-for a visual check run ``python scripts/virtual_cursor_demo.py``.-"""-from __future__ import annotations--import os-import time--import pytest--from jarvis.overlay.virtual_cursor import get_virtual_cursor, set_virtual_cursor--pytestmark = pytest.mark.skipif(- os.environ.get("JARVIS_GUI_TEST") != "1",- reason="GUI smoke test — set JARVIS_GUI_TEST=1 on an interactive desktop to run",-)--[email protected](autouse=True)-def _reset_singleton():- set_virtual_cursor(None)- yield- set_virtual_cursor(None)---def test_window_starts_registers_and_draws_without_error():- from ui.orb.virtual_cursor_window import TkVirtualCursor-- cur = TkVirtualCursor()- started = cur.start(timeout_s=8.0)- if not started:- pytest.skip("no display / Tk unavailable on this host (headless)")-- try:- # Becomes the process-wide cursor so the click tools feed it.- assert get_virtual_cursor() is cur- # Drive a move and a click through the public API from this thread.- cur.show_move(400, 300)- cur.show_click(640, 360, button="left", double=False)- cur.show_click(200, 200, button="left", double=True)- time.sleep(0.2) # let a few render ticks run- finally:- cur.shutdown()-- # After shutdown the no-op object is restored.- from jarvis.overlay.virtual_cursor import NullVirtualCursor-- assert isinstance(get_virtual_cursor(), NullVirtualCursor)diff --git a/tests/overlay/test_visual_regression.py b/tests/overlay/test_visual_regression.pydeleted file mode 100644index cf493736c4..0000000000--- a/tests/overlay/test_visual_regression.py+++ /dev/null@@ -1,219 +0,0 @@-"""Phase 9.4 — visual regression with Playwright.--Skips entirely when:- - Playwright is not installed (``pytest.importorskip``)- - overlay-ui/dist/edge-glow.html is missing (no npm run build was run)- - PLAYWRIGHT_BROWSERS_PATH points at nothing (browser not- installed)--Tests verify:- - typing/clicking states have a visible edge glow (opacity > 0.3)- - idle/listening/thinking/speaking/hidden have NO glow- (opacity ~0)- - prefers-reduced-motion replaces the animation with static opacity 0.4- - the state display is hidden without ?debug=1, visible with ?debug=1--Snapshots land under ``tests/overlay/__visual__/``. By default no-snapshots are stored — tests measure computed style, not pixels.-Pixel comparison arrives with Phase 9.6+ once the mascot is added.-"""--from __future__ import annotations--import http.server-import os-import socketserver-import threading-from pathlib import Path--import pytest--playwright_sync = pytest.importorskip("playwright.sync_api")-sync_playwright = playwright_sync.sync_playwright---REPO_ROOT = Path(__file__).resolve().parents[2]-DIST_DIR = REPO_ROOT / "OS-Level" / "overlay-ui" / "dist"-EDGE_GLOW_HTML = DIST_DIR / "edge-glow.html"---def _skip_if_no_build() -> None:- if not EDGE_GLOW_HTML.is_file():- pytest.skip(f"edge-glow.html not found under {EDGE_GLOW_HTML} — `npm run build`?")---def _skip_if_no_browser() -> None:- # Playwright throws executable-not-found when the browser is missing.- # We can't reliably check upfront — we catch the error- # at launch() and skip then.- pass---class _SilentHandler(http.server.SimpleHTTPRequestHandler):- """SimpleHTTPRequestHandler without stderr spam."""-- def log_message(self, format: str, *args: object) -> None: # noqa: A002- return--[email protected](scope="module")-def http_server():- """Local HTTP server for ``dist/``. Chromium blocks ES modules- over ``file://`` via CORS — so we serve them."""- _skip_if_no_build()-- cwd = str(DIST_DIR)-- class _RootedHandler(_SilentHandler):- def __init__(self, *args, **kwargs) -> None:- super().__init__(*args, directory=cwd, **kwargs)-- httpd = socketserver.TCPServer(("127.0.0.1", 0), _RootedHandler)- port = httpd.server_address[1]- thread = threading.Thread(target=httpd.serve_forever, daemon=True)- thread.start()- try:- yield f"http://127.0.0.1:{port}"- finally:- httpd.shutdown()- httpd.server_close()- thread.join(timeout=2)--[email protected](scope="module")-def page_url(http_server: str) -> str:- return f"{http_server}/edge-glow.html"--[email protected](scope="module")-def browser_ctx():- _skip_if_no_browser()- try:- with sync_playwright() as p:- browser = p.chromium.launch(headless=True)- yield browser- browser.close()- except Exception as exc: # noqa: BLE001- pytest.skip(f"Playwright browser not available: {exc!r}")---def _opacity_of(page, selector: str) -> float:- raw = page.evaluate(- f"() => getComputedStyle(document.querySelector('{selector}')).opacity"- )- return float(raw)--- os.environ.get("CI") == "true" and os.environ.get("PLAYWRIGHT_HAS_BROWSER") != "1",- reason="CI without Playwright browser install",-)-def test_idle_has_no_glow(browser_ctx, page_url: str) -> None:- page = browser_ctx.new_page()- try:- page.goto(page_url)- # Initial state (no bridge -> applyState('idle')).- page.wait_for_function(- "document.documentElement.dataset.state === 'idle'", timeout=2000- )- assert _opacity_of(page, ".edge-glow") < 0.05- finally:- page.close()--- os.environ.get("CI") == "true" and os.environ.get("PLAYWRIGHT_HAS_BROWSER") != "1",- reason="CI without Playwright browser install",-)[email protected]("state", ["typing", "clicking"])-def test_glow_active_in_action_states(browser_ctx, page_url: str, state: str) -> None:- page = browser_ctx.new_page()- try:- page.goto(page_url)- page.evaluate(f"document.documentElement.dataset.state = '{state}'")- # Briefly wait for the transition.- page.wait_for_timeout(300)- assert _opacity_of(page, ".edge-glow") > 0.5- finally:- page.close()--- os.environ.get("CI") == "true" and os.environ.get("PLAYWRIGHT_HAS_BROWSER") != "1",- reason="CI without Playwright browser install",-)- "state", ["listening", "thinking", "speaking", "hidden"]-)-def test_no_glow_in_non_action_states(- browser_ctx, page_url: str, state: str-) -> None:- page = browser_ctx.new_page()- try:- page.goto(page_url)- page.evaluate(f"document.documentElement.dataset.state = '{state}'")- page.wait_for_timeout(300)- assert _opacity_of(page, ".edge-glow") < 0.05- finally:- page.close()--- os.environ.get("CI") == "true" and os.environ.get("PLAYWRIGHT_HAS_BROWSER") != "1",- reason="CI without Playwright browser install",-)-def test_state_display_hidden_without_debug_flag(- browser_ctx, page_url: str-) -> None:- page = browser_ctx.new_page()- try:- page.goto(page_url)- page.wait_for_function(- "document.documentElement.dataset.state === 'idle'", timeout=2000- )- display = page.evaluate(- "() => getComputedStyle(document.querySelector('#state-display')).display"- )- assert display == "none"- finally:- page.close()--- os.environ.get("CI") == "true" and os.environ.get("PLAYWRIGHT_HAS_BROWSER") != "1",- reason="CI without Playwright browser install",-)-def test_state_display_visible_with_debug_flag(- browser_ctx, page_url: str-) -> None:- page = browser_ctx.new_page()- try:- page.goto(f"{page_url}?debug=1")- page.wait_for_function(- "document.documentElement.dataset.state === 'idle'", timeout=2000- )- display = page.evaluate(- "() => getComputedStyle(document.querySelector('#state-display')).display"- )- assert display != "none"- finally:- page.close()--- os.environ.get("CI") == "true" and os.environ.get("PLAYWRIGHT_HAS_BROWSER") != "1",- reason="CI without Playwright browser install",-)-def test_reduced_motion_uses_static_glow(browser_ctx, page_url: str) -> None:- """Plan §19.1: prefers-reduced-motion -> opacity 0.4 instead of animation."""- page = browser_ctx.new_page()- page.emulate_media(reduced_motion="reduce")- try:- page.goto(page_url)- page.evaluate("document.documentElement.dataset.state = 'typing'")- page.wait_for_timeout(300)- opacity = _opacity_of(page, ".edge-glow")- # Static low-intensity per Plan = 0.4 (+/- transition).- assert 0.3 <= opacity <= 0.5, f"reduced-motion glow opacity={opacity}"- finally:- page.close()diff --git a/tests/overlay/test_window_glow_smoke.py b/tests/overlay/test_window_glow_smoke.pydeleted file mode 100644index 39dc93cbf3..0000000000--- a/tests/overlay/test_window_glow_smoke.py+++ /dev/null@@ -1,37 +0,0 @@-"""EdgeGlowWindow smoke test — instantiates headless, without ``show()``."""--from __future__ import annotations--import pytest--pytest.importorskip("PySide6.QtWidgets")---def test_edge_glow_window_instantiates_headless(qapp) -> None:- from PySide6.QtCore import Qt- from PySide6.QtGui import QGuiApplication-- from overlay.window_glow import EdgeGlowWindow-- primary = QGuiApplication.primaryScreen()- assert primary is not None, "offscreen platform must provide a screen"-- win = EdgeGlowWindow(primary, hide_from_capture=False)- try:- # Sanity: flags are set — NO show() (per the plan).- flags = win.windowFlags()- assert flags & Qt.WindowType.FramelessWindowHint- assert flags & Qt.WindowType.WindowStaysOnTopHint- assert flags & Qt.WindowType.WindowTransparentForInput- assert flags & Qt.WindowType.Tool- assert flags & Qt.WindowType.NoDropShadowWindowHint-- assert win.testAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)- assert win.testAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)- assert win.testAttribute(Qt.WidgetAttribute.WA_NoSystemBackground)- assert win.testAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)-- # Geometry matches the screen.- assert win.geometry() == primary.geometry()- finally:- win.deleteLater()diff --git a/tests/overlay/test_window_mascot_smoke.py b/tests/overlay/test_window_mascot_smoke.pydeleted file mode 100644index 3203fc8ac5..0000000000--- a/tests/overlay/test_window_mascot_smoke.py+++ /dev/null@@ -1,77 +0,0 @@-"""MascotWindow smoke — instantiates headless, without show()."""--from __future__ import annotations--import pytest--pytest.importorskip("PySide6.QtWidgets")---def test_mascot_window_instantiates_headless(qapp, tmp_path) -> None:- from PySide6.QtCore import Qt-- from overlay.state import StateMachine- from overlay.window_mascot import MascotWindow-- machine = StateMachine()-- saved = []-- def _save(pos) -> None:- saved.append(pos)-- win = MascotWindow(- initial_x=100,- initial_y=200,- monitor_name="\\\\.\\DISPLAY1",- size_px=160,- hide_from_capture=False,- state_machine=machine,- on_position_saved=_save,- )- try:- flags = win.windowFlags()- # Plan §12.2 — exactly this flag combination, WITHOUT- # WindowTransparentForInput.- assert flags & Qt.WindowType.FramelessWindowHint- assert flags & Qt.WindowType.WindowStaysOnTopHint- assert flags & Qt.WindowType.Tool- assert flags & Qt.WindowType.NoDropShadowWindowHint- assert not (flags & Qt.WindowType.WindowTransparentForInput)-- assert win.testAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)- assert win.testAttribute(Qt.WidgetAttribute.WA_NoSystemBackground)- assert win.testAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)- # IMPORTANT: mascot is NOT TransparentForMouseEvents.- assert not win.testAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)-- # Geometry + Mask.- assert win.size().width() == 160- assert win.size().height() == 160- # Mask is set (can't be compared directly,- # just that mask().isEmpty() is False).- assert not win.mask().isEmpty()-- # Position.- assert win.x() == 100- assert win.y() == 200- finally:- win.deleteLater()---def test_mascot_window_skips_state_bridge_without_machine(qapp) -> None:- from overlay.window_mascot import MascotWindow-- win = MascotWindow(- initial_x=0,- initial_y=0,- monitor_name="X",- state_machine=None,- hide_from_capture=False,- )- try:- # Bridge should be None when there's no machine.- assert win._bridge is None # noqa: SLF001- assert win._channel is None # noqa: SLF001- finally:- win.deleteLater()diff --git a/tests/unit/brain/test_local_action_gate.py b/tests/unit/brain/test_local_action_gate.pyindex ff6be579fa..083c703324 100644--- a/tests/unit/brain/test_local_action_gate.py+++ b/tests/unit/brain/test_local_action_gate.py@@ -595,66 +595,6 @@ def test_orb_reset_false_positive_corpus(text: str) -> None:)-# -----------------------------------------------------------------------# Mascot respawn voice commands (mirror of ADR-0016 L2 for the overlay-# supervisor — BUG-012 class, cap-fired / hidden / hung subprocess).-# ------------------------------------------------------------------------- "text",- [- "Hey Jarvis, Maskottchen wieder auftauchen",- "Hey Jarvis, Maskottchen wieder auftauchen?",- "Hey Jarvis, Maskottchen zurück",- "Maskottchen zurück",- "Maskottchen weg",- "Maskottchen kommt zurück",- "Hey Jarvis, Maskottchen reset",- "Hey Jarvis, Maskottchen respawn",- "Hey Jarvis, Maskottchen spawnen",- "Hey Jarvis, spawne das Maskottchen",- "Hey Jarvis, respawn the mascot",- "Hey Jarvis, mascot back",- "Hey Jarvis, Mascot come back",- "Wo ist das Maskottchen?",- "Hey Jarvis, Spawner",- "Spawner",- "Hey Jarvis, der Spawner",- ],-)-def test_mascot_respawn_phrases_dispatch_respawn_mascot(text: str) -> None:- """Every phrasing in the user's vocabulary for "bring the mascot back"- must produce a DIRECT plan that calls ``respawn_mascot``."""- plan = match_local_action(text)- assert plan is not None, f"no match for: {text!r}"- assert plan == LocalActionPlan(- mode=LocalActionMode.DIRECT,- tool_calls=(LocalToolCall(name="respawn_mascot", args={}),),- )--- "text",- [- # Conversational queries that mention mascot/spawn but are NOT a- # respawn command. Regression guard for the regex anchoring.- "Spawne mir mal ein Terminal",- "Hey Jarvis, das Maskottchen-Konzept ist toll",- "Wo ist mein Schlüssel?",- "Was macht der Spawner intern?",- "respawn the server",- ],-)-def test_mascot_respawn_false_positive_corpus(text: str) -> None:- plan = match_local_action(text)- if plan is None:- return- assert plan.tool_calls and plan.tool_calls[0].name != "respawn_mascot", (- f"false positive: {text!r} matched mascot-respawn"- )--# ---------------------------------------------------------------------------# UNSUPPORTED gate — capability-coupling spec §Layer 2, insertion point (a)#diff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.pyindex 893ebdd47d..2cc4a86870 100644--- a/tests/unit/brain/test_routing.py+++ b/tests/unit/brain/test_routing.py@@ -54,11 +54,6 @@ class _FakeHotkeyTool:schema: dict[str, Any] = {}-class _FakeRespawnMascotTool:- name = "respawn_mascot"- schema: dict[str, Any] = {}--class _FakeNavigateTool:name = "navigate"schema: dict[str, Any] = {}@@ -2779,8 +2774,8 @@ def test_explicit_trigger_outranks_disambiguation_guards(utterance: str) -> Nonedef _seeded_strict_manager_with_local_actions() -> tuple[BrainManager, _RecordingExecutor]:"""Strict-mode manager over the REAL seeded registry, with spawn_worker AND- the local-action tools (incl. respawn_mascot) wired — the exact production- gate path for the end-to-end ``generate()`` mandate tests."""+ the local-action tools wired — the exact production gate path for the+ end-to-end ``generate()`` mandate tests."""from jarvis.core.capabilities import get_registryfrom jarvis.core.capabilities_seed import seed_registry@@ -2796,7 +2791,6 @@ def _seeded_strict_manager_with_local_actions() -> tuple[BrainManager, _Recordin"open_app": _FakeOpenAppTool(),"type_text": _FakeTypeTextTool(),"hotkey": _FakeHotkeyTool(),- "respawn_mascot": _FakeRespawnMascotTool(),},tool_executor=executor, # type: ignore[arg-type])@@ -2850,7 +2844,7 @@ async def test_explicit_subagent_outranks_navigation_fast_path() -> None:config=config,bus=EventBus(),tools={"spawn_worker": _FakeTool(), "navigate": _FakeNavigateTool()},- local_action_tools={"respawn_mascot": _FakeRespawnMascotTool()},+ local_action_tools={"open_app": _FakeOpenAppTool()},tool_executor=executor, # type: ignore[arg-type])manager._vision_provider = _VisionShouldNotRun()@@ -2866,22 +2860,6 @@ async def test_explicit_subagent_outranks_navigation_fast_path() -> None:), "navigation fast-path ran instead of standing down for the explicit trigger"-async def test_mascot_respawn_still_wins_over_explicit_spawn_word() -> None:- """No-regression: 'Spawne das Maskottchen' is a deterministic local recovery- that legitimately reuses the word 'spawn' — it must respawn the mascot, NOT- dispatch a heavy worker."""- manager, executor = _seeded_strict_manager_with_local_actions()- await manager.generate("Spawne das Maskottchen")- assert not _spawn_calls(executor), (- "'Spawne das Maskottchen' wrongly dispatched a heavy worker instead of "- "respawning the mascot"- )- assert any(- getattr(c[0], "name", "") == "respawn_mascot" for c in executor.calls- ), "mascot respawn tool was not called"--@pytest.mark.asyncioasync def test_external_task_without_trigger_still_refuses() -> None:"""No-regression: WITHOUT an explicit trigger, an unsupported external task