Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

chore: auto-save WIP via Claude stop-hook safety net (2026-07-10 18:10)

Ruben Lütke2f75ed9e0a1f
diff --git a/jarvis/ui/jarvisbar/overlay.py b/jarvis/ui/jarvisbar/overlay.py
index d99306eeee..b0db223028 100644
--- a/jarvis/ui/jarvisbar/overlay.py
+++ b/jarvis/ui/jarvisbar/overlay.py
@@ -67,6 +67,55 @@ AUDIBLE_HOLD_S = 0.5
WATCHDOG_INTERVAL_MS = 1000
FRAME_STALL_THRESHOLD_NS = 2_000_000_000 # 2 s of silence ⇒ the loop is dead
+# Frame pacing (BUG: "JarvisBar stutters" forensic, 2026-07-10). A 41s GIF
+# capture frame-diffed to only ~5 visual updates/second on average, in a
+# burst-then-freeze pattern (freezes up to 1.25s). Measured root causes, on
+# this machine:
+#
+# 1. The bar's window style itself (frameless + ``-topmost`` + a color-key
+# ``-transparentcolor`` + a translucent ``-alpha``) is a Windows *layered*
+# window; every ``ImageTk.PhotoImage``/``itemconfig`` swap makes DWM
+# recomposite it. A benchmark that swaps a CONSTANT-COLOR image on an
+# identically-styled window (zero render work) still only reached ~31
+# updates/s against an ``after(16)`` (60fps) schedule — a ~15ms fixed
+# per-tick compositing tax, independent of what gets drawn. So the 60fps
+# target was already unreachable on this window style even at zero cost.
+# The idle pill draws NOTHING beyond its at-rest background (see
+# ``renderer.render``'s idle branch), so idle-at-rest frames are paying
+# that compositing tax for a BYTE-IDENTICAL image every single tick — pure
+# waste. ``_IDLE_SETTLE_TICKS`` below skips the render/PhotoImage/
+# itemconfig work once the resting pill has visibly settled.
+# 2. A background thread holding the GIL (simulating wake-poll/other Python
+# work sharing this process) collapsed the SAME loop to ~4-5 renders/s
+# with 250-360ms gaps — matching the GIF's freeze pattern. This is GIL/CPU
+# contention from OTHER threads in the process; no delay-scheduling choice
+# made here can prevent it (a Windows thread-priority raise for the Tk
+# thread was benchmarked too and showed no measurable improvement against
+# pure GIL contention, so it is deliberately NOT used). What this loop CAN
+# do is shrink its own contribution to that contention — the idle-skip
+# above is the main lever, and adaptive pacing (below) prevents an
+# occasional slow render (measured up to ~30ms in "think"+hovered mode)
+# from compounding into an even longer visible gap.
+#
+# Idle-static skip: once the resting pill's eased size has stopped changing
+# (ease() with factor 0.5 converges to sub-pixel precision within a handful
+# of ticks; 30 is a generous margin) AND the state is idle/not-hovered/
+# not-muted (draws nothing — see renderer.render), every further tick would
+# repaint the exact same pixels. Skipped ticks still stamp the heartbeat and
+# re-arm the loop, so the watchdog/self-healing contract is untouched — only
+# the render()/PhotoImage()/itemconfig() work is skipped.
+_IDLE_SETTLE_TICKS = 30
+
+# Adaptive pacing: the nominal target stays 16ms (~60fps aspirational — the
+# real ceiling is lower, see above), but the actual next delay is derived
+# from how long THIS tick took, not a blind constant. In the common case
+# (render cost << 16ms) this is indistinguishable from the old fixed delay.
+# It only matters after an unusually slow tick, where it schedules the next
+# one sooner instead of adding a full 16ms on top of the overrun — this
+# bounds how much a single slow frame can widen the gap to the next one.
+TARGET_FRAME_MS = 16
+MIN_FRAME_DELAY_MS = 1
+
def _primary_work_area() -> tuple[int, int, int, int] | None:
"""Primary-monitor work area (left, top, right, bottom) EXCLUDING the
@@ -118,6 +167,12 @@ class JarvisBarOverlay:
# revival watchdog compares against this to tell a living loop from a
# silently-dead one. 0 = "no frame has run yet" → the watchdog holds off.
self._last_frame_ns = 0
+ # Idle-static skip bookkeeping (see _IDLE_SETTLE_TICKS docstring above
+ # _schedule_frame): tracks how many consecutive ticks have shared the
+ # same (effective_mode, hovered, muted) key, so a settled idle pill's
+ # repaint can be skipped once its eased size has stopped moving.
+ self._static_tick_key: tuple[str, bool, bool] | None = None
+ self._static_tick_count = 0
self._root: Any = None
self._canvas: Any = None
self._renderer: renderer.JarvisBarRenderer | None = None
diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
index 6a168ac085..a623f952ed 100644
--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
@@ -312,7 +312,7 @@ export function useSectionHealth() {
detail.provider_label ?? detail.result.provider,
),
}));
- } else {
+ } else if (event.type !== "jarvis:provider-tested") {
clearSection(section);
}
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
index 504267f20c..76b62bbc28 100644
--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
@@ -1193,7 +1193,12 @@ function ProviderCard({
{/* Footer: the live connectivity test, visually separated from the
configuration body so "set up" and "verify" read as two steps. */}
<div className="border-t border-border/60 pt-2.5">
- <ProviderTestControl providerId={descriptor.id} />
+ <ProviderTestControl
+ providerId={descriptor.id}
+ providerLabel={descriptor.label}
+ section={descriptor.tier}
+ active={descriptor.active}
+ />
</div>
</div>
);
@@ -1219,29 +1224,56 @@ const TEST_STATUS_TONE: Record<ProviderTestStatus, string> = {
* the API-Keys view was missing: the green "configured" badge only ever meant a
* key STRING was stored, never that the provider answers.
*/
-function ProviderTestControl({ providerId }: { providerId: string }) {
+function ProviderTestControl({
+ providerId,
+ providerLabel,
+ section,
+ active,
+}: {
+ providerId: string;
+ providerLabel: string;
+ section: ProviderTier;
+ active: boolean;
+}) {
const t = useT();
const [running, setRunning] = useState(false);
const [result, setResult] = useState<ProviderTestResult | null>(null);
+ const activeRef = useRef(active);
+ activeRef.current = active;
+
+ function publish(next: ProviderTestResult) {
+ window.dispatchEvent(
+ new CustomEvent("jarvis:provider-tested", {
+ detail: {
+ section,
+ provider: providerId,
+ provider_label: providerLabel,
+ active: activeRef.current,
+ result: next,
+ },
+ }),
+ );
+ }
async function run() {
setRunning(true);
setResult(null);
try {
- setResult(await testProvider(providerId));
+ const next = await testProvider(providerId);
+ setResult(next);
+ publish(next);
} catch (e) {
- setResult({
+ const next: ProviderTestResult = {
provider: providerId,
status: "error",
detail: (e as Error).message,
latency_ms: 0,
integration_ok: false,
- });
+ };
+ setResult(next);
+ publish(next);
} finally {
setRunning(false);
- // Let the tab indicators re-check: if this was the active provider, its
- // tab dot should reflect the fresh result instead of a stale cached one.
- window.dispatchEvent(new Event("jarvis:provider-tested"));
}
}
diff --git a/tests/unit/plugins/wake/test_vosk_kws_provider.py b/tests/unit/plugins/wake/test_vosk_kws_provider.py
index 563732cfc5..300b4be959 100644
--- a/tests/unit/plugins/wake/test_vosk_kws_provider.py
+++ b/tests/unit/plugins/wake/test_vosk_kws_provider.py
@@ -11,12 +11,16 @@ up. What is pinned here:
- Near-silent candidates are rejected on raw ENERGY (never transcript).
- A confirm infrastructure error fails OPEN (never eats a real wake).
- The wake detector yields the canonical keyword, never transcript text.
+- The grammar re-score and the free decode run CONCURRENTLY (spawn-latency
+ mission 2026-07-10): they are independent passes over the same audio, so
+ paying their SUM instead of their MAX is a pure latency regression.
"""
from __future__ import annotations
import asyncio
import json
import sys
+import time
import types
from collections.abc import AsyncIterator
@@ -243,3 +247,82 @@ async def test_cooldown_suppresses_immediate_refire(fake_vosk) -> None:
fired = await _run_detect(p, [_chunk() for _ in range(24)])
assert fired == ["nova"] # second grammar hit lands inside the cooldown
assert p.stats()["suppressed_cooldown"] >= 1
+
+
+# --- latency: concurrent grammar re-score + free decode ------------------------
+
+
+class _SlowFakeRecognizer:
+ """Recognizer whose ``FinalResult()`` sleeps, to prove the grammar
+ re-score and the free decode run CONCURRENTLY rather than sequentially.
+
+ Grammar mode re-hears the phrase with a passing confidence; free mode
+ returns a sound-close transcript at the same span, so
+ ``_verify_candidate`` legitimately CONFIRMS — this test only cares about
+ the WALL-CLOCK time the call took, not the decision content (that is
+ covered by the tests above).
+ """
+
+ SLEEP_S = 0.12
+
+ def __init__(self, model, rate, grammar=None): # noqa: ANN001
+ self._model = model
+ self._grammar = grammar
+
+ def SetWords(self, flag): # noqa: ANN001, N802
+ pass
+
+ def AcceptWaveform(self, pcm): # noqa: ANN001, N802
+ return False
+
+ def PartialResult(self): # noqa: N802
+ return json.dumps({"partial": ""})
+
+ def Result(self): # noqa: N802
+ return json.dumps({"text": ""})
+
+ def FinalResult(self): # noqa: N802
+ # time.sleep releases the GIL — this stands in for a real vosk decode
+ # call, which likewise releases the GIL during its C++ work.
+ time.sleep(self.SLEEP_S)
+ if self._grammar is not None:
+ phrase = self._model.phrase.lower()
+ return json.dumps({
+ "text": phrase,
+ "result": _timed_words(phrase, self._model.grammar_conf),
+ })
+ return json.dumps({
+ "text": self._model.free_text,
+ "result": _timed_words(self._model.free_text, 0.9),
+ })
+
+
+def test_verify_candidate_runs_grammar_and_free_decode_concurrently(monkeypatch) -> None:
+ mod = types.ModuleType("vosk")
+ state = {"model": None}
+
+ def _model_factory(path): # noqa: ANN001
+ state["model"] = _FakeModel(path)
+ return state["model"]
+
+ mod.Model = _model_factory
+ mod.KaldiRecognizer = _SlowFakeRecognizer
+ mod.SetLogLevel = lambda *_a: None
+ monkeypatch.setitem(sys.modules, "vosk", mod)
+
+ p = VoskKwsProvider("Hey Nova", model_path="fake", keyword="nova")
+ p._ensure_model() # noqa: SLF001
+ window = np.full(48000, 0.2, dtype=np.float32)
+
+ t0 = time.perf_counter()
+ result = p._verify_candidate(window) # noqa: SLF001
+ elapsed = time.perf_counter() - t0
+
+ assert result is True
+ # Sequential execution would cost >= 2 * SLEEP_S (~0.24 s). A generous
+ # margin (1.7x one sleep) leaves headroom for scheduler jitter while
+ # still failing hard on a regression back to sequential calls.
+ assert elapsed < _SlowFakeRecognizer.SLEEP_S * 1.7, (
+ f"_verify_candidate took {elapsed:.3f}s — looks SEQUENTIAL "
+ f"(~2x{_SlowFakeRecognizer.SLEEP_S}s), not concurrent"
+ )