okami.mom/strata

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

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
20.1 KiB423 linesraw
1"""The Strata Monitor as `strata launch` opens it: the same monitor plus a Connect view and a quit question.
2
3Everything about the monitor itself (the views, colours, polling, key hints) is `strata_cli.monitor.MonitorApp`, unchanged.
4This subclass adds
5* the seventh view, Connect (key 7, and the arrow keys reach it like any other view: Overview ... Logs, Connect, then round to Overview): the
6  address, the API key hint and copy-ready setup for each app, with `c` copy, `w` write the config for you after a backup, `h` check that the
7  app's settings reach a server that answers a prompt and a tool call correctly;
8* q: asks whether to keep serving in the background or stop (stopping frees the graphics memory).
9
10The list says two different things about each app and keeps them apart: what its maker's version was tested with ("Vendor tested", fixed
11history), and whether THIS server answered the app's prompt and tool call just now ("This server": Not checked / Checking / Passed / Failed).
12"""
13
14from __future__ import annotations
15
16import textwrap
17import threading
18
19from rich.text import Text
20from textual.widgets import Static
21
22from strata_cli import nav
23from strata_cli.launch import check, harness
24from strata_cli.launch.screens import ConfirmScreen
25from strata_cli.launch.widgets import DARK, LIGHT, Glyphs
26from strata_cli.monitor import MonitorApp
27
28CONNECT = 6                                   # the index of the Connect view (the seventh)
29
30
31def connect_palette(theme: str, color: bool):
32    """The colours of the Connect view for the monitor's theme: dark, light (readable on white), or the terminal's own (no colours set)."""
33    if not color or theme == "terminal":
34        return None
35    return LIGHT if theme == "light" else DARK
36
37
38class LaunchMonitor(MonitorApp):
39    def __init__(self, endpoint, snapshot, *, info: dict, ask_quit: bool = True, **kw) -> None:
40        super().__init__(endpoint, snapshot, **kw)
41        self.info = info
42        self.ask_quit = ask_quit                  # False: plain `strata monitor` (q detaches, nothing to stop)
43        self.connect_enabled = True
44        self.connect_index = 0
45        self.show_key = False
46        self.check_results: dict[str, list[check.Check] | str] = {}
47        self.glyphs = Glyphs()
48        self.stop_requested = False
49        self.notice = ""
50        self.view_before_connect = 0
51        self.quiet_note: str | None = None        # "New engine X is available. Press u to update." (from the last check; local file only)
52        self.updating = False
53
54    # ---- a newer engine: one quiet line, and u to update (strata_control/engine_update.py)
55    def on_mount(self) -> None:
56        super().on_mount()
57        self._note_refresh()
58        if self.info.get("daily_check"):
59            try:
60                from strata_control import engine_update
61                engine_update.start_daily_check(on_done=self._note_from_thread)     # a thread of its own; offline it ends without a word
62            except Exception:                    # noqa: BLE001 - never a message
63                pass
64
65    def _note_refresh(self) -> None:
66        try:
67            from strata_control import engine_update
68            self.quiet_note = engine_update.monitor_note()
69        except Exception:                        # noqa: BLE001
70            self.quiet_note = None
71        if self.is_mounted and self.view < 6:
72            self._paint()
73
74    def _note_from_thread(self) -> None:
75        try:
76            self.call_from_thread(self._note_refresh)
77        except Exception:                        # noqa: BLE001 - the monitor may be closing
78            pass
79
80    def action_update_engine(self) -> None:
81        if self.updating or self.closing:
82            return
83        self.updating = True
84        threading.Thread(target=self._update_worker, name="strata-engine-update", daemon=True).start()
85
86    def _say_line(self, text: str) -> None:
87        def show() -> None:
88            self.selection_notice = text
89            self._paint()
90        try:
91            self.call_from_thread(show)
92        except Exception:                        # noqa: BLE001
93            pass
94
95    def _ask_from_thread(self, question: str, default: bool) -> bool:
96        box: dict = {}
97        done = threading.Event()
98
99        def show() -> None:
100            def got(choice: str | None) -> None:
101                box["yes"] = choice == "yes"
102                done.set()
103            self.push_screen(ConfirmScreen(question, "An engine update needs the model stopped first. Nothing is changed unless you choose Yes.",
104                                           [("yes", "Yes"), ("no", "No")]), got)
105        self.call_from_thread(show)
106        done.wait()
107        return bool(box.get("yes", default))
108
109    def _update_worker(self) -> None:
110        from strata_control import engine_update, updater
111        try:
112            self._say_line("Checking for a newer engine...")
113            out = engine_update.run_flow(ask=self._ask_from_thread, say=self._say_line)
114            text = engine_update.summary(out)
115        except updater.UpdateError as exc:
116            text = str(exc)
117        except Exception as exc:                 # noqa: BLE001 - a sentence, never a trace
118            text = f"The update did not run: {exc}"
119        self.updating = False
120
121        def finish() -> None:
122            self.selection_notice = text
123            self.next_poll_at = 0.0               # the model may be back: look again now
124            self._note_refresh()
125        try:
126            self.call_from_thread(finish)
127        except Exception:                        # noqa: BLE001
128            pass
129
130    @property
131    def connect_open(self) -> bool:
132        return self.view == CONNECT
133
134    # ---- quit asks
135    def action_quit(self) -> None:
136        if self.closing:
137            return
138        if not self.ask_quit:
139            return super().action_quit()
140
141        def done(choice: str | None) -> None:
142            if choice == "keep":
143                self.closing = True
144                self.exit()
145            elif choice == "stop":
146                self.stop_requested = True
147                self.closing = True
148                self.exit()
149
150        self.push_screen(ConfirmScreen("Leave the monitor?", "Keeping it serving lets your apps go on using the model. "
151                                       "Stopping unloads the model and frees the graphics memory.",
152                                       [("keep", "Keep serving in the background"), ("stop", "Stop serving and free the memory"),
153                                        ("cancel", "Stay in the monitor")]), done)
154
155    # ---- the Connect view is the seventh view
156    def _harness(self) -> harness.Harness:
157        return harness.HARNESSES[self.connect_index % len(harness.HARNESSES)]
158
159    def action_connect(self) -> None:
160        self._set_view(CONNECT)
161
162    def _set_view(self, index: int) -> None:
163        if index != CONNECT and self.view == CONNECT:
164            self.notice = ""
165        if index == CONNECT and self.view != CONNECT:
166            self.view_before_connect = self.view
167            self.notice = ""
168        super()._set_view(index)
169
170    def action_next_row(self) -> None:
171        if self.connect_open:
172            self.connect_index = (self.connect_index + 1) % len(harness.HARNESSES)
173            self.notice = ""
174            self._paint()
175        else:
176            super().action_next_row()
177
178    def action_previous_row(self) -> None:
179        if self.connect_open:
180            self.connect_index = (self.connect_index - 1) % len(harness.HARNESSES)
181            self.notice = ""
182            self._paint()
183        else:
184            super().action_previous_row()
185
186    def action_filter_clear(self) -> None:
187        if self.connect_open:
188            self._set_view(self.view_before_connect)          # Esc leaves the Connect view for the one you came from
189        else:
190            super().action_filter_clear()
191
192    def action_request_detail(self) -> None:
193        if not self.connect_open:
194            super().action_request_detail()
195
196    def on_key(self, event) -> None:
197        if event.key == "u":
198            self.action_update_engine()
199            event.stop()
200            return
201        if not self.connect_open:
202            return
203        key = event.key
204        if key == "c":
205            self._copy()
206        elif key == "w":
207            self._write()
208        elif key == "k":
209            self.show_key = not self.show_key
210            self._paint()
211        elif key == "h":
212            self._check()
213        else:
214            return
215        event.stop()
216
217    def _rendered(self) -> dict:
218        h = self._harness()
219        key = self.info.get("key") or ""
220        if not self.info.get("model"):
221            self.info["model"] = ((self.latest or {}).get("model") or {}).get("id") or "strata"
222        return harness.render(h, harness.target(self.info["url"], key, self.info.get("model") or ((self.latest or {}).get("model") or {}).get("id") or "strata", self.info.get("context")))
223
224    def _copy(self) -> None:
225        out = self._rendered()
226        text = "\n\n".join(f"# {f['path']}\n{f['text']}" for f in out["files"])
227        if out["env"]:
228            text += "\n\n" + "\n".join(f"{k}={v}" for k, v in out["env"].items())
229        try:
230            self.copy_to_clipboard(text)
231            self.notice = "Copied (if your terminal allows it)."
232        except Exception:                                    # noqa: BLE001
233            self.notice = "! Your terminal does not allow copying; use: strata connect " + self._harness().id
234        self._paint()
235
236    def _write(self) -> None:
237        h = self._harness()
238        out = self._rendered()
239        if not out["files"]:
240            self.notice = "! Nothing to write for this app."
241            self._paint()
242            return
243
244        def done(choice: str | None) -> None:
245            if choice != "write":
246                return
247            lines = []
248            for f in out["files"]:
249                try:
250                    r = harness.write_file(f)
251                    lines.append(f"{r['action']} {r['path']}" + (f" (backup {r['backup']})" if r["backup"] else ""))
252                except OSError as e:
253                    lines.append(f"could not write {f['path']}: {e}")
254            self.notice = "; ".join(lines)
255            self._paint()
256
257        self.push_screen(ConfirmScreen(f"Write {h.title}'s settings?", "A file that exists is copied to a backup first.\n"
258                                       + "\n".join(f"  {f['path']}" for f in out["files"]),
259                                       [("write", "Write it"), ("no", "Not now")]), done)
260
261    def _check(self) -> None:
262        h = self._harness()
263        self.check_results[h.id] = "running"
264        self.notice = "Checking: one prompt and one tool call. This can take a minute on a big model."
265        self._paint()
266        key = self.info.get("key") or ""
267        url = self.info["url"]
268        model = self.info.get("model") or "strata"
269
270        def work() -> None:
271            res = check.run_checks(h.id, url, key, model)
272            self.check_results[h.id] = res
273            self.notice = "Checked: " + ("both worked." if all(c.ok for c in res) else "something did not work; see the lines below the setup.")
274            try:
275                self.call_from_thread(self._paint)
276            except Exception:                                # noqa: BLE001
277                pass
278
279        threading.Thread(target=work, daemon=True).start()
280
281    # ---- painting
282    def _paint(self, size=None) -> None:
283        if not self.connect_open:
284            super()._paint(size)
285            if self.ask_quit and not self.error and not self.selection_notice and self.connection_state == "connected" and not self.frozen:
286                try:
287                    msg = "Read only  |  q asks: keep serving or stop  |  7 connect an app"
288                    width = (size or self.screen.size).width
289                    if width < 78:
290                        msg = "q asks: keep serving or stop  |  7 connect"
291                    if self.quiet_note:                          # a newer engine: the one quiet line replaces the hints it has no room beside
292                        msg = self.quiet_note + ("  |  q asks: keep serving or stop" if width >= 110 else "")
293                    self.query_one("#message", Static).update(msg)
294                except Exception:                            # noqa: BLE001
295                    pass
296            return
297        size = self.screen.size if size is None else size
298        width = max(30, size.width - 2)
299        self.query_one("#content", Static).update(self.connect_text(width, size.height - 2))
300        pal = connect_palette(self.theme_choice, self.color_choice != "never")
301        idle = ("c copy  w write it for me (keeps a backup)  h check it  k key  Esc back  " if width >= 100 else "c copy  w write  h check  Esc back  ") + \
302               f"{nav.keys(True)} views  q quit"
303        msg = self.notice or idle
304        mute = pal.mute if pal else ""
305        self.query_one("#message", Static).update(Text(msg, style=(pal.warn if pal else "") if msg.startswith("!") else mute, no_wrap=False))
306        self.query_one("#message", Static).styles.height = 2 if len(msg) > width else 1
307
308    # ---- what each app's row says
309    @staticmethod
310    def vendor_tested(h: harness.Harness) -> str:
311        """What the app's maker's version was tested with (fixed history, nothing to do with this server)."""
312        return "built into Strata" if h.built_in else (h.tested or "not tested")
313
314    def server_state(self, h: harness.Harness) -> tuple[str, str]:
315        """(words, kind) for THIS server and this app: Not checked / Checking / Passed (n/n) / Failed (n/n); kind is none | run | ok | bad."""
316        res = self.check_results.get(h.id)
317        if res == "running":
318            return "Checking...", "run"
319        if isinstance(res, list) and res:
320            okn = sum(1 for c in res if c.ok)
321            return (f"Passed ({okn}/{len(res)})", "ok") if okn == len(res) else (f"Failed ({okn}/{len(res)})", "bad")
322        return "Not checked", "none"
323
324
325    @staticmethod
326    def fit(text: str, width: int) -> str:
327        """One line, cut with an ellipsis instead of wrapping onto the next row."""
328        return text if len(text) <= width else text[:max(1, width - 1)] + "…"
329
330    def connect_text(self, width: int, height: int | None = None) -> Text:
331        g = self.glyphs
332        height = max(8, height if height is not None else self.screen.size.height)
333        compact = height < 24 or width < 70
334        pal = connect_palette(self.theme_choice, self.color_choice != "never")
335        accent = pal.accent if pal else ""
336        mute = pal.mute if pal else "dim"
337        warn_style = pal.warn if pal else "bold"
338        bad_style = pal.bad if pal else "bold"
339        sel_bg = f" on {pal.sel}" if pal else " reverse"
340        bold_accent = f"bold {accent}".strip()
341        state = {"connected": "[LIVE]", "stale": "[STALE]", "connecting": "[CONNECTING]", "disconnected": "[DISCONNECTED]",
342                 "auth_required": "[AUTH REQUIRED]"}.get(self.connection_state, "[LIVE]")
343        t = Text(no_wrap=True, overflow="crop")
344        head = f"STRATA  Connect   {self.info['url']}"
345        if len(head) + len(state) + 2 <= width:
346            t.append(head, style=bold_accent)
347            t.append(" " * max(2, width - len(head) - len(state)) + state + "\n", style=bold_accent)
348        else:
349            t.append(self.fit(head, width) + "\n", style=bold_accent)
350        t.append_text(nav.styled(CONNECT, width, True, accent=accent, color=pal is not None))
351        t.append("\n")
352        t.append(g.rule * min(width, 100) + "\n", style=mute)
353        key = self.info.get("key") or ""
354        shown = key if self.show_key else (key[:10] + g.mask * 4 if key else "off")
355        if compact:
356            t.append(self.fit(f"Connect an app  {self.info['url']}/v1  key {shown} (k {'hide' if self.show_key else 'show'})", width) + "\n", style=bold_accent)
357        else:
358            t.append("Connect an app", style=bold_accent)
359            line = f"     URL {self.info['url']}/v1    model {self.info.get('model') or 'strata'}    key {shown}  "
360            if len(line) > width - 9:                        # too long for the line: the model name goes, the address and the key stay
361                line = f"     URL {self.info['url']}/v1    key {shown}  "
362            t.append(self.fit(line, width - 9))
363            t.append("(k hide)" if self.show_key else "(k show)", style=mute)
364            t.append("\n")
365            t.append(self.fit(f"     Claude Code and other Anthropic apps use {self.info['url']} (no /v1)", width) + "\n", style=mute)
366            for u in self.info.get("urls", [])[1:]:
367                t.append(self.fit(f"     also reachable at {u}/v1", width) + "\n", style=mute)
368        # columns by width: App | Works with | Vendor tested | This server (the narrow ones drop "Works with", then "Vendor tested")
369        show_speaks, show_tested = width >= 80, width >= 57
370        cols = [("App", 17)] + ([("Works with", 18)] if show_speaks else []) + ([("Vendor tested", 24)] if show_tested else []) + [("This server", 0)]
371        t.append(("" if compact else "\n") + "   " + "".join(name.ljust(w) if w else name for name, w in cols) + "\n", style="bold")
372        for i, h in enumerate(harness.HARNESSES):
373            sel = i == self.connect_index % len(harness.HARNESSES)
374            words, kind = self.server_state(h)
375            style = {"run": warn_style, "ok": accent, "bad": bad_style, "none": ""}[kind]
376            cells = [h.title[:16]] + ([h.speaks] if show_speaks else []) + ([self.vendor_tested(h)[:23]] if show_tested else [])
377            row = "  " + (g.cursor + " " if sel else "  ")
378            for cell, (_n, w) in zip(cells, cols):
379                row += cell.ljust(w)
380            row += words
381            t.append(self.fit(row, width - 1).ljust(width - 1) + "\n", style=(f"{bold_accent}{sel_bg}".strip() if sel else style))
382        if not compact:
383            note = ("Vendor tested = the app version its maker tested this setup with. This server = whether YOUR server answered the app's "
384                    "prompt and tool call (press h)." if width >= 100 else
385                    "Vendor tested: a past test of the app version. This server: press h to check yours.")
386            t.append(self.fit(note, width) + "\n", style=mute)
387        h = self._harness()
388        out = self._rendered()
389        used = t.plain.count("\n") + 1
390        room = height - used - 3
391        if room < 5:                                         # no room for the app's setup text: the list and the keys are what matter here
392            return t
393        t.append("\n")
394        paths = ", ".join(f["path"] for f in out["files"]) or ("built into the Strata app" if h.built_in else "")
395        t.append(f"{h.title} setup", style=bold_accent)
396        t.append(self.fit(f"   {paths}", width - len(h.title) - 6) + "\n", style=mute)
397        room -= 2
398        limit_lines: list[str] = []
399        for n in out["limits"]:
400            wrapped = textwrap.wrap(n, max(30, width - 6)) or [n]
401            limit_lines += ["  - " + wrapped[0]] + ["    " + w for w in wrapped[1:]]
402        code: list[str] = []
403        for f in out["files"][:1]:
404            body = f["text"] if self.show_key else harness.mask(f["text"], key)
405            code += ["  " + ln for ln in body.splitlines()]
406        for k, v in out["env"].items():
407            code.append(f"  {k}={v if self.show_key else harness.mask(v, key)}")
408        res = self.check_results.get(h.id)
409        res_lines = ([f"  {g.tick if c.ok else 'x'} {c.name}: {c.detail}" for c in res] if isinstance(res, list) else [])
410        want_code = min(len(code), max(3, room - min(len(limit_lines), 6) - len(res_lines) - 1))
411        for ln in code[:want_code]:
412            t.append(self.fit(ln, width) + "\n")
413        if len(code) > want_code:
414            t.append(f"  ... {len(code) - want_code} more lines (c copies all)\n", style=mute)
415        left = max(0, room - want_code - (1 if len(code) > want_code else 0) - len(res_lines))
416        if limit_lines:
417            t.append("Good to know\n", style=bold_accent)
418            for ln in limit_lines[:max(2, left)]:
419                t.append(self.fit(ln, width) + "\n", style=warn_style if ln.lstrip().startswith("- WARNING") else mute)
420        if isinstance(res, list):
421            for c, ln in zip(res, res_lines):
422                t.append(self.fit(ln, width) + "\n", style=accent if c.ok else bad_style)
423        return t