Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
- ruff now also checks the PTH and RUF rule sets on iris/ and tests/, and every finding was fixed without changing behaviour; the protected files keep their per-file ignores for the new rules too.
- Tests are type-checked by mypy as well; 14 test modules still sit on the ignore list until they are typed.
- git, Cline CLI and lms output are decoded as UTF-8 with replacement, so the dashboard's agent status and autopilot survive any text on a non-UTF-8 locale code page.
- The dashboard's Settings tab has a "Start Iris in the tray at login" switch that writes or removes the Startup-folder entry (`/api/startup`); an installer build answers that it manages its own entry.

## 1.0.0 (release date): steady, safer and measured

Expand Down
47 changes: 33 additions & 14 deletions iris/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,28 +54,47 @@ def startup_python(exe: Path) -> Path:
SHORTCUT_NAME = "Iris.lnk"


def startup_state() -> str | None:
"""The path of the first STARTUP_NAMES file in the Startup folder, or None when none is there."""
d = startup_dir()
for name in STARTUP_NAMES:
if (d / name).exists():
return str(d / name)
return None


def startup_enable() -> Path:
"""Write Iris.vbs to the Startup folder, remove the old names it replaces, and return its path."""
vbs = startup_dir() / "Iris.vbs"
vbs.parent.mkdir(parents=True, exist_ok=True)
exe = startup_python(Path(sys.executable))
line = f'CreateObject("WScript.Shell").Run """{exe}"" -m iris app --background", 0, False\n'
vbs.write_text(line, encoding="utf-8")
for name in STARTUP_NAMES[1:]:
(startup_dir() / name).unlink(missing_ok=True)
return vbs


def startup_disable() -> None:
"""Remove every file `iris startup on` may have left in the Startup folder."""
d = startup_dir()
for name in STARTUP_NAMES:
(d / name).unlink(missing_ok=True)


def startup_main(argv: list[str]) -> int:
"""`iris startup on|off|status`: start the tray app at login, with no console window."""
what = argv[0] if argv else "status"
if what == "on":
vbs = startup_dir() / "Iris.vbs"
vbs.parent.mkdir(parents=True, exist_ok=True)
exe = startup_python(Path(sys.executable))
line = f'CreateObject("WScript.Shell").Run """{exe}"" -m iris app --background", 0, False\n'
vbs.write_text(line, encoding="utf-8")
for name in STARTUP_NAMES[1:]:
(startup_dir() / name).unlink(missing_ok=True)
vbs = startup_enable()
print(f"Iris starts in the tray at login ({vbs}). Let LM Studio start its server at login too.")
elif what == "off":
for name in STARTUP_NAMES:
(startup_dir() / name).unlink(missing_ok=True)
startup_disable()
print("Iris no longer starts at login.")
elif what == "status":
for name in STARTUP_NAMES:
path = startup_dir() / name
if path.exists():
print(f"on ({path})")
break
state = startup_state()
if state is not None:
print(f"on ({state})")
else:
print("off")
else:
Expand Down
46 changes: 44 additions & 2 deletions iris/dashboard/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,12 @@
/api/eval/history the trend over the last 10 saved runs in that same folder: success rate per run,
per-task pass counts with one entry per run, and the flaky tasks; cached 30 s
/api/queue the prompts waiting in the agent queue, oldest first (read only)
/api/startup whether Iris starts in the tray at login and where its Startup-folder file is;
an installer build answers with "managed": true on top, because it manages that entry itself

POST (the only writes): /api/models/load {model}, /api/models/unload {model | "all"}
and /api/iris/model {model}, which writes the model key of ~/.iris/settings.json.
POST (the only writes): /api/models/load {model}, /api/models/unload {model | "all"},
/api/iris/model {model}, which writes the model key of ~/.iris/settings.json, and
/api/startup {on}, which writes or removes Iris.vbs in the Startup folder.
Every POST must carry the X-Iris-Token header (a random token generated at server start
and injected into the served page) and an Origin or Referer of this very dashboard;
anything else is a 403. The model id must be one LM Studio reports right now, else 400.
Expand Down Expand Up @@ -224,6 +227,7 @@ def _lms_exe() -> str:
"/api/skills/approve", "/api/skills/remove",
"/api/settings", "/api/app/voice/restart",
"/api/setup/server", "/api/setup/mic", "/api/setup/speaker", "/api/setup/done", "/api/packs/install",
"/api/startup",
) # the only POST routes: model control, the prompt queue, Cline, skill review, settings and the app's voice loop
# set by `iris app`: "restart_voice" -> a callable; empty under `iris dashboard`
APP_HOOKS: dict[str, Callable[[], str]] = {}
Expand Down Expand Up @@ -847,6 +851,40 @@ def app_voice_restart() -> dict[str, Any]:
return {"ok": True, "message": hook()}


