From a0e09803ac8b2ddc8c1253d8aedfeeaf093ed671 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:20:27 +0200 Subject: [PATCH 1/3] Models folder: move the model files to another folder (strata models move): copied and checked file by file, stoppable, run configs follow --- strata_cli/cli.py | 52 +++- strata_control/models_move.py | 477 +++++++++++++++++++++++++++++ tests/terminal/test_models_move.py | 283 +++++++++++++++++ 3 files changed, 811 insertions(+), 1 deletion(-) create mode 100644 strata_control/models_move.py create mode 100644 tests/terminal/test_models_move.py diff --git a/strata_cli/cli.py b/strata_cli/cli.py index 80e66518..d36946f3 100644 --- a/strata_cli/cli.py +++ b/strata_cli/cli.py @@ -159,6 +159,13 @@ def parser() -> argparse.ArgumentParser: models_import.add_argument("--plan", action="store_true", required=True, help="inspect only; adoption requires a qualified model workflow") models_import.add_argument("--output", choices=("human", "json"), default="human") + models_move = models_sp.add_parser("move", help="move the model files (models, packs, mtp) to another folder: copied, checked, then the old copies removed") + models_move.add_argument("to", metavar="NEW_FOLDER") + models_move.add_argument("--from", dest="source", metavar="OLD_FOLDER", help="the folder the models are in now (default: the data folder in use)") + models_move.add_argument("--install-dir", help="absolute path to a Strata installation whose run configs should follow the files") + models_move.add_argument("--plan", action="store_true", help="say what would happen and change nothing") + models_move.add_argument("--cancel-file", metavar="PATH", help="stop (safely) when this file appears") + models_move.add_argument("--output", choices=("human", "json", "jsonl"), default="human") engine = sp.add_parser("engine", help="engine tuning and component actions") engine_sp = engine.add_subparsers(dest="engine_command", required=True) calibrate = engine_sp.add_parser("calibrate", help="measure, review and apply engine tuning") @@ -495,7 +502,7 @@ def parser() -> argparse.ArgumentParser: code_sessions.add_argument("--output", choices=("human", "json"), default="human") for one_shot in (profile_create, profile_list, profile_show, profile_validate, profile_set, profile_source, profile_edit, profile_history, profile_rollback, doctor, - components_verify, models_list, models_inspect, models_import, calibrate, + components_verify, models_list, models_inspect, models_import, models_move, calibrate, runtime_start, runtime_status, runtime_verify, runtime_stop, runtime_cleanup, runtime_restart, *ops_items, bench_run, bench_report, bench_compare, code_sessions, *update_parsers): one_shot.add_argument("--json", action="store_true", help="alias for --output json") @@ -547,6 +554,8 @@ def _models(a: argparse.Namespace) -> int: print(_import_problem(result), file=sys.stderr) return 5 return _success({"plan": result}, machine=a.output == "json", human=_import_words(result)) + if a.models_command == "move": + return _models_move(a) if a.models_command == "list": if a.served: if a.install_dir: @@ -603,6 +612,47 @@ def _import_problem(plan: dict) -> str: return text +def _models_move(a: argparse.Namespace) -> int: + from strata_control import discovery, models, models_move as mm + machine = a.output in ("json", "jsonl") + old = Path(a.source) if a.source else discovery.data_dir(Path.home() / "Strata")[0] + new = Path(a.to).expanduser() + if a.plan: + result = mm.plan(old, new) + if machine: + print(json.dumps({"schema_version": 1, "ok": result["ok"], "plan": result}, ensure_ascii=False, allow_nan=False)) + else: + print(result["issue"]["message"] if result["issue"] else + f"{len(result['models'])} model(s), {result['models_bytes'] / 1e9:.1f} GB; {result['free_bytes'] / 1e9:.1f} GB free in {new}.") + return 0 if result["ok"] else 5 + try: + installs = [models.resolve_install(a.install_dir)[0]] if a.install_dir else [p for p, _s in models.all_installs()] + except Exception: + installs = [] + configs = [c for i in installs for c in mm.config_files(i)] + cancel = Path(a.cancel_file) if a.cancel_file else None + + def show(event: dict) -> None: + if a.output == "jsonl": + print(json.dumps(event, ensure_ascii=False, allow_nan=False), flush=True) + elif not machine: + print(f"\r{event['done'] / 1e9:.1f} of {event['total'] / 1e9:.1f} GB {event['file']}", end="", flush=True) + try: + summary = mm.move(old, new, on_progress=show, cancelled=(lambda: cancel.exists()) if cancel else None, configs=configs) + except mm.MoveError as e: + extra = getattr(e, "summary", {}) + if machine: + print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": e.code, "message": str(e), "details": e.details}, **extra}, ensure_ascii=False)) + else: + print(f"\nstrata: {e} {e.details}".rstrip(), file=sys.stderr) + return 5 + if machine: + print(json.dumps({"schema_version": 1, "ok": True, "event": "result", **summary}, ensure_ascii=False)) + else: + print("\n" + ("Your models are moved." if summary["done"] else "Moving stopped. Nothing was lost.")) + return 0 if summary["done"] else 6 + + def _import_words(plan: dict) -> str: """The plain-words result of `strata models import --plan`: what the files are, what is already set up, what changes (nothing).""" cand = plan.get("candidate_selection") or {} diff --git a/strata_control/models_move.py b/strata_control/models_move.py new file mode 100644 index 00000000..36eb6fc2 --- /dev/null +++ b/strata_control/models_move.py @@ -0,0 +1,477 @@ +"""Move the model files (models, packs, mtp) from one data folder to another (0.2.2, Settings > Storage > Models folder). + +The desktop app and the Terminal both use this: ``strata models move``. Rules, in the order they matter: + +* Nothing is deleted until its copy is whole and checked. One file at a time: copy to ``name.part``, compare the size, read the copy + back and compare its SHA-256 with the original's (and with the pinned SHA-256 in the file's ``.done`` mark when it has one), rename it + into place, only then remove the original. The extra space needed is never more than the move itself. +* Stopping is safe. The file in flight is discarded (its ``.part`` is removed), files already moved stay, and the run configs are + rewritten for every model whose files are all in the new folder. The data folder in the settings is changed by the caller only + when the whole move is done, so the app is never pointed at an incomplete folder. +* The same drive is a rename (instant). Another drive is a copy. +* A crash leaves at worst a model in both folders; ``name.part`` files are never trusted. +""" + +from __future__ import annotations + +import errno +import hashlib +import json +import os +import re +import shutil +import tempfile +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Callable + +ITEMS = ("models", "packs", "mtp") +STATE_FILE = "models-move.json" +MARGIN = 1.05 # room beside the files themselves: 5 % +CHUNK = 8 * 1024 * 1024 + + +class MoveError(Exception): + """A move that stopped for a reason the person can act on. ``code`` is one of: not_found, not_writable, inside, disk_full, verify, busy, io.""" + + def __init__(self, code: str, message: str, details: str = ""): + super().__init__(message) + self.code = code + self.details = details + + +class Stopped(Exception): + """The person asked to stop.""" + + +@dataclass +class Entry: + rel: str # path under the data folder, with "/" (models//file.gguf) + size: int + group: str # the model it belongs to: "models/", "packs/", "mtp" + + +# ----------------------------------------------------------------------------------------------- what is there + +def _item_dirs(data: Path) -> list[Path]: + """The models / packs / mtp folders of a data folder (any spelling of the name: ``Models`` and ``models`` are one library).""" + try: + names = sorted(p for p in data.iterdir() if p.is_dir() and p.name.lower() in ITEMS) + except OSError: + return [] + return names + + +def inventory(data: Path) -> list[Entry]: + """Every file Strata keeps in a data folder: nothing else is touched. Unfinished downloads (``.part``) are left where they are.""" + found: list[Entry] = [] + for top in _item_dirs(data): + for root, _dirs, files in os.walk(top): + for name in files: + if name.endswith(".part"): + continue + path = Path(root) / name + try: + size = path.stat().st_size + except OSError: + continue + rel = path.relative_to(data).as_posix() + parts = rel.split("/") + kind = parts[0].lower() + group = kind if kind == "mtp" or len(parts) < 3 else parts[1].lower() # a model's GGUF files and its pack are one model + found.append(Entry(rel, size, group)) + found.sort(key=lambda e: (e.group, e.rel)) + return found + + +def groups(entries: list[Entry]) -> list[dict]: + """The models in a list of files, for the person: name (the folder name), bytes.""" + out: dict[str, int] = {} + for e in entries: + out[e.group] = out.get(e.group, 0) + e.size + return [{"group": g, "name": g, "bytes": b} for g, b in out.items()] + + +def _near(path: Path) -> Path: + """The folder that exists and holds ``path`` (or ``path`` itself).""" + p = path + while not p.exists() and p.parent != p: + p = p.parent + return p + + +def same_drive(a: Path, b: Path) -> bool: + try: + return os.stat(_near(a)).st_dev == os.stat(_near(b)).st_dev + except OSError: + return False + + +def _same(a: Path, b: Path) -> bool: + return os.path.normcase(os.path.abspath(a)) == os.path.normcase(os.path.abspath(b)) + + +def _inside(child: Path, parent: Path) -> bool: + c, p = os.path.normcase(os.path.abspath(child)), os.path.normcase(os.path.abspath(parent)) + return c != p and c.startswith(p.rstrip(os.sep) + os.sep) + + +def _write_test(folder: Path) -> str | None: + """None when files can be written in ``folder`` (made if missing); else the raw refusal.""" + try: + folder.mkdir(parents=True, exist_ok=True) + fd, name = tempfile.mkstemp(prefix=".strata-write-test", dir=folder) + os.close(fd) + os.remove(name) + return None + except OSError as e: + return f"{errno.errorcode.get(e.errno, e.errno)}: {e.strerror or e}, {e.filename or folder}" + + +# ----------------------------------------------------------------------------------------------- plan + +def plan(old: Path, new: Path, *, free=None, write_test: bool = True) -> dict: + """What picking ``new`` for the models folder means, without changing anything. + + Returns ``{ok, issue, old, new, same, same_drive, free_bytes, models_bytes, needed_bytes, models, choices}``. ``issue`` is None or + ``{code, message, details}``: not_found (the folder or its drive is gone), not_writable, inside (one folder inside the other), + same (nothing to do). ``choices`` says which of move / keep / empty can be done and why not. + """ + old, new = Path(old), Path(new) + free = free or (lambda p: shutil.disk_usage(p).free) + entries = inventory(old) if old.is_dir() else [] + total = sum(e.size for e in entries) + result = {"ok": False, "issue": None, "old": str(old), "new": str(new), "same": False, "same_drive": False, "free_bytes": 0, + "models_bytes": total, "needed_bytes": 0, "models": groups(entries), "choices": {}} + + def refuse(code, message, details=""): + result["issue"] = {"code": code, "message": message, "details": details} + result["choices"] = {k: {"possible": False, "reason": message} for k in ("move", "keep", "empty")} + return result + + if _same(old, new): + result["same"] = True + return refuse("same", "That is the folder Strata already uses.") + if _inside(new, old) or _inside(old, new): + return refuse("inside", "Pick a folder outside the current one.") + if not new.exists(): + # a folder that will be made is fine when its parent is there; a drive that is not plugged in is not + drive = Path(new.anchor) if new.anchor else None + if drive is not None and not drive.exists(): + return refuse("not_found", f"Strata can't find {new}.", f"{drive} does not exist") + if write_test: + raw = _write_test(new) + if raw: + return refuse("not_writable", f"Strata can't save files in {new}.", raw) + result["same_drive"] = same_drive(old, new) + try: + result["free_bytes"] = int(free(_near(new))) + except OSError: + result["free_bytes"] = 0 + # a same-drive move is a rename: it needs no room + needed = 0 if result["same_drive"] else int(total * MARGIN) + result["needed_bytes"] = needed + can_move = bool(entries) and result["free_bytes"] >= needed + reason_move = "" if can_move else ("You have no models to move." if not entries + else f"Your models need {_gb(needed)}, this drive has {_gb(result['free_bytes'])} free.") + result["choices"] = {"move": {"possible": can_move, "reason": reason_move}, "keep": {"possible": True, "reason": ""}, + "empty": {"possible": True, "reason": ""}} + result["ok"] = True + return result + + +def _gb(n: int) -> str: + g = n / 1e9 + return f"{g:.0f} GB" if g >= 10 else f"{g:.1f} GB" + + +# ----------------------------------------------------------------------------------------------- the move + +def _sha256_of(path: Path, stop: Callable[[], bool], tick: Callable[[int], None] | None = None) -> str: + h = hashlib.sha256() + with open(path, "rb") as f: + while True: + if stop(): + raise Stopped() + block = f.read(CHUNK) + if not block: + break + h.update(block) + if tick: + tick(len(block)) + return h.hexdigest() + + +def _pinned(src: Path) -> str | None: + """The SHA-256 a finished download wrote in its ``.done`` mark (setup.py: ``sha256 ``), when there is one.""" + mark = src.with_name(src.name + ".done") + try: + m = re.search(r"sha256\s+([0-9a-fA-F]{64})", mark.read_text(encoding="utf-8", errors="replace")) + except OSError: + return None + return m.group(1).lower() if m else None + + +def _disk_full(e: OSError) -> bool: + return e.errno in (errno.ENOSPC, errno.EDQUOT) or getattr(e, "winerror", None) in (112, 39) + + +def _copy_verified(src: Path, dst: Path, size: int, stop: Callable[[], bool], tick: Callable[[int], None]) -> None: + """Copy src to dst (through dst.part), prove the copy is the same file, rename it into place. The source is left alone.""" + part = dst.with_name(dst.name + ".part") + dst.parent.mkdir(parents=True, exist_ok=True) + h = hashlib.sha256() + try: + with open(src, "rb") as fin, open(part, "wb") as fout: + while True: + if stop(): + raise Stopped() + block = fin.read(CHUNK) + if not block: + break + h.update(block) + fout.write(block) + tick(len(block)) + fout.flush() + os.fsync(fout.fileno()) + if part.stat().st_size != size: + raise MoveError("verify", f"The copy of {src.name} has the wrong size.", f"{part.stat().st_size} != {size}") + want = h.hexdigest() + pinned = _pinned(src) + if pinned and pinned != want: + raise MoveError("verify", f"{src.name} does not match its saved checksum, so it was not moved.", f"sha256 {want} != pinned {pinned}") + got = _sha256_of(part, stop) + if got != want: + raise MoveError("verify", f"The copy of {src.name} did not match the original.", f"sha256 {got} != {want}") + os.replace(part, dst) + except OSError as e: + _quiet_remove(part) + if _disk_full(e): + raise MoveError("disk_full", "The drive ran out of space.", f"{errno.errorcode.get(e.errno, e.errno)}: {e.strerror}, {e.filename or dst}") from e + raise MoveError("io", f"Strata could not copy {src.name}.", f"{type(e).__name__}: {e}") from e + except BaseException: + _quiet_remove(part) + raise + + +def _quiet_remove(path: Path) -> None: + try: + os.remove(path) + except OSError: + pass + + +def _read_state(new: Path) -> dict: + try: + return json.loads((new / STATE_FILE).read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + + +def interrupted(data: Path) -> dict | None: + """The unfinished move recorded in a data folder (``models-move.json``), for 'A move was interrupted'.""" + st = _read_state(data) + return st if st.get("state") == "running" else None + + +def _write_state(new: Path, **fields) -> None: + try: + tmp = new / (STATE_FILE + ".tmp") + tmp.write_text(json.dumps(fields, indent=1), encoding="utf-8") + os.replace(tmp, new / STATE_FILE) + except OSError: + pass + + +def repoint_config(cfg_file: Path, old: Path, new: Path) -> bool: + """A run config whose model files moved from ``old`` to ``new`` names them there (each path only when its file is now there and no longer + at the old place). Same rule as setup.py repoint_config. Returns whether the file changed.""" + try: + cfg = json.loads(cfg_file.read_text(encoding="utf-8-sig")) + except (OSError, ValueError): + return False + + def fix(v): + if isinstance(v, list): + return [fix(x) for x in v] + if isinstance(v, dict): + return {k: fix(x) for k, x in v.items()} + if isinstance(v, str): + o = str(old) + nv, no = os.path.normcase(v), os.path.normcase(o) + if nv.startswith(no + os.sep) or nv.startswith(no + "/"): + rest = v[len(o):] + if re.split(r"[\\/]", rest.lstrip("\\/"))[0].lower() in ITEMS: + n = str(new) + rest + if Path(n).exists() and not Path(v).exists(): + return n + return v + + fixed = fix(cfg) + if fixed == cfg: + return False + tmp = cfg_file.with_name(cfg_file.name + ".move-tmp") + tmp.write_text(json.dumps(fixed, indent=2) + "\n", encoding="utf-8") + os.replace(tmp, cfg_file) + return True + + +def config_files(install: Path | None) -> list[Path]: + """The ``strata-.json`` run configs of an install folder.""" + if not install or not Path(install).is_dir(): + return [] + return [p for p in Path(install).glob("strata-*.json") if not p.name.endswith(".shared-settings.json")] + + +def _prune(folder: Path, stop_at: Path) -> None: + """Remove empty folders from ``folder`` upward, never ``stop_at`` itself.""" + p = folder + while p != stop_at and _inside(p, stop_at): + try: + p.rmdir() + except OSError: + return + p = p.parent + + +def move(old: Path, new: Path, *, on_progress: Callable[[dict], None] | None = None, cancelled: Callable[[], bool] | None = None, + configs: list[Path] | None = None, now: Callable[[], float] = time.time) -> dict: + """Move the model files from ``old`` to ``new``. Returns the summary; raises MoveError (nothing lost) or Stopped. + + ``summary = {done: bool, stopped: bool, moved: [group], remaining: [group], bytes_moved, total_bytes, files_moved, same_drive}``. + """ + old, new = Path(old), Path(new) + emit = on_progress or (lambda _e: None) + stop = cancelled or (lambda: False) + p = plan(old, new, write_test=True) + if p["issue"]: + raise MoveError(p["issue"]["code"], p["issue"]["message"], p["issue"]["details"]) + entries = inventory(old) + total = sum(e.size for e in entries) + if not p["choices"]["move"]["possible"] and entries: + raise MoveError("disk_full", p["choices"]["move"]["reason"]) + # unfinished copies of an earlier run are never trusted + for top in _item_dirs(new): + for root, _d, files in os.walk(top): + for name in files: + if name.endswith(".part"): + _quiet_remove(Path(root) / name) + same = p["same_drive"] + todo = {e.group: [] for e in entries} + for e in entries: + todo[e.group].append(e) + left = {g: len(v) for g, v in todo.items()} + moved_groups: list[str] = [] + state = {"state": "running", "from": str(old), "to": str(new), "started": now(), "bytes": total} + _write_state(new, **state) + done_bytes = 0 + files_moved = 0 + last_emit = [0.0] + started = now() + seen_inodes: dict[tuple, Path] = {} + base_event = lambda **kw: {"event": "progress", "total": total, "same_drive": same, **kw} + + def progress(current: str, group: str, index: int, force: bool = False): + t = now() + if not force and t - last_emit[0] < 0.25: + return + last_emit[0] = t + rate = done_bytes / max(t - started, 0.001) + emit(base_event(done=done_bytes, file=current, group=group, index=index, count=len(entries), + seconds_left=(int((total - done_bytes) / rate) if rate > 0 and not same else 0))) + + def repoint(only_whole: bool = True): + for cfg in (configs or []): + try: + repoint_config(cfg, old, new) + except OSError: + pass + + try: + for index, e in enumerate(entries, 1): + if stop(): + raise Stopped() + src, dst = old / e.rel, new / e.rel + progress(e.rel, e.group, index, force=True) + if not src.exists(): + done_bytes += e.size + left[e.group] -= 1 + else: + if same: + dst.parent.mkdir(parents=True, exist_ok=True) + try: + if dst.exists(): + os.remove(dst) + os.replace(src, dst) + except OSError as err: + raise MoveError("io", f"Strata could not move {src.name}.", f"{type(err).__name__}: {err}") from err + done_bytes += e.size + else: + ino = None + try: + st = src.stat() + ino = (st.st_dev, st.st_ino) if st.st_nlink > 1 and st.st_ino else None + except OSError: + pass + if ino and ino in seen_inodes and seen_inodes[ino].exists(): + # the same file under two names (a shared pack): one copy, the second name links to it + try: + dst.parent.mkdir(parents=True, exist_ok=True) + if dst.exists(): + os.remove(dst) + os.link(seen_inodes[ino], dst) + except OSError: + _copy_verified(src, dst, e.size, stop, lambda n: None) + done_bytes += e.size + else: + resumed = False + if dst.exists() and dst.stat().st_size == e.size: + # a crash between the rename and the delete: the copy may be whole; prove it before the original goes + resumed = _sha256_of(dst, stop) == _sha256_of(src, stop) + if resumed: + done_bytes += e.size + else: + def tick(n, group=e.group, rel=e.rel, idx=index): + nonlocal done_bytes + done_bytes += n + progress(rel, group, idx) + before = done_bytes + try: + _copy_verified(src, dst, e.size, stop, tick) + except BaseException: + done_bytes = before + raise + if ino: + seen_inodes[ino] = dst + try: + os.remove(src) + except OSError as err: + raise MoveError("io", f"Strata copied {src.name} but could not remove the old copy.", f"{type(err).__name__}: {err}") from err + _prune(src.parent, old) + files_moved += 1 + left[e.group] -= 1 + if left[e.group] == 0: + moved_groups.append(e.group) + repoint() + repoint() + state.update(state="done", finished=now()) + _write_state(new, **state) + _quiet_remove(new / STATE_FILE) + return {"done": True, "stopped": False, "moved": moved_groups, "remaining": [], "bytes_moved": done_bytes, "total_bytes": total, + "files_moved": files_moved, "same_drive": same} + except Stopped: + repoint() + state.update(state="stopped") + _write_state(new, **state) + _quiet_remove(new / STATE_FILE) if not moved_groups and not files_moved else None + remaining = [g for g, n in left.items() if n > 0] + return {"done": False, "stopped": True, "moved": moved_groups, "remaining": remaining, "bytes_moved": done_bytes, "total_bytes": total, + "files_moved": files_moved, "same_drive": same} + except MoveError as err: + repoint() + state.update(state="failed", error=err.code) + _write_state(new, **state) + err.summary = {"moved": moved_groups, "remaining": [g for g, n in left.items() if n > 0], "bytes_moved": done_bytes, "total_bytes": total, + "files_moved": files_moved} + raise diff --git a/tests/terminal/test_models_move.py b/tests/terminal/test_models_move.py new file mode 100644 index 00000000..80a1408b --- /dev/null +++ b/tests/terminal/test_models_move.py @@ -0,0 +1,283 @@ +"""Moving the models to another folder (strata models move): same drive, another drive, stop, a failed check, disk full, resume.""" +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from strata_control import models_move as mm + + +def sha(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +class MoveCase(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix="strata-move-") + self.addCleanup(self.tmp.cleanup) + self.base = Path(self.tmp.name) + self.old = self.base / "old" + self.new = self.base / "new" + self.files = { + "models/gyro-s/a.gguf": b"A" * 300_000, + "models/gyro-s/b.gguf": b"B" * 200_000, + "packs/gyro-s/dense.bin": b"D" * 100_000, + "models/coder/c.gguf": b"C" * 150_000, + "mtp/rt/experts.bin": b"M" * 50_000, + } + for rel, data in self.files.items(): + f = self.old / rel + f.parent.mkdir(parents=True, exist_ok=True) + f.write_bytes(data) + # a finished download carries the pinned checksum in its mark + (self.old / "models/gyro-s/a.gguf.done").write_text(f"done sha256 {sha(self.files['models/gyro-s/a.gguf'])}\n") + (self.old / "notes.txt").write_text("not a model file") # Strata moves its own folders only + self.install = self.base / "install" + self.install.mkdir() + self.config = self.install / "strata-gyro-s.json" + self.config.write_text(json.dumps({"args": ["--native", str(self.old / "models/gyro-s/a.gguf"), "--pack", str(self.old / "packs/gyro-s")], + "mtp": str(self.old / "mtp/rt")})) + self.total = sum(len(v) for v in self.files.values()) + + def tree(self, root: Path) -> set[str]: + return {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file() and p.name != mm.STATE_FILE} + + def copy_mode(self): + """Another drive: the files are copied, whatever this machine's volumes are.""" + return mock.patch.object(mm, "same_drive", return_value=False) + + def run_move(self, **kw): + events = [] + summary = mm.move(self.old, self.new, on_progress=events.append, configs=[self.config], **kw) + return summary, events + + +class PlanTests(MoveCase): + def test_plan_numbers_and_choices(self): + with self.copy_mode(): + p = mm.plan(self.old, self.new, free=lambda _p: 10**9) + self.assertTrue(p["ok"]) + self.assertGreaterEqual(p["models_bytes"], self.total) + self.assertGreater(p["needed_bytes"], p["models_bytes"]) # the 5 % margin + self.assertTrue(p["choices"]["move"]["possible"]) + self.assertEqual({m["name"] for m in p["models"]}, {"gyro-s", "coder", "mtp"}) + + def test_not_enough_room_switches_move_off(self): + with self.copy_mode(): + p = mm.plan(self.old, self.new, free=lambda _p: 1000) + self.assertTrue(p["ok"]) + self.assertFalse(p["choices"]["move"]["possible"]) + self.assertIn("free", p["choices"]["move"]["reason"]) + self.assertTrue(p["choices"]["keep"]["possible"] and p["choices"]["empty"]["possible"]) + + def test_same_drive_needs_no_room(self): + p = mm.plan(self.old, self.new, free=lambda _p: 0) + self.assertTrue(p["same_drive"]) + self.assertTrue(p["choices"]["move"]["possible"]) + + def test_inside_and_same_are_refused(self): + self.assertEqual(mm.plan(self.old, self.old / "sub")["issue"]["code"], "inside") + self.assertEqual(mm.plan(self.old / "sub", self.old)["issue"]["code"], "inside") + self.assertEqual(mm.plan(self.old, self.old)["issue"]["code"], "same") + + def test_a_folder_that_cannot_be_written_is_refused(self): + with mock.patch.object(mm, "_write_test", return_value="EPERM: operation not permitted, mkdir 'x'"): + p = mm.plan(self.old, self.new) + self.assertEqual(p["issue"]["code"], "not_writable") + self.assertIn("EPERM", p["issue"]["details"]) + + def test_nothing_is_changed_by_a_plan(self): + before = self.tree(self.old) + mm.plan(self.old, self.new) + self.assertEqual(self.tree(self.old), before) + + +class MoveTests(MoveCase): + def check_whole(self): + self.assertEqual({k for k in self.tree(self.new) if not k.endswith(".done")}, set(self.files)) + for rel, data in self.files.items(): + self.assertEqual((self.new / rel).read_bytes(), data) + self.assertEqual(self.tree(self.old), {"notes.txt"}) # only what is not Strata's own is left + cfg = json.loads(self.config.read_text()) + self.assertEqual(Path(cfg["args"][1]), self.new / "models/gyro-s/a.gguf") + self.assertEqual(Path(cfg["mtp"]), self.new / "mtp/rt") + self.assertFalse((self.new / mm.STATE_FILE).exists()) + + def test_same_drive_is_a_rename(self): + with mock.patch.object(shutil, "copyfileobj", side_effect=AssertionError("copied")), mock.patch.object(mm, "_copy_verified", side_effect=AssertionError("copied")): + summary, _events = self.run_move() + self.assertTrue(summary["done"] and summary["same_drive"]) + self.check_whole() + + def test_another_drive_copies_checks_and_removes(self): + with self.copy_mode(): + summary, events = self.run_move() + self.assertTrue(summary["done"] and not summary["same_drive"]) + self.assertEqual(summary["files_moved"], len(self.files) + 1) # + the .done mark + self.check_whole() + self.assertTrue(events and events[-1]["done"] <= self.total + 100) + self.assertEqual(events[0]["event"], "progress") + + def test_stop_keeps_what_moved_and_removes_the_partial_copy(self): + calls = {"n": 0} + + def stop(): + calls["n"] += 1 + return calls["n"] > 6 # a few chunks into the second file or so + with self.copy_mode(): + summary, _events = self.run_move(cancelled=stop) + self.assertTrue(summary["stopped"] and not summary["done"]) + self.assertEqual([p for p in self.new.rglob("*.part")], []) + # every file is in exactly one place, nothing is lost + for rel, data in self.files.items(): + places = [r for r in (self.old, self.new) if (r / rel).exists()] + self.assertEqual(len(places), 1, rel) + self.assertEqual((places[0] / rel).read_bytes(), data) + self.assertTrue(summary["remaining"]) + # a model that moved whole now points at the new folder; one that did not stays where it is + cfg = json.loads(self.config.read_text()) + for value in (cfg["args"][1], cfg["args"][3], cfg["mtp"]): + self.assertTrue(Path(value).exists(), value) + + def test_stop_before_anything_leaves_the_old_folder_as_it_was(self): + with self.copy_mode(): + summary, _ = self.run_move(cancelled=lambda: True) + self.assertTrue(summary["stopped"]) + self.assertEqual(summary["files_moved"], 0) + self.assertEqual({k for k in self.tree(self.old) if not k.endswith(".done")}, set(self.files) | {"notes.txt"}) + self.assertFalse((self.new / mm.STATE_FILE).exists()) + + def test_a_copy_that_does_not_match_is_never_trusted(self): + real = mm._sha256_of + calls = {"n": 0} + + def lies(path, stop, tick=None): + calls["n"] += 1 + return "0" * 64 if str(path).endswith(".part") and calls["n"] == 1 else real(path, stop, tick) + with self.copy_mode(), mock.patch.object(mm, "_sha256_of", side_effect=lies): + with self.assertRaises(mm.MoveError) as caught: + self.run_move() + self.assertEqual(caught.exception.code, "verify") + self.assertEqual(list(self.new.rglob("*.part")), []) + self.assertEqual({k for k in self.tree(self.old) if not k.endswith(".done")}, set(self.files) | {"notes.txt"}) # the original is untouched + + def test_a_file_that_differs_from_its_pinned_checksum_is_not_moved(self): + (self.old / "models/gyro-s/a.gguf.done").write_text("done sha256 " + "1" * 64) + with self.copy_mode(): + with self.assertRaises(mm.MoveError) as caught: + self.run_move() + self.assertEqual(caught.exception.code, "verify") + self.assertTrue((self.old / "models/gyro-s/a.gguf").exists()) + self.assertFalse((self.new / "models/gyro-s/a.gguf").exists()) + + def test_disk_full_stops_at_once_and_loses_nothing(self): + real = mm._copy_verified + seen = {"n": 0} + + def full(src, dst, size, stop, tick): + seen["n"] += 1 + if seen["n"] == 3: + part = dst.with_name(dst.name + ".part") + part.parent.mkdir(parents=True, exist_ok=True) + part.write_bytes(b"half") + try: + raise OSError(28, "No space left on device", str(dst)) + except OSError as e: + mm._quiet_remove(part) + raise mm.MoveError("disk_full", "The drive ran out of space.", str(e)) from e + return real(src, dst, size, stop, tick) + with self.copy_mode(), mock.patch.object(mm, "_copy_verified", side_effect=full): + with self.assertRaises(mm.MoveError) as caught: + self.run_move() + self.assertEqual(caught.exception.code, "disk_full") + self.assertEqual(list(self.new.rglob("*.part")), []) + for rel, data in self.files.items(): + places = [r for r in (self.old, self.new) if (r / rel).exists()] + self.assertEqual(len(places), 1, rel) + self.assertIn("remaining", caught.exception.summary) + + def test_a_real_disk_full_error_is_named(self): + with mock.patch("builtins.open", side_effect=OSError(28, "No space left on device", "x")): + with self.assertRaises(mm.MoveError) as caught: + mm._copy_verified(self.old / "models/coder/c.gguf", self.new / "x.gguf", 1, lambda: False, lambda n: None) + self.assertEqual(caught.exception.code, "disk_full") + + def test_a_crash_leaves_a_part_and_the_next_run_finishes(self): + stale = self.new / "models/gyro-s/a.gguf.part" + stale.parent.mkdir(parents=True) + stale.write_bytes(b"cut off") + # a file that was copied and renamed, but whose original was not removed yet + done = self.new / "models/coder/c.gguf" + done.parent.mkdir(parents=True) + done.write_bytes(self.files["models/coder/c.gguf"]) + with self.copy_mode(): + summary, _ = self.run_move() + self.assertTrue(summary["done"]) + self.check_whole() + + def test_an_interrupted_move_is_remembered(self): + with self.copy_mode(): + with self.assertRaises(mm.MoveError): + with mock.patch.object(mm, "_copy_verified", side_effect=mm.MoveError("io", "x")): + self.run_move() + self.assertEqual(mm.interrupted(self.new), None) # failed is not "running" + mm._write_state(self.new, state="running", **{"from": str(self.old), "to": str(self.new)}) + self.assertEqual(mm.interrupted(self.new)["from"], str(self.old)) + + def test_configs_are_rewritten_only_for_files_that_are_there(self): + self.config.write_text(json.dumps({"args": ["--native", str(self.old / "models/gone.gguf")]})) + with self.copy_mode(): + self.run_move() + self.assertEqual(json.loads(self.config.read_text())["args"][1], str(self.old / "models/gone.gguf")) + + @unittest.skipUnless(os.environ.get("STRATA_TEST_OTHER_VOLUME"), "set STRATA_TEST_OTHER_VOLUME to a folder on another volume (e.g. a subst or USB drive)") + def test_a_real_second_volume(self): + other = Path(os.environ["STRATA_TEST_OTHER_VOLUME"]) / f"strata-move-{os.getpid()}" + self.addCleanup(shutil.rmtree, other, True) + self.new = other + summary, _ = self.run_move() + self.assertTrue(summary["done"]) + self.check_whole() + + +class CommandLineTests(MoveCase): + def test_json_plan_and_run(self): + from strata_cli import cli + import contextlib + import io + out = io.StringIO() + with contextlib.redirect_stdout(out), self.copy_mode(): + code = cli.main(["models", "move", str(self.new), "--from", str(self.old), "--plan", "--output", "json"]) + self.assertEqual(code, 0) + self.assertTrue(json.loads(out.getvalue())["plan"]["choices"]["move"]["possible"]) + out = io.StringIO() + with contextlib.redirect_stdout(out), self.copy_mode(): + code = cli.main(["models", "move", str(self.new), "--from", str(self.old), "--install-dir", str(self.install), "--output", "jsonl"]) + self.assertEqual(code, 0, out.getvalue()) + lines = [json.loads(line) for line in out.getvalue().splitlines() if line.startswith("{")] + self.assertEqual(lines[-1]["event"], "result") + self.assertTrue(lines[-1]["done"]) + self.assertTrue((self.new / "models/coder/c.gguf").exists()) + + def test_the_cancel_file_stops_the_run(self): + from strata_cli import cli + import contextlib + import io + cancel = self.base / "cancel" + cancel.write_text("x") + out = io.StringIO() + with contextlib.redirect_stdout(out), self.copy_mode(): + code = cli.main(["models", "move", str(self.new), "--from", str(self.old), "--cancel-file", str(cancel), "--output", "json"]) + self.assertEqual(code, 6) + self.assertTrue(json.loads(out.getvalue().splitlines()[-1])["stopped"]) + self.assertTrue((self.old / "models/coder/c.gguf").exists()) + + +if __name__ == "__main__": + unittest.main() From 1d6a040129ac0a11ff822ca372f55ab94dfd58cc Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:29:44 +0200 Subject: [PATCH 2/3] Settings > Storage: Models folder card with the three choices (move, keep, start empty), progress, stop, and plain errors; host routes and Control calls; 78 strings in 8 languages; tests --- apps/host/server/control-runtime.mjs | 17 ++ apps/host/server/index.mjs | 10 +- apps/host/server/native-control.mjs | 80 +++++- .../src/components/ModelsFolderDialog.tsx | 230 ++++++++++++++++++ apps/host/src/components/SettingsStorage.tsx | 3 + apps/host/src/components/ui.tsx | 6 +- apps/host/src/lib/native.ts | 2 +- apps/host/src/locales/de.json | 80 +++++- apps/host/src/locales/en.json | 80 +++++- apps/host/src/locales/es.json | 80 +++++- apps/host/src/locales/ja.json | 80 +++++- apps/host/src/locales/ko.json | 80 +++++- apps/host/src/locales/pt.json | 80 +++++- apps/host/src/locales/ru.json | 80 +++++- apps/host/src/locales/zh.json | 80 +++++- apps/host/src/styles/annotation-fixes.css | 22 ++ apps/host/tests/models-folder.test.mjs | 161 ++++++++++++ 17 files changed, 1153 insertions(+), 18 deletions(-) create mode 100644 apps/host/src/components/ModelsFolderDialog.tsx create mode 100644 apps/host/tests/models-folder.test.mjs diff --git a/apps/host/server/control-runtime.mjs b/apps/host/server/control-runtime.mjs index 6f352b54..0447572d 100644 --- a/apps/host/server/control-runtime.mjs +++ b/apps/host/server/control-runtime.mjs @@ -207,6 +207,23 @@ export function createControl({ control = findControl(), env = process.env, run if (result.json?.plan && Array.isArray(result.json.plan.issues)) return result.json.plan; throw failure(result, 'The files could not be checked.'); }, + /** What picking `to` as the models folder means (sizes, free space, which choices are possible, why not): nothing is changed. */ + async planModelsMove(from, to) { + const result = await call(['models', 'move', to, ...(from ? ['--from', from] : []), '--plan', '--output', 'json'], { timeoutMs: 120_000 }); + if (result.json?.plan) return result.json.plan; + throw failure(result, 'The folder could not be checked.'); + }, + /** + * Move the model files to `to` (copied, checked, then the old copies removed). `onEvent` gets the progress lines; a file at `cancelFile` stops it + * safely. Resolves with the summary (done / stopped, what moved, what is left); a failure is a ControlError whose `output` carries the details. + */ + async moveModels(from, to, { installDir = null, cancelFile = null, onEvent = null } = {}) { + const args = ['models', 'move', to, ...(from ? ['--from', from] : []), ...(installDir ? ['--install-dir', installDir] : []), ...(cancelFile ? ['--cancel-file', cancelFile] : []), '--output', 'jsonl']; + const result = await call(args, { timeoutMs: 24 * 3600_000, onLine: onEvent ?? (() => {}) }); + if (result.json?.ok && result.json.event === 'result') return result.json; + const error = result.json?.error; + throw Object.assign(new ControlError(error?.message ?? (result.stderr.split(/\r?\n/).filter(Boolean).pop() || 'The models could not be moved.'), { exitCode: result.code, output: result.json }), { code: error?.code ?? 'move_failed', details: error?.details ?? '' }); + }, async saveProfile(name, configPath) { const listed = await call(['profile', 'list', '--output', 'json'], { timeoutMs: 20_000 }); const known = (listed.json?.profiles ?? []).some(p => p.id === name); diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 30a5557a..eb454cb4 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -966,6 +966,14 @@ async function api(req, res, path, method, url) { if(path==='/api/native'&&method==='GET')return json(res,200,await native.refresh(url.searchParams.get('refresh')==='1')); if(path==='/api/native'&&method==='PATCH')return json(res,200,await native.configure(await readBody(req))); if(path==='/api/native/directory'&&method==='POST')return json(res,200,native.setDownloadDirectory((await readBody(req)).directory)); + /* Settings > Storage > Models folder: pick (or type) a folder, say what it means, then start the choice. Copying is Control's (strata models move). */ + if(path==='/api/native/models-folder/plan'&&method==='POST'){ + const typed=await typedFolder((await readBody(req)).path,{isAbsolute}); + const picked=typed?{path:typed}:await chooseFolder('Choose a folder for your models'); + if(picked.unavailable){const u=chooserUnavailable(picked);return error(res,501,u.message,{code:u.code});} + if(picked.cancelled)return json(res,200,{cancelled:true}); + return json(res,200,{plan:await native.planModelsFolder(picked.path)});} + if(path==='/api/native/models-folder/start'&&method==='POST'){const body=await readBody(req);const result=await native.startModelsFolder({folder:body.path,choice:body.choice,stopRunning:body.stopRunning===true});return json(res,result.id?202:200,result);} if(path==='/api/native/plan'&&method==='POST')return json(res,200,await native.plan(await readBody(req))); if(path==='/api/native/operations'&&method==='POST'){if(storageChanging)return error(res,409,'Wait for the model folder check to finish.');const body=await readBody(req);return json(res,202,native.operation(body.kind,body.args));} if(path==='/api/native/logs'&&method==='GET')return json(res,200,{logs:native.logs()}); @@ -1010,7 +1018,7 @@ async function api(req, res, path, method, url) { if(nativeSettingsFile&&method==='POST')return json(res,200,await native.openSettingsFile(nativeSettingsFile[1])); // Credentials are handled only on the host. Responses and events expose a key-set flag. - return error(res,404,'Unknown native control action.');}catch(e){return error(res,/Finish|Unload|running|current operation/.test(e.message)?409:400,e.message);}} + return error(res,404,'Unknown native control action.');}catch(e){return error(res,/Finish|Unload|running|current operation/.test(e.message)?409:400,e.message,{...(e.code&&typeof e.code==='string'?{code:e.code}:{}),...(e.details?{details:String(e.details)}:{})});}} if (path === '/api/model-providers' && method === 'GET') return json(res, 200, withPictureAnswers(modelProviders.list())); if (path === '/api/model-providers/discover' && method === 'POST') { diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 618abeed..75f7c0ce 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -2,8 +2,8 @@ import { spawn } from 'node:child_process'; import {chooseParallel,applyParallel,withoutParallel,FALLBACK_NOTE} from './native-parallel.mjs'; import { randomBytes, randomUUID, createHash } from 'node:crypto'; -import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, realpathSync, copyFileSync, renameSync, unlinkSync, chmodSync, statSync, accessSync, constants } from 'node:fs'; -import { join, resolve, dirname, basename } from 'node:path'; +import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, realpathSync, copyFileSync, renameSync, rmSync, statfsSync, unlinkSync, chmodSync, statSync, accessSync, constants } from 'node:fs'; +import { join, resolve, dirname, basename, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; import { createServer } from 'node:net'; import { NATIVE_FIELDS, APP_OWNED_FIELDS, withoutDraftLayer, validateNativeSettings, validateMcpServers, publicMcpServers, publicNativeEnv, restoreNativeEnv } from './native-settings.mjs'; @@ -52,7 +52,8 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp let defaultId=null,timer=null,closing=false,polling=false; const emit=()=>{const value=state();writeFileSync(join(directory,'native-jobs.json'),JSON.stringify(value.jobs),{mode:0o600});changed(value);}; const append=(instanceId,line)=>{logs.push({at:new Date().toISOString(),instanceId,line:String(line).slice(0,2000)});if(logs.length>400)logs.shift();}; - function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,mcpServers,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,engineAbort,rawResult,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),componentUpdates:packaged&&typeof control.update==='function',calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};} + function diskSpace(path){try{const s=statfsSync(path);return {free:Number(s.bavail)*Number(s.bsize),total:Number(s.blocks)*Number(s.bsize)};}catch{return null;}} + function state(){const folder=preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),space=folder?diskSpace(folder):null;return {...snapshot,downloadDirectory:folder,downloadFreeBytes:space?.free??null,downloadTotalBytes:space?.total??null,fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,mcpServers,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,engineAbort,rawResult,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),componentUpdates:packaged&&typeof control.update==='function',calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};} let sourceCache={path:'',time:0,text:''}; function sourceText(){try{const path=join(packaged?control.control.dir:preferences.repo,'serve/server.py'),time=statSync(path).mtimeMs;if(sourceCache.path===path&&sourceCache.time===time)return sourceCache.text;sourceCache={path,time,text:readFileSync(path,'utf8')};return sourceCache.text;}catch{return '';}} function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:APP_OWNED_FIELDS.includes(field.id)||field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));} @@ -126,7 +127,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);let visionReader=false;if(packaged){try{const e=await control.engine();const root=e?.engine?.root??(e?.engine?.exe?dirname(e.engine.exe):'');visionReader=!!root&&['strata-vision','strata-vision.exe'].some(n=>existsSync(join(root,n)));}catch{visionReader=false;}}const markImages=c=>c&&Array.isArray(c.families)?{...c,families:c.families.map(f=>({...f,imagesCapable:!!f.images,images:!!f.images&&visionReader,sizes:(f.sizes??[]).map(s=>({...s,imagesCapable:!!s.images,images:!!s.images&&visionReader}))}))}:c;snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog:markEngine(packaged?markImages(catalog):catalog,status.engine),engineInfo:{version:status.engine?.version??null,source:status.engine?.source??null},visionReader:packaged?visionReader:true,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});const run=refreshing;if(!force&&snapshot.available){run.catch(()=>{});return state();}return run; } function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};packagedInstall=null;disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);} - function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');let path;try{path=realpathSync(input.trim());}catch{throw new Error('That folder does not exist. Check the path, or that the drive is connected.');}if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');/* A whole drive (D:\) is not filled with models: D:\Strata is made and used. */if(isDriveRoot(path)){const own=dataFolderFromPick(path).path;makeFolder(own);path=realpathSync(own);}try{accessSync(path,constants.R_OK|constants.W_OK);}catch{throw new Error('Strata cannot write in that folder. Choose a folder you can save files in.');}preferences={...preferences,downloadDirectory:path};/* the same choice for the installer and the Terminal: the Control settings file */if(packaged)rememberDataFolder(controlSettingsFile(),path,Date.now()/1000,true);writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});shareDataFolder();emit();return state();} + function setDownloadDirectory(input,{insideJob=false}={}){if(!insideJob&&[...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');let path;try{path=realpathSync(input.trim());}catch{throw new Error('That folder does not exist. Check the path, or that the drive is connected.');}if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');/* A whole drive (D:\) is not filled with models: D:\Strata is made and used. */if(isDriveRoot(path)){const own=dataFolderFromPick(path).path;makeFolder(own);path=realpathSync(own);}try{accessSync(path,constants.R_OK|constants.W_OK);}catch{throw new Error('Strata cannot write in that folder. Choose a folder you can save files in.');}preferences={...preferences,downloadDirectory:path};/* the same choice for the installer and the Terminal: the Control settings file */if(packaged)rememberDataFolder(controlSettingsFile(),path,Date.now()/1000,true);writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});shareDataFolder();emit();return state();} function recordFile(model){if(!safeId(model))throw new Error('Choose an installed model.');const entry=snapshot.installed?.models?.find(i=>i.model===model);if(!entry)throw new Error('This model is not installed. Download and prepare it first.');const path=realpathSync(entry.configPath??join(repo(),entry.config));if(dirname(path)!==repo()||!/^strata-[a-z0-9_-]+\.json$/i.test(basename(path)))throw new Error('The model configuration is outside the Strata installation.');return {entry,path};} function record(model){const {entry,path}=recordFile(model);return {entry,path,config:readJson(path)};} /* The text file a power user edits by hand: where it is and what is wrong in it (run-config-check.mjs). */ @@ -377,10 +378,77 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} return autotuner.start(job,job.kind==='recheck'?'recheck':'tune',{configPath:path,presetId:args.presetId,mode:args.mode,use:args.use,goal:room?'room':'speed',leaveRam:room?20:0,allowSmallDifferences:args.allowSmallDifferences===true,name:args.name},{onProgress:p=>{job.summary=p.text??job.summary;emit();}}); } function operation(kind,args={}){if(!['install','load','benchmark','tune','autotune','recheck','calibrate','update-engine','update-strata','rollback','remove'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');if(kind==='install'||kind==='load'){const refusal=engineRefusal(snapshot.catalog,args.model,snapshot.engineInfo);if(refusal)throw new Error(refusal);}return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):kind==='autotune'||kind==='recheck'?autotune(job,args):kind==='remove'?removeModel(job,args):program(job,args),{guided:args.guided===true,model:args.model,...(args.family?{family:args.family}:{})});} - async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install'){job.engineAbort?.abort();await tool('strata_install',{cancel:true});}else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate','autotune','recheck'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();} + /* ---- The models folder card (0.2.2): what a picked folder means, and the three choices. The copying is Control's (strata models move). ---- */ + const currentModelsFolder=()=>preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder)??null; + const moveFile=()=>join(directory,'models-move.cancel'); + const folderWords=error=>({message:error.message,details:error.details||''}); + /** A picked folder as the data folder: a whole drive (D:\) becomes D:\Strata, and the person is told (the models then live in D:\Strata\Models). */ + function pickedModelsFolder(input){ + if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a models folder.'); + const picked=resolve(input.trim()),target=dataFolderFromPick(picked); + return {picked,folder:target.path,wholeDrive:!!target.note,shown:target.note?join(target.path,'Models'):target.path}; + } + async function planModelsFolder(input){ + if(!packaged)throw new Error('Changing the models folder is part of the Strata app.'); + const now=currentModelsFolder();if(!now)throw new Error('Strata is still reading your models folder. Try again in a moment.'); + const pick=pickedModelsFolder(input),plan=await control.planModelsMove(now,pick.folder); + return {...plan,...pick,current:now,running:instances.size,busy:[...jobs.values()].some(j=>j.state==='running')}; + } + /* "Start empty": the old models are no longer listed. Their run configs are moved (not deleted) into old-models beside the others; the model files are not touched. */ + function setAsideConfigs(old){ + const folder=repo(),kept=join(folder,'old-models'),aside=[]; + const under=value=>typeof value==='string'&&[ 'models','packs','mtp' ].some(item=>{const base=join(old,item).toLowerCase();const v=value.toLowerCase();return v===base||v.startsWith(base+sep)||v.startsWith(base+'/');}); + const scan=value=>Array.isArray(value)?value.some(scan):value&&typeof value==='object'?Object.values(value).some(scan):under(value); + for(const name of readdirSync(folder)){ + if(!/^strata-[a-z0-9_-]+\.json$/i.test(name)||name.endsWith('.shared-settings.json'))continue; + if(!scan(readJson(join(folder,name))))continue; + mkdirSync(kept,{recursive:true});renameSync(join(folder,name),join(kept,name));aside.push(name); + } + return aside; + } + async function startModelsFolder({folder:input,choice,stopRunning=false}){ + if(!packaged)throw new Error('Changing the models folder is part of the Strata app.'); + if(!['move','keep','empty'].includes(choice))throw new Error('Choose what to do with your models.'); + if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or stop the download to change the folder.'); + const plan=await planModelsFolder(input); + if(plan.issue)throw Object.assign(new Error(plan.issue.message),{details:plan.issue.details,code:plan.issue.code}); + if(!plan.choices[choice].possible)throw Object.assign(new Error(plan.choices[choice].reason||'That choice is not possible here.'),{code:'not_possible'}); + if(instances.size){ + if(!stopRunning)throw Object.assign(new Error('A model is running. Stop it first, then change the folder.'),{code:'running'}); + for(const id of [...instances.keys()])await unload(id); + } + const old=plan.current,target=plan.folder; + if(choice!=='move'){ + makeFolder(target); + const aside=choice==='empty'?setAsideConfigs(old):[]; + setDownloadDirectory(target);lastRead=0;await refresh(true); + return {done:true,choice,folder:target,oldFolder:old,setAside:aside}; + } + rmSync(moveFile(),{force:true}); + return begin('models-move',async job=>{ + job.cancelFile=moveFile();job.summary='Starting…'; + try{ + const result=await control.moveModels(old,target,{installDir:repo(),cancelFile:moveFile(),onEvent:event=>{ + if(event.event!=='progress')return; + job.progress={done:event.done,total:event.total,file:event.file,group:event.group,index:event.index,count:event.count,secondsLeft:event.seconds_left||0,sameDrive:!!event.same_drive}; + job.summary=`${Math.round(event.done/1e8)/10} of ${Math.round(event.total/1e8)/10} GB`;emit();}}); + const finished={done:!!result.done,stopped:!!result.stopped,moved:result.moved??[],remaining:result.remaining??[],bytes:result.bytes_moved??0,total:result.total_bytes??0,from:old,to:target,files:result.files_moved??0,sameDrive:!!result.same_drive}; + /* Only a whole move changes the folder the app uses: a stopped move leaves it where it was, and every model works where it is. */ + if(result.done){setDownloadDirectory(target,{insideJob:true});finished.folder=target;} + job.progress=null; + return {summary:result.done?'Your models are moved.':'Moving stopped. Nothing was lost.',...finished}; + }catch(error){ + const left=error.output; + job.result={failed:true,code:error.code,moved:left?.moved??[],remaining:left?.remaining??[],bytes:left?.bytes_moved??0,total:left?.total_bytes??0,from:old,to:target}; + job.progress=null; + throw error; + }finally{rmSync(moveFile(),{force:true});} + },{family:undefined}); + } + async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install'){job.engineAbort?.abort();await tool('strata_install',{cancel:true});}else if(job.kind==='models-move'){/* a safe stop: the copy in flight is dropped, files already moved stay */try{writeFileSync(job.cancelFile,'stop');}catch{/* the run ends anyway */}job.summary='Stopping…';emit();return state();}else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate','autotune','recheck'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();} async function close(){closing=true;clearInterval(timer);const installing=packaged&&child&&[...jobs.values()].some(j=>j.kind==='install'&&j.state==='running');if(installing)await send('tools/call',{name:'strata_install',arguments:{cancel:true}},15000).catch(()=>{});const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();} // Remove nonserializable process references from public jobs. const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,engineAbort,rawResult,...job})=>job);return value;}; async function localPreview(path){if(!packaged)throw new Error('Checking local model files is part of the Strata app.');if(typeof path!=='string'||!path.trim()||[...path].some(c=>c.charCodeAt(0)<32))throw new Error('Choose a folder.');return control.importPlan(path.trim());} - return {state:publicState,tuneStatus,tuneEffective,tuneOff,tunePresets:{list:()=>autotuner.list(),action:(kind,id,extra)=>autotuner.action(kind,id,extra),undoFor:async args=>autotuner.undoFor(tuneConfig(args).path)},refresh,localPreview,configure,setDownloadDirectory,plan,settings,save,settingsFile,openSettingsFile,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close}; + return {state:publicState,tuneStatus,tuneEffective,tuneOff,tunePresets:{list:()=>autotuner.list(),action:(kind,id,extra)=>autotuner.action(kind,id,extra),undoFor:async args=>autotuner.undoFor(tuneConfig(args).path)},refresh,localPreview,configure,setDownloadDirectory,planModelsFolder,startModelsFolder,plan,settings,save,settingsFile,openSettingsFile,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close}; } diff --git a/apps/host/src/components/ModelsFolderDialog.tsx b/apps/host/src/components/ModelsFolderDialog.tsx new file mode 100644 index 00000000..bf628542 --- /dev/null +++ b/apps/host/src/components/ModelsFolderDialog.tsx @@ -0,0 +1,230 @@ +import { tr, localeTag } from '../lib/i18n'; +import { useEffect, useMemo, useState } from 'react'; +import { Bar, Btn, Dialog, Icon } from './ui'; +import { api, ApiError } from '../lib/client'; +import { nativeAction, refreshNative, useNative, type NativeJob, type NativeState } from '../lib/native'; +import { nativeShortName } from '../lib/native-names'; +import { sizeGb } from '../lib/format'; + +type Choice = 'move' | 'keep' | 'empty'; +interface Plan { + ok: boolean; + issue: { code: string; message: string; details: string } | null; + old: string; new: string; same_drive: boolean; + free_bytes: number; models_bytes: number; needed_bytes: number; + models: { group: string; name: string; bytes: number }[]; + choices: Record; + folder: string; picked: string; wholeDrive: boolean; shown: string; current: string; running: number; busy: boolean; +} +interface Outcome { done?: boolean; stopped?: boolean; failed?: boolean; code?: string; moved?: string[]; remaining?: string[]; bytes?: number; total?: number; from?: string; to?: string; sameDrive?: boolean } + +const gb = (bytes: number) => sizeGb(bytes / 1e9); +const driveOf = (path: string) => /^[A-Za-z]:/.test(path) ? path.slice(0, 2) : path; +const list = (items: string[]) => { try { return new Intl.ListFormat(localeTag(), { type: 'conjunction' }).format(items); } catch { return items.join(', '); } }; + +/** The model a folder name belongs to, in the words the Storage list uses ("Gyro-S"); the draft layer and loose files have no name of their own. */ +function modelName(group: string, native: NativeState | null) { + const hit = native?.installed?.models.find(m => m.model.toLowerCase() === group.toLowerCase()); + return hit ? nativeShortName(hit.model) : null; +} + +function timeLeft(seconds: number) { + if (seconds <= 0) return null; + if (seconds < 60) return tr('Less than a minute left'); + const minutes = Math.ceil(seconds / 60); + if (minutes <= 1) return tr('About a minute left'); + if (minutes < 120) return tr('About {0} minutes left', [minutes]); + return tr('About {0} hours left', [Math.ceil(minutes / 60)]); +} + +function Failure({ message, next, details }: { message: string; next?: string; details?: string }) { + return
{tr(message)}{next ?

{tr(next)}

: null}{details ?
{tr('Details')}
{details}
: null}
; +} + +/** Settings > Storage > Models folder: the card, the folder dialog with its three choices, the progress of a move and what came of it. */ +export function ModelsFolderCard({ blocked }: { blocked: boolean }) { + const native = useNative(); + const [plan, setPlan] = useState(null); + const [stage, setStage] = useState<'issue' | 'drive' | 'choose' | null>(null); + const [choice, setChoice] = useState('move'); + const [pending, setPending] = useState(false); + const [error, setError] = useState<{ message: string; details?: string } | null>(null); + const [typing, setTyping] = useState(false), [typed, setTyped] = useState(''); + const [jobId, setJobId] = useState(null); + const [outcome, setOutcome] = useState<{ job: NativeJob } | null>(null); + const [notice, setNotice] = useState(''); + const [stopping, setStopping] = useState(false); + const folder = native?.downloadDirectory ?? ''; + const free = native?.downloadFreeBytes ?? null; + const usage = native?.installed?.usage?.total_bytes ?? 0; + const moving = native?.jobs.find(j => j.kind === 'models-move' && j.state === 'running') ?? null; + const finished = jobId ? native?.jobs.find(j => j.id === jobId && j.kind === 'models-move' && j.state !== 'running') : undefined; + useEffect(() => { if (finished && !outcome) { setOutcome({ job: finished }); setStopping(false); void refreshNative(true); } }, [finished, outcome]); + const total = native?.downloadTotalBytes ?? null; + const used = free !== null && total ? Math.min(100, Math.max(1, ((total - free) / total) * 100)) : 0; + useEffect(() => { if (moving && !jobId) setJobId(moving.id); }, [moving, jobId]); + + function leave() { setPlan(null); setStage(null); setError(null); setTyping(false); } + async function pick(path = '') { + setPending(true); + setError(null); + setNotice(''); + try { + const result = await api.post<{ cancelled?: boolean; plan?: Plan }>('/api/native/models-folder/plan', { path }); + if (result.cancelled || !result.plan) return; + const next = result.plan; + setTyping(false); + setPlan(next); + if (next.issue?.code === 'same') { setPlan(null); return; } + setChoice(next.choices.move.possible ? 'move' : 'keep'); + setStage(next.issue ? 'issue' : next.wholeDrive ? 'drive' : 'choose'); + } + catch (e) { + if (e instanceof ApiError && e.status === 501) { setTyping(true); setError({ message: e.message }); } + else setError({ message: (e as Error).message, details: ((e as ApiError).body as { details?: string } | undefined)?.details }); + } + finally { setPending(false); } + } + async function start() { + if (!plan) return; + setPending(true); + setError(null); + try { + const result = await api.post('/api/native/models-folder/start', { path: plan.picked, choice, stopRunning: true }); + if (result.id) { setJobId(result.id); setOutcome(null); setStage(null); await refreshNative(true); setPlan(prev => prev); return; } + setNotice(choice === 'keep' ? tr('Strata now also uses {0}. New downloads go there, and your current models stay where they are.', [plan.shown]) + : tr('Strata now uses {0}. Your old model files are still in {1}; Strata does not delete them.', [plan.shown, plan.current])); + await refreshNative(true); + leave(); + } + catch (e) { setError({ message: (e as Error).message, details: ((e as ApiError).body as { details?: string } | undefined)?.details }); } + finally { setPending(false); } + } + async function stop() { + if (!moving) return; + setStopping(true); + try { await nativeAction(`operations/${moving.id}/cancel`); } + catch (e) { setError({ message: (e as Error).message }); } + } + function closeResult() { setOutcome(null); setJobId(null); leave(); setNotice(''); } + + const progress = moving?.progress as { done: number; total: number; file: string; group: string; index: number; count: number; secondsLeft: number; sameDrive: boolean } | null | undefined; + const percent = progress && progress.total > 0 ? Math.round((progress.done / progress.total) * 100) : 0; + const planNames = useMemo(() => (plan?.models ?? []).map(m => ({ ...m, label: modelName(m.group, native) })).filter(m => m.label), [plan, native]); + const savedPlan = useMemo(() => plan, [plan]); + + return <> +
+
{tr('Models folder')} void pick()}>{tr(pending && !plan ? 'Waiting for the folder…' : 'Change folder')}
+

