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-06 20:48)

Ruben Lütked2e0ad549d1b
diff --git a/jarvis/__main__.py b/jarvis/__main__.py
index e7d130753f..a83fb53c94 100644
--- a/jarvis/__main__.py
+++ b/jarvis/__main__.py
@@ -331,12 +331,7 @@ def _cmd_reset_onboarding() -> int:
from jarvis.setup import state as onb_state
removed = onb_state.reset_onboarding(_ONBOARDING_STATE_PATH)
- marker = cfg.DATA_DIR / ".setup-complete"
- if marker.exists():
- try:
- marker.unlink()
- except OSError as exc:
- print(f"Could not remove {marker}: {exc}")
+ onb_state.remove_setup_complete_marker(_ONBOARDING_STATE_PATH)
print(f"Onboarding reset. Cleared keys: {removed or 'none'}; removed .setup-complete.")
print("Next launch will show the setup guide.")
return 0
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 3bf1037ae9..2712ab7119 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -2632,20 +2632,25 @@ def ensure_project_root_cwd() -> Path:
def is_first_run() -> bool:
- """Return True when the user has not yet completed the setup wizard."""
- # Delegates to jarvis.setup.state so the stdlib-only fast-boot onboarding
- # path and this heavy module can never disagree on the marker location.
+ """True when the LEGACY ``.setup-complete`` marker is absent.
+
+ This only reflects the terminal wizard / legacy marker — the in-app
+ onboarding records completion in ``setup_state.json`` instead (see
+ ``jarvis.setup.state.is_onboarding_complete``). Delegates to
+ ``jarvis.setup.state`` so the stdlib-only fast-boot onboarding path and
+ this heavy module can never disagree on the marker location.
+ """
from jarvis.setup.state import setup_complete_marker_exists
return not setup_complete_marker_exists()
def mark_setup_complete() -> None:
- DATA_DIR.mkdir(parents=True, exist_ok=True)
- (DATA_DIR / ".setup-complete").write_text(
- f"Setup completed on Python {sys.version.split()[0]}\n",
- encoding="utf-8",
- )
+ # Read/write/delete of the marker all live in jarvis.setup.state so the
+ # location can never desync between callers.
+ from jarvis.setup.state import write_setup_complete_marker
+
+ write_setup_complete_marker(f"Setup completed on Python {sys.version.split()[0]}\n")
# ----------------------------------------------------------------------
diff --git a/jarvis/setup/onboarding_fastpath.py b/jarvis/setup/onboarding_fastpath.py
index 511e5e2700..364a4fe0bb 100644
--- a/jarvis/setup/onboarding_fastpath.py
+++ b/jarvis/setup/onboarding_fastpath.py
@@ -108,9 +108,12 @@ async def _send_json(send: Any, payload: dict, status: int = 200) -> None:
async def handle(scope: dict, receive: Any, send: Any) -> bool:
"""Answer an ``/api/onboarding/*`` request; True iff handled.
- Mirrors ``onboarding_routes.py``: every write is fail-open (the state
- helpers never raise) and unknown sub-paths return 404 so a typo is
- visible instead of silently held.
+ Mirrors ``onboarding_routes.py`` in payload shape and semantics; every
+ write is fail-open (the state helpers never raise). One deliberate
+ simplification: any unknown sub-path OR wrong method returns 404 (the
+ FastAPI router would answer 405 for a wrong method) — nothing in the
+ frontend depends on that distinction, and a flat 404 keeps this handler
+ trivially small.
"""
if scope.get("type") != "http":
return False
diff --git a/jarvis/setup/state.py b/jarvis/setup/state.py
index b7ce1181d6..6e2992ec68 100644
--- a/jarvis/setup/state.py
+++ b/jarvis/setup/state.py
@@ -83,6 +83,31 @@ def setup_complete_marker_exists(path: Path | None = None) -> bool:
return setup_complete_marker_path(path).exists()
+def write_setup_complete_marker(content: str, path: Path | None = None) -> None:
+ """Write the legacy completion marker (read/write/delete all route through
+ this module so the location can never desync between callers)."""
+ target = setup_complete_marker_path(path)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content, encoding="utf-8")
+
+
+def remove_setup_complete_marker(path: Path | None = None) -> bool:
+ """Delete the legacy completion marker. True iff it existed and was removed.
+
+ Never raises — a locked/undeletable marker is logged; the caller's message
+ stays honest via the return value.
+ """
+ target = setup_complete_marker_path(path)
+ if not target.exists():
+ return False
+ try:
+ target.unlink()
+ return True
+ except OSError as exc:
+ logger.warning("remove_setup_complete_marker: cannot remove %s: %s", target, exc)
+ return False
+
+
def load_setup_state(path: Path | None = None) -> dict[str, Any]:
"""Read the setup-state file and return its dict view.
@@ -291,6 +316,8 @@ __all__ = [
"state_path",
"setup_complete_marker_path",
"setup_complete_marker_exists",
+ "write_setup_complete_marker",
+ "remove_setup_complete_marker",
"load_setup_state",
"has_seen_obsidian_setup",
"mark_obsidian_seen",
diff --git a/jarvis/ui/web/frontend/src/hooks/useOnboarding.ts b/jarvis/ui/web/frontend/src/hooks/useOnboarding.ts
index 510127110a..d80d2d2859 100644
--- a/jarvis/ui/web/frontend/src/hooks/useOnboarding.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useOnboarding.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
export interface LegalReference {
label: string;
@@ -44,17 +44,25 @@ export function useOnboarding(opts?: { retryDelaysMs?: number[] }) {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const retryDelays = opts?.retryDelaysMs ?? RETRY_DELAYS_MS;
+ // Generation guard: a newer refetch (or unmount, which bumps it in the
+ // effect cleanup) makes every older in-flight retry loop a no-op, so a
+ // stale slow response can never clobber fresher state and no timer keeps
+ // firing after the gate is gone.
+ const genRef = useRef(0);
const refetch = useCallback(async () => {
+ const gen = ++genRef.current;
setError(null);
for (let attempt = 0; ; attempt++) {
try {
const res = await fetch("/api/onboarding/state");
+ if (genRef.current !== gen) return; // superseded or unmounted
if (!res.ok) throw new Error(`HTTP ${res.status}`);
setState((await res.json()) as OnboardingState);
setLoading(false);
return;
} catch (e) {
+ if (genRef.current !== gen) return;
const delay = retryDelays[attempt];
if (delay === undefined) {
setError((e as Error).message);
@@ -62,6 +70,7 @@ export function useOnboarding(opts?: { retryDelaysMs?: number[] }) {
return;
}
await new Promise((r) => setTimeout(r, delay));
+ if (genRef.current !== gen) return;
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- retryDelays is a stable test seam
@@ -69,6 +78,9 @@ export function useOnboarding(opts?: { retryDelaysMs?: number[] }) {
useEffect(() => {
void refetch();
+ return () => {
+ genRef.current++; // invalidate in-flight retry loops on unmount
+ };
}, [refetch]);
const saveStep = useCallback(async (step: string, skipped?: string[]) => {
diff --git a/jarvis/ui/web/onboarding_routes.py b/jarvis/ui/web/onboarding_routes.py
index 39606dd7b9..19c79d599f 100644
--- a/jarvis/ui/web/onboarding_routes.py
+++ b/jarvis/ui/web/onboarding_routes.py
@@ -11,7 +11,7 @@ from __future__ import annotations
import logging
from pathlib import Path
-from fastapi import APIRouter
+from fastapi import APIRouter, Response
from pydantic import BaseModel
from jarvis.setup import state as st
@@ -44,7 +44,10 @@ def _safe_state_payload() -> dict:
@router.get("/state")
-async def get_state() -> dict:
+async def get_state(response: Response) -> dict:
+ # Same no-cache guarantee the fast-boot handler gives: the gate must never
+ # act on a cached completed/incomplete verdict.
+ response.headers["cache-control"] = "no-store, max-age=0"
return _safe_state_payload()
diff --git a/tests/missions/test_env_oauth_expiry.py b/tests/missions/test_env_oauth_expiry.py
new file mode 100644
index 0000000000..e7e38c2545
--- /dev/null
+++ b/tests/missions/test_env_oauth_expiry.py
@@ -0,0 +1,114 @@
+"""The live Claude OAuth token reader must be EXPIRY-aware.
+
+Forensic ground truth (2026-07-06, missions 019f36e5 + 019f38b1): the Claude
+Max OAuth access token in ``~/.claude/.credentials.json`` expired at 02:53 and
+nothing on the host refreshes it anymore (interactive Claude sessions run on a
+different CLAUDE_CONFIG_DIR profile). ``read_live_claude_oauth_token`` returned
+the DEAD token anyway (it never read ``expiresAt``), ``build_worker_env``
+injected it as ``CLAUDE_CODE_OAUTH_TOKEN``, and the worker — pinned to an
+isolated CLAUDE_CONFIG_DIR with no refresh token — failed every spawn with
+"Failed to authenticate. API Error: 401 Invalid authentication credentials".
+
+Contract under test: a token whose ``expiresAt`` lies in the past is treated
+as ABSENT (never injected); a missing ``expiresAt`` stays fail-open so older
+CLI credential shapes keep working.
+"""
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from jarvis.missions.isolation import env as env_mod
+
+
+def _write_credentials(
+ tmp_path: Path,
+ *,
+ token: str = "sk-ant-oat01-test-token",
+ expires_at_ms: float | None = None,
+ omit_expiry: bool = False,
+) -> Path:
+ creds = tmp_path / ".credentials.json"
+ oauth: dict[str, object] = {"accessToken": token}
+ if not omit_expiry and expires_at_ms is not None:
+ oauth["expiresAt"] = expires_at_ms
+ creds.write_text(
+ json.dumps({"claudeAiOauth": oauth}), encoding="utf-8"
+ )
+ return creds
+
+
+def _pin_credentials_path(monkeypatch: pytest.MonkeyPatch, path: Path) -> None:
+ monkeypatch.setattr(env_mod, "_claude_credentials_path", lambda: path)
+
+
+NOW_S = 1_783_300_000.0 # arbitrary fixed wall clock for the tests
+
+
+def test_valid_token_is_returned(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ creds = _write_credentials(
+ tmp_path, expires_at_ms=(NOW_S + 3600.0) * 1000.0
+ )
+ _pin_credentials_path(monkeypatch, creds)
+ token = env_mod.read_live_claude_oauth_token(now_fn=lambda: NOW_S)
+ assert token == "sk-ant-oat01-test-token"
+ assert env_mod.live_claude_oauth_status(now_fn=lambda: NOW_S) == "valid"
+
+
+def test_expired_token_is_never_returned(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The 2026-07-06 shape: expiresAt hours in the past → treat as absent."""
+ creds = _write_credentials(
+ tmp_path, expires_at_ms=(NOW_S - 18 * 3600.0) * 1000.0
+ )
+ _pin_credentials_path(monkeypatch, creds)
+ assert env_mod.read_live_claude_oauth_token(now_fn=lambda: NOW_S) is None
+ assert env_mod.live_claude_oauth_status(now_fn=lambda: NOW_S) == "expired"
+
+
+def test_token_expiring_within_slack_is_treated_as_expired(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A token that dies seconds from now would 401 mid-mission — skip it."""
+ creds = _write_credentials(
+ tmp_path, expires_at_ms=(NOW_S + 10.0) * 1000.0
+ )
+ _pin_credentials_path(monkeypatch, creds)
+ assert env_mod.read_live_claude_oauth_token(now_fn=lambda: NOW_S) is None
+
+
+def test_missing_expiry_field_stays_fail_open(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Older credential shapes without expiresAt keep working (back-compat)."""
+ creds = _write_credentials(tmp_path, omit_expiry=True)
+ _pin_credentials_path(monkeypatch, creds)
+ token = env_mod.read_live_claude_oauth_token(now_fn=lambda: NOW_S)
+ assert token == "sk-ant-oat01-test-token"
+ assert env_mod.live_claude_oauth_status(now_fn=lambda: NOW_S) == "valid"
+
+
+def test_absent_file_reports_absent(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _pin_credentials_path(monkeypatch, tmp_path / "nope" / ".credentials.json")
+ assert env_mod.read_live_claude_oauth_token(now_fn=lambda: NOW_S) is None
+ assert env_mod.live_claude_oauth_status(now_fn=lambda: NOW_S) == "absent"
+
+
+def test_non_oat_token_reports_absent(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Only sk-ant-oat bearers count — anything else is not a live OAuth login."""
+ creds = _write_credentials(
+ tmp_path, token="sk-ant-api03-classic-key",
+ expires_at_ms=(NOW_S + 3600.0) * 1000.0,
+ )
+ _pin_credentials_path(monkeypatch, creds)
+ assert env_mod.read_live_claude_oauth_token(now_fn=lambda: NOW_S) is None
+ assert env_mod.live_claude_oauth_status(now_fn=lambda: NOW_S) == "absent"
diff --git a/tests/unit/setup/test_setup_marker.py b/tests/unit/setup/test_setup_marker.py
index 80c65e4bd7..c7d8115d80 100644
--- a/tests/unit/setup/test_setup_marker.py
+++ b/tests/unit/setup/test_setup_marker.py
@@ -20,3 +20,31 @@ def test_default_marker_matches_config_data_dir() -> None:
from jarvis.core.config import DATA_DIR
assert st.setup_complete_marker_path() == DATA_DIR / ".setup-complete"
+
+
+def test_write_and_remove_roundtrip(tmp_path: Path) -> None:
+ state_file = tmp_path / "setup_state.json"
+ st.write_setup_complete_marker("Setup completed on Python 3.11\n", state_file)
+ assert st.setup_complete_marker_exists(state_file) is True
+ assert st.remove_setup_complete_marker(state_file) is True
+ assert st.setup_complete_marker_exists(state_file) is False
+ assert st.remove_setup_complete_marker(state_file) is False # already gone
+
+
+def test_no_caller_rebuilds_the_marker_path() -> None:
+ """Read/write/delete must all route through jarvis.setup.state — a literal
+ '.setup-complete' STRING (a rebuilt path) anywhere else can silently desync
+ and revive the 'onboarding reappears every restart' bug class. Prose
+ mentions in docstrings/log messages are fine; quoted literals are not."""
+ import re
+ from pathlib import Path as P
+
+ literal = re.compile(r"""['"]\.setup-complete['"]""")
+ repo = P(__file__).resolve().parents[3]
+ offenders = []
+ for py in (repo / "jarvis").rglob("*.py"):
+ if py.name == "state.py" and py.parent.name == "setup":
+ continue
+ if literal.search(py.read_text(encoding="utf-8", errors="replace")):
+ offenders.append(str(py.relative_to(repo)))
+ assert offenders == [], f"rebuilt marker path outside jarvis/setup/state.py: {offenders}"