idormoy commited on
Commit
2f4e56c
·
verified ·
1 Parent(s): 380e7c5

Add a dashboard settings page so the app can be configured

Browse files
src/focus_buddy/config.py CHANGED
@@ -29,6 +29,15 @@ class SpeechEngine(str, Enum):
29
  NONE = "none"
30
 
31
 
 
 
 
 
 
 
 
 
 
32
  def _env_bool(name: str, default: bool = False) -> bool:
33
  raw = os.getenv(name)
34
  if raw is None:
@@ -97,6 +106,11 @@ class Settings:
97
  # and finds nothing at all once installed as a wheel. Anchoring to the
98
  # working directory makes both installs behave the same.
99
  load_dotenv(find_dotenv(usecwd=True))
 
 
 
 
 
100
 
101
  backend = Backend(os.getenv("FOCUS_BUDDY_BACKEND", Backend.CLOUD.value).lower())
102
  speech = SpeechEngine(os.getenv("FOCUS_BUDDY_SPEECH", SpeechEngine.OPENAI.value).lower())
 
29
  NONE = "none"
30
 
31
 
32
+ def user_config_path() -> Path:
33
+ """Where the dashboard settings page saves what the user typed.
34
+
35
+ Not the package directory: an app installed from the app store lives in
36
+ site-packages, which is the wrong place to write to and may be read-only.
37
+ """
38
+ return Path.home() / ".config" / "focus_buddy" / "config.env"
39
+
40
+
41
  def _env_bool(name: str, default: bool = False) -> bool:
42
  raw = os.getenv(name)
43
  if raw is None:
 
106
  # and finds nothing at all once installed as a wheel. Anchoring to the
107
  # working directory makes both installs behave the same.
108
  load_dotenv(find_dotenv(usecwd=True))
109
+ # Then whatever the dashboard settings page saved. override=False so a
110
+ # developer's .env and any real environment variable still win.
111
+ saved = user_config_path()
112
+ if saved.exists():
113
+ load_dotenv(saved, override=False)
114
 
115
  backend = Backend(os.getenv("FOCUS_BUDDY_BACKEND", Backend.CLOUD.value).lower())
116
  speech = SpeechEngine(os.getenv("FOCUS_BUDDY_SPEECH", SpeechEngine.OPENAI.value).lower())
src/focus_buddy/main.py CHANGED
@@ -63,9 +63,18 @@ def _report(settings: Settings) -> list[str]:
63
  return errors
64
 
65
 
 
 
 
 
66
  class FocusBuddy(ReachyMiniApp):
67
  """Reachy Mini app that watches for focus-breaking habits and nudges you."""
68
 
 
 
 
 
 
69
  def __init__(self, running_on_wireless: bool = False, settings: Settings | None = None) -> None:
70
  """Create the app.
71
 
@@ -76,6 +85,34 @@ class FocusBuddy(ReachyMiniApp):
76
  """
77
  super().__init__(running_on_wireless)
78
  self._settings = settings
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
  def run(self, reachy_mini: ReachyMini, stop_event: threading.Event) -> None:
81
  """Run the focus loop until the dashboard stops the app."""
@@ -84,13 +121,10 @@ class FocusBuddy(ReachyMiniApp):
84
  settings = self._settings
85
  if settings is None:
86
  # Dashboard launch: nothing has read the environment for us yet.
87
- settings = Settings.from_env()
88
- errors = _report(settings)
89
- if errors:
90
- # Surfaced by the dashboard through ReachyMiniApp.error.
91
- raise RuntimeError(
92
- "Focus Buddy is not configured correctly:\n- " + "\n- ".join(errors)
93
- )
94
 
95
  body = ReachyBody(reachy_mini)
96
  loop = build_loop(body, settings)
 
63
  return errors
64
 
65
 
66
+ # How often to re-read the configuration while waiting for the settings page.
67
+ _CONFIG_POLL_S = 2.0
68
+
69
+
70
  class FocusBuddy(ReachyMiniApp):
71
  """Reachy Mini app that watches for focus-breaking habits and nudges you."""
72
 
73
+ # Serving this makes the dashboard show a settings page for the app. Without
74
+ # it there is no way to supply an API key to an app-store install, which is
75
+ # what made the first version exit immediately on a fresh robot.
76
+ custom_app_url = "http://0.0.0.0:7860/"
77
+
78
  def __init__(self, running_on_wireless: bool = False, settings: Settings | None = None) -> None:
79
  """Create the app.
80
 
 
85
  """
