Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: ask to update Codex when it is too old for unsloth start codex (#16843)
Nilaye006948c6c71
diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.pyindex c04d294cf21..d6b4718c194 100644--- a/unsloth_cli/commands/start.py+++ b/unsloth_cli/commands/start.py@@ -656,9 +656,16 @@ def _vibe_install_hint() -> str:return _VIBE_WINDOWS_INSTALL_HINT if os.name == "nt" else _VIBE_POSIX_INSTALL_HINT-def _npm_install_hint(package: str, *, ignore_scripts: bool = False) -> str:+def _npm_install_hint(+ package: str,+ *,+ ignore_scripts: bool = False,+ prefix: Optional[Path] = None,+) -> str:parts = ["npm", "install", "-g"]- if os.name != "nt":+ if prefix is not None:+ parts.extend(("--prefix", str(prefix)))+ elif os.name != "nt":# No home (bare container UID): fall back to npm's own prefix instead of failing.try:parts.extend(("--prefix", str(Path.home() / ".local")))@@ -3284,6 +3291,7 @@ def _merge_codex_config(# Keep custom-model behavior aligned with Codex's own unknown-model fallback. This Apache-2.0 prompt is copied from openai/codex rust-v0.144.0 models-manager/prompt.md._CODEX_FALLBACK_PROMPT = Path(__file__).parent.parent / "codex_fallback_prompt.md"_CODEX_MODEL_CATALOG_MIN_VERSION = (0, 110, 0)+_CODEX_PROFILE_FILE_MIN_VERSION = (0, 134, 0)_CODEX_PATCH_LINE_ENDINGS_MIN_VERSION = (0, 148, 0)# Older Codex sends no reasoning for a model without reasoning summaries, and older Pi has no samplingParams._CODEX_REASONING_REQUEST_MIN_VERSION = (0, 145, 0)@@ -3307,6 +3315,18 @@ def _codex_executable_version(executable: str) -> Optional[tuple[int, int, int]]return tuple(int(part) for part in match.groups()) if match else None+def _codex_update_hint(executable: str) -> Optional[str]:+ # Update the copy that resolves: a new one in ~/.local/bin sits behind an older one earlier on PATH, so an unknown install gets None.+ if any(part in ("Cellar", "Caskroom") for part in Path(os.path.realpath(executable)).parts):+ return "brew upgrade codex"+ directory = Path(executable).parent+ prefix = directory if os.name == "nt" else directory.parent+ package = prefix / ("node_modules" if os.name == "nt" else "lib/node_modules") / "@openai/codex"+ if package.is_dir():+ return _npm_install_hint("@openai/codex@latest", prefix = prefix)+ return None++def _codex_supports_model_catalog() -> bool:executable = _which_with_install_dirs("codex")if executable is None:@@ -4609,7 +4629,6 @@ def _install_command(install_hint: str) -> tuple[list[str], Optional[dict]]:"Unsloth-managed Node installation was found. Install Node.js with npm, ""then re-run.")- args = shlex.split(install_hint)env = dict(os.environ)# dirname, not Path().parent: Path picks its flavour from os.name, which the tests override. Empty means npm is a bare name; prepending "" would put the cwd on PATH.npm_dir = os.path.dirname(npm)@@ -4617,7 +4636,8 @@ def _install_command(install_hint: str) -> tuple[list[str], Optional[dict]]:if npm_dir:env["PATH"] = os.pathsep.join([npm_dir, current_path]) if current_path else npm_dirif os.name == "nt":- command = "& " + " ".join(_powershell_quote(arg) for arg in [npm, *args[1:]])+ # The hint is already PowerShell-quoted; shlex would drop the doubled ' of a path like O'Brien.+ command = "& " + _powershell_quote(npm) + install_hint.lstrip()[len("npm") :]return (["powershell",@@ -4629,14 +4649,19 @@ def _install_command(install_hint: str) -> tuple[list[str], Optional[dict]]:],env,)- return [npm, *args[1:]], env+ return [npm, *shlex.split(install_hint)[1:]], env-def _install_agent(name: str, install_hint: str) -> Optional[str]:+def _install_agent(+ name: str,+ install_hint: str,+ *,+ update: bool = False,+) -> Optional[str]:# Missing agent under --launch: offer to run its documented install command, then re-resolve it on PATH. Consent-based, and a non-interactive stdin cannot answer the prompt, so both the no-TTY and declined cases return None and let the caller print the hint and exit.if not sys.stdin.isatty():return None- typer.echo(f"`{name}` is not installed.")+ typer.echo(f"`{name}` is {'too old' if update else 'not installed'}.")# Make the supply-chain risk explicit before the prompt: these are the vendors' own installers (curl | bash, irm | iex, npm), run with the user's privileges, and nothing checks a signature or hash on the fetched content. Naming the source turns a blind "yes" into informed consent.source = _install_source(install_hint)if source:@@ -4660,7 +4685,8 @@ def _install_agent(name: str, install_hint: str) -> Optional[str]:"there is no signature or hash check.")typer.secho(warning, fg = "yellow", err = True)- if not typer.confirm(f"Install `{name}` now with `{install_hint}`?", default = False):+ action = "Update" if update else "Install"+ if not typer.confirm(f"{action} `{name}` now with `{install_hint}`?", default = False):return Noneinstall_command, install_env = _install_command(install_hint)try:@@ -7540,7 +7566,23 @@ def codex(install_hint = _npm_install_hint("@openai/codex")# Before the install prompt: _install_agent runs a remote installer, and this can refuse outright, so asking first fetches a tool the run cannot use._preflight_agent_gguf(_CODEX_GGUF_AGENT, model, serve = serve, launch = launch)- _require_agent_for_launch("codex", install_hint, launch and not app)+ executable = _require_agent_for_launch("codex", install_hint, launch and not app)+ version = executable and _codex_executable_version(executable)+ if version and version < _CODEX_PROFILE_FILE_MIN_VERSION:+ needed = (+ f"Codex {'.'.join(map(str, _CODEX_PROFILE_FILE_MIN_VERSION))} or newer is needed, "+ f"but {executable} is {'.'.join(map(str, version))}."+ )+ update_hint = _codex_update_hint(executable)+ updated = update_hint and _install_agent("codex", update_hint, update = True)+ version = updated and _codex_executable_version(updated)+ if not updated or (version and version < _CODEX_PROFILE_FILE_MIN_VERSION):+ if update_hint:+ _fail(f"{needed} Update it with `{update_hint}`.")+ _fail(+ f"{needed} Update it the way it was installed, or remove it so "+ "`unsloth start codex` can install a current one."+ )codex_effort = _codex_reasoning_effort(reasoning, reasoning_effort)if codex_effort and not _agent_version_at_least("codex", _CODEX_REASONING_REQUEST_MIN_VERSION):codex_effort = Nonediff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.pyindex 8bda9030a7c..2e2eeff1d53 100644--- a/unsloth_cli/tests/test_start.py+++ b/unsloth_cli/tests/test_start.py@@ -23,6 +23,7 @@ import urllib.errorimport urllib.parsefrom pathlib import Pathfrom types import ModuleType, SimpleNamespace+from unittest import mock_REPO_ROOT = Path(__file__).resolve().parents[2]if str(_REPO_ROOT) not in sys.path:@@ -253,6 +254,20 @@ def test_install_command_uses_resolved_npm_cmd_on_windows(monkeypatch):assert env is not None+def test_install_command_keeps_an_apostrophe_in_a_windows_prefix(monkeypatch):+ _simulate_windows(monkeypatch)+ monkeypatch.setattr(start, "_npm_executable", lambda: r"C:\Managed Node\npm.cmd")+ prefix = r"C:\Users\O'Brien\AppData\Roaming\npm"+ hint = start._npm_install_hint("@openai/codex@latest", prefix = prefix)++ command, _ = start._install_command(hint)++ assert command[-1] == (+ "& 'C:\\Managed Node\\npm.cmd' install -g --prefix "+ "'C:\\Users\\O''Brien\\AppData\\Roaming\\npm' '@openai/codex@latest'"+ )++def test_install_agent_posix_failure_omits_execution_policy_hint(monkeypatch, capsys):monkeypatch.setattr(start.os, "name", "posix")monkeypatch.setattr(start.sys, "stdin", SimpleNamespace(isatty = lambda: True))@@ -4297,6 +4312,99 @@ def test_agent_too_old_to_send_the_flags_keeps_the_server_pin(assert "model_reasoning_effort" not in profile[email protected]("subagent", [[], ["--as-subagent"], ["--auto-route"]])+ "version, launches", [((0, 133, 0), False), ((0, 134, 0), True), (None, True)]+)+def test_codex_too_old_for_profile_files_stops_before_launch(+ version, launches, subagent, fake_studio, tmp_path, monkeypatch+):+ monkeypatch.chdir(tmp_path)+ monkeypatch.setattr(start, "_which_with_install_dirs", lambda name: f"/bin/{name}")+ monkeypatch.setattr(+ start, "_require_agent_for_launch", lambda name, hint, launch: f"/bin/{name}"+ )+ monkeypatch.setattr(start, "_codex_executable_version", lambda executable: version)+ launched = []+ monkeypatch.setattr(start, "_launch", lambda *args, **kwargs: launched.append(args))+ result = CliRunner().invoke(start.start_app, ["codex", *subagent])+ assert bool(launched) is launches+ if launches:+ assert result.exit_code == 0, result.output+ else:+ assert result.exit_code == 1+ assert "Codex 0.134.0 or newer is needed, but /bin/codex is 0.133.0" in result.output+ assert "Update it the way it was installed, or remove it" in result.output+ assert not any(call[1].endswith("/api/inference/load") for call in fake_studio)++[email protected]("after, launches", [((0, 134, 0), True), ((0, 133, 0), False)])+def test_codex_too_old_offers_the_update_with_the_managed_npm(+ after, launches, fake_studio, tmp_path, monkeypatch+):+ monkeypatch.chdir(tmp_path)+ monkeypatch.setattr(start, "_require_agent_for_launch", lambda *a: "/bin/codex")+ versions = iter([(0, 133, 0), after])+ monkeypatch.setattr(start, "_codex_executable_version", lambda _: next(versions, after))+ hint = start._npm_install_hint("@openai/codex@latest")+ monkeypatch.setattr(start, "_codex_update_hint", lambda _: hint)+ install_agent = start._install_agent++ def install_from_a_tty(*args, **kwargs):+ # CliRunner swaps sys.stdin, so fake the TTY only for the prompt.+ with mock.patch.object(start.sys, "stdin", SimpleNamespace(isatty = lambda: True)):+ return install_agent(*args, **kwargs)++ monkeypatch.setattr(start, "_install_agent", install_from_a_tty)+ prompts = []+ monkeypatch.setattr(start.typer, "confirm", lambda text, **k: prompts.append(text) or True)+ monkeypatch.setattr(start, "_npm_executable", lambda: "/studio/node/bin/npm")+ ran = []+ monkeypatch.setattr(+ start.subprocess,+ "run",+ lambda command, env = None, **k: ran.append((command, env)) or SimpleNamespace(returncode = 0),+ )+ monkeypatch.setattr(start.shutil, "which", lambda name, **k: f"/bin/{name}")+ launched = []+ monkeypatch.setattr(start, "_launch", lambda *args, **kwargs: launched.append(args))+ result = CliRunner().invoke(start.start_app, ["codex"])+ assert prompts == [f"Update `codex` now with `{hint}`?"]+ if os.name == "nt":+ assert ran[0][0][-1] == "& " + start._powershell_quote("/studio/node/bin/npm") + hint[3:]+ else:+ assert ran[0][0] == ["/studio/node/bin/npm", *shlex.split(hint)[1:]]+ assert ran[0][1]["PATH"].startswith(os.path.dirname("/studio/node/bin/npm"))+ assert bool(launched) is launches+ if not launches:+ assert result.exit_code == 1+ assert f"Update it with `{hint}`" in result.output+++def test_codex_update_hint_targets_the_resolved_install(tmp_path):+ prefix = tmp_path / "global"+ bin_dir = prefix if os.name == "nt" else prefix / "bin"+ package = prefix / ("node_modules" if os.name == "nt" else "lib/node_modules")+ (package / "@openai" / "codex").mkdir(parents = True)+ assert start._codex_update_hint(str(bin_dir / "codex")) == start._npm_install_hint(+ "@openai/codex@latest", prefix = prefix+ )+ assert start._codex_update_hint(str(tmp_path / "elsewhere" / "codex")) is None++[email protected](os.name == "nt", reason = "Homebrew links codex with a symlink")+def test_codex_update_hint_uses_brew_for_a_homebrew_codex(tmp_path):+ target = tmp_path / "Caskroom" / "codex" / "0.133.0" / "codex"+ target.parent.mkdir(parents = True)+ target.touch()+ link = tmp_path / "bin" / "codex"+ link.parent.mkdir()+ link.symlink_to(target)+ # A leftover npm package under the same prefix must not win over the brew-owned link.+ (tmp_path / "lib" / "node_modules" / "@openai" / "codex").mkdir(parents = True)+ assert start._codex_update_hint(str(link)) == "brew upgrade codex"++def test_opencode_v1_reads_the_effort_as_reasoning_effort_option(fake_studio, tmp_path, monkeypatch):