diff --git a/docs/TERMINAL_LAUNCH.md b/docs/TERMINAL_LAUNCH.md index fc16b3f1..ecec84ef 100644 --- a/docs/TERMINAL_LAUNCH.md +++ b/docs/TERMINAL_LAUNCH.md @@ -66,12 +66,15 @@ strata launch --model q2_0 --pool-cores 2-14:2 --no-tui # experime strata launch --plan --model q2_0 # what would happen; nothing changes strata launch --model q2_0 --yes --no-tui # no questions (for one: download on a computer with no engine yet) strata launch --model q2_0 --open # also open the server's page in your browser once it serves +strata launch --model q2_0 --context 64k --restart --no-tui # a model is already serving other choices (or holds the port): stop it and start these strata launch --list-presets | --delete-preset NAME | --status | --stop [--preset NAME] | --show-key ``` `strata launch --help` lists everything with examples. An unknown model or flag gets a plain message with the closest match. Presets are small files in `launch-presets/` beside the profiles folder; the run uses the shared profile `launch-` and the shared tuning presets (`strata presets`), so the app sees them too. Flags next to `--preset` change that start only -(add `--save-preset` to keep them). `--plan` shows the model (also for your own files, which it recognises), the context, the picture setting and what would be downloaded and how big (0 when everything is already here). A model that was tuned before for the same choices on the same computer is not measured again by `--tune quick`; the stored result is used and the run says so. Add `--retune` to measure again. +(add `--save-preset` to keep them). `--plan` shows the model (also for your own files, which it recognises), the context, the picture setting and what would be downloaded and how big (0 when everything is already here). A model that was tuned before for the same choices on the same computer is not measured again by `--tune quick`; the stored result is used and the run says so. Add `--retune` to measure again (the model of the same launch is stopped for the measuring and starts again with the result). + +**A launch while a model is already serving.** The same choices: nothing restarts, the running addresses are printed. Different choices (another context, pictures, access, or another model on the same port): the screens ask once, "Restart the model with these settings? Answers in progress stop.", with Restart and Cancel; `--no-tui` refuses with one line naming the running model, its port and settings, and says to add `--restart` or run `strata launch --stop` first. `--yes` alone never restarts. With `--restart` the old server is stopped first and the new one starts on the same port. A different port given with `--port` runs beside the first one; two big models may not fit in the graphics memory together, and the launch says so. ## Connect your apps: `strata connect` diff --git a/strata_cli/launch/app.py b/strata_cli/launch/app.py index 29d57560..1e8f7bcf 100644 --- a/strata_cli/launch/app.py +++ b/strata_cli/launch/app.py @@ -44,6 +44,7 @@ class Ctx: feed: str | None = None move_data: bool = False retune: bool = False + restart: bool = False notes: list[str] = field(default_factory=list) start_own_files: bool = False picked_in_list: bool = False @@ -264,7 +265,8 @@ class LaunchApp(App): s = self.ctx.settings self.cancel = threading.Event() self.runner = Runner(s, catalog=self.ctx.catalog, emit=self._emit, cancel=self.cancel, feed=self.ctx.feed, confirm=self._ask_from_run, - move_data=self.ctx.move_data, retune=self.ctx.retune) + move_data=self.ctx.move_data, retune=self.ctx.retune, restart=self.ctx.restart, + confirm_restart=self._ask_restart) gb = getattr(self.runner, "download_gb", lambda: 0.0)() if not confirmed else 0.0 if gb >= 1.0: free = self.ctx.catalog.disk_free(s.data_dir or self.ctx.catalog.data_dir()) @@ -288,9 +290,13 @@ class LaunchApp(App): self.running = True threading.Thread(target=self._work, daemon=True).start() - def _ask_from_run(self, title: str, text: str) -> bool: + def _ask_restart(self, title: str, text: str) -> bool: + """Another model is serving other choices: ask once, in the same pop-up, whether to restart it. Cancel leaves it running.""" + return self._ask_from_run(title, text, [("go", "Restart"), ("no", "Cancel")], default=False) + + def _ask_from_run(self, title: str, text: str, options: list[tuple[str, str]] | None = None, default: bool = True) -> bool: """A question from the run (a worker thread): show it on the screen and wait for the answer. Enter means yes.""" - box: dict[str, bool] = {"go": True} + box: dict[str, bool] = {"go": default} answered = threading.Event() def done(choice: str | None) -> None: @@ -298,7 +304,7 @@ class LaunchApp(App): answered.set() def show() -> None: - self.push_screen(ConfirmScreen(title, text, [("go", "Download anyway"), ("no", "Not now")]), done) + self.push_screen(ConfirmScreen(title, text, options or [("go", "Download anyway"), ("no", "Not now")]), done) try: self.call_from_thread(show) @@ -405,7 +411,8 @@ 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, open_page: bool = False, move_data: bool = False, retune: bool = False) -> int: + save: bool = False, open_page: bool = False, move_data: bool = False, retune: bool = False, + restart: 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) @@ -420,7 +427,7 @@ def run_tui(settings: S.LaunchSettings | None, *, catalog: Catalog | None = None s.name = f"{s.model or 'model'} {S.context_label(s.context)}" if save: store.save(s, s.name) - ctx = Ctx(catalog=catalog, computer=computer, rows=rows, settings=s, glyphs=Glyphs(), feed=feed, move_data=move_data, retune=retune) + ctx = Ctx(catalog=catalog, computer=computer, rows=rows, settings=s, glyphs=Glyphs(), feed=feed, move_data=move_data, retune=retune, restart=restart) app = LaunchApp(ctx, auto_run=auto_run) result = app.run() if getattr(app, "return_code", 0) not in (0, None) or getattr(app, "_exception", None) is not None: diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index e46fa2f0..92237f6d 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -127,6 +127,9 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser] o.add_argument("--retune", action="store_true", help="with --tune (quick is used when --tune is not given): measure again even when this model was already tuned on this computer " "(by default a stored tuning result is reused and no measuring is done)") + o.add_argument("--restart", action="store_true", + help="when a model is already serving other choices (or holds the port), stop it and start these. Without it the screens ask once " + "and --no-tui refuses; --yes alone never restarts. The same choices are never restarted: the running address is printed") 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)") @@ -648,13 +651,13 @@ 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, open_page=bool(a.open)) + return _tui(app.run_tui, None, catalog=catalog, feed=a.feed, open_page=bool(a.open), restart=bool(getattr(a, "restart", False))) if catalog is None: return fail("This Terminal does not carry the model list. Install it again with the one-line installer.", 5) if getattr(a, "retune", False) and s.tune == "skip": s.tune = "quick" runner = Runner(s, catalog=catalog, emit=_printer(machine), feed=a.feed, assume_yes=bool(a.yes or machine), confirm=_ask_yes, - retune=bool(getattr(a, "retune", False))) + retune=bool(getattr(a, "retune", False)), restart=bool(getattr(a, "restart", False))) try: runner.check_own_files() # the person's own files: a wrong path is said now, and the files name the model except LaunchError as e: @@ -720,7 +723,7 @@ def run_launch(a: argparse.Namespace) -> int: 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), open_page=bool(a.open), - move_data=move_data, retune=bool(getattr(a, "retune", False))) + move_data=move_data, retune=bool(getattr(a, "retune", False)), restart=bool(getattr(a, "restart", False))) try: result = runner.run() except LaunchError as e: @@ -739,12 +742,12 @@ def run_launch(a: argparse.Namespace) -> int: _say(result.final_text) return 0 if machine: - print(json.dumps({"schema_version": 1, "ok": True, "name": s.name, "profile": result.profile, "urls": result.urls, + print(json.dumps({"schema_version": 1, "ok": True, "name": s.name, "profile": result.profile, "urls": result.urls, "reused": result.reused, "api_key": "set" if result.key else None, "tuned": result.tune_word, "notices": result.notices + [n.line() for n in notes]})) return 0 _say("") - _say("Strata is serving.") + _say("Already serving these choices; nothing was restarted." if result.reused else "Strata is serving.") for u in result.urls: label = ("This computer" if "127.0.0.1" in u else "Cloudflare" if "trycloudflare" in u else "Tailscale" if ("ts.net" in u or u.split("//")[1].startswith("100.")) else "Network") diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 9092f75b..e5ef15f7 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -131,6 +131,7 @@ class Result: serving: bool = True # False: the model is ready but nothing was started (no engine yet) engine_problem: str | None = None # the plain reason there is no engine, when serving is False final_text: str = "" # what to tell the person when serving is False + reused: bool = False # the same choices were already serving: nothing was stopped or started NO_ENGINE_NEXT = ("Update Strata (`strata update`) and run `strata launch` again. Nothing was downloaded, and any model files you already have are kept.") @@ -433,8 +434,11 @@ class Runner: cancel: threading.Event | None = None, feed: str | None = None, python: str | None = None, components_dir: str | None = None, hardware: dict | None = None, confirm: Callable[[str, str], bool] | None = None, assume_yes: bool = False, move_data: bool = False, - retune: bool = False): + retune: bool = False, restart: bool = False, confirm_restart: Callable[[str, str], bool] | None = None): self.s = s + self.restart = restart # --restart: a server that serves other choices (or holds this port) is stopped and replaced without asking + self.confirm_restart = confirm_restart # the screens: asked (question, detail) once; True = restart. None (no screens) and no --restart: refuse in one line + self._stop_first: list[str] = [] # other launch profiles that hold this port; stopped before the measuring and the start self.retune = retune # --retune: measure again even when a tuning result for this model on this computer is stored self.move_data = move_data # --move-data / the answer "move": the model files already here go to the new --data-dir self.confirm = confirm # asked (title, text) before a model is downloaded with no engine; True = go on @@ -1190,6 +1194,7 @@ class Runner: the result (E07). Other engines are never touched here; the tuner says plainly when another program holds the card.""" from strata_control import runtime from strata_control.profiles import ProfileError + self.stop_others() try: serving = runtime.status(self.profile).get("state") in ("ready", "starting") except Exception: # noqa: BLE001 - no state to read: nothing of ours is running @@ -1221,11 +1226,116 @@ class Runner: tune_word: str | None = None + # ---- 0. a server is already running + CHOICE_SKIP = ("schema", "name", "tuned_preset", "tuned_at", "last_used", "created", "api_key") + + def choices(self) -> dict: + """The choices that make one server different from another (not the bookkeeping, and the key only as a fingerprint).""" + import hashlib + d = {k: v for k, v in self.s.to_dict(with_key=False).items() if k not in self.CHOICE_SKIP} + d["key"] = hashlib.sha256(("none" if self.s.no_key and not self.s.api_key else self.s.api_key or "").encode("utf-8")).hexdigest()[:16] + return json.loads(json.dumps(d, sort_keys=True)) + + def _choices_file(self, profile: str | None = None) -> Path: + return launch_dir() / f"{(profile or self.profile)[7:]}.choices.json" + + def save_choices(self) -> None: + try: + write_private(self._choices_file(), self.choices()) + except OSError: + pass + + def _saved_choices(self, profile: str) -> dict | None: + try: + return json.loads(self._choices_file(profile).read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + + def serving_launches(self) -> list[dict]: + """Launch servers that are up now (this one included): [{profile, name, port, choices}].""" + from strata_control import profiles, runtime + out = [] + try: + listing = profiles.list_profiles() + except Exception: # noqa: BLE001 + return out + for row in listing: + pid = row["id"] + if not pid.startswith("launch-"): + continue + try: + if runtime.status(pid).get("state") not in ("ready", "starting"): + continue + prof, _rev = profiles.load(pid) + except Exception: # noqa: BLE001 + continue + port = int((prof.get("overrides") or {}).get("port", S.DEFAULT_PORT)) + out.append({"profile": pid, "name": pid[7:], "port": port, "choices": self._saved_choices(pid)}) + return out + + @staticmethod + def describe_running(row: dict) -> str: + c = row.get("choices") or {} + bits = [] + if c.get("context"): + bits.append(f"context {S.context_label(c['context'])}") + if c.get("vision"): + bits.append(f"pictures {c['vision']}") + if c.get("access"): + bits.append(f"access {S.ACCESS_WORDS.get(c['access'], c['access'])}") + return f"{row['name']} is serving on port {row['port']}" + (f" ({', '.join(bits)})" if bits else "") + + def check_serving(self) -> "Result | None": + """G04/E01. The same choices already serving: return that server (nothing stops or starts). Other choices on this profile, or another + launch on this port: ask once on the screens, go on with --restart, else refuse in one line and change nothing. A launch on another port + runs beside the others (the person asked for two), with a warning about graphics memory.""" + running = self.serving_launches() + if not running: + return None + own = next((r for r in running if r["profile"] == self.profile), None) + same_port = [r for r in running if r["profile"] != self.profile and r["port"] == int(self.s.port)] + beside = [r for r in running if r["profile"] != self.profile and r["port"] != int(self.s.port)] + if own and not self.retune and not same_port and own["choices"] == self.choices() and own["port"] == int(self.s.port): + self.config_path = launch_dir() / f"{self.name}.json" + urls = acc.urls_for(self.s, tunnel_url=(acc.tunnel_info(self.profile) or {}).get("url")) + self.emit("done", "Already serving these choices; nothing was restarted.", 100, urls=urls) + return Result(self.profile, urls, self.s.api_key, None, self.notices, str(self.config_path), reused=True) + for r in beside: + self.notices.append(f"{r['name']} is already loaded on port {r['port']}. Two models at once may not fit in the graphics memory; " + "the new one can fail to start. Stop the first with `strata launch --stop` if it does.") + blocking = ([own] if own and not self.retune else []) + same_port + if not blocking: + return None + what = "; ".join(self.describe_running(r) for r in blocking) + if not self.restart: + if self.confirm_restart is not None: + if not self.confirm_restart("Restart the model with these settings?", "Answers in progress stop."): + raise LaunchError("Left as it is: the running model keeps serving.", "", 130) + else: + raise LaunchError(f"A model is already running: {what}. These choices are different.", + "Add --restart to stop it and start these, or run `strata launch --stop` first.", 6) + self._stop_first = [r["profile"] for r in same_port] + return None + + def stop_others(self) -> None: + """Stop the other launch servers that hold this port, so the new one gets it (no "port already in use").""" + from strata_control import runtime + from strata_control.profiles import ProfileError + for pid in self._stop_first: + self.emit("start", f"Stopping {pid[7:]} so the new choices can use port {int(self.s.port)}…", None) + try: + runtime.stop(pid, timeout=120) + acc.stop_tunnel(pid) + except ProfileError as e: + raise LaunchError(f"The running server {pid[7:]} could not be stopped: {e}.", "Run `strata launch --stop` first.", 6) from None + self._stop_first = [] + # ---- 5. start def start(self) -> None: from strata_control import runtime from strata_control.profiles import ProfileError name = self.profile + self.stop_others() st = runtime.status(name) if st.get("state") in ("ready", "starting"): self.emit("start", "A server for this preset is already running; restarting it with these choices…") @@ -1456,6 +1566,10 @@ class Runner: self.restart_after = start try: self.check_own_files() # a wrong --model-path is said before the engine is downloaded + if start: + reused = self.check_serving() # before anything is downloaded or stopped + if reused is not None: + return reused self.ensure_engine() self.check_cancel() base = self.ensure_model() @@ -1476,6 +1590,7 @@ class Runner: if not start: return Result(self.profile, [], self.s.api_key, self.tune_word, self.notices, str(cfg)) self.start() + self.save_choices() tunnel = self.open_access() urls = acc.urls_for(self.s, tunnel_url=tunnel) res = Result(self.profile, urls, self.s.api_key, self.tune_word, self.notices, str(cfg), tunnel) diff --git a/tests/terminal/test_tui_stress_launch.py b/tests/terminal/test_tui_stress_launch.py new file mode 100644 index 00000000..7514ae7f --- /dev/null +++ b/tests/terminal/test_tui_stress_launch.py @@ -0,0 +1,152 @@ +"""G04/E01 from the TUI stress test: a second launch while a model serves (same choices, other choices, no screens, --restart, +another context on the same port).""" + +import os +import unittest +from unittest import mock + +from strata_cli.launch import settings as S +from strata_cli.launch.catalog import Catalog +from strata_cli.launch.runner import LaunchError, Runner +from tests.terminal.launch_support import HW_12, Home, catalog, run_cli + + +class SecondLaunchTests(unittest.TestCase): + def setUp(self): + self.home = Home().__enter__() + self.addCleanup(self.home.__exit__, None, None, None) + p = mock.patch.object(Catalog, "hardware", lambda self, fresh=False: dict(HW_12, disk_free_gb=500.0)) + p.start() + self.addCleanup(p.stop) + + def runner(self, **kw): + s = S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768, name="gyro") + r = Runner(s, catalog=catalog(), **kw) + r.said = [] + r.emit_cb = lambda e: r.said.append(e.text) + return r + + @staticmethod + def row(r, port=8080, name=None, choices=None): + return [{"profile": "launch-" + (name or r.name), "name": name or r.name, "port": port, + "choices": r.choices() if choices is None else choices}] + + def test_same_choices_reuse_the_running_server(self): + r = self.runner() + rows = self.row(r) + with mock.patch.object(Runner, "serving_launches", lambda self: rows), \ + mock.patch.object(Runner, "ensure_engine", side_effect=AssertionError("must not run")), \ + mock.patch("strata_control.runtime.stop", side_effect=AssertionError("must not stop")): + res = r.run() + self.assertTrue(res.reused) + self.assertTrue(res.urls) + self.assertTrue(any("nothing was restarted" in x for x in r.said)) + + def test_other_choices_without_screens_refuse_in_one_line(self): + r = self.runner() + rows = self.row(r, choices={**r.choices(), "vision": "cpu", "context": 65536}) + with mock.patch.object(Runner, "serving_launches", lambda self: rows): + with self.assertRaises(LaunchError) as cm: + r.run() + self.assertEqual(cm.exception.code, 6) + self.assertIn("port 8080", cm.exception.text) + self.assertIn("context 64K", cm.exception.text) + self.assertIn("--restart", cm.exception.next) + self.assertIn("strata launch --stop", cm.exception.next) + + def test_yes_alone_does_not_restart(self): + r = self.runner(assume_yes=True) + rows = self.row(r, choices={**r.choices(), "context": 65536}) + with mock.patch.object(Runner, "serving_launches", lambda self: rows): + with self.assertRaises(LaunchError): + r.run() + + def test_screens_ask_once_and_cancel_leaves_it_running(self): + asked = [] + r = self.runner(confirm_restart=lambda q, d: asked.append((q, d)) or False) + rows = self.row(r, choices={**r.choices(), "context": 65536}) + with mock.patch.object(Runner, "serving_launches", lambda self: rows), \ + mock.patch("strata_control.runtime.stop") as stop: + with self.assertRaises(LaunchError) as cm: + r.run() + self.assertEqual(asked, [("Restart the model with these settings?", "Answers in progress stop.")]) + self.assertEqual(cm.exception.code, 130) + stop.assert_not_called() + + def test_screens_restart_goes_on(self): + r = self.runner(confirm_restart=lambda q, d: True) + rows = self.row(r, choices={**r.choices(), "context": 65536}) + with mock.patch.object(Runner, "serving_launches", lambda self: rows), \ + mock.patch.object(Runner, "ensure_engine", side_effect=RuntimeError("went on")): + with self.assertRaises(RuntimeError): + r.run() + + def test_restart_flag_goes_on_without_asking(self): + r = self.runner(restart=True) + rows = self.row(r, choices={**r.choices(), "context": 65536}) + with mock.patch.object(Runner, "serving_launches", lambda self: rows), \ + mock.patch.object(Runner, "ensure_engine", side_effect=RuntimeError("went on")): + with self.assertRaises(RuntimeError): + r.run() + + def test_a_changed_context_on_the_same_port_stops_the_old_profile_first(self): + r = self.runner(restart=True) + rows = self.row(r, name="gyro-s-32k", choices={"context": 32768}) # another profile name, same port 8080 + order = [] + with mock.patch.object(Runner, "serving_launches", lambda self: rows): + self.assertIsNone(r.check_serving()) + self.assertEqual(r._stop_first, ["launch-gyro-s-32k"]) + with mock.patch("strata_control.runtime.stop", side_effect=lambda n, timeout=0: order.append(n)), \ + mock.patch("strata_cli.launch.access.stop_tunnel"): + r.stop_others() + self.assertEqual(order, ["launch-gyro-s-32k"]) + self.assertEqual(r._stop_first, []) + + def test_a_changed_context_without_restart_names_the_running_one(self): + r = self.runner() + rows = self.row(r, name="gyro-s-32k", choices={"context": 32768}) + with mock.patch.object(Runner, "serving_launches", lambda self: rows): + with self.assertRaises(LaunchError) as cm: + r.check_serving() + self.assertIn("gyro-s-32k", cm.exception.text) + + def test_a_different_port_runs_beside_with_a_memory_warning(self): + r = self.runner() + r.s.port = 8081 + rows = self.row(r, name="other", port=8080, choices={}) + with mock.patch.object(Runner, "serving_launches", lambda self: rows): + self.assertIsNone(r.check_serving()) + self.assertEqual(r._stop_first, []) + self.assertTrue(any("graphics memory" in n for n in r.notices)) + + def test_command_line_refuses_restarts_and_yes_alone_does_not(self): + rows = [{"profile": "launch-q2-0-32k", "name": "q2-0-32k", "port": 8080, "choices": {"context": 1}}] + with mock.patch.object(Runner, "serving_launches", lambda self: rows): + code, out, err = run_cli(["launch", "--no-tui", "--model", "q2_0", "--context", "32k"]) + self.assertEqual(code, 6, err) + self.assertIn("--restart", err) + self.assertIn("q2-0-32k", err) + code, out, err = run_cli(["launch", "--no-tui", "--yes", "--model", "q2_0", "--context", "32k"]) + self.assertEqual(code, 6) + seen = {} + + def go(self, *a, **k): + seen["restart"] = self.restart + from strata_cli.launch.runner import Result + return Result("launch-x", ["http://127.0.0.1:8080"], None, None, [], "/x") + + with mock.patch.object(Runner, "run", go): + code, out, err = run_cli(["launch", "--no-tui", "--yes", "--restart", "--model", "q2_0", "--context", "32k"]) + self.assertEqual(code, 0, err) + self.assertTrue(seen["restart"]) + + def test_restart_is_in_help_and_docs(self): + code, out, _ = run_cli(["launch", "--help"]) + self.assertIn("--restart", out) + root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + with open(os.path.join(root, "docs", "TERMINAL_LAUNCH.md"), encoding="utf-8") as f: + self.assertIn("--restart", f.read()) + + +if __name__ == "__main__": + unittest.main()