86
  super().__init__(running_on_wireless)
87
  self._settings = settings
88
+ # Only the dashboard needs the page; the CLI has flags and a shell.
89
+ if settings is None:
90
+ from .settings_page import attach
91
+
92
+ attach(self.settings_app)
93
+
94
+ def _await_configuration(self, stop_event: threading.Event) -> Settings | None:
95
+ """Block until the settings page yields a usable configuration.
96
+
97
+ Returns None if the app is stopped first. Waiting rather than raising is
98
+ the whole point: an unconfigured app has to stay alive long enough for
99
+ someone to open its settings page and type a key into it.
100
+ """
101
+ announced = False
102
+ while not stop_event.is_set():
103
+ settings = Settings.from_env()
104
+ errors = _report(settings)
105
+ if not errors:
106
+ return settings
107
+ if not announced:
108
+ # Also surfaced by the dashboard through ReachyMiniApp.error.
109
+ self.error = "Focus Buddy needs configuring:\n- " + "\n- ".join(errors)
110
+ logger.error(
111
+ "%s\nWaiting for the settings page at %s", self.error, self.custom_app_url
112
+ )
113
+ announced = True
114
+ stop_event.wait(_CONFIG_POLL_S)
115
+ return None
116
 
117
  def run(self, reachy_mini: ReachyMini, stop_event: threading.Event) -> None:
118
  """Run the focus loop until the dashboard stops the app."""
 
121
  settings = self._settings
122
  if settings is None:
123
  # Dashboard launch: nothing has read the environment for us yet.
124
+ settings = self._await_configuration(stop_event)
125
+ if settings is None:
126
+ return
127
+ self.error = ""
 
 
 
128
 
129
  body = ReachyBody(reachy_mini)
130
  loop = build_loop(body, settings)
src/focus_buddy/perception/landmarks.py CHANGED
@@ -229,9 +229,18 @@ def default_sidecar_python() -> Path:
229
 
230
  Derived rather than spelled out a second time: the setup command and the
231
  lookup have to agree, and two literals eventually will not.
 
 
 
 
232
  """
233
  posix = default_sidecar_dir() / "bin" / "python"
234
- return posix if posix.exists() else default_sidecar_dir() / "Scripts" / "python.exe"
 
 
 
 
 
235
 
236
 
237
  def sidecar_script() -> Path:
 
229
 
230
  Derived rather than spelled out a second time: the setup command and the
231
  lookup have to agree, and two literals eventually will not.
232
+
233
+ Falls back to the platform's layout rather than the other one when neither
234
+ exists, so the "no interpreter at ..." error names a plausible path instead
235
+ of pointing a mac user at Scripts/python.exe.
236
  """
237
  posix = default_sidecar_dir() / "bin" / "python"
238
+ windows = default_sidecar_dir() / "Scripts" / "python.exe"
239
+ if posix.exists():
240
+ return posix
241
+ if windows.exists():
242
+ return windows
243
+ return windows if os.name == "nt" else posix
244
 
245
 
246
  def sidecar_script() -> Path:
