okami.mom/strata

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

Niko1221Merge main c1ff07f1a into f-own-intfefaa985c

main
14.7 KiB304 linesraw
1"""Tester report T05, T09, T11 and the smaller wizard items, with Textual's pilot at 120x40, 80x24, 60x20 and 40x15: the Folder step knows an installed
2model, the Advanced command follows the choices, the final choices stay on screen, the key hints wrap instead of being cut off."""
3
4from __future__ import annotations
5
6import asyncio
7import json
8import os
9import unittest
10from pathlib import Path
11from unittest import mock
12
13from strata_cli.launch import settings as S
14from strata_cli.launch.app import Ctx, LaunchApp
15from strata_cli.launch import params as P
16from tests.terminal.launch_support import HW_12, Home, text_of
17from tests.terminal.test_launch_tui import FakeRunner, make_ctx, press, flat, typed
18
19SIZES = ((120, 40), (80, 24), (60, 20), (40, 15))
20
21
22async def settled(pilot, check, timeout=30.0):
23    """Wait until `check()` stops raising AssertionError (or the query fails because the screen is not there yet); give up after `timeout`."""
24    loop = asyncio.get_running_loop()
25    deadline = loop.time() + timeout
26    while loop.time() < deadline:
27        try:
28            check()
29            return
30        except Exception:
31            await pilot.pause(0.05)
32
33
34class Base(unittest.TestCase):
35    def setUp(self):
36        self.home = Home().__enter__()
37        self.addCleanup(self.home.__exit__, None, None, None)
38        FakeRunner.instances.clear()
39        FakeRunner.behaviour = "ok"
40        FakeRunner.download = 0.0
41        p = mock.patch("strata_cli.launch.app.Runner", FakeRunner)
42        p.start()
43        self.addCleanup(p.stop)
44
45    def run_app(self, coro, ctx=None, size=(120, 40)):
46        ctx = ctx or make_ctx()
47        app = LaunchApp(ctx)
48
49        async def go():
50            async with app.run_test(size=size) as pilot:
51                await pilot.pause(0.2)
52                return await coro(app, pilot, ctx)
53        return asyncio.run(go())
54
55
56class SaveChoices(Base):
57    def test_the_three_choices_and_the_name_are_on_screen_at_every_size(self):
58        choices = ("Save as a preset and launch", "Launch without saving", "Save the preset and stop here")
59
60        def check(app, size):
61            shown = text_of(app)
62            for choice in choices:
63                self.assertIn(choice, shown, (size, shown))
64            body = app.screen.query_one("#body")
65            menu = app.screen.menu()
66            self.assertLessEqual(menu.region.bottom, body.region.bottom, size)               # the choices are inside the body, not below it
67            self.assertGreaterEqual(menu.region.y, body.region.y, size)
68            name = app.screen.query_one("#name")
69            self.assertLessEqual(name.region.bottom, body.region.bottom, size)
70            self.assertIn("Enter:", flat(app), size)                                           # the footer says which action Enter does
71
72        async def case(app, pilot, ctx):
73            await press(pilot, *("enter",) * 7, "n", "enter")
74            for size in SIZES:
75                await pilot.resize_terminal(*size)
76                # wait for the layout to settle (a loaded machine redraws late), not for a fixed time; the checks themselves are unchanged
77                await settled(pilot, lambda: check(app, size))
78                check(app, size)
79        self.run_app(case)
80
81    def test_the_footer_names_the_action_enter_will_do(self):
82        async def case(app, pilot, ctx):
83            await press(pilot, *("enter",) * 7, "n", "enter")
84            self.assertIn("Enter: Save as a preset and launch", flat(app))
85            await press(pilot, "down")
86            self.assertIn("Enter: Launch without saving", flat(app))
87            await press(pilot, "down")
88            self.assertIn("Enter: Save the preset and stop here", flat(app))
89        self.run_app(case)
90
91    def test_the_full_layout_is_kept_when_it_fits(self):
92        async def case(app, pilot, ctx):
93            await press(pilot, *("enter",) * 7, "n", "enter")
94            shown = text_of(app)
95            for part in ("Save as preset, then launch", "Context", "Pictures", "Parallel", "Tuning", "Access", "Storage"):
96                self.assertIn(part, shown)
97        self.run_app(case)
98
99
100def path_of(n: int) -> str:
101    """A storage path of exactly `n` characters, starting with /home/ana/ and ending with /Strata-data."""
102    head, tail = "/home/ana/", "/Strata-data"
103    p = head + ("models-and-more-" * 20)[: n - len(head) - len(tail)] + tail
104    assert len(p) == n
105    return p
106
107
108class StoragePath(Base):
109    """A storage folder longer than the row used to wrap and push "Save the preset and stop here" off an 80x24 screen (RULES.md, --keep scratch
110    path length); it is now shortened in the middle to one row, and every choice stays on screen for any length."""
111
112    def test_every_choice_stays_on_an_80x24_screen_for_any_path_length(self):
113        choices = ("Save as a preset and launch", "Launch without saving", "Save the preset and stop here")
114        for n in (36, 80, 200):
115            ctx = make_ctx()
116            path = path_of(n)
117
118            async def case(app, pilot, ctx, path=path, n=n):
119                await press(pilot, *("enter",) * 7, "n", "enter")
120                ctx.settings.data_dir = path
121                app.screen.paint()
122
123                def check():
124                    shown = text_of(app)
125                    for choice in choices:
126                        self.assertIn(choice, shown, (n, shown))
127                    body, menu = app.screen.query_one("#body"), app.screen.menu()
128                    self.assertLessEqual(menu.region.bottom, body.region.bottom, n)
129                    rows = [r for r in shown.split("\n") if "Storage" in r]
130                    self.assertEqual(len(rows), 1, (n, shown))
131                    row = rows[0].strip()
132                    self.assertTrue(row.startswith("Storage   /home/ana/"), (n, row))
133                    self.assertTrue(row.endswith("/Strata-data"), (n, row))
134                    self.assertLessEqual(len(rows[0]), 80, (n, row))
135                    if n <= 60:
136                        self.assertIn(path, row, "a path that fits is shown whole")
137                    else:
138                        self.assertIn("\u2026", row, "a long path is shortened in the middle")
139                await settled(pilot, check)
140                check()
141            self.run_app(case, ctx=ctx, size=(80, 24))
142
143    def test_middle_shorten(self):
144        from strata_cli.launch.screens import middle_shorten
145        self.assertEqual(middle_shorten("C:/a/b", 10), "C:/a/b")
146        p = "C:\\Users\\Ana\\Documents\\Strata\\a-very-long-folder-name-for-models\\Strata-data"
147        s = middle_shorten(p, 40)
148        self.assertEqual(len(s), 40)
149        self.assertEqual(s, "C:\\Users\\Ana\\Do\u2026e-for-models\\Strata-data")          # 2/5 of the room for the start, the rest for the end
150        self.assertEqual(middle_shorten(p, 40, "..."), "C:\\Users\\Ana\\D...-for-models\\Strata-data")
151        self.assertEqual(middle_shorten(p, 3), p[0] + "\u2026" + p[-1])            # the smallest: one character on each side
152        self.assertEqual(middle_shorten("/home/\u6a21\u578b\u6a21\u578b\u6a21\u578b/data", 12), "/hom\u2026\u578b/data")   # wide characters count as two cells
153
154
155class AdvancedLayout(Base):
156    HELP = "  --prefill N          prompt chunk size (default 2048)\n  --kv fp16|int8       KV storage\n"
157
158    def ctx_with_engine(self, **choices):
159        ctx = make_ctx()
160        ctx.settings.family, ctx.settings.model = "qwen", "IQ3_XXS"
161        for k, v in choices.items():
162            setattr(ctx.settings, k, v)
163        base = {"exe": "component:strata-engine", "vision": {"mmproj": "/x/mmproj.gguf", "gpu": False},
164                "args": ["--native", "/very/long/path/to/the/models/folder/Qwen3.8-Flash-Next-Something-IQ3_XXS-00001-of-00002.gguf",
165                         "--pack", "/very/long/path/to/the/data/packs/iq3_xxs", "--max-context", "131072", "--kv", "int8", "--prefill", "auto",
166                         "--vision"]}
167        for p in (mock.patch.object(Ctx, "base_config", lambda self: base), mock.patch.object(Ctx, "engine_exe", lambda self: "/engine/strata"),
168                  mock.patch("strata_cli.launch.params.engine_help_text", return_value=self.HELP)):
169            p.start()
170            self.addCleanup(p.stop)
171        return ctx
172
173    def test_the_command_follows_the_wizard_choices(self):
174        ctx = self.ctx_with_engine(context=102400, kv="q4_0", vision="off")
175        cmd = ctx.command_text()
176        self.assertIn("--max-context 102400", cmd)
177        self.assertIn("--kv q4_0", cmd)
178        self.assertNotIn("--vision", cmd)
179        self.assertNotIn("131072", cmd)
180        ctx2 = self.ctx_with_engine(context=65536, kv="int8", vision="cpu")
181        cmd2 = ctx2.command_text()
182        self.assertIn("--max-context 65536", cmd2)
183        self.assertIn("--vision", cmd2)
184        # and the "Same as" line agrees with it
185        self.assertIn("--context 100k", S.flags_text(ctx.settings))
186        self.assertIn("--kv q4_0", S.flags_text(ctx.settings))
187        self.assertIn("--vision off", S.flags_text(ctx.settings))
188
189    def test_the_preview_is_inside_its_own_scroll_area_at_every_size_and_the_next_key_is_visible(self):
190        ctx = self.ctx_with_engine(context=102400, kv="q4_0", vision="off")
191
192        async def case(app, pilot, ctx):
193            await press(pilot, *("enter",) * 7)
194            self.assertEqual(app.current, "advanced")
195            for size in SIZES:
196                await pilot.resize_terminal(*size)
197                await pilot.pause(0.3)
198                body = app.screen.query_one("#body")
199                box = app.screen.query_one("#cmdbox")
200                self.assertGreaterEqual(box.region.y, body.region.y, size)
201                self.assertLessEqual(box.region.bottom, body.region.bottom, size)                # the preview never leaves the body
202                self.assertGreaterEqual(box.region.height, 3, size)
203                self.assertIn("n next", flat(app), size)                                           # the key hints wrap instead of being cut off
204                self.assertIn("Command that will run", text_of(app), size)
205        self.run_app(case, ctx)
206
207    def test_tab_scrolls_the_preview_and_esc_comes_back(self):
208        ctx = self.ctx_with_engine(context=102400, kv="q4_0", vision="off")
209
210        async def case(app, pilot, ctx):
211            await press(pilot, *("enter",) * 7)
212            await pilot.resize_terminal(60, 20)
213            await pilot.pause(0.3)
214            await press(pilot, "tab")
215            self.assertTrue(app.screen.query_one("#cmdbox").has_focus)
216            await press(pilot, "down", "down")
217            await press(pilot, "escape")
218            self.assertFalse(app.screen.query_one("#cmdbox").has_focus)
219            self.assertEqual(app.current, "advanced")                      # Esc only gave the focus back; it did not leave the step
220            await press(pilot, "n")
221            self.assertEqual(app.current, "access")
222        self.run_app(case, ctx)
223
224    def test_descriptions_use_plain_words(self):
225        text = "  --expert-cache N   R4: experts held in VRAM (default auto)\n  --mystery N   R7 internal thing T2\n"
226        rows = {p.name: p for p in P.parse_help(text)}
227        self.assertNotIn("R4", rows["--expert-cache"].short)
228        self.assertIn("graphics memory", rows["--expert-cache"].short)
229        self.assertNotRegex(rows["--mystery"].short, r"\bR\d|\bT\d")
230
231
232class HintsWrap(Base):
233    def test_long_key_hints_wrap_instead_of_being_cut(self):
234        async def case(app, pilot, ctx):
235            await press(pilot, *("enter",) * 7)
236            for width in (120, 80, 60, 40):
237                await pilot.resize_terminal(width, 24)
238                await pilot.pause(0.25)
239                hints = app.screen.query_one("#hints")
240                self.assertGreaterEqual(hints.region.height, 1)
241                self.assertIn("n next", flat(app), width)
242        ctx = make_ctx()
243        ctx.settings.family, ctx.settings.model = "qwen", "IQ3_XXS"
244        self.run_app(case, ctx)
245
246
247class InstalledModelFolder(Base):
248    """The GUI's installation: weights, pack, picture reader there; the draft layer gone."""
249
250    def build(self):
251        base = Path(os.environ["LOCALAPPDATA"]).parent / "gui"
252        docs = base / "Documents" / "Strata"
253        gguf = docs / "Models" / "qwen-IQ3_XXS" / "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf"
254        gguf.parent.mkdir(parents=True)
255        gguf.write_bytes(b"x")
256        pack = docs / "packs" / "iq3_xxs"
257        pack.mkdir(parents=True)
258        mm = docs / "Models" / "mmproj-Qwen3.8-Flash-Next-BF16.gguf"
259        mm.write_bytes(b"x")
260        install = Path(os.environ["STRATA_INSTALL_DIR"])
261        install.mkdir(parents=True, exist_ok=True)
262        cfg = {"exe": "component:strata-engine", "tokenizer": str(pack), "args": ["--pack", str(pack), "--native", str(gguf), "--mtp", str(docs / "mtp" / "rt"),
263                                                                                 "--max-context", "32768", "--kv", "int8"],
264               "vision": {"mmproj": str(mm), "gpu": False}}
265        (install / "strata-iq3_xxs.json").write_text(json.dumps(cfg))
266        return docs
267
268    def test_the_folder_starts_where_the_model_is_and_says_what_is_missing(self):
269        docs = self.build()
270        ctx = make_ctx()
271        ctx.settings.family, ctx.settings.model, ctx.settings.vision = "qwen", "IQ3_XXS", "cpu"
272
273        async def case(app, pilot, ctx):
274            await press(pilot, "enter", "up", "enter")                 # Start -> Model (up: IQ3_XXS, the 64 GB tier pre-selects IQ3_S) -> Folder
275            self.assertEqual(app.current, "folder")
276            field = app.screen.query_one("#folderpath")
277            self.assertEqual(Path(field.value).resolve(), docs.resolve())
278            shown = flat(app)
279            self.assertIn("The model is already downloaded", shown)
280            self.assertIn("Only the draft layer is missing (5.2 GB)", shown)
281            self.assertNotIn("Needs about", shown)
282            self.assertNotIn("download the model", shown.lower())
283        self.run_app(case, ctx)
284
285    def test_everything_there_says_already_downloaded(self):
286        docs = self.build()
287        (docs / "mtp" / "rt").mkdir(parents=True)
288        (docs / "mtp" / "rt" / "experts.bin").write_bytes(b"x")
289        ctx = make_ctx()
290        ctx.settings.family, ctx.settings.model, ctx.settings.vision = "qwen", "IQ3_XXS", "cpu"
291
292        async def case(app, pilot, ctx):
293            await press(pilot, "enter", "up", "enter")                 # up: IQ3_XXS (IQ3_S is pre-selected)
294            shown = flat(app)
295            self.assertIn("Already downloaded", shown)
296            self.assertIn("Nothing more to download", shown)
297            # and the final screen does not warn about a download
298            await press(pilot, *("enter",) * 5, "n", "enter")
299            self.assertIn("Nothing needs to be downloaded", flat(app))
300        self.run_app(case, ctx)
301
302
303if __name__ == "__main__":
304    unittest.main()