strata launch --show-key shows the key of a model setup.py set up (#3570)

--show-key only knew a running launch or a preset. A model set up by setup.py (START-HERE.bat, ./setup.sh) keeps its generated key in strata-<model>.json, so the command
said there was no key and people read the JSON by hand. With no launch and no --preset, it now looks at the run configs of the installed models: one model with a key
prints that key (stdout is the key alone; a hint line with the model and the file goes to stderr), several models ask for --model NAME (any case, the size or the full
id), a name that matches nothing says so. --preset never falls back to a setup config, and no key is printed while the choice is open. Tests:
tests/terminal/test_launch_show_key_setup.py.
This commit is contained in:
Niko1221 committed 2026-10-26 19:45:45 +01:00
1 parent 10a62b8d2f
commit 47c98bb23a
2 files changed
+117 -5

No files matched your search

+43 -5
View File
@@ -147,7 +147,8 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser]
m.add_argument("--delete-preset", metavar="NAME", help="delete a saved preset")
m.add_argument("--status", action="store_true", help="show what this command is serving now")
m.add_argument("--stop", action="store_true", help="stop what this command started (with --preset NAME: that one)")
m.add_argument("--show-key", action="store_true", help="print the API key of --preset NAME (or of the running launch)")
m.add_argument("--show-key", action="store_true", help="print the API key of --preset NAME (or of the running launch); with none of those, the key of a model setup.py set up "
"(--model NAME picks one when several have a key)")
c = sp.add_parser(
"connect", help="print (or write) the setup for an app that uses the running server", epilog=EXAMPLES,
@@ -650,6 +651,31 @@ def launch_info(name: str | None = None) -> dict | None:
"port": port, "access": preset.access if preset else None}
def setup_config_keys(wanted: str | None = None) -> list[tuple[str, Path, str]]:
"""(model id, config file, API key) for the models setup.py set up (strata-<model>.json in the install folders) that carry a key, #3570.
`wanted` keeps the model whose id is that name or ends with it (coder-iq1_m for IQ1_M); case does not matter."""
from strata_control import models
try:
listed = models.list_installed().get("models", [])
except Exception: # noqa: BLE001 - a folder that cannot be read has no key to show
return []
found = []
for entry in listed:
source = entry.get("source_config")
if not source:
continue
model_id = str(entry.get("id") or Path(source).stem)
if wanted and not (model_id.lower() == wanted.lower() or model_id.lower().endswith(wanted.lower())):
continue
try:
key = str(json.loads(Path(source).read_text(encoding="utf-8-sig")).get("api_key") or "").strip()
except (OSError, ValueError, AttributeError):
continue
if key and key.lower() != "none":
found.append((model_id, Path(source), key))
return found
def run_launch(a: argparse.Namespace) -> int:
from strata_cli.launch import store
from strata_cli.launch.catalog import Catalog, CatalogUnavailable
@@ -694,10 +720,22 @@ def run_launch(a: argparse.Namespace) -> int:
return 0
if a.show_key:
info = launch_info(a.preset)
if not info or not info.get("key"):
return fail("There is no API key for that launch." + ("" if a.preset else " Name a preset with --preset NAME."), 5)
_say(info["key"])
return 0
if info and info.get("key"):
_say(info["key"])
return 0
if not a.preset:
# not a launch: a model set up by setup.py keeps its key in its own strata-<model>.json (#3570)
found = setup_config_keys(getattr(a, "model", None))
if len(found) == 1:
_say(found[0][2])
if not machine:
print(f"(the key of {found[0][0]}, from {found[0][1]})", file=sys.stderr)
return 0
if len(found) > 1:
return fail("Several models set up by setup.py have an API key: " + ", ".join(f[0] for f in found) + ". Name one with --model NAME.", 5)
if getattr(a, "model", None):
return fail(f"No model set up by setup.py matches '{a.model}' and has an API key, and no launch is running.", 5)
return fail("There is no API key for that launch." + ("" if a.preset else " Name a preset with --preset NAME, or a model set up by setup.py with --model NAME."), 5)
try:
catalog = Catalog()
@@ -0,0 +1,74 @@
"""#3570: `strata launch --show-key` printed a key only for a launch (a running one or a preset). A model set up by setup.py keeps its key in
strata-<model>.json, so there the command said "no key" and people read the JSON by hand. It now reads that file when no launch has one."""
from __future__ import annotations
import contextlib
import io
import json
import tempfile
import unittest
from pathlib import Path
from unittest import mock
from strata_cli import cli
from strata_cli.launch import cmd as launch_cmd
class ShowKeyOfSetupConfigs(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.root = Path(tmp.name)
def config(self, model_id, key="__none__", **extra):
path = self.root / f"strata-{model_id}.json"
body = {"exe": "x", "args": [], **extra}
if key != "__none__":
body["api_key"] = key
path.write_text(json.dumps(body), encoding="utf-8")
return {"id": model_id, "source_config": str(path)}
def run_cli(self, entries, *argv, launch=None):
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err), \
mock.patch.object(launch_cmd, "launch_info", return_value=launch), \
mock.patch("strata_control.models.list_installed", return_value={"models": entries}):
code = cli.main(["launch", "--show-key", *argv])
return code, out.getvalue().strip(), err.getvalue()
def test_the_only_model_with_a_key_is_shown(self):
code, out, err = self.run_cli([self.config("coder-iq1_m", "abc123-secret"), self.config("qwen-q2_0")])
self.assertEqual((code, out), (0, "abc123-secret"))
self.assertIn("coder-iq1_m", err) # the hint is on stderr: stdout stays the key alone, for scripts
def test_a_launch_that_has_a_key_comes_first(self):
code, out, _ = self.run_cli([self.config("coder-iq1_m", "from-the-file")], launch={"key": "from-the-launch"})
self.assertEqual((code, out), (0, "from-the-launch"))
def test_several_models_need_a_name_and_the_name_picks_one_in_any_case(self):
entries = [self.config("coder-iq1_m", "key-one"), self.config("qwen-iq3_xxs", "key-two")]
code, out, err = self.run_cli(entries)
self.assertEqual(code, 5)
self.assertEqual(out, "")
self.assertIn("coder-iq1_m", err)
self.assertIn("--model NAME", err)
self.assertNotIn("key-one", err + out) # no key is printed while the choice is open
code, out, _ = self.run_cli(entries, "--model", "IQ3_XXS")
self.assertEqual((code, out), (0, "key-two"))
def test_no_key_anywhere_and_a_name_that_matches_nothing_are_told_plainly(self):
code, out, err = self.run_cli([self.config("qwen-q2_0")])
self.assertEqual((code, out), (5, ""))
self.assertIn("There is no API key", err)
code, out, err = self.run_cli([self.config("qwen-q2_0", "none")], "--model", "iq1_m")
self.assertEqual(code, 5)
self.assertIn("iq1_m", err)
def test_a_preset_name_never_falls_back_to_a_setup_config(self):
code, out, err = self.run_cli([self.config("coder-iq1_m", "abc123-secret")], "--preset", "mine")
self.assertEqual((code, out), (5, ""))
self.assertNotIn("abc123", err)
if __name__ == "__main__":
unittest.main()