{tr('Strata saves the big model files here.')}

+ {folder || tr('Reading model directory…')} + {free !== null ?
{tr('{0} free', [gb(free)])} {tr('on this drive')}{tr('Your models use {0}', [gb(usage)])}
: null} + {blocked && !moving ?

{tr('Finish or stop the download to change the folder.')}

: null} + {typing ?
{ e.preventDefault(); if (typed.trim()) void pick(typed.trim()); }}> + + setTyped(e.target.value)} placeholder={tr('Full path to an existing folder')} spellCheck={false} autoFocus/> +
{tr('Use this directory')}
+
: null} + {notice ?

{notice}

: null} + {error && !stage ? : null} +
+ + {plan?.issue?.code === 'not_found' ? null : {tr('Cancel')}} { leave(); void pick(); }}>{tr('Choose another folder')}}> + {plan?.issue ? : null} + + + {tr('Cancel')} setStage('choose')}>{tr('Continue')}}> + {plan ? <> +
{tr('New folder')}{plan.shown}{tr('{0} free on this drive', [gb(plan.free_bytes)])}
+
{tr('You picked the whole drive {0}. Strata keeps its files in a folder of their own, so your models go in {1}.', [plan.picked, plan.shown])}
+

{tr('The three choices follow, as in step 2.')}

+ : null} +
+ + { if (!pending) leave(); }} + actions={plan ? <>{plan.choices.move.possible ? {tr('Cancel')} : { leave(); void pick(); }}>{tr('Choose another folder')}} void start()}>{tr(pending ? 'Working…' : choice === 'move' ? 'Move my models' : choice === 'keep' ? 'Use both folders' : 'Start empty')} : null}> + {plan ? : null} + + + undefined} + actions={ void stop()}>{tr(stopping ? 'Stopping…' : 'Stop moving')}}> +
{tr('{0} of {1} GB', [progress ? (progress.done / 1e9 >= 10 ? Math.round(progress.done / 1e9) : (progress.done / 1e9).toFixed(1)) : 0, Math.round((progress?.total ?? 0) / 1e9)])}{progress && !progress.sameDrive ? timeLeft(progress.secondsLeft) : null}
+