src/focus_buddy/settings_page.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The settings page the Reachy Mini dashboard shows for this app.
2
+
3
+ An app installed from the app store arrives with no ``.env`` and no way for the
4
+ user to set an environment variable, so the first run of Focus Buddy failed
5
+ configuration and exited before anyone could supply an API key. The SDK's answer
6
+ is a per-app settings page: set ``custom_app_url`` on the app class and the
7
+ framework serves ``<package>/static/index.html`` there, which the dashboard
8
+ links to.
9
+
10
+ This module owns the read/write half of that page. What the user types is saved
11
+ to :func:`~focus_buddy.config.user_config_path`, which is under the home
12
+ directory rather than in site-packages, and is picked up by
13
+ :meth:`Settings.from_env` on the next read.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ import os
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from .config import Backend, Settings, SpeechEngine, user_config_path
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+ # Only these may be written from the page. An allowlist rather than "any
28
+ # FOCUS_BUDDY_* key", so a typo cannot quietly create a setting nothing reads.
29
+ WRITABLE = (
30
+ "OPENAI_API_KEY",
31
+ "FOCUS_BUDDY_BACKEND",
32
+ "FOCUS_BUDDY_SPEECH",
33
+ "FOCUS_BUDDY_NUDGE_COOLDOWN_S",
34
+ )
35
+
36
+
37
+ def read_saved(path: Path | None = None) -> dict[str, str]:
38
+ """Read the saved settings file into a plain dict."""
39
+ path = path or user_config_path()
40
+ values: dict[str, str] = {}
41
+ if not path.exists():
42
+ return values
43
+ for line in path.read_text(encoding="utf-8").splitlines():
44
+ line = line.strip()
45
+ if not line or line.startswith("#") or "=" not in line:
46
+ continue
47
+ key, _, value = line.partition("=")
48
+ values[key.strip()] = value.strip()
49
+ return values
50
+
51
+
52
+ def save(updates: dict[str, str], path: Path | None = None) -> Path:
53
+ """Merge ``updates`` into the saved settings and apply them to this process.
54
+
55
+ Values are written verbatim, so a key is stored as the user typed it. Empty
56
+ values clear the setting rather than storing a blank, which is what lets the
57
+ page offer "use the default" without a separate control.
58
+ """
59
+ path = path or user_config_path()
60
+ values = read_saved(path)
61
+ for key, value in updates.items():
62
+ if key not in WRITABLE:
63
+ logger.warning("Ignoring unwritable setting %s", key)
64
+ continue
65
+ value = (value or "").strip()
66
+ if value:
67
+ values[key] = value
68
+ os.environ[key] = value
69
+ else:
70
+ values.pop(key, None)
71
+ os.environ.pop(key, None)
72
+
73
+ path.parent.mkdir(parents=True, exist_ok=True)
74
+ body = "\n".join(f"{k}={v}" for k, v in sorted(values.items()))
75
+ path.write_text(
76
+ "# Written by the Focus Buddy settings page. Safe to edit by hand.\n" + body + "\n",
77
+ encoding="utf-8",
78
+ )
79
+ # The API key is the whole reason this file exists; keep it off the disk of
80
+ # anyone else who can read the home directory.
81
+ path.chmod(0o600)
82
+ logger.info("Saved settings to %s", path)
83
+ return path
84
+
85
+
86
+ def current_state() -> dict[str, Any]:
87
+ """Describe the configuration for the page, without leaking the key."""
88
+ settings = Settings.from_env()
89
+ errors = settings.validate()
90
+ saved = read_saved()
91
+ key = os.getenv("OPENAI_API_KEY") or saved.get("OPENAI_API_KEY", "")
92
+ return {
93
+ "backend": settings.backend.value,
94
+ "speech": settings.speech.value,
95
+ "nudge_cooldown_s": settings.nudge_cooldown_s,
96
+ # Never the key itself: this is served over plain HTTP on the LAN.
97
+ "has_api_key": bool(key),
98
+ "api_key_hint": f"…{key[-4:]}" if len(key) >= 4 else "",
99
+ "ready": not errors,
100
+ "errors": errors,
101
+ "warnings": settings.warnings,
102
+ "backends": [b.value for b in Backend],
103
+ "speech_engines": [s.value for s in SpeechEngine],
104
+ }
105
+
106
+
107
+ def attach(settings_app: Any) -> None:
108
+ """Add the settings endpoints to the FastAPI the SDK built for this app."""
109
+ if settings_app is None: # pragma: no cover - only when custom_app_url is unset
110
+ return
111
+
112
+ @settings_app.get("/api/settings")
113
+ async def get_settings() -> dict[str, Any]:
114
+ """Report the current configuration and why it is or is not usable."""
115
+ return current_state()
116
+
117
+ @settings_app.post("/api/settings")
118
+ async def post_settings(payload: dict[str, str]) -> dict[str, Any]:
119
+ """Save what the page submitted, then report the new state."""
120
+ save(payload)
121
+ return current_state()
src/focus_buddy/setup_sidecar.py CHANGED
@@ -18,6 +18,7 @@ which talks to it over a pipe.
18
  from __future__ import annotations
19
 
20
  import argparse
 
21
  import shutil
22
  import subprocess
23
  import sys
@@ -34,7 +35,12 @@ REQUIREMENTS = ("mediapipe==0.10.14", "numpy<2", "pillow>=10.0")
34
  def sidecar_python(venv_dir: Path) -> Path:
35
  """Locate the interpreter inside a sidecar venv, on either layout."""
36
  posix = venv_dir / "bin" / "python"
37
- return posix if posix.exists() else venv_dir / "Scripts" / "python.exe"
 
 
 
 
 
38
 
39
 
40
  def build(path: Path, recreate: bool = False) -> Path:
 
18
  from __future__ import annotations
19
 
20
  import argparse
21
+ import os
22
  import shutil
