Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Terminal hands over to the Control that strata update installed

Niko1221f39d9519045f
diff --git a/strata.py b/strata.py
index defae0b04..52b9c72af 100644
--- a/strata.py
+++ b/strata.py
@@ -28,6 +28,11 @@ def _preflight(argv):
if __name__ == "__main__":
+ # a newer Control installed by `strata update` takes over before anything heavy is imported (stdlib only)
+ from strata_cli.handover import maybe_hand_over
+ handed = maybe_hand_over(sys.argv[1:])
+ if handed is not None:
+ raise SystemExit(handed)
code = _preflight(sys.argv[1:])
if code:
raise SystemExit(code)
diff --git a/strata_cli/handover.py b/strata_cli/handover.py
new file mode 100644
index 000000000..509645939
--- /dev/null
+++ b/strata_cli/handover.py
@@ -0,0 +1,141 @@
+"""Hand the Terminal over to a newer Control that `strata update` installed.
+
+`strata update` stages a newer Control in ``<components>/control/<ver>/`` and writes ``<components>/control/active.json``. The
+desktop app follows that pointer; the Terminal on PATH is a different install, so without this it kept running the old one.
+`maybe_hand_over` runs at the very start of ``strata.py``, before any heavy import, and (only when that Control is newer and whole)
+runs the same command line with the newer Control's own interpreter and entry point.
+
+Rules: standard library only; never an older or equal target; never a pointer that leaves the control folder; never a loop
+(``STRATA_HANDOVER`` marks a process that was already handed over); a broken target costs one warning line and the current
+Control keeps running. ``STRATA_NO_HANDOVER=1`` turns it off.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+ENV_GUARD = "STRATA_HANDOVER"
+ENV_OFF = "STRATA_NO_HANDOVER"
+_FOLDER = re.compile(r"^[\w.+-]+$")
+_VERSION = re.compile(r"^[0-9]+(\.[0-9]+){1,3}$")
+
+
+def components_dir(environ=None) -> Path:
+ """The per-user component folder (same rule as strata_control/engine_component.py components_dir)."""
+ environ = os.environ if environ is None else environ
+ if environ.get("STRATA_COMPONENTS_DIR"):
+ return Path(environ["STRATA_COMPONENTS_DIR"])
+ home = Path.home()
+ if os.name == "nt":
+ return Path(environ.get("LOCALAPPDATA") or str(home / "AppData" / "Local")) / "Strata" / "components"
+ return Path(environ.get("XDG_DATA_HOME") or str(home / ".local" / "share")) / "strata" / "components"
+
+
+def version_key(text) -> tuple[int, ...] | None:
+ if not isinstance(text, str) or not _VERSION.fullmatch(text.strip()):
+ return None
+ parts = [int(p) for p in text.strip().split(".")]
+ return tuple(parts + [0] * (4 - len(parts)))
+
+
+def _read_json(path: Path):
+ return json.loads(path.read_text(encoding="utf-8-sig"))
+
+
+def bundled_python(folder: Path) -> Path:
+ return folder / "python" / "python.exe" if os.name == "nt" else folder / "python" / "bin" / "python3"
+
+
+def find_target(running: str, environ=None, root: Path | None = None):
+ """(folder, version, problem). folder is a newer, whole Control; or None with problem None (nothing to do) or a reason
+ (a newer Control is named but cannot be used)."""
+ root = components_dir(environ) if root is None else Path(root)
+ base = root / "control"
+ try:
+ pointer = _read_json(base / "active.json")
+ except (OSError, ValueError):
+ return None, None, None
+ if not isinstance(pointer, dict):
+ return None, None, None
+ name = pointer.get("folder")
+ if not isinstance(name, str) or not _FOLDER.fullmatch(name) or name in (".", ".."):
+ return None, None, "its pointer names a folder outside the control folder"
+ folder = base / name
+ try:
+ if folder.resolve().parent != base.resolve():
+ return None, None, "its pointer names a folder outside the control folder"
+ except OSError:
+ return None, None, None
+ # the version that counts is the one in the folder; the pointer's claim is only a fallback
+ version = None
+ for source in ("VERSION", "BUNDLE.json"):
+ try:
+ if source == "VERSION":
+ version = (folder / source).read_text(encoding="utf-8-sig").strip()
+ else:
+ version = _read_json(folder / source).get("version")
+ except (OSError, ValueError, AttributeError):
+ continue
+ if version_key(version):
+ break
+ version = None
+ if version is None:
+ version = pointer.get("version")
+ have, want = version_key(running), version_key(version)
+ if want is None or have is None or want <= have:
+ return None, None, None # never an older or equal Control; an unreadable version is ignored
+ if not (bundled_python(folder).is_file() and (folder / "strata.py").is_file() and (folder / "strata_control").is_dir()):
+ return None, version, f"{folder} is missing its interpreter or entry point"
+ return folder, version, None
+
+
+def _child_env(environ) -> dict:
+ env = dict(environ)
+ env[ENV_GUARD] = "1"
+ env["PYTHONNOUSERSITE"] = "1"
+ env.pop("PYTHONHOME", None)
+ env.pop("PYTHONPATH", None)
+ return env
+
+
+def maybe_hand_over(argv, environ=None, root=None, running=None, execv=None, run=None, warn=None) -> int | None:
+ """Returns None to carry on with the current Control, or an exit code when a newer Control already ran this command
+ (Windows; on POSIX the process is replaced and this does not return)."""
+ environ = os.environ if environ is None else environ
+ if environ.get(ENV_GUARD) or environ.get(ENV_OFF):
+ return None
+ if running is None:
+ import strata_cli
+ running = strata_cli.version()
+ warn = warn or (lambda text: sys.stderr.write(text + "\n"))
+ try:
+ folder, version, problem = find_target(running, environ, root)
+ except Exception: # noqa: BLE001 - a hand-over must never be the thing that breaks the CLI
+ return None
+ if problem:
+ what = f"Control {version}" if version else "Control"
+ warn(f"strata: a newer {what} was installed but {problem}; running {running} instead. Run `strata update` again to repair it.")
+ return None
+ if folder is None:
+ return None
+ python, entry = str(bundled_python(folder)), str(folder / "strata.py")
+ command = [python, entry, *argv]
+ env = _child_env(environ)
+ if os.name != "nt":
+ try:
+ (execv or os.execve)(python, command, env)
+ except OSError as exc:
+ warn(f"strata: could not start the updated Control {version} ({exc.strerror or exc}); running {running} instead.")
+ return None
+ try:
+ return (run or subprocess.call)(command, env=env, cwd=os.getcwd())
+ except KeyboardInterrupt:
+ return 130
+ except OSError as exc:
+ warn(f"strata: could not start the updated Control {version} ({exc.strerror or exc}); running {running} instead.")
+ return None
diff --git a/strata_cli/update_cmd.py b/strata_cli/update_cmd.py
index 4bdb089c0..67e89937b 100644
--- a/strata_cli/update_cmd.py
+++ b/strata_cli/update_cmd.py
@@ -114,7 +114,7 @@ def _line(name: str, result: dict) -> str:
return f"{name:<8}{before or 'none'} {result.get('note') or status}"
if result.get("component") == "control":
if status == "updated":
- return f"{name:<8}{result.get('installed_before') or '?'} -> {result.get('installed_after')} updated (takes effect on the next start)"
+ return f"{name:<8}{result.get('installed_before') or '?'} -> {result.get('installed_after')} updated. The next `strata` command already runs it; the app switches on its next start"
if status == "current":
return f"{name:<8}{result.get('installed_before')} up to date"
if status == "not-in-feed":
diff --git a/strata_control/updater.py b/strata_control/updater.py
index 9c12445cb..308c10941 100644
--- a/strata_control/updater.py
+++ b/strata_control/updater.py
@@ -931,7 +931,7 @@ def update_control(ctx: Context, feed: feedmod.Feed, state: State) -> dict:
ctx.say("test", f"Test-starting Control {pkg.version}", component="control")
try:
done = subprocess.run([interpreter, str(entry), "--version"], capture_output=True, text=True, timeout=120, cwd=str(stage),
- env={**ctx.environ, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1"},
+ env={**ctx.environ, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1", "STRATA_HANDOVER": "1"},
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
except (OSError, subprocess.SubprocessError) as exc:
raise TestStartFailed(f"Control {pkg.version}", f"{type(exc).__name__}: {exc}") from None
@@ -957,7 +957,7 @@ def update_control(ctx: Context, feed: feedmod.Feed, state: State) -> dict:
"from": decision["installed"], "to": pkg.version, "ok": True})
archive.unlink(missing_ok=True)
result.update({"changed": True, "status": "updated", "installed_after": pkg.version,
- "note": "Control switches on the next start of the app or the terminal"})
+ "note": "the Terminal hands over to it from the next command; the app uses it from its next start"})
return result
finally:
shutil.rmtree(longpath.long_path(stage), ignore_errors=True)
diff --git a/tests/terminal/test_handover.py b/tests/terminal/test_handover.py
new file mode 100644
index 000000000..a623d76da
--- /dev/null
+++ b/tests/terminal/test_handover.py
@@ -0,0 +1,160 @@
+"""`strata update` installs a newer Control; the Terminal on PATH hands over to it (it used to keep running the old one)."""
+
+import json
+import os
+import stat
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+from strata_cli import handover
+
+ROOT = Path(__file__).resolve().parents[2]
+WINDOWS = os.name == "nt"
+
+
+def make_control(components: Path, version: str, folder: str | None = None, whole: bool = True, point: bool = True) -> Path:
+ folder = folder or version
+ d = components / "control" / folder
+ (d / "strata_control").mkdir(parents=True, exist_ok=True)
+ (d / "VERSION").write_text(version + "\n", encoding="utf-8")
+ (d / "strata.py").write_text("print('control', %r)\n" % version, encoding="utf-8")
+ if whole:
+ py = handover.bundled_python(d)
+ py.parent.mkdir(parents=True, exist_ok=True)
+ py.write_text("stub", encoding="utf-8")
+ if point:
+ (components / "control" / "active.json").write_text(json.dumps({"version": version, "folder": folder}), encoding="utf-8")
+ return d
+
+
+class Handover(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory(prefix="strata-handover-")
+ self.addCleanup(self.temp.cleanup)
+ self.comp = Path(self.temp.name) / "components"
+ self.comp.mkdir()
+ self.env = {"STRATA_COMPONENTS_DIR": str(self.comp)}
+ self.calls, self.warnings = [], []
+
+ def go(self, running="0.1.46", env=None, argv=("status",)):
+ def fake(*args, **kwargs):
+ self.calls.append((args, kwargs))
+ return 7
+ env = {**self.env, **(env or {})}
+ return handover.maybe_hand_over(list(argv), environ=env, running=running, execv=fake, run=fake, warn=self.warnings.append)
+
+ def test_a_newer_control_takes_over_with_its_own_interpreter_and_the_same_arguments(self):
+ d = make_control(self.comp, "0.1.46.1")
+ result = self.go(argv=("serve", "--port", "1"))
+ self.assertEqual(len(self.calls), 1)
+ args, kwargs = self.calls[0]
+ python, command = (args[0], args[1]) if not WINDOWS else (args[0][0], args[0])
+ self.assertEqual(Path(python), handover.bundled_python(d))
+ self.assertEqual(command[1:], [str(d / "strata.py"), "serve", "--port", "1"])
+ env = kwargs.get("env") or args[2]
+ self.assertEqual(env["STRATA_HANDOVER"], "1")
+ if WINDOWS:
+ self.assertEqual(result, 7, "the exit code of the newer Control is passed through")
+ self.assertEqual(self.warnings, [])
+
+ def test_no_loop_when_already_handed_over(self):
+ make_control(self.comp, "0.1.46.1")
+ self.assertIsNone(self.go(env={"STRATA_HANDOVER": "1"}))
+ self.assertIsNone(self.go(env={"STRATA_NO_HANDOVER": "1"}))
+ self.assertEqual(self.calls, [])
+
+ def test_a_broken_target_falls_back_with_one_warning(self):
+ make_control(self.comp, "0.1.46.1", whole=False)
+ self.assertIsNone(self.go())
+ self.assertEqual(self.calls, [])
+ self.assertEqual(len(self.warnings), 1)
+ self.assertIn("0.1.46.1", self.warnings[0])
+ self.assertIn("running 0.1.46 instead", self.warnings[0])
+
+ def test_a_target_that_fails_to_start_falls_back(self):
+ make_control(self.comp, "0.1.46.1")
+
+ def boom(*a, **k):
+ raise OSError(8, "Exec format error")
+ result = handover.maybe_hand_over(["status"], environ=self.env, running="0.1.46", execv=boom, run=boom, warn=self.warnings.append)
+ self.assertIsNone(result)
+ self.assertEqual(len(self.warnings), 1)
+
+ def test_an_older_or_equal_target_is_ignored(self):
+ make_control(self.comp, "0.1.45")
+ self.assertIsNone(self.go(running="0.1.46"))
+ make_control(self.comp, "0.1.46")
+ self.assertIsNone(self.go(running="0.1.46"))
+ self.assertIsNone(self.go(running="0.1.46.1"))
+ self.assertEqual((self.calls, self.warnings), ([], []))
+
+ def test_the_version_in_the_folder_counts_not_the_pointers_claim(self):
+ d = make_control(self.comp, "0.1.45")
+ (self.comp / "control" / "active.json").write_text(json.dumps({"version": "9.9.9", "folder": "0.1.45"}), encoding="utf-8")
+ self.assertIsNone(self.go(running="0.1.46"))
+ self.assertTrue(d.is_dir())
+
+ def test_a_pointer_cannot_leave_the_control_folder(self):
+ outside = Path(self.temp.name) / "etc"
+ (outside / "strata_control").mkdir(parents=True)
+ (outside / "VERSION").write_text("9.0.0", encoding="utf-8")
+ (outside / "strata.py").write_text("print('evil')", encoding="utf-8")
+ py = handover.bundled_python(outside)
+ py.parent.mkdir(parents=True)
+ py.write_text("x", encoding="utf-8")
+ (self.comp / "control").mkdir(exist_ok=True)
+ for folder in ("../../etc", "..", "../etc", "a/b", "/etc", "..\\etc", ""):
+ (self.comp / "control" / "active.json").write_text(json.dumps({"version": "9.0.0", "folder": folder}), encoding="utf-8")
+ self.assertIsNone(self.go(), folder)
+ self.assertEqual(self.calls, [])
+
+ @unittest.skipIf(WINDOWS, "needs a symlink")
+ def test_a_folder_that_is_a_link_out_of_the_control_folder_is_refused(self):
+ real = make_control(Path(self.temp.name) / "elsewhere", "9.0.0", point=False)
+ (self.comp / "control").mkdir(exist_ok=True)
+ (self.comp / "control" / "9.0.0").symlink_to(real, target_is_directory=True)
+ (self.comp / "control" / "active.json").write_text(json.dumps({"version": "9.0.0", "folder": "9.0.0"}), encoding="utf-8")
+ self.assertIsNone(self.go())
+ self.assertEqual(self.calls, [])
+
+ def test_no_pointer_or_garbage_means_nothing_happens(self):
+ self.assertIsNone(self.go())
+ (self.comp / "control").mkdir()
+ for text in ("{", "[]", "null", json.dumps({"folder": "x"})):
+ (self.comp / "control" / "active.json").write_text(text, encoding="utf-8")
+ self.assertIsNone(self.go(), text)
+ self.assertEqual((self.calls, self.warnings), ([], []))
+
+ @unittest.skipIf(WINDOWS, "a shell stub stands in for the bundled interpreter")
+ def test_end_to_end_the_real_entry_point_hands_over_and_does_not_loop(self):
+ newer = make_control(self.comp, "99.0.0")
+ py = handover.bundled_python(newer)
+ py.write_text('#!/bin/sh\nexec "%s" "$@"\n' % sys.executable, encoding="utf-8")
+ py.chmod(py.stat().st_mode | stat.S_IXUSR)
+ (newer / "strata.py").write_text("import os,sys\nprint('control 99', os.environ.get('STRATA_HANDOVER'), sys.argv[1:])\nraise SystemExit(3)\n",
+ encoding="utf-8")
+ done = subprocess.run([sys.executable, str(ROOT / "strata.py"), "--version"], capture_output=True, text=True,
+ env={**os.environ, "STRATA_COMPONENTS_DIR": str(self.comp)})
+ self.assertEqual(done.returncode, 3, done.stderr)
+ self.assertIn("control 99 1 ['--version']", done.stdout)
+ # with the guard set the current Control runs, and says its own version
+ done = subprocess.run([sys.executable, str(ROOT / "strata.py"), "--version"], capture_output=True, text=True,
+ env={**os.environ, "STRATA_COMPONENTS_DIR": str(self.comp), "STRATA_HANDOVER": "1"})
+ self.assertEqual(done.returncode, 0, done.stderr)
+ self.assertTrue(done.stdout.startswith("strata "), done.stdout)
+
+ def test_the_entry_point_falls_back_when_the_target_is_broken(self):
+ make_control(self.comp, "99.0.0", whole=False)
+ done = subprocess.run([sys.executable, str(ROOT / "strata.py"), "--version"], capture_output=True, text=True,
+ env={**os.environ, "STRATA_COMPONENTS_DIR": str(self.comp)})
+ self.assertEqual(done.returncode, 0, done.stderr)
+ self.assertTrue(done.stdout.startswith("strata "), done.stdout)
+ self.assertEqual(len(done.stderr.strip().splitlines()), 1, done.stderr)
+ self.assertIn("99.0.0", done.stderr)
+
+
+if __name__ == "__main__":
+ unittest.main()