# --- start at login ---------------------------------------------------------------

def startup_payload() -> dict[str, Any]:
"""Whether Iris starts in the tray at login and where its Startup-folder file is; an installer build
manages that entry itself, so it answers with "managed": true on top."""
from iris import doctor
from iris.__main__ import startup_state # lazy: __main__ pulls in the agent and voice modules

path = startup_state()
payload: dict[str, Any] = {"on": path is not None, "path": path}
if doctor.bundled():
payload["managed"] = True
return payload


def startup_action(body: dict[str, Any]) -> dict[str, Any]:
"""Write or remove the Startup-folder entry; an installer build manages it itself (409)."""
from iris import doctor
from iris.__main__ import startup_disable, startup_enable # lazy, as in startup_payload

if not isinstance(body, dict):
raise ModelActionError(400, "the body must be a JSON object")
on = body.get("on")
if not isinstance(on, bool):
raise ModelActionError(400, "on must be true or false")
if doctor.bundled(): # the installer manages its own startup entry
raise ModelActionError(409, "the installer manages its own startup entry")
if on:
startup_enable()
else:
startup_disable()
return startup_payload()


# --- the server -----------------------------------------------------------------

class Handler(BaseHTTPRequestHandler):
Expand Down Expand Up @@ -887,6 +925,8 @@ def do_GET(self) -> None: # GET stays read-only; the write routes refuse it wit
from iris import settings

self._json(settings.payload())
elif path == "/api/startup":
self._json(startup_payload()) # readable via GET; writes go through the POST below
elif path in WRITE_ROUTES:
self._json({"error": "write routes only accept POST"}, code=405)
elif path == "/api/system":
Expand Down Expand Up @@ -986,6 +1026,8 @@ def do_POST(self) -> None: # the write routes and nothing else
payload = settings.save(body.get("values") or {})
elif path == "/api/app/voice/restart":
payload = app_voice_restart()
elif path == "/api/startup":
payload = startup_action(body)
elif path == "/api/packs/install":
from iris import packs

Expand Down
31 changes: 30 additions & 1 deletion iris/dashboard/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,11 @@ <h2>Set up Iris<span class="log-path" id="setup-version"></span></h2>
<h2>Settings<span class="log-path" id="settings-path"></span></h2>
<div class="set-intro">Saved to config.toml, which stays the place to edit by hand too. Voice settings apply
when listening starts again; everything else on the next request.</div>
<div class="set-row" id="startup-row">
<label for="startup-check">Start Iris in the tray at login</label>
<input type="checkbox" id="startup-check">
<div class="set-help" id="startup-note"></div>
</div>
<form id="settings-form" class="set-form"><div class="empty">loading...</div></form>
<div class="set-bar"><button type="submit" form="settings-form" class="mbtn" id="settings-save">Save</button>
<span id="settings-msg" class="set-msg"></span>
Expand Down Expand Up @@ -1514,6 +1519,30 @@ <h2>Settings<span class="log-path" id="settings-path"></span></h2>
form.replaceChildren(...groups.values());
}
async function loadSettings(){ renderSettings(await j("/api/settings")); }

