From 4440a303f8e89b7eb79ea2547be8459c0df60ec0 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 22:46:10 +0200 Subject: [PATCH] Terminal: no browser opens by itself (launch config forbids it, --open is the only way), and the start message promises a browser only with --open --- serve/server.py | 8 ++- strata_cli/launch/app.py | 8 ++- strata_cli/launch/cmd.py | 16 ++++- strata_cli/launch/runner.py | 3 + strata_cli/launch/screens.py | 11 +++- tests/terminal/test_tuiqa_browser.py | 88 ++++++++++++++++++++++++++++ 6 files changed, 128 insertions(+), 6 deletions(-) create mode 100644 tests/terminal/test_tuiqa_browser.py diff --git a/serve/server.py b/serve/server.py index ca222a04..695c7538 100644 --- a/serve/server.py +++ b/serve/server.py @@ -652,6 +652,9 @@ def experts_loading_words(args: list, size: str) -> str: return f"loading the experts into RAM ({size}) and locking part of them for the GPU." +OPENS_BROWSER = False # set in main() when the server was started with --open: only then may a message say a browser opens + + def narrate_start(log_path: str, offset: int, args: list, done: threading.Event, heartbeat=20.0) -> None: """While the engine starts, say in the server window what it is doing, from its log: the start reads tens of GB into RAM and locks part of it for the GPU, and on many PCs everything is slow or frozen for a minute or more - @@ -690,7 +693,8 @@ def narrate_start(log_path: str, offset: int, args: list, done: threading.Event, if "PLE on" in line or "expert arena:" in line or "experts via mmap" in line: # #505: mapped say("arena", f"[strata] {loading}\n" " YOUR PC CAN BE SLOW OR STOP RESPONDING FOR 1-3 MINUTES NOW - this is normal.\n" - " Please wait and don't close this window; the browser opens when it is ready.") + " Please wait and don't close this window" + + ("; the browser opens when it is ready." if OPENS_BROWSER else "; the server says when it is ready.")) elif " loaded " in line and "GiB at" in line: say("loaded", "[strata] experts loaded: " + line.split(" loaded ", 1)[1].strip() + f" ({time.time() - t0:.0f} s so far)") @@ -7565,6 +7569,8 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in "[{\"gpus\": [0, 1]}, {\"gpus\": [2, 3]}])") launch_args = list(sys.argv[1:] if argv is None else argv) a = ap.parse_args(launch_args) + global OPENS_BROWSER + OPENS_BROWSER = bool(a.open) # Every ordinary way of being asked to stop takes Ctrl+C's path (QUIT to the engine, then exit): SIGTERM (#96 docker # stop; systemd), SIGHUP (the terminal closed, ssh dropped), and on Windows Ctrl+Break and the console's close, # logoff and shutdown events. They are installed before anything slow starts, so one that arrives while the model diff --git a/strata_cli/launch/app.py b/strata_cli/launch/app.py index 1433e578..72f26908 100644 --- a/strata_cli/launch/app.py +++ b/strata_cli/launch/app.py @@ -402,7 +402,7 @@ def run_monitor(info: dict, *, keep_default: bool = True, color: str = "auto") - def run_tui(settings: S.LaunchSettings | None, *, catalog: Catalog | None = None, feed: str | None = None, auto_run: bool = False, - save: bool = False) -> int: + save: bool = False, open_page: bool = False) -> int: """Open the launch screens. `settings` given and `auto_run`: skip the questions and go straight to the run.""" catalog = catalog or Catalog() print("Looking at this computer…", flush=True) @@ -433,4 +433,8 @@ def run_tui(settings: S.LaunchSettings | None, *, catalog: Catalog | None = None if not result.serving: print(result.final_text) return 0 - return run_monitor(_info_for(result, ctx.settings)) + info = _info_for(result, ctx.settings) + if open_page: # only with an explicit --open: nothing else opens a browser + from strata_cli.launch.cmd import open_page as open_in_browser + open_in_browser(info["url"]) + return run_monitor(info) diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 08fb3f5c..940914a9 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -103,6 +103,7 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser] o = p.add_argument_group("running") o.add_argument("--save-preset", metavar="NAME", help="save these choices under this name") o.add_argument("--no-tui", action="store_true", help="no screens: serve, print the address and return") + o.add_argument("--open", action="store_true", help="open the server's web page in your browser once it is serving (nothing opens a browser without this)") o.add_argument("--yes", action="store_true", help="do not ask questions (for one: whether to download the model on a computer with no engine yet)") o.add_argument("--plan", action="store_true", help="show what would happen and exit; nothing is changed") o.add_argument("--feed", metavar="URL|DIR", help="where the signed update feed (engine downloads) is; default: STRATA_UPDATE_FEED or the project's") @@ -355,6 +356,15 @@ def _ask_yes(title: str, text: str) -> bool: return answer in ("", "y", "yes") +def open_page(url: str) -> bool: + """Open the server's page in the browser. Only ever called for an explicit --open (or the monitor's b key).""" + try: + import webbrowser + return bool(webbrowser.open(url)) + except Exception: # noqa: BLE001 - no browser here: the address is printed anyway + return False + + def _tui(run, *args, **kw) -> int: """Open the screens. An error of the screens themselves ends with a plain sentence and a non-zero exit code, never a traceback and exit 0 (tester report T02).""" @@ -496,7 +506,7 @@ def run_launch(a: argparse.Namespace) -> int: if catalog is None: return fail("This Terminal does not carry the model list, so the screens cannot open. Install it again with the one-line installer.", 5) from strata_cli.launch import app - return _tui(app.run_tui, None, catalog=catalog, feed=a.feed) + return _tui(app.run_tui, None, catalog=catalog, feed=a.feed, open_page=bool(a.open)) if catalog is None: return fail("This Terminal does not carry the model list. Install it again with the one-line installer.", 5) s, notes = apply_defaults(s, catalog) @@ -534,7 +544,7 @@ def run_launch(a: argparse.Namespace) -> int: _say(f"[!] {fw}") if interactive and have_choices: from strata_cli.launch import app - return _tui(app.run_tui, s, catalog=catalog, feed=a.feed, auto_run=True, save=bool(a.save_preset)) + return _tui(app.run_tui, s, catalog=catalog, feed=a.feed, auto_run=True, save=bool(a.save_preset), open_page=bool(a.open)) try: result = runner.run() except LaunchError as e: @@ -571,6 +581,8 @@ def run_launch(a: argparse.Namespace) -> int: for n in result.notices: _say(f"[!] {n}") local = next((u for u in result.urls if "127.0.0.1" in u), result.urls[0] if result.urls else "") + if a.open and local: + open_page(local) if result.key and os.name == "nt": _say(f" Watch it: $env:STRATA_API_KEY = strata launch --show-key; strata monitor --url {local} --credential-env STRATA_API_KEY") elif result.key: diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index eabf314a..3081be1f 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -192,6 +192,9 @@ def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str] else: cfg.pop("api_key", None) cfg.setdefault("exe", "component:strata-engine") + cfg["open_browser"] = False # strata launch never opens a browser by itself (only `--open` does, after the start) + if isinstance(cfg.get("args"), list): + cfg["args"] = [a for a in cfg["args"] if a != "--open"] if log: cfg["log"] = log apply_cards(cfg, gpus) diff --git a/strata_cli/launch/screens.py b/strata_cli/launch/screens.py index 20e87b9c..96dbf475 100644 --- a/strata_cli/launch/screens.py +++ b/strata_cli/launch/screens.py @@ -1286,7 +1286,16 @@ class SaveScreen(Base): self.query_one("#summary", Static).update(t) def explain(self) -> Text: - return Text("Press Enter on the first choice to save and start. The first start may download the model and tune; the monitor opens when it is serving.", style=MUTE) + st = self.ctx.model_state() + if st.remaining_gb < 0.05: + fetch = "Nothing needs to be downloaded." + elif st.only_helpers: + fetch = "The model is already downloaded; Strata fetches " + st._names() + "." # noqa: SLF001 + else: + fetch = f"Strata downloads about {st.remaining_gb:.0f} GB first." + tune = " It tunes first." if self.ctx.settings.tune != "skip" else "" + return Text(f"Press Enter on the first choice to save and start. {fetch}{tune} The Strata monitor opens in this window when it is serving; " + "no web page opens by itself.", style=MUTE) def action_rename(self) -> None: self.query_one("#name", Input).focus() diff --git a/tests/terminal/test_tuiqa_browser.py b/tests/terminal/test_tuiqa_browser.py new file mode 100644 index 00000000..46bf765b --- /dev/null +++ b/tests/terminal/test_tuiqa_browser.py @@ -0,0 +1,88 @@ +"""Owner rule 2026-10-18: the Terminal never opens a browser by itself; only an explicit --open does (the monitor's b key is also a request). The generic +start message promises a browser only when one will open.""" + +from __future__ import annotations + +import contextlib +import io +import tempfile +import threading +import time +import unittest +from pathlib import Path +from unittest import mock + +from strata_cli.launch import cmd, settings as S +from strata_cli.launch.runner import Result, Runner, derive_config +from strata_control import tune_knobs +from tests.terminal.launch_support import Home, run_cli + + +def served() -> Result: + return Result("launch-x", ["http://127.0.0.1:8081"], None, None, [], "/x") + + +class NoBrowserByItself(unittest.TestCase): + def setUp(self): + self.home = Home().__enter__() + self.addCleanup(self.home.__exit__, None, None, None) + + def test_the_launch_config_forbids_a_browser_and_drops_open_from_the_args(self): + base = {"exe": "e", "args": ["--native", "x.gguf", "--open", "--max-context", "32768"], "open_browser": True} + cfg = derive_config(base, S.LaunchSettings(), bool_flags=tune_knobs.BOOL_FLAGS) + self.assertIs(cfg["open_browser"], False) + self.assertNotIn("--open", cfg["args"]) + self.assertEqual(cfg["args"][:2], ["--native", "x.gguf"]) + + def test_a_plain_launch_opens_no_browser(self): + with mock.patch.object(Runner, "run", return_value=served()), mock.patch("webbrowser.open") as opened: + code, out, err = run_cli(["launch", "--no-tui", "--model", "q2_0"]) + self.assertEqual(code, 0, err) + opened.assert_not_called() + + def test_open_opens_the_local_page_once(self): + with mock.patch.object(Runner, "run", return_value=served()), mock.patch("webbrowser.open", return_value=True) as opened: + code, out, err = run_cli(["launch", "--no-tui", "--model", "q2_0", "--open"]) + self.assertEqual(code, 0, err) + opened.assert_called_once_with("http://127.0.0.1:8081") + + def test_the_screens_open_a_browser_only_for_open(self): + from strata_cli.launch import app as launch_app + from tests.terminal.launch_support import HW_12, catalog + for flag, calls in ((False, 0), (True, 1)): + with mock.patch.object(launch_app.LaunchApp, "run", lambda self, **kw: served()), \ + mock.patch.object(launch_app, "run_monitor", lambda info, **kw: 0), mock.patch("webbrowser.open", return_value=True) as opened: + with contextlib.redirect_stdout(io.StringIO()): + launch_app.run_tui(S.LaunchSettings(family="qwen", model="Q2_0", context=32768, vision="off"), catalog=catalog(HW_12), + auto_run=True, open_page=flag) + self.assertEqual(opened.call_count, calls, flag) + + def test_open_is_in_the_help(self): + code, out, err = run_cli(["launch", "--help"]) + self.assertIn("--open", out) + self.assertIn("nothing opens a browser without this", out.replace("\n", " ").replace(" ", " ")) + + +class StartMessage(unittest.TestCase): + def narrate(self, opens: bool) -> str: + from serve import server + d = tempfile.mkdtemp() + log = Path(d) / "engine.log" + log.write_text("strata generate: expert arena: resident, 31.64 GiB\n", encoding="utf-8") + done, out = threading.Event(), io.StringIO() + with mock.patch.object(server, "OPENS_BROWSER", opens), contextlib.redirect_stdout(out): + t = threading.Thread(target=server.narrate_start, args=(str(log), 0, [], done)) + t.start() + time.sleep(0.8) + done.set() + t.join(5) + return out.getvalue() + + def test_the_browser_is_promised_only_with_open(self): + self.assertNotIn("browser", self.narrate(False)) + self.assertIn("the server says when it is ready", self.narrate(False)) + self.assertIn("the browser opens when it is ready", self.narrate(True)) + + +if __name__ == "__main__": + unittest.main()