23
  import subprocess
24
  import sys
 
35
  def sidecar_python(venv_dir: Path) -> Path:
36
  """Locate the interpreter inside a sidecar venv, on either layout."""
37
  posix = venv_dir / "bin" / "python"
38
+ windows = venv_dir / "Scripts" / "python.exe"
39
+ if posix.exists():
40
+ return posix
41
+ if windows.exists():
42
+ return windows
43
+ return windows if os.name == "nt" else posix
44
 
45
 
46
  def build(path: Path, recreate: bool = False) -> Path:
src/focus_buddy/static/index.html ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>Focus Buddy settings</title>
7
+ <style>
8
+ :root { color-scheme: light dark; --fg:#1a1a1f; --muted:#63636e; --bg:#fbfbfd;
9
+ --card:#fff; --line:#e3e3ea; --accent:#4f46e5; --ok:#0f7b4f; --bad:#b42318; }
10
+ @media (prefers-color-scheme: dark) {
11
+ :root { --fg:#ececf1; --muted:#a0a0ae; --bg:#141419; --card:#1c1c23;
12
+ --line:#2e2e38; --accent:#8b85f5; --ok:#4ade80; --bad:#f87171; }
13
+ }
14
+ * { box-sizing: border-box; }
15
+ body { margin:0; padding:24px; background:var(--bg); color:var(--fg);
16
+ font:15px/1.55 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
17
+ main { max-width: 560px; margin: 0 auto; }
18
+ h1 { font-size:22px; margin:0 0 4px; }
19
+ p.sub { color:var(--muted); margin:0 0 20px; }
20
+ .card { background:var(--card); border:1px solid var(--line); border-radius:12px;
21
+ padding:18px; margin-bottom:14px; }
22
+ label { display:block; font-weight:600; margin:14px 0 6px; }
23
+ label:first-child { margin-top:0; }
24
+ input, select { width:100%; padding:9px 11px; border:1px solid var(--line);
25
+ border-radius:8px; background:var(--bg); color:var(--fg); font-size:15px; }
26
+ small { display:block; color:var(--muted); margin-top:5px; }
27
+ button { margin-top:18px; width:100%; padding:11px; border:0; border-radius:8px;
28
+ background:var(--accent); color:#fff; font-size:15px; font-weight:600; cursor:pointer; }
29
+ button:disabled { opacity:.55; cursor:default; }
30
+ #status { margin-bottom:14px; padding:12px 14px; border-radius:10px;
31
+ border:1px solid var(--line); background:var(--card); }
32
+ .ok { color:var(--ok); font-weight:600; }
33
+ .bad { color:var(--bad); font-weight:600; }
34
+ ul { margin:8px 0 0; padding-left:20px; color:var(--muted); }
35
+ </style>
36
+ </head>
37
+ <body>
38
+ <main>
39
+ <h1>👀 Focus Buddy</h1>
40
+ <p class="sub">Notices the habits that break your focus, and says so.</p>
41
+
42
+ <div id="status">Loading…</div>
43
+
44
+ <div class="card">
45
+ <label for="backend">How it sees</label>
46
+ <select id="backend"></select>
47
+ <small id="backend-help"></small>
48
+
49
+ <label for="speech">How it speaks</label>
50
+ <select id="speech"></select>
51
+
52
+ <label for="key">OpenAI API key</label>
53
+ <input id="key" type="password" placeholder="sk-…" autocomplete="off" />
54
+ <small id="key-help">Only needed for the cloud backend or OpenAI speech.</small>
55
+
56
+ <label for="cooldown">Seconds between nudges</label>
57
+ <input id="cooldown" type="number" min="3" step="1" placeholder="60" />
58
+
59
+ <button id="save">Save</button>
60
+ </div>
61
+ </main>
62
+
63
+ <script>
64
+ const HELP = {
65
+ "edge": "Landmark geometry on this machine. No API key, no model, ~0.05s a frame. Detects face-touching, nail-biting, gaze and whether you are at the desk — but not phone use. Needs the sidecar: run focus-buddy-setup-sidecar once.",
66
+ "cloud": "An OpenAI vision model. Detects everything including phone use. Needs an API key and sends each frame to OpenAI.",
67
+ "edge-vlm": "The old local vision model. Kept because it runs, not because it works: it scored at chance on a labelled set and takes seconds per frame."
68
+ };
69
+
70
+ const $ = (id) => document.getElementById(id);
71
+
72
+ function fill(sel, options, value) {
73
+ sel.innerHTML = "";
74
+ for (const o of options) {
75
+ const el = document.createElement("option");
76
+ el.value = o; el.textContent = o;
77
+ if (o === value) el.selected = true;
78
+ sel.appendChild(el);
79
+ }
80
+ }
81
+
82
+ function render(s) {
83
+ fill($("backend"), s.backends, s.backend);
84
+ fill($("speech"), s.speech_engines, s.speech);
85
+ $("cooldown").value = s.nudge_cooldown_s;
86
+ $("key").placeholder = s.has_api_key ? `saved (${s.api_key_hint})` : "sk-…";
87
+ $("backend-help").textContent = HELP[$("backend").value] || "";
88
+
89
+ const box = $("status");
90
+ if (s.ready) {
91
+ box.innerHTML = `<span class="ok">Ready.</span> Focus Buddy will start watching.`;
92
+ } else {
93
+ box.innerHTML = `<span class="bad">Not configured yet.</span><ul>`
94
+ + s.errors.map(e => `<li>${e.replace(/</g, "&lt;")}</li>`).join("") + `</ul>`;
95
+ }
96
+ if (s.warnings && s.warnings.length) {
97
+ box.innerHTML += `<ul>` + s.warnings.map(w => `<li>${w.replace(/</g, "&lt;")}</li>`).join("") + `</ul>`;
98
+ }
99
+ }
100
+
101
+ async function load() {
102
+ render(await (await fetch("api/settings")).json());
103
+ }
104
+
105
+ $("backend").addEventListener("change", () => {
106
+ $("backend-help").textContent = HELP[$("backend").value] || "";
107
+ });
108
+
109
+ $("save").addEventListener("click", async () => {
110
+ const btn = $("save");
111
+ btn.disabled = true; btn.textContent = "Saving…";
112
+ const body = {
113
+ FOCUS_BUDDY_BACKEND: $("backend").value,
114
+ FOCUS_BUDDY_SPEECH: $("speech").value,
115
+ FOCUS_BUDDY_NUDGE_COOLDOWN_S: $("cooldown").value,
116
+ };
117
+ // Blank means "keep what is already saved", not "clear it".
118
+ if ($("key").value.trim()) body.OPENAI_API_KEY = $("key").value.trim();
119
+ render(await (await fetch("api/settings", {
120
+ method: "POST",
121
+ headers: { "Content-Type": "application/json" },
122
+ body: JSON.stringify(body),
123
+ })).json());
124
+ $("key").value = "";
125
+ btn.disabled = false; btn.textContent = "Save";
126
+ });
127
+
128
+ load();
129
+ setInterval(load, 5000);
130
+ </script>
131
+ </body>
132
+ </html>
tests/test_settings_page.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The dashboard settings page: what it saves, and what it must never hand back.
2
+
3
+ This exists because an app-store install has no .env and no way to set an
4
+ environment variable, so without a settings page Focus Buddy could not be
5
+ configured at all -- it validated, raised and exited before anyone could type a
6
+ key into it.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import pytest
12
+
13
+ from focus_buddy import settings_page
14
+ from focus_buddy.config import Backend, Settings, SpeechEngine
15
+
16
+
17
+ @pytest.fixture
18
+ def config_file(tmp_path, monkeypatch):
19
+ """Point the settings file at a temporary home."""
20
+ path = tmp_path / "config.env"
21
+ monkeypatch.setattr(settings_page, "user_config_path", lambda: path)
22
+ monkeypatch.setattr("focus_buddy.config.user_config_path", lambda: path)
23
+ # Settings.from_env also loads a .env found from the working directory. On a
24
+ # developer's machine that is the repo's own, complete with a real key, which
25
+ # would make "a fresh install cannot start" quietly pass for the wrong reason.
26
+ monkeypatch.setattr("dotenv.find_dotenv", lambda *a, **k: "")
27
+ for name in ("OPENAI_API_KEY", "FOCUS_BUDDY_BACKEND", "FOCUS_BUDDY_SPEECH"):
28
+ monkeypatch.delenv(name, raising=False)
29
+ return path
30
+
31
+
32
+ class TestSaveAndRead:
33
+ def test_round_trips_a_value(self, config_file):
34
+ settings_page.save({"OPENAI_API_KEY": "sk-abc"}, config_file)
35
+ assert settings_page.read_saved(config_file)["OPENAI_API_KEY"] == "sk-abc"
36
+
37
+ def test_merges_rather_than_replaces(self, config_file):
38
+ settings_page.save({"OPENAI_API_KEY": "sk-abc"}, config_file)
39
+ settings_page.save({"FOCUS_BUDDY_SPEECH": "none"}, config_file)
40
+ saved = settings_page.read_saved(config_file)
41
+ assert saved["OPENAI_API_KEY"] == "sk-abc"
42
+ assert saved["FOCUS_BUDDY_SPEECH"] == "none"
43
+
44
+ def test_applies_to_the_running_process(self, config_file, monkeypatch):
45
+ """The app re-reads settings while waiting; it must see the new value."""
46
+ settings_page.save({"OPENAI_API_KEY": "sk-live"}, config_file)
47
+ import os
48
+
49
+ assert os.environ["OPENAI_API_KEY"] == "sk-live"
50
+
51
+ def test_empty_clears_rather_than_storing_blank(self, config_file):
52
+ settings_page.save({"FOCUS_BUDDY_SPEECH": "none"}, config_file)
53
+ settings_page.save({"FOCUS_BUDDY_SPEECH": ""}, config_file)
54
+ assert "FOCUS_BUDDY_SPEECH" not in settings_page.read_saved(config_file)
55
+
56
+ def test_only_allowlisted_keys_are_written(self, config_file):
57
+ """A typo must not quietly create a setting nothing reads."""
58
+ settings_page.save({"PATH": "/evil", "FOCUS_BUDDY_NONSENSE": "1"}, config_file)
59
+ saved = settings_page.read_saved(config_file)
60
+ assert "PATH" not in saved and "FOCUS_BUDDY_NONSENSE" not in saved
61
+
62
+ def test_file_is_not_world_readable(self, config_file):
63
+ """It holds an API key."""
64
+ settings_page.save({"OPENAI_API_KEY": "sk-abc"}, config_file)
65
+ assert config_file.stat().st_mode & 0o077 == 0
66
+
67
+ def test_missing_file_reads_as_empty(self, tmp_path):
68
+ assert settings_page.read_saved(tmp_path / "absent.env") == {}
69
+
70
+ def test_comments_and_blanks_are_ignored(self, config_file):
71
+ config_file.write_text("# a comment\n\nFOCUS_BUDDY_SPEECH=none\nnot-a-pair\n")
72
+ assert settings_page.read_saved(config_file) == {"FOCUS_BUDDY_SPEECH": "none"}
73
+
74
+
75
+ class TestCurrentState:
76
+ def test_reports_why_a_fresh_install_cannot_start(self, config_file):
77
+ state = settings_page.current_state()
78
+ assert state["ready"] is False
79
+ assert any("OPENAI_API_KEY" in error for error in state["errors"])
80
+
81
+ def test_becomes_ready_once_a_key_is_saved(self, config_file):
82
+ settings_page.save({"OPENAI_API_KEY": "sk-abc"}, config_file)
83
+ assert settings_page.current_state()["ready"] is True
84
+
85
+ def test_never_returns_the_key_itself(self, config_file):
86
+ """The page is served over plain HTTP on the LAN."""
87
+ settings_page.save({"OPENAI_API_KEY": "sk-secret-value"}, config_file)
88
+ state = settings_page.current_state()
89
+ assert "sk-secret-value" not in repr(state)
90
+ assert state["has_api_key"] is True
91
+ assert state["api_key_hint"] == "…alue"
92
+
93
+ def test_offers_every_backend_and_speech_engine(self, config_file):
94
+ state = settings_page.current_state()
95
+ assert state["backends"] == [b.value for b in Backend]
96
+ assert state["speech_engines"] == [s.value for s in SpeechEngine]
97
+
98
+
99
+ class TestConfigLoading:
100
+ def test_settings_pick_up_the_saved_file(self, config_file, monkeypatch):
101
+ settings_page.save({"FOCUS_BUDDY_SPEECH": "none"}, config_file)
102
+ monkeypatch.delenv("FOCUS_BUDDY_SPEECH", raising=False)
103
+ assert Settings.from_env().speech is SpeechEngine.NONE
104
+
105
+ def test_a_real_environment_variable_still_wins(self, config_file, monkeypatch):
106
+ """Saved settings fill gaps; they do not override an explicit env var."""
107
+ settings_page.save({"FOCUS_BUDDY_BACKEND": "cloud"}, config_file)
108
+ monkeypatch.setenv("FOCUS_BUDDY_BACKEND", "edge")
109
+ assert Settings.from_env().backend is Backend.EDGE