// --- start at login: one switch above the form, saved straight away -------------
async function loadStartup(){
const d = await j("/api/startup");
const box = $("startup-check"), note = $("startup-note");
if (!d){ box.disabled = true; return; }
box.checked = !!d.on;
box.disabled = !!d.managed;
note.textContent = d.managed ? "The installer manages its own startup entry." : (d.path || "");
}
$("startup-check").onchange = async () => {
const box = $("startup-check"), msg = $("settings-msg");
const wanted = box.checked;
const r = await postModel("/api/startup", {on: wanted});
if (r && typeof r.on === "boolean"){
box.checked = r.on;
msg.className = "set-msg ok";
msg.textContent = r.on ? "Iris starts in the tray at login." : "Iris no longer starts at login.";
} else {
box.checked = !wanted; // put it back: the change did not go through
msg.className = "set-msg bad";
msg.textContent = (r && r.error) || "could not save the start-at-login switch";
}
};
function sameValue(a, b){ return JSON.stringify(a ?? null) === JSON.stringify(b ?? null); }
async function saveSettings(){
if (!settingsData) return;
Expand Down Expand Up @@ -1729,7 +1758,7 @@ <h2>Settings<span class="log-path" id="settings-path"></span></h2>
for (const p of PANES) $(p + "-pane").classList.toggle("hidden", p !== name);
if (name === "eval") loadEval(); // the eval tab fetches when shown, not on every poll
if (name === "skills") loadSkills();
if (name === "settings") loadSettings();
if (name === "settings"){ loadSettings(); loadStartup(); }
if (name === "setup") loadSetup();
clearInterval(logsTimer);
if (name === "logs"){ loadLogs(); logsTimer = setInterval(loadLogs, 3000); } // only polls while visible
Expand Down
7 changes: 3 additions & 4 deletions iris/doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,11 +140,10 @@ def checks(payload: dict[str, Any] | None = None) -> list[tuple[bool, str]]:
have = (desktop_dir() / SHORTCUT_NAME).exists()
out.append((have, f"shortcut: {SHORTCUT_NAME} on the desktop" if have else
"shortcut: none on the desktop; iris shortcut puts one there (optional)"))
from iris.__main__ import STARTUP_NAMES, startup_dir
from iris.__main__ import startup_state

d = startup_dir()
hit = next((f for f in STARTUP_NAMES if (d / f).exists()), None)
out.append((True, f"start at login: on ({d / hit})" if hit else
state = startup_state()
out.append((True, f"start at login: on ({state})" if state else
"start at login: off; iris startup on starts the tray app at login (optional)"))
out.append(_speed_line())
return out
Expand Down
48 changes: 48 additions & 0 deletions tests/test___main___behaviour.py
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,54 @@ def test_startup_off_removes_vbs_cmd_and_lnk(tmp_path, monkeypatch, capsys):
assert not (old / name).exists()


def test_startup_state_names_the_first_file_that_exists(tmp_path, monkeypatch):
from iris.__main__ import STARTUP_NAMES, startup_state

d = tmp_path / "Startup"
d.mkdir()
monkeypatch.setenv("IRIS_STARTUP_DIR", str(d))
assert startup_state() is None # empty folder: nothing starts at login
(d / "Iris.cmd").write_text("x", encoding="utf-8")
assert startup_state() == str(d / "Iris.cmd") # the old names count too
for name in STARTUP_NAMES:
(d / name).write_text("x", encoding="utf-8")
assert startup_state() == str(d / "Iris.vbs") # vbs is first in STARTUP_NAMES


def test_startup_enable_writes_vbs_and_removes_the_old_names(tmp_path, monkeypatch):
import sys

from iris.__main__ import startup_enable

d = tmp_path / "Startup"
d.mkdir()
(d / "Iris.cmd").write_text("old", encoding="utf-8")
(d / "Iris.lnk").write_bytes(b"old")
monkeypatch.setenv("IRIS_STARTUP_DIR", str(d))
exe = tmp_path / "python.exe"
exe.write_bytes(b"")
monkeypatch.setattr(sys, "executable", str(exe))
vbs = startup_enable()
assert vbs == d / "Iris.vbs"
expected = f'CreateObject("WScript.Shell").Run """{exe}"" -m iris app --background", 0, False\n'
assert (d / "Iris.vbs").read_text(encoding="utf-8") == expected
assert not (d / "Iris.cmd").exists() and not (d / "Iris.lnk").exists()


def test_startup_disable_removes_every_name(tmp_path, monkeypatch):
from iris.__main__ import startup_disable

d = tmp_path / "Startup"
d.mkdir()
for name in ("Iris.vbs", "Iris.cmd", "Iris.lnk"):
(d / name).write_text("x", encoding="utf-8")
monkeypatch.setenv("IRIS_STARTUP_DIR", str(d))
startup_disable()
for name in ("Iris.vbs", "Iris.cmd", "Iris.lnk"):
assert not (d / name).exists()
startup_disable() # already off is fine


def test_shortcut_writes_a_lnk_with_the_paths_in_the_environment(tmp_path, monkeypatch, capsys):
import subprocess

Expand Down
78 changes: 78 additions & 0 deletions tests/test_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -954,6 +954,84 @@ def test_iris_model_post_needs_the_token_and_origin(srv, tmp_path, monkeypatch):
assert code == 403


# --- start at login (the Startup folder) ------------------------------------------

def _clean_startup_env(monkeypatch, tmp_path):
"""Point the Startup folder at a temp dir so tests never touch the real one."""
monkeypatch.setenv("IRIS_STARTUP_DIR", str(tmp_path / "startup"))


def test_startup_get_reports_off_when_the_folder_is_empty(srv, tmp_path, monkeypatch):
base = f"http://{HOST}:{srv.server_address[1]}"
_clean_startup_env(monkeypatch, tmp_path)

status, _, raw = get(base + "/api/startup") # a read route: no token needed
assert status == 200 and json.loads(raw) == {"on": False, "path": None}


def test_startup_get_reports_on_with_the_vbs_path(srv, tmp_path, monkeypatch):
base = f"http://{HOST}:{srv.server_address[1]}"
_clean_startup_env(monkeypatch, tmp_path)
(tmp_path / "startup").mkdir()
(tmp_path / "startup" / "Iris.vbs").write_text("x", encoding="utf-8")

status, _, raw = get(base + "/api/startup")
body = json.loads(raw)
assert status == 200 and body["on"] is True
assert body["path"].endswith("Iris.vbs")


def test_startup_post_on_writes_the_vbs_into_the_startup_folder(srv, tmp_path, monkeypatch):
base = f"http://{HOST}:{srv.server_address[1]}"
_clean_startup_env(monkeypatch, tmp_path)

code, body = post(base + "/api/startup", {"on": True}, token=srv.token, origin=base)
assert code == 200 and body["on"] is True
vbs = tmp_path / "startup" / "Iris.vbs"
assert vbs.exists()
assert "-m iris app --background" in vbs.read_text(encoding="utf-8")


def test_startup_post_off_removes_the_vbs(srv, tmp_path, monkeypatch):
base = f"http://{HOST}:{srv.server_address[1]}"
_clean_startup_env(monkeypatch, tmp_path)
(tmp_path / "startup").mkdir()
(tmp_path / "startup" / "Iris.vbs").write_text("x", encoding="utf-8")

code, body = post(base + "/api/startup", {"on": False}, token=srv.token, origin=base)
assert code == 200 and body["on"] is False
assert not (tmp_path / "startup" / "Iris.vbs").exists()


@pytest.mark.parametrize("body", [{}, {"on": "yes"}, {"on": 1}])
def test_startup_post_bad_body_is_400(srv, tmp_path, monkeypatch, body):
base = f"http://{HOST}:{srv.server_address[1]}"
_clean_startup_env(monkeypatch, tmp_path)

code, _ = post(base + "/api/startup", body, token=srv.token, origin=base)
assert code == 400


def test_startup_action_refuses_a_body_that_is_not_an_object():
# the HTTP handler refuses non-object JSON before it gets here; the function checks on its own anyway
with pytest.raises(d.ModelActionError) as err:
d.startup_action([True]) # type: ignore[arg-type] # the wrong type is the point
assert err.value.code == 400


def test_startup_is_managed_under_the_installer_build(srv, tmp_path, monkeypatch):
base = f"http://{HOST}:{srv.server_address[1]}"
_clean_startup_env(monkeypatch, tmp_path)
from iris import doctor

monkeypatch.setattr(doctor, "bundled", lambda: True) # the same module object the dashboard holds

status, _, raw = get(base + "/api/startup")
assert status == 200 and json.loads(raw)["managed"] is True
code, body = post(base + "/api/startup", {"on": True}, token=srv.token, origin=base)
assert code == 409 and "installer" in body["error"]


def test_resolve_model_re_resolves_on_every_call(tmp_path, monkeypatch):
"""The choice is read on every request: a file edit applies without a restart."""
from iris.llm import resolve_model
Expand Down