okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Save and launch saves the preset only after the restart question is answered Restart; the question names the running model and port3b1ab2848

main
5.3 KiB150 linesraw
1"""Saved launch presets: the whole answer set of the setup screens under a name.
2
3One small JSON file per preset in `launch-presets/` beside the profiles folder (so it is found wherever the profiles are, and
4`STRATA_LAUNCH_PRESET_DIR` moves it for tests). The files are private to the user (they can hold the API key). The tuned
5settings themselves are NOT copied here: a preset points at the tuning preset the tuner saved (`strata presets`, the store the
6desktop app also uses), so a re-tune in either place is seen in both. The profile the run uses (`strata profile`) is the shared
7one too (named `launch-<slug>`).
8"""
9
10from __future__ import annotations
11
12import json
13import os
14import tempfile
15import time
16from strata_control import atomic as _atomic_mod
17from pathlib import Path
18from typing import Any
19
20from strata_cli.launch.settings import LaunchSettings, slug
21
22
23class PresetError(ValueError):
24    """A saved launch preset is missing or damaged; the message is for the user."""
25
26
27def preset_dir() -> Path:
28    explicit = os.environ.get("STRATA_LAUNCH_PRESET_DIR")
29    if explicit:
30        return Path(explicit).expanduser()
31    from strata_control import profiles
32    return profiles.profile_dir().parent / "launch-presets"
33
34
35def _path(name: str) -> Path:
36    return preset_dir() / f"{slug(name)}.json"
37
38
39def _private_write(path: Path, payload: bytes) -> None:
40    path.parent.mkdir(parents=True, exist_ok=True)
41    fd, tmp = tempfile.mkstemp(prefix=".launch-", suffix=".tmp", dir=path.parent)
42    try:
43        with os.fdopen(fd, "wb") as fh:
44            fh.write(payload)
45            fh.flush()
46            os.fsync(fh.fileno())
47        try:
48            os.chmod(tmp, 0o600)
49        except OSError:
50            pass
51        _atomic_mod.replace(tmp, path)
52    finally:
53        if os.path.exists(tmp):
54            os.unlink(tmp)
55    if os.name == "nt":
56        try:
57            from strata_control import private_files
58            private_files.restrict_to_current_user(path, directory=False)
59        except Exception:                                    # noqa: BLE001 - a file the user can read is still theirs
60            pass
61
62
63def now_text() -> str:
64    now = time.time()
65    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now)) + f".{int((now % 1) * 1000000):06d}"
66
67
68def check_name(name: str) -> None:
69    """The error `save` would raise for this name, without writing anything."""
70    if not (name or "").strip():
71        raise PresetError("A preset needs a name.")
72    _path(name.strip())
73
74
75def save(settings: LaunchSettings, name: str | None = None) -> LaunchSettings:
76    """Write (or replace) the preset called `name` (default: the settings' own name)."""
77    name = (name or settings.name or "").strip()
78    if not name:
79        raise PresetError("A preset needs a name.")
80    path = _path(name)
81    previous = load(name, missing_ok=True)
82    s = settings.copy(name=name)
83    s.created = (previous.created if previous else None) or s.created or now_text()
84    _private_write(path, (json.dumps(s.to_dict(), indent=2, ensure_ascii=False, sort_keys=True) + "\n").encode("utf-8"))
85    return s
86
87
88def load(name: str, *, missing_ok: bool = False) -> LaunchSettings | None:
89    path = _path(name)
90    try:
91        data = json.loads(path.read_text(encoding="utf-8-sig"))
92    except FileNotFoundError:
93        if missing_ok:
94            return None
95        raise PresetError(f"There is no saved preset called '{name}'." + _near(name)) from None
96    except (OSError, ValueError):
97        raise PresetError(f"The saved preset '{name}' cannot be read. Delete it (strata launch --delete-preset \"{name}\") "
98                          "and save it again.") from None
99    if not isinstance(data, dict):
100        raise PresetError(f"The saved preset '{name}' is damaged.")
101    s = LaunchSettings.from_dict(data)
102    s.name = s.name or name
103    return s
104
105
106def _near(name: str) -> str:
107    from strata_cli.launch.settings import closest
108    names = [p.name for p in list_presets() if p.name]
109    near = closest(name, names) if names else None
110    if near:
111        return f" Did you mean '{near}'?"
112    return (" Saved presets: " + ", ".join(names) + ".") if names else " No presets are saved yet."
113
114
115def list_presets() -> list[LaunchSettings]:
116    folder = preset_dir()
117    out: list[LaunchSettings] = []
118    if not folder.is_dir():
119        return out
120    for path in sorted(folder.glob("*.json")):
121        try:
122            data = json.loads(path.read_text(encoding="utf-8-sig"))
123            s = LaunchSettings.from_dict(data)
124            s.name = s.name or path.stem
125            out.append(s)
126        except (OSError, ValueError):
127            continue
128    out.sort(key=lambda s: s.last_used or s.created or "", reverse=True)
129    return out
130
131
132def delete(name: str) -> None:
133    path = _path(name)
134    if not path.is_file():
135        raise PresetError(f"There is no saved preset called '{name}'." + _near(name))
136    path.unlink()
137
138
139def touch_used(name: str) -> None:
140    s = load(name, missing_ok=True)
141    if s is not None:
142        s.last_used = now_text()
143        save(s, name)
144
145
146def summary(s: LaunchSettings) -> dict[str, Any]:
147    """The columns of the start screen."""
148    return {"name": s.name, "model": s.model or ("own files" if s.model_path else "-"),
149            "context": s.context, "parallel": s.parallel, "tuned": s.is_tuned, "tuned_at": s.tuned_at,
150            "last_used": s.last_used, "access": s.access}