Skip to content

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

feat(onboarding): declining the Terms cleanly quits the app

Ruben Lütke9cbf1cae414c
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index fd61ab90ee..a7c6d14999 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -2127,6 +2127,39 @@ class DesktopApp:
)
return True
+ def request_quit(self) -> bool:
+ """Cleanly quit the app WITHOUT relaunching (Terms declined).
+
+ Same quit sequence as ``request_restart`` — mark the quit, destroy the
+ window, hard-exit if shutdown stalls — but no relauncher is spawned,
+ so the process simply ends. Used by the onboarding Terms gate
+ (design 2026-07-09): declining the Terms must not leave a half-running
+ assistant behind. Returns ``True`` if the quit was scheduled,
+ ``False`` on a headless host (no window to close).
+ """
+ from loguru import logger
+
+ from jarvis.ui.relauncher import run_restart_quit_sequence
+
+ window = getattr(self, "_window", None)
+ if window is None:
+ return False
+
+ def _mark_quit() -> None:
+ self._user_requested_quit = True
+
+ def _quit_soon() -> None:
+ run_restart_quit_sequence(
+ set_quit=_mark_quit,
+ destroy_window=window.destroy,
+ )
+
+ threading.Thread(
+ target=_quit_soon, name="jarvis-decline-quit", daemon=True
+ ).start()
+ logger.info("Quit scheduled (Terms declined; hard-exit fallback armed).")
+ return True
+
async def _start_speech_and_orb(
self,
loop: asyncio.AbstractEventLoop,
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/RiskGate.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/RiskGate.test.tsx
new file mode 100644
index 0000000000..8ff7c72137
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/onboarding/RiskGate.test.tsx
@@ -0,0 +1,62 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+
+import { RiskGate } from "./RiskGate";
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+it("declining posts the quit request and shows the goodbye screen", async () => {
+ const calls: Array<[string, RequestInit | undefined]> = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockImplementation((url: string, init?: RequestInit) => {
+ calls.push([url, init]);
+ return Promise.resolve({
+ ok: true,
+ json: () => Promise.resolve({ ok: true, quitting: true }),
+ });
+ }),
+ );
+ const onAccept = vi.fn();
+ render(<RiskGate onAccept={onAccept} />);
+
+ fireEvent.click(screen.getByRole("button", { name: /decline/i }));
+
+ await waitFor(() =>
+ expect(
+ calls.some(
+ ([url, init]) =>
+ url === "/api/onboarding/decline-terms" && init?.method === "POST",
+ ),
+ ).toBe(true),
+ );
+ expect(screen.getByText(/shutting down/i)).toBeDefined();
+ expect(onAccept).not.toHaveBeenCalled();
+});
+
+it("shows the goodbye screen even when the quit request fails", async () => {
+ // A warming/erroring backend must not trap the user on the gate: the
+ // goodbye state renders either way and the user just closes the window.
+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("net")));
+ render(<RiskGate onAccept={() => undefined} />);
+
+ fireEvent.click(screen.getByRole("button", { name: /decline/i }));
+
+ await waitFor(() => expect(screen.getByText(/shutting down/i)).toBeDefined());
+});
+
+it("declining needs no checkbox tick; accepting still does", () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({ ok: true, json: () => Promise.resolve({}) }),
+ );
+ render(<RiskGate onAccept={() => undefined} />);
+
+ const decline = screen.getByRole("button", { name: /decline/i }) as HTMLButtonElement;
+ const proceed = screen.getByRole("button", { name: /continue/i }) as HTMLButtonElement;
+ expect(decline.disabled).toBe(false);
+ expect(proceed.disabled).toBe(true);
+});
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/RiskGate.tsx b/jarvis/ui/web/frontend/src/components/onboarding/RiskGate.tsx
index 11ccd65565..e7015d492c 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/RiskGate.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/RiskGate.tsx
@@ -8,10 +8,16 @@ import { useT } from "@/i18n";
* first run). Frontend-only: it gates the flow via local state and never mutates
* onboarding/completed state, so it cannot reintroduce the "onboarding reappears
* every restart" bug. The user must tick the checkbox before continuing.
+ *
+ * Declining is a real, equal-weight choice (design 2026-07-09): it asks the
+ * backend to quit the whole app and renders a terminal goodbye state for the
+ * browser surface (the desktop window disappears with the process). Nothing is
+ * persisted on decline — the next start shows this gate again.
*/
export function RiskGate({ onAccept }: { onAccept: () => void }) {
const t = useT();
const [accepted, setAccepted] = useState(false);
+ const [declined, setDeclined] = useState(false);
// Full Terms text, fetched lazily on first expand — proceeding through this
// gate records the acceptance (see OnboardingGate), so the text must be
// reachable right here.
@@ -31,6 +37,31 @@ export function RiskGate({ onAccept }: { onAccept: () => void }) {
}
};
+ const decline = async () => {
+ // Show the goodbye state first — the backend kills the process moments
+ // after answering, so this screen is the last thing the browser renders.
+ setDeclined(true);
+ try {
+ await fetch("/api/onboarding/decline-terms", { method: "POST" });
+ } catch {
+ // Best-effort: a warming/erroring backend cannot block the goodbye
+ // screen; the user closes the window either way.
+ }
+ };
+
+ if (declined) {
+ return (
+ <div className="flex w-full max-w-lg flex-col gap-4 rounded-2xl border border-border bg-card p-8 shadow-2xl">
+ <h1 className="font-display text-xl font-semibold">
+ {t("onboarding.risk.declined_title")}
+ </h1>
+ <p className="text-sm leading-relaxed text-muted-foreground">
+ {t("onboarding.risk.declined_body")}
+ </p>
+ </div>
+ );
+ }
+
return (
<div className="flex w-full max-w-lg flex-col gap-5 rounded-2xl border border-primary/40 bg-card p-8 shadow-2xl">
<div className="flex items-center gap-3">
@@ -63,9 +94,14 @@ export function RiskGate({ onAccept }: { onAccept: () => void }) {
/>
<span>{t("onboarding.risk.accept_label")}</span>
</label>
- <Button className="w-full" disabled={!accepted} onClick={() => accepted && onAccept()}>
- {t("onboarding.risk.proceed")}
- </Button>
+ <div className="flex gap-3">
+ <Button variant="outline" className="flex-1" onClick={() => void decline()}>
+ {t("onboarding.risk.decline")}
+ </Button>
+ <Button className="flex-1" disabled={!accepted} onClick={() => accepted && onAccept()}>
+ {t("onboarding.risk.proceed")}
+ </Button>
+ </div>
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 9b2590644b..c78cb9ccf5 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -1501,6 +1501,9 @@
"liability": "Die Nutzung erfolgt vollständig auf eigenes Risiko. Die Entwickler übernehmen keine Haftung für Schäden, Datenverlust oder andere Folgen. Fahre nur fort, wenn du das verstehst und akzeptierst.",
"accept_label": "Ich verstehe die Risiken und akzeptiere, dass ich Personal Jarvis auf eigenes Risiko nutze.",
"proceed": "Verstanden — fortfahren",
+ "decline": "Ablehnen & beenden",
+ "declined_title": "Jarvis wird beendet",
+ "declined_body": "Du hast die Bedingungen abgelehnt, deshalb wird Personal Jarvis jetzt geschlossen — es wurde nichts eingerichtet und nichts gespeichert. Starte die App jederzeit erneut, wenn du es dir anders überlegst; diese Frage erscheint dann wieder.",
"view_terms": "Vollständige Nutzungsbedingungen anzeigen",
"terms_loading": "Bedingungen werden geladen…"
},
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index e76f53299a..7640b073b3 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -1502,6 +1502,9 @@
"liability": "You use it entirely at your own risk. The developers accept no liability for any damage, data loss, or other consequences. Only continue if you understand and accept this.",
"accept_label": "I understand the risks and accept that I use Personal Jarvis at my own risk.",
"proceed": "I understand — continue",
+ "decline": "Decline & quit",
+ "declined_title": "Jarvis is shutting down",
+ "declined_body": "You declined the Terms, so Personal Jarvis is closing now — nothing was set up and nothing was saved. Start the app again anytime if you change your mind; this screen will ask again.",
"view_terms": "View the full Terms of Use",
"terms_loading": "Loading terms…"
},
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index b38da718a1..e1828a1c89 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -1501,6 +1501,9 @@
"liability": "Lo usas completamente bajo tu propia responsabilidad. Los desarrolladores no aceptan responsabilidad alguna por daños, pérdida de datos u otras consecuencias. Continúa solo si lo entiendes y lo aceptas.",
"accept_label": "Entiendo los riesgos y acepto que uso Personal Jarvis bajo mi propia responsabilidad.",
"proceed": "Lo entiendo — continuar",
+ "decline": "Rechazar y salir",
+ "declined_title": "Jarvis se está cerrando",
+ "declined_body": "Has rechazado los términos, así que Personal Jarvis se cierra ahora — no se configuró ni se guardó nada. Vuelve a iniciar la aplicación cuando quieras si cambias de opinión; esta pregunta aparecerá de nuevo.",
"view_terms": "Ver los Términos de uso completos",
"terms_loading": "Cargando los términos…"
},
diff --git a/jarvis/ui/web/onboarding_routes.py b/jarvis/ui/web/onboarding_routes.py
index 19c79d599f..7149b92111 100644
--- a/jarvis/ui/web/onboarding_routes.py
+++ b/jarvis/ui/web/onboarding_routes.py
@@ -9,9 +9,11 @@ not on blocking.
from __future__ import annotations
import logging
+import os
+import threading
from pathlib import Path
-from fastapi import APIRouter, Response
+from fastapi import APIRouter, HTTPException, Request, Response
from pydantic import BaseModel
from jarvis.setup import state as st
@@ -68,6 +70,42 @@ async def post_accept_terms() -> dict:
return {"ok": True, "version": CURRENT_TERMS_VERSION}
+def _schedule_app_shutdown(request: Request) -> None:
+ """Quit the whole app shortly after the decline response flushes.
+
+ Desktop hosts get the clean ``DesktopApp.request_quit()`` sequence (mark
+ quit → destroy window → hard-exit backstop, same as the restart path but
+ without a relauncher). Headless hosts have no window to destroy, so a
+ short-delayed hard exit is the honest equivalent — the HTTP 200 reaches
+ the browser first, then the server is gone.
+ """
+ desktop = getattr(request.app.state, "desktop_app", None)
+ fn = getattr(desktop, "request_quit", None)
+ if callable(fn):
+ try:
+ if fn():
+ return
+ except Exception: # noqa: BLE001 — a decline must still end the process
+ log.warning("desktop quit failed; falling back to hard exit", exc_info=True)
+ threading.Timer(0.8, os._exit, args=(0,)).start()
+
+
[email protected]("/decline-terms")
+async def post_decline_terms(request: Request) -> dict:
+ """Declining the Terms quits the app (design 2026-07-09).
+
+ The install one-liner never asks anything, so the Terms gate on first
+ launch is the ONE consent moment — declining it must not leave a
+ half-running assistant behind. Nothing is persisted on decline: the next
+ start shows the gate again. 409 once the Terms are accepted — the gate no
+ longer exists then, and this endpoint must not double as a kill switch.
+ """
+ if _safe_state_payload()["terms"]["accepted"]:
+ raise HTTPException(status_code=409, detail="terms already accepted")
+ _schedule_app_shutdown(request)
+ return {"ok": True, "quitting": True}
+
+
@router.post("/acknowledge-wake-word")
async def post_ack_wake_word() -> dict:
st.acknowledge_wake_word(_path())
diff --git a/tests/unit/ui/test_onboarding_routes.py b/tests/unit/ui/test_onboarding_routes.py
index 8032f1bfed..20f5ca224d 100644
--- a/tests/unit/ui/test_onboarding_routes.py
+++ b/tests/unit/ui/test_onboarding_routes.py
@@ -81,6 +81,75 @@ def test_router_registers_all_paths():
"/api/onboarding/terms",
"/api/onboarding/step",
"/api/onboarding/accept-terms",
+ "/api/onboarding/decline-terms",
"/api/onboarding/acknowledge-wake-word",
"/api/onboarding/complete",
}
+
+
+# ---------------------------------------------------------------- decline-terms
+# Design 2026-07-09: the install one-liner never asks anything, so the Terms
+# gate is the ONE consent moment — declining it quits the whole app.
+
+
+def test_decline_terms_quits_before_acceptance(client, monkeypatch):
+ calls: list[int] = []
+ monkeypatch.setattr(
+ onboarding_routes, "_schedule_app_shutdown", lambda req: calls.append(1)
+ )
+ r = client.post("/api/onboarding/decline-terms")
+ assert r.status_code == 200
+ assert r.json() == {"ok": True, "quitting": True}
+ assert calls == [1]
+ # Nothing is persisted on decline — the next start shows the gate again.
+ assert client.get("/api/onboarding/state").json()["terms"]["accepted"] is False
+
+
+def test_decline_terms_409_after_acceptance(client, monkeypatch):
+ calls: list[int] = []
+ monkeypatch.setattr(
+ onboarding_routes, "_schedule_app_shutdown", lambda req: calls.append(1)
+ )
+ client.post("/api/onboarding/accept-terms")
+ r = client.post("/api/onboarding/decline-terms")
+ assert r.status_code == 409
+ assert calls == []
+
+
+def test_schedule_shutdown_prefers_desktop_quit(monkeypatch):
+ from types import SimpleNamespace
+
+ timers: list[object] = []
+
+ class FakeTimer:
+ def __init__(self, *args, **kwargs):
+ timers.append(self)
+
+ def start(self): # pragma: no cover - must never run in this test
+ raise AssertionError("hard-exit timer must not start on a desktop host")
+
+ monkeypatch.setattr(onboarding_routes.threading, "Timer", FakeTimer)
+ quit_calls: list[int] = []
+ desktop = SimpleNamespace(request_quit=lambda: quit_calls.append(1) or True)
+ req = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(desktop_app=desktop)))
+ onboarding_routes._schedule_app_shutdown(req)
+ assert quit_calls == [1]
+ assert timers == []
+
+
+def test_schedule_shutdown_headless_falls_back_to_hard_exit(monkeypatch):
+ from types import SimpleNamespace
+
+ started: list[tuple] = []
+
+ class FakeTimer:
+ def __init__(self, *args, **kwargs):
+ self.args = args
+
+ def start(self):
+ started.append(self.args)
+
+ monkeypatch.setattr(onboarding_routes.threading, "Timer", FakeTimer)
+ req = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace()))
+ onboarding_routes._schedule_app_shutdown(req)
+ assert len(started) == 1 # armed exactly one delayed exit, nothing immediate