{tr('Keep Strata open. You can keep using other apps. Your models cannot be loaded until the move is done.')}

+ {progress ?
{tr('Details')}
    +
  • {tr('Now copying: {0}, file {1} of {2}', [modelName(progress.group, native) ?? progress.group, progress.index, progress.count])}
  • +
  • {tr('From {0} to {1}', [savedPlan?.current ?? '', savedPlan?.folder ?? ''])}
: null} +
+ + { closeResult(); void pick(); }}/> + ; +} + +function ChooseBody({ plan, choice, setChoice, names, error }: { plan: Plan; choice: Choice; setChoice: (c: Choice) => void; names: (Plan['models'][number] & { label: string | null })[]; error: { message: string; details?: string } | null }) { + const none = plan.models_bytes === 0; + const short = !none && !plan.choices.move.possible; + const lacking = Math.max(0, plan.needed_bytes - plan.free_bytes); + const options: { id: Choice; title: string; text: string; need: string }[] = [ + { id: 'move', title: 'Move my models there', text: none ? 'You have no models to move.' : plan.same_drive ? 'Strata moves your {0} of models to the new folder. This is the same drive, so it takes a moment.' : 'Strata copies your {0} of models to the new folder, checks them, then removes the old copies.', + need: none ? '' : plan.same_drive ? 'Needs no extra space.' : 'Needs {0} free in the new folder. You have {1}.' }, + { id: 'keep', title: 'Keep them where they are and also use the new folder', text: 'Nothing is copied. Your current models keep working, and new downloads go to the new folder.', need: short ? 'Needs no space now. New downloads must fit in {1}.' : 'Needs no space now.' }, + { id: 'empty', title: 'Start empty', text: 'Strata uses the new folder from now on and does not list your current models. Your old files are not deleted.', need: 'Needs no space now. Each model you download later needs its own space.' }, + ]; + const values = [gb(plan.models_bytes), gb(plan.free_bytes)]; + const running = plan.running > 0; + return <> +
{tr('New folder')}{plan.shown}{tr('{0} free on this drive', [gb(plan.free_bytes)])}
+ {short ?
{tr('Your models need {0}, this drive has {1} free.', [gb(plan.needed_bytes), gb(plan.free_bytes)])}
{tr('Free up about {0} there, pick another folder, or choose one of the other two options.', [gb(lacking)])}
: null} +
+ {options.map(o => { const possible = plan.choices[o.id].possible; return ; })} +
+ {running ?

{tr('A running model is stopped first; load it again when the move is done.')}

: null} + {error ? : null} +
{tr('Details')}
    + {names.length ?
  • {tr('{0} would move.', [list(names.map(m => `${m.label}, ${gb(m.bytes)}`))])}
  • : null} + {short ?
  • {tr('Free space is measured on the drive that holds {0}.', [plan.shown])}
  • : <> +
  • {tr('Old folder: {0}', [plan.current])}
  • +
  • {tr('Strata copies one file at a time and checks its size before it removes the old one.')}
  • +
  • {tr('You can stop at any time; files already moved stay usable.')}
  • } +
+ ; +} + +function ResultDialog({ outcome, plan, native, onClose, onAgain }: { outcome: NativeJob | null; plan: Plan | null; native: NativeState | null; onClose: () => void; onAgain: () => void }) { + if (!outcome) return null; + const result = (outcome.result ?? {}) as Outcome; + const sized = (groups: string[]) => list(groups.map(g => { const m = plan?.models.find(x => x.group === g); const name = modelName(g, native); return name ? `${name} (${gb(m?.bytes ?? 0)})` : null; }).filter((x): x is string => !!x)); + if (outcome.state === 'error') { + const full = result.code === 'disk_full'; + const where = driveOf(result.to ?? ''); + const some = (result.moved?.length ?? 0) > 0; + return {tr('Close')}{tr('Choose another folder')}}> +
+ {full ? tr('{0} filled up after {1}, so the move stopped.', [where, gb(result.bytes ?? 0)]) : tr(outcome.error ?? 'The models could not be moved.')} +

{full ? (some ? tr('Nothing was lost. Models already moved are in the new folder, the rest are still in {0}, and the half-copied file was removed. Free up space on {1} or choose another folder, then try again.', [result.from ?? '', where]) + : tr('Nothing was lost. All your models are still in {0}, and the half-copied file was removed. Free up space on {1} or choose another folder, then try again.', [result.from ?? '', where])) + : tr('Nothing was lost. Your models that were not moved are still in {0}. Choose another folder to try again.', [result.from ?? ''])}

+ {outcome.details ?
{tr('Details')}
{outcome.details}
: null} +
+
; + } + if (result.stopped) { + const moved = sized(result.moved ?? []), left = sized(result.remaining ?? []); + return {tr('Close')}}> +
{tr('Nothing was lost.')}
+ {moved ? tr('{0} is in the new folder.', [moved]) + ' ' : ''}{left ? tr('{0} is still in the old folder.', [left]) + ' ' : ''}{moved && left ? tr('Both work.') : ''}
+

{tr('Models in both folders are listed as normal. You can finish moving later with Change folder.')}

+
; + } + return {tr('Done')}}> +
{tr('{0} now live in {1}', [gb(result.total ?? 0), plan?.shown ?? result.to ?? ''])} + {result.sameDrive ? null : <>
{tr('The old copies were removed and {0} is free again on {1}.', [gb(result.total ?? 0), driveOf(result.from ?? '')])}}
+
; +} diff --git a/apps/host/src/components/SettingsStorage.tsx b/apps/host/src/components/SettingsStorage.tsx index ba0dab55..9fbf9344 100644 --- a/apps/host/src/components/SettingsStorage.tsx +++ b/apps/host/src/components/SettingsStorage.tsx @@ -6,6 +6,7 @@ import { pickerGroups, pickerVersionState } from '../lib/model-picker'; import { sizeGb } from '../lib/format'; import { useNative } from '../lib/native'; import { NativeDeleteDialog } from './NativeDelete'; +import { ModelsFolderCard } from './ModelsFolderDialog'; import { nativeShortName } from '../lib/native-names'; export function SettingsStorage() { const state = useStore(s => s); @@ -77,7 +78,9 @@ export function SettingsStorage() { setPending(false); } } + const downloading = !!native?.jobs.some(j => j.state === 'running' && j.kind !== 'models-move') || !!library?.downloads.active || !!state.imageModels?.variants.some(v => v.state === 'downloading'); return <> + {native?.available && native.downloadDirectory ? : null}
{tr("Model directory")} { setDirectory(currentDirectory); setEditing(!editing); setDirectoryError(''); setNotice(''); }}>{tr(editing ? 'Cancel' : 'Change directory')}

{tr("Your models are saved here. Use an existing folder to reuse supported downloads.")}

diff --git a/apps/host/src/components/ui.tsx b/apps/host/src/components/ui.tsx index a319355f..8a475f0e 100644 --- a/apps/host/src/components/ui.tsx +++ b/apps/host/src/components/ui.tsx @@ -384,7 +384,7 @@ export function Select({ value, valueSuffix, options, onChange ); } /** One modal surface for confirmations and narrow-screen inspectors. */ -export function Dialog({ open, title, onClose, children, actions, headerActions, compact = false, sheet = false, wide = false, hideTitle = false, className }: { +export function Dialog({ open, title, onClose, children, actions, headerActions, compact = false, sheet = false, wide = false, hideTitle = false, className, noClose = false }: { open: boolean; title: ReactNode; onClose: () => void; @@ -396,6 +396,8 @@ export function Dialog({ open, title, onClose, children, actions, headerActions, wide?: boolean; hideTitle?: boolean; className?: string; + /** No close button: the person must use the dialog's own buttons (a move that is running). */ + noClose?: boolean; }) { const ref = useRef(null); const id = useId(); @@ -418,7 +420,7 @@ export function Dialog({ open, title, onClose, children, actions, headerActions, return createPortal(
- {plan?.issue?.code === 'not_found' ? null : {tr('Cancel')}} { leave(); void pick(); }}>{tr('Choose another folder')}}> {plan?.issue ? : null} - {tr('Cancel')} setStage('choose')}>{tr('Continue')}}> {plan ? <>
{tr('New folder')}{plan.shown}{tr('{0} free on this drive', [gb(plan.free_bytes)])}
{tr('You picked the whole drive {0}. Strata keeps its files in a folder of their own, so your models go in {1}.', [plan.picked, plan.shown])}
-

{tr('The three choices follow, as in step 2.')}

+

{tr('The three choices come next.')}

: null}
- { if (!pending) leave(); }} + { if (!pending) leave(); }} actions={plan ? <>{plan.choices.move.possible ? {tr('Cancel')} : { leave(); void pick(); }}>{tr('Choose another folder')}} void start()}>{tr(pending ? 'Working…' : choice === 'move' ? 'Move my models' : choice === 'keep' ? 'Use both folders' : 'Start empty')} : null}> {plan ? : null} - undefined} + undefined} actions={ void stop()}>{tr(stopping ? 'Stopping…' : 'Stop moving')}}>
{tr('{0} of {1} GB', [progress ? (progress.done / 1e9 >= 10 ? Math.round(progress.done / 1e9) : (progress.done / 1e9).toFixed(1)) : 0, Math.round((progress?.total ?? 0) / 1e9)])}{progress && !progress.sameDrive ? timeLeft(progress.secondsLeft) : null}

{tr('Keep Strata open. You can keep using other apps. Your models cannot be loaded until the move is done.')}

@@ -224,7 +224,7 @@ function ResultDialog({ outcome, plan, native, onClose, onAgain }: { outcome: Na
; } return {tr('Done')}}> -
{tr('{0} now live in {1}', [gb(result.total ?? 0), plan?.shown ?? result.to ?? ''])} +
{(() => { const [before, after] = tr('{0} now live in {1}', [gb(result.total ?? 0), '@@']).split('@@'); return <>{before}{plan?.shown ?? result.to ?? ''}{after}; })()} {result.sameDrive ? null : <>
{tr('The old copies were removed and {0} is free again on {1}.', [gb(result.total ?? 0), driveOf(result.from ?? '')])}}
; } diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.json index 7fead023..449d2b35 100644 --- a/apps/host/src/locales/de.json +++ b/apps/host/src/locales/de.json @@ -3367,7 +3367,7 @@ "s8278": "Neuer Ordner", "s8279": "{0} frei auf diesem Laufwerk", "s8280": "Sie haben das ganze Laufwerk {0} gewählt. Strata legt seine Dateien in einem eigenen Ordner ab, Ihre Modelle liegen daher in {1}.", - "s8281": "Danach folgen die drei Möglichkeiten wie in Schritt 2.", + "s8281": "Als Nächstes folgen die drei Möglichkeiten.", "s8282": "Meine Modelle verschieben", "s8283": "Beide Ordner verwenden", "s8284": "Leer beginnen", diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.json index 0f6eb0a6..fb3f94b3 100644 --- a/apps/host/src/locales/en.json +++ b/apps/host/src/locales/en.json @@ -3367,7 +3367,7 @@ "s8278": "New folder", "s8279": "{0} free on this drive", "s8280": "You picked the whole drive {0}. Strata keeps its files in a folder of their own, so your models go in {1}.", - "s8281": "The three choices follow, as in step 2.", + "s8281": "The three choices come next.", "s8282": "Move my models", "s8283": "Use both folders", "s8284": "Start empty", diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.json index a0f3f33d..716bee35 100644 --- a/apps/host/src/locales/es.json +++ b/apps/host/src/locales/es.json @@ -3367,7 +3367,7 @@ "s8278": "Carpeta nueva", "s8279": "{0} libres en esta unidad", "s8280": "Has elegido toda la unidad {0}. Strata guarda sus archivos en una carpeta propia, así que tus modelos irán en {1}.", - "s8281": "A continuación vienen las tres opciones, como en el paso 2.", + "s8281": "A continuación verás las tres opciones.", "s8282": "Mover mis modelos", "s8283": "Usar ambas carpetas", "s8284": "Empezar vacío", diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.json index 3d3d0929..344db3ea 100644 --- a/apps/host/src/locales/ja.json +++ b/apps/host/src/locales/ja.json @@ -3367,7 +3367,7 @@ "s8278": "新しいフォルダ", "s8279": "このドライブの空き: {0}", "s8280": "ドライブ全体 {0} を選びました。Strata は専用のフォルダにファイルを置くため、モデルは {1} に保存されます。", - "s8281": "次に、手順 2 と同じ 3 つの選択肢が表示されます。", + "s8281": "次に 3 つの選択肢が表示されます。", "s8282": "モデルを移動する", "s8283": "両方のフォルダを使う", "s8284": "空の状態で始める", diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.json index 498dfb34..bbf5989b 100644 --- a/apps/host/src/locales/ko.json +++ b/apps/host/src/locales/ko.json @@ -3367,7 +3367,7 @@ "s8278": "새 폴더", "s8279": "이 드라이브의 여유 공간: {0}", "s8280": "드라이브 전체 {0}을(를) 선택했습니다. Strata는 자체 폴더에 파일을 보관하므로 모델은 {1}에 저장됩니다.", - "s8281": "다음으로 2단계와 같은 세 가지 선택지가 나옵니다.", + "s8281": "다음으로 세 가지 선택지가 나옵니다.", "s8282": "내 모델 이동", "s8283": "두 폴더 모두 사용", "s8284": "빈 상태로 시작", diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.json index 678d549f..cecc2f1a 100644 --- a/apps/host/src/locales/pt.json +++ b/apps/host/src/locales/pt.json @@ -3367,7 +3367,7 @@ "s8278": "Pasta nova", "s8279": "{0} livres nesta unidade", "s8280": "Você escolheu a unidade inteira {0}. O Strata guarda seus arquivos em uma pasta própria, então seus modelos ficam em {1}.", - "s8281": "Em seguida vêm as três opções, como na etapa 2.", + "s8281": "Em seguida, você verá as três opções.", "s8282": "Mover meus modelos", "s8283": "Usar as duas pastas", "s8284": "Começar vazio", diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.json index da83fc83..670c0531 100644 --- a/apps/host/src/locales/ru.json +++ b/apps/host/src/locales/ru.json @@ -3367,7 +3367,7 @@ "s8278": "Новая папка", "s8279": "Свободно на этом диске: {0}", "s8280": "Вы выбрали весь диск {0}. Strata хранит свои файлы в отдельной папке, поэтому модели будут в {1}.", - "s8281": "Дальше будут три варианта, как на шаге 2.", + "s8281": "Дальше будут три варианта.", "s8282": "Переместить мои модели", "s8283": "Использовать обе папки", "s8284": "Начать с пустой", diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.json index 61e95aab..b670fc47 100644 --- a/apps/host/src/locales/zh.json +++ b/apps/host/src/locales/zh.json @@ -3367,7 +3367,7 @@ "s8278": "新文件夹", "s8279": "此驱动器可用 {0}", "s8280": "你选择了整个驱动器 {0}。Strata 会把文件放在自己的文件夹里,因此你的模型将存放在 {1}。", - "s8281": "接下来会出现三个选项,与第 2 步相同。", + "s8281": "接下来会出现三个选项。", "s8282": "移动我的模型", "s8283": "同时使用两个文件夹", "s8284": "从空文件夹开始", diff --git a/apps/host/src/styles/annotation-fixes.css b/apps/host/src/styles/annotation-fixes.css index de133dc6..8d31cb62 100644 --- a/apps/host/src/styles/annotation-fixes.css +++ b/apps/host/src/styles/annotation-fixes.css @@ -768,3 +768,6 @@ html[data-motion='reduced'] .task-tree-row[data-leaving] { opacity: 0; } .models-details ul { margin:8px 0 0; padding-left:18px; color:var(--st-ink-soft); font-size:var(--st-fs-sm); } .models-ok { display:flex; align-items:center; gap:12px; } .models-ok__mark { display:grid; place-items:center; flex:none; width:44px; height:44px; border-radius:50%; background:var(--st-accent-tint); color:var(--st-accent-text); } +.models-dialog .dialog-body { display:grid; gap:14px; } +.models-path { font-family:var(--st-font-mono); font-size:12px; font-weight:400; background:var(--st-surface-2); padding:2px 6px; border-radius:6px; overflow-wrap:anywhere; } +.models-dialog .storage-directory__path { margin:0; } diff --git a/apps/host/tests/models-folder.test.mjs b/apps/host/tests/models-folder.test.mjs index cf950ec2..7ff268ed 100644 --- a/apps/host/tests/models-folder.test.mjs +++ b/apps/host/tests/models-folder.test.mjs @@ -159,3 +159,23 @@ test('a move needs the app: the Control command line is built from the plan and const failing = createControl({ control: { dir: '/c', python: '/c/py', cli: '/c/strata.py' }, run: async () => ({ code: 5, json: { ok: false, error: { code: 'disk_full', message: 'The drive ran out of space.', details: 'ENOSPC' }, moved: [] }, text: '', stderr: '' }) }); await assert.rejects(failing.moveModels('/o', '/n'), e => e.code === 'disk_full' && e.details === 'ENOSPC' && /ran out of space/.test(e.message)); }); + +test('the models folder strings exist in all 8 languages with the same placeholders', () => { + const read = lang => JSON.parse(readFileSync(new URL(`../src/locales/${lang}.json`, import.meta.url), 'utf8')); + const en = read('en'); + const ours = Object.keys(en).filter(k => Number(k.slice(1)) >= 8261 && Number(k.slice(1)) <= 8338); + assert.equal(ours.length, 78); + for (const lang of ['de', 'es', 'ja', 'ko', 'pt', 'ru', 'zh']) { + const text = read(lang); + for (const key of ours) { + assert.ok(text[key], `${lang} ${key}`); + assert.deepEqual((text[key].match(/\{\d\}/g) ?? []).sort(), (en[key].match(/\{\d\}/g) ?? []).sort(), `${lang} ${key} placeholders`); + } + } + // every string the dialog shows through tr() is in the catalogue + const source = readFileSync(new URL('../src/components/ModelsFolderDialog.tsx', import.meta.url), 'utf8'); + const values = new Set(Object.values(en)); + for (const text of ['Models folder', 'Change folder', 'Move my models', 'Use both folders', 'Start empty', 'Stop moving', 'Your models are moved', 'Moving stopped']) { + assert.ok(source.includes(text) && values.has(text), text); + } +}); diff --git a/docs/INSTALL.md b/docs/INSTALL.md index d860d042..afb1e866 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -311,7 +311,9 @@ The model files are the only big part (70 to 190 GB). Put them where there is ro - **In the app:** the first screen shows the model folder with a button to change it, and Settings > Storage changes it later. Pick a folder you can save files in; a whole drive (`D:\`) becomes `D:\Strata`, which Strata makes and says so. - Models you already have in the old folder stay there and keep working; nothing is moved or deleted for you. + Change folder then asks what to do with your models: move them (copied file by file and checked before the old copies are removed; you can stop at any time), + keep them where they are and also use the new folder, or start empty (the old files are never deleted). From the Terminal the same move is + `strata models move NEW_FOLDER` (add `--plan` to see what it would do first). - **In the Terminal:** `strata launch --data-dir D:\Strata` once. The folder is remembered for the next `strata launch` and `strata models list`. Until you give it one, the Terminal uses the folder the app chose; the app keeps its own setting (Settings > Storage) and does not read the Terminal's. `--move-data` moves the models you already have into it; without it they stay where they diff --git a/strata_control/models_move.py b/strata_control/models_move.py index 36eb6fc2..e42a4b8d 100644 --- a/strata_control/models_move.py +++ b/strata_control/models_move.py @@ -102,6 +102,9 @@ def _near(path: Path) -> Path: def same_drive(a: Path, b: Path) -> bool: + """Both folders are on one volume (a move is then a rename). STRATA_MOVE_ALWAYS_COPY=1 copies anyway: for testing the copy path on one disk.""" + if os.environ.get("STRATA_MOVE_ALWAYS_COPY") == "1": + return False try: return os.stat(_near(a)).st_dev == os.stat(_near(b)).st_dev except OSError: