Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
monitor: the classic Windows console switches to Cascadia Mono when installed, else a solid-block look with palette colours; several cards and CPUs in the Overview (totals, a Cards strip, sockets); whole card names in view 5
Niko12211d0397652995
diff --git a/serve/telemetry.py b/serve/telemetry.pyindex b1054759f..88cb9c358 100644--- a/serve/telemetry.py+++ b/serve/telemetry.py@@ -423,6 +423,47 @@ def free_vram_mib(index=0, amd=False):# ------------------------------------------------------------------------------------------------ CPU / RAM+def _cpu_topology(root: str = "/sys/devices/system"):+ """(sockets, NUMA nodes) of this computer: how many CPU packages it has and how many memory nodes (None where it cannot be read).+ Linux reads /sys, Windows asks GetLogicalProcessorInformationEx / GetNumaHighestNodeNumber, macOS asks sysctl (Apple silicon and every Mac+ sold so far: one package, no NUMA)."""+ try:+ if os.name == "nt":+ import ctypes+ kernel32 = ctypes.windll.kernel32+ needed = ctypes.c_ulong(0)+ kernel32.GetLogicalProcessorInformationEx(3, None, ctypes.byref(needed)) # RelationProcessorPackage+ buf = ctypes.create_string_buffer(needed.value)+ sockets = None+ if needed.value and kernel32.GetLogicalProcessorInformationEx(3, buf, ctypes.byref(needed)):+ sockets, offset = 0, 0+ while offset + 8 <= needed.value:+ relationship = int.from_bytes(buf.raw[offset:offset + 4], "little")+ size = int.from_bytes(buf.raw[offset + 4:offset + 8], "little")+ if size <= 0:+ break+ sockets += 1 if relationship == 3 else 0+ offset += size+ high = ctypes.c_ulong(0)+ numa = high.value + 1 if kernel32.GetNumaHighestNodeNumber(ctypes.byref(high)) else None+ return (sockets or None), numa+ if sys.platform == "darwin":+ import subprocess+ out = subprocess.run(["sysctl", "-n", "hw.packages"], capture_output=True, text=True, timeout=5).stdout.strip()+ return (int(out) if out.isdigit() else 1), None+ import glob+ packages = set()+ for f in glob.glob(os.path.join(root, "cpu", "cpu[0-9]*", "topology", "physical_package_id")):+ try:+ packages.add(open(f, encoding="utf-8").read().strip())+ except OSError:+ continue+ nodes = len(glob.glob(os.path.join(root, "node", "node[0-9]*")))+ return (len(packages) or None), (nodes or None)+ except Exception: # noqa: BLE001 - a missing figure is shown as missing, never guessed+ return None, None++def _cpu_name():if os.name == "nt":try:@@ -534,6 +575,8 @@ class Telemetry:"cpu_name": _cpu_name(),"cores": (self.ps.cpu_count(logical=False) if self.ps else None) or None,"threads": os.cpu_count(),+ "sockets": _cpu_topology()[0],+ "numa_nodes": _cpu_topology()[1],"psutil": self.ps is not None,}self._disk_prev = Nonediff --git a/strata_cli/consoleinfo.py b/strata_cli/consoleinfo.pyindex 9c78ff39b..d13dabcb1 100644--- a/strata_cli/consoleinfo.py+++ b/strata_cli/consoleinfo.py@@ -1,9 +1,16 @@"""What kind of terminal this is, for the few places that must change what they draw.-The classic Windows console window (conhost: the default window of Windows PowerShell and cmd on Windows 10) uses Consolas, which-has no glyphs for the eighth-block sparkline characters, the rounded box corners or the check mark: they show as empty boxes.+The classic Windows console window (conhost: the default window of Windows PowerShell and cmd on Windows 10) uses Consolas or Lucida Console,+which have no glyphs for the eighth-block sparkline characters or the check mark: they show as empty boxes (Consolas has the full, half and+shade blocks, the box-drawing set and the rounded corners; Lucida Console has no rounded corners and no filled circle).Windows Terminal, VS Code's terminal, ConEmu and every Linux/macOS terminal with a modern font have them. `STRATA_GLYPHS=ascii|unicode`-overrides the guess.+overrides the guess (`solid` draws the classic console's solid look without touching the window's font).++In the classic console only, `classic_style()` does the best it can with no admin rights and no registry change:+* Cascadia Mono installed: this window's font is switched to it (the console font API) and the full Unicode look is drawn;+* otherwise the "solid" look: solid block bars with a thin track, ▄ / █ sparklines, square boxes, the 16 palette colours conhost really has,+ and `•` instead of `●` when the font is not Consolas (Lucida has no `●`).+Windows Terminal, Linux and macOS never get either: `legacy_console()` is False there."""from __future__ import annotations@@ -11,11 +18,13 @@ from __future__ import annotationsimport osimport sys+TIP = "For the full look, use Windows Terminal (built into Windows 11)"+def legacy_console() -> bool:"""True for the classic Windows console (no Windows Terminal, no VS Code, no ConEmu, no ssh session into it)."""forced = os.environ.get("STRATA_GLYPHS", "").strip().lower()- if forced in ("ascii", "legacy"):+ if forced in ("ascii", "legacy", "solid"):return Trueif forced == "unicode":return False@@ -50,3 +59,126 @@ def console_columns() -> int | None:return int(info.window.Right - info.window.Left + 1)except Exception: # noqa: BLE001return None+++# ------------------------------------------------------------------------------------------------ the font of the classic console++def _font_struct():+ import ctypes++ class COORD(ctypes.Structure):+ _fields_ = [("X", ctypes.c_short), ("Y", ctypes.c_short)]++ class CONSOLE_FONT_INFOEX(ctypes.Structure):+ _fields_ = [("cbSize", ctypes.c_ulong), ("nFont", ctypes.c_ulong), ("dwFontSize", COORD), ("FontFamily", ctypes.c_uint),+ ("FontWeight", ctypes.c_uint), ("FaceName", ctypes.c_wchar * 32)]+ return CONSOLE_FONT_INFOEX+++def console_font() -> str | None:+ """The face name of this console window's font (Windows only), or None."""+ if os.name != "nt":+ return None+ try:+ import ctypes+ S = _font_struct()+ info = S()+ info.cbSize = ctypes.sizeof(S)+ handle = ctypes.windll.kernel32.GetStdHandle(-11)+ if not ctypes.windll.kernel32.GetCurrentConsoleFontEx(handle, False, ctypes.byref(info)):+ return None+ return info.FaceName or None+ except Exception: # noqa: BLE001+ return None+++def cascadia_installed() -> bool:+ """Is Cascadia Mono installed (it comes with Windows Terminal and Visual Studio, and can be installed alone)?"""+ if os.name != "nt":+ return False+ try:+ import winreg+ for root in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER):+ try:+ with winreg.OpenKey(root, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts") as key:+ i = 0+ while True:+ name = winreg.EnumValue(key, i)[0]+ if name.lower().startswith("cascadia mono"):+ return True+ i += 1+ except OSError:+ continue+ except Exception: # noqa: BLE001+ return False+ fonts = os.path.join(os.environ.get("WINDIR", "C:\\Windows"), "Fonts")+ return any(os.path.isfile(os.path.join(fonts, n)) for n in ("CascadiaMono.ttf", "CascadiaMonoPL.ttf"))+++def switch_font(face: str = "Cascadia Mono") -> bool:+ """Set THIS console window's font through the console font API (no admin, nothing saved, gone when the window closes); True if it took."""+ if os.name != "nt":+ return False+ try:+ import ctypes+ S = _font_struct()+ info = S()+ info.cbSize = ctypes.sizeof(S)+ handle = ctypes.windll.kernel32.GetStdHandle(-11)+ if not ctypes.windll.kernel32.GetCurrentConsoleFontEx(handle, False, ctypes.byref(info)):+ return False+ height = info.dwFontSize.Y or 16+ info.FaceName = face+ info.dwFontSize.X = 0+ info.dwFontSize.Y = height+ info.FontFamily = 54 # TMPF_TRUETYPE | fixed pitch | modern+ info.FontWeight = 400+ if not ctypes.windll.kernel32.SetCurrentConsoleFontEx(handle, False, ctypes.byref(info)):+ return False+ return console_font() == face+ except Exception: # noqa: BLE001+ return False+++def decide_style(*, legacy: bool, cascadia_ok: bool, font: str | None) -> dict:+ """The look for this console (pure: the tests give it the facts).++ {"mode": "none"} not the classic console: nothing here changes+ {"mode": "full", "font": "Cascadia Mono", ...} the font was switched to Cascadia Mono: the full Unicode look+ {"mode": "solid", "font": face, "bullet": "●"|"•"} solid blocks and palette colours; the bullet depends on the font+ `tip` is the one line every classic console shows."""+ if not legacy:+ return {"mode": "none", "bullet": "●", "tip": None, "font": font}+ if cascadia_ok:+ return {"mode": "full", "bullet": "●", "tip": TIP, "font": "Cascadia Mono"}+ bullet = "●" if (font or "").lower().startswith("consolas") else "•" # Lucida Console (and unknown fonts) have no ●+ return {"mode": "solid", "bullet": bullet, "tip": TIP, "font": font}+++_cached: dict | None = None+++def classic_style() -> dict:+ """decide_style for this process, switching the font to Cascadia Mono once when that is possible. Cheap after the first call."""+ global _cached+ if _cached is not None:+ return _cached+ legacy = legacy_console()+ forced = os.environ.get("STRATA_GLYPHS", "").strip().lower() in ("ascii", "legacy", "solid")+ switched = False+ font = console_font() if (legacy and forced) else None+ if legacy and not forced and os.name == "nt":+ font = console_font()+ if font and font.lower().startswith("cascadia mono"):+ switched = True+ elif cascadia_installed():+ switched = switch_font("Cascadia Mono")+ font = console_font() if switched else font+ _cached = decide_style(legacy=legacy, cascadia_ok=switched, font=font)+ return _cached+++def forget_style() -> None:+ """For the tests: decide again."""+ global _cached+ _cached = Nonediff --git a/strata_cli/launch/widgets.py b/strata_cli/launch/widgets.pyindex 01c7d2c27..6efd80b59 100644--- a/strata_cli/launch/widgets.py+++ b/strata_cli/launch/widgets.py@@ -23,9 +23,12 @@ ACCENT, WARN, BAD, SEL, RULE = "#34d399", "#f5c56b", "#f28b82", "#1f2a27", "#3a4def unicode_ok() -> bool:if os.environ.get("TERM") == "dumb":return False- from strata_cli.consoleinfo import legacy_console- if legacy_console(): # the classic Windows console's font has no arrows, check marks or block glyphs- return False+ from strata_cli import consoleinfo+ if consoleinfo.legacy_console(): # the classic Windows console's font has no arrows, check marks or block glyphs ...+ if os.environ.get("STRATA_GLYPHS", "").strip().lower() in ("ascii", "legacy"):+ return False+ if consoleinfo.classic_style()["mode"] != "full": # ... unless the window's font could be switched to Cascadia Mono+ return Falseenc = getattr(sys.stdout, "encoding", None) or "utf-8"try:"›─↑↓•█░".encode(enc)diff --git a/strata_cli/monitor.py b/strata_cli/monitor.pyindex 7861803b0..a6c32f46d 100644--- a/strata_cli/monitor.py+++ b/strata_cli/monitor.py@@ -26,9 +26,17 @@ def choose_glyphs(requested: str, encoding: str | None, term: str | None) -> str"""Prefer readable Unicode when the output stream can encode its graph cells."""if requested != "auto":return requested- from strata_cli.consoleinfo import legacy_console- if term == "dumb" or not encoding or legacy_console():+ from strata_cli import consoleinfo+ if term == "dumb" or not encoding:return "ascii"+ if consoleinfo.legacy_console():+ forced = os.environ.get("STRATA_GLYPHS", "").strip().lower()+ if forced in ("ascii", "legacy"):+ return "ascii"+ if forced == "solid":+ return "solid"+ # the classic Windows console: the full Unicode look when the window's font could be switched to Cascadia Mono, else solid blocks+ return "unicode" if consoleinfo.classic_style()["mode"] == "full" else "solid"try:"▁█░".encode(encoding)except (LookupError, UnicodeEncodeError):@@ -128,8 +136,9 @@ class MonitorApp(App):self.theme_choice = "terminal" if theme == "auto" else themeself.color_choice = "never" if os.environ.get("NO_COLOR") is not None else colorself.glyph_choice = choose_glyphs(glyphs, sys.stdout.encoding, os.environ.get("TERM"))- from strata_cli.consoleinfo import legacy_console- self.margin = 3 if legacy_console() else 2 # one more column of room in the classic Windows console (its scroll bar)+ from strata_cli import consoleinfo+ self.classic = consoleinfo.classic_style() if consoleinfo.legacy_console() else None+ self.margin = 3 if self.classic else 2 # one more column of room in the classic Windows console (its scroll bar)self.history = MonitorHistory()self.activity_continuity = ActivityContinuity()self.displayed_activity_continuity = self.activity_continuity.status()@@ -166,6 +175,11 @@ class MonitorApp(App):self.query_one("#content").styles.color = fgself.query_one("#message").styles.color = mute+ @property+ def text_glyphs(self) -> str:+ """The glyph set of the text views (2-6): the Overview's solid look is not theirs, they keep the plain ASCII fallback."""+ return "ascii" if self.glyph_choice == "solid" else self.glyph_choice+def _paint(self, size=None) -> None:size = self.screen.size if size is None else sizesnapshot = {**self.displayed, "recent": (self.displayed.get("recent") or [])[:self.requests]}@@ -178,13 +192,14 @@ class MonitorApp(App):self.metrics_model, width=max(30, min(size.width - self.margin, 100 if self.margin > 2 else 1000)), height=max(8, size.height - 2),connection=getattr(self.endpoint, "base_url", getattr(self.endpoint, "root", "")),connection_state=self.connection_state, frozen=self.frozen, glyphs=self.glyph_choice,- color=self.color_choice != "never", theme=self.theme_choice, connect=self.connect_enabled)+ color=self.color_choice != "never", theme=self.theme_choice, connect=self.connect_enabled,+ bullet=(self.classic or {}).get("bullet", "●"))elif self.view == 0 and size.width >= 78 and size.height >= 23:display = render_dashboard(snapshot, width=max(30, size.width - self.margin), height=max(8, size.height - 2),history=self.history, connection=getattr(self.endpoint, "base_url", getattr(self.endpoint, "root", "")),connection_state=self.connection_state, frozen=self.frozen,- filter_text=self.filter_text, glyphs=self.glyph_choice,+ filter_text=self.filter_text, glyphs=self.text_glyphs,color=self.color_choice != "never", theme=self.theme_choice)elif self.view != 0 and size.width >= 128 and size.height >= 36 and self.connection_state not in ("connecting", "disconnected", "auth_required", "incompatible"):@@ -193,14 +208,14 @@ class MonitorApp(App):height=max(8, size.height - 2), history=self.history,connection=getattr(self.endpoint, "base_url", getattr(self.endpoint, "root", "")),connection_state=self.connection_state, frozen=self.frozen,- filter_text=self.filter_text, glyphs=self.glyph_choice,+ filter_text=self.filter_text, glyphs=self.text_glyphs,color=self.color_choice != "never", theme=self.theme_choice,selected=self.selected, detail=self.detail, serving_pane=self.serving_pane)else:content = render_view(snapshot, VIEWS[self.view],width=max(30, size.width - self.margin), height=max(8, size.height - 2),selected=self.selected, frozen=self.frozen,- filter_text=self.filter_text, glyphs=self.glyph_choice,+ filter_text=self.filter_text, glyphs=self.text_glyphs,connection=getattr(self.endpoint, "base_url", getattr(self.endpoint, "root", "")),serving_pane=self.serving_pane,detail=self.detail, connection_state=self.connection_state)@@ -223,6 +238,8 @@ class MonitorApp(App):self.query_one("#content", Static).update(display)idle_message = ("Read only | q keeps server on" if size.width < 60 else"Read only | q detaches without stopping Strata")+ if self.classic and self.classic.get("tip"): # the classic Windows console: one line about the full look+ idle_message = ("Read only | q detaches | " if size.width >= 100 else "") + self.classic["tip"]msg = self.error or self.selection_notice or ("Connecting to Strata" if self.connection_state == "connecting" else"Telemetry unavailable; status only" if self.connection_state == "telemetry_unavailable" else"Frozen display; collection continues" if self.frozen elsediff --git a/strata_cli/overview.py b/strata_cli/overview.pyindex b8ab044a6..12bb689aa 100644--- a/strata_cli/overview.py+++ b/strata_cli/overview.py@@ -28,6 +28,8 @@ RED = "#f28b82"ACCENT = "#34d399"GREY = "#59636b"STATES = ("Idle", "Reading", "Generating", "Queued", "Error")+# the classic Windows console draws with its 16 palette colours; these are the names that map onto them (glyphs="solid")+SOLID_ACCENT, SOLID_BLUE, SOLID_AMBER, SOLID_RED, SOLID_TRACK = "bright_green", "bright_blue", "yellow", "red", "bright_black"def _num(v: Any) -> float | None:@@ -57,6 +59,26 @@ def request_speed(r: dict) -> float | None:return round(out / (ms / 1000.0), 1) if out and ms and ms > 0 else None+def _cards(hw: dict, static: dict) -> list[dict]:+ """Each graphics card's own readings when the server lists two or more (hardware.gpus); [] for one card or none: the Overview then+ draws exactly what it always drew."""+ raw = hw.get("gpus") if isinstance(hw.get("gpus"), list) else []+ cards = [{"index": c.get("index"), "name": c.get("name"), "util": _num(c.get("util")), "mem_used": _gib(c.get("mem_used")),+ "mem_total": _gib(c.get("mem_total")), "temp": _num(c.get("temp")), "power": _num(c.get("power")),+ "power_limit": _num(c.get("power_limit"))} for c in raw[:16] if isinstance(c, dict)]+ return cards if len(cards) >= 2 else []+++def _total(values: list) -> float | None:+ present = [v for v in values if v is not None]+ return sum(present) if present else None+++def _most(values: list) -> float | None:+ present = [v for v in values if v is not None]+ return max(present) if present else None++def build(metrics: dict | None) -> dict | None:"""The numbers the Overview draws, or None when the server does not serve /metrics (an old server: the caller falls back)."""if not isinstance(metrics, dict) or not isinstance(metrics.get("live"), dict):@@ -105,14 +127,15 @@ def build(metrics: dict | None) -> dict | None:slots, total_slots = _num(engine.get("expert_slots")), _num(engine.get("experts"))cache_mib = _num(engine.get("expert_cache_mib"))gen, genmax, width = _num(hw.get("gpu_pcie_gen")), _num(hw.get("gpu_pcie_gen_max")), _num(hw.get("gpu_pcie_width"))- return {+ model = {"model": engine.get("model"), "max_context": max_ctx, "state": state, "state_raw": state_raw, "queued": int(queued),"progress": (done, total), "phase_text": {"Idle": "Waiting for a request", "Reading": "Reading prompt", "Generating": "Generating a reply","Queued": "Requests are queued", "Error": "Model unavailable"}[state],"context": (used, max_ctx),"speed": (speed, speed_note, _series(history, "tok_s") if speed_note == "now" or not _series(history, "prefill_tok_s_mean") else_series(history, "tok_s")),- "gpu": {"name": static.get("gpu_name"), "util": _num(hw.get("gpu_util")), "util_hist": _series(history, "gpu_util"),+ "gpu": {"cards": _cards(hw, static),+ "name": static.get("gpu_name"), "util": _num(hw.get("gpu_util")), "util_hist": _series(history, "gpu_util"),"vram_used": _gib(hw.get("gpu_mem_used")), "vram_total": _gib(hw.get("gpu_mem_total")) or(_num(static.get("gpu_vram_total_mib")) / 1024.0 if _num(static.get("gpu_vram_total_mib")) else None),"vram_hist": _series(history, "gpu_mem_used", GIB), "temp": _num(hw.get("gpu_temp")), "temp_hist": _series(history, "gpu_temp"),@@ -120,7 +143,8 @@ def build(metrics: dict | None) -> dict | None:"pcie_rx": _num(hw.get("gpu_pcie_rx_mb")), "pcie_hist": _series(history, "gpu_pcie_rx_mb"),"pcie_gen": gen if gen is not None else genmax, "pcie_width": width, "count": _num(static.get("gpu_count"))},"cpu": {"load": _num(hw.get("cpu_pct") if hw.get("cpu_pct") is not None else hw.get("cpu")), "hist": _series(history, "cpu"),- "cores": _num(static.get("cores")), "threads": _num(static.get("threads"))},+ "cores": _num(static.get("cores")), "threads": _num(static.get("threads")), "sockets": _num(static.get("sockets")),+ "numa": _num(static.get("numa_nodes"))},"disk": {"read": _num(hw.get("disk_read_mb")), "write": _num(hw.get("disk_write_mb")), "hist": _series(history, "disk_read_mb")},"ram": (_gib(hw.get("ram_used")), _gib(hw.get("ram_total"))),"experts": {"slots": slots, "total": total_slots, "gb": (cache_mib / 1024.0 if cache_mib is not None else None)},@@ -131,12 +155,53 @@ def build(metrics: dict | None) -> dict | None:"tps": request_speed(r), "duration": _num(r.get("duration_s"))} for r in recent[:6]],"sampled_at": _num(metrics.get("time")),}+ cards = model["gpu"]["cards"]+ if cards: # two or more cards: the tiles say it for the whole computer, the Cards strip says it per card+ g = model["gpu"]+ g["util"] = _most([c["util"] for c in cards]) # the busiest card+ g["vram_used"] = _total([c["mem_used"] for c in cards]) # all cards together+ g["vram_total"] = _total([c["mem_total"] for c in cards])+ g["vram_hist"] = [g["vram_used"]] * 60 if g["vram_used"] is not None else [] # the server keeps a history of card 0 only: a flat line, not a wrong one+ g["temp"] = _most([c["temp"] for c in cards]) # the hottest card+ g["power"] = _total([c["power"] for c in cards])+ g["power_limit"] = _total([c["power_limit"] for c in cards])+ g["count"] = float(len(cards))+ return model# ------------------------------------------------------------------------------------------------ drawing-def spark(values: list[float | None], width: int, glyphs: str, lo: float | None = None, hi: float | None = None) -> str:- """One row of block characters for the last `width` samples; blanks where a sample is missing; ASCII ramp when `glyphs` is ascii."""+def solid_spark(values: list, width: int, lo: float | None, hi: float | None) -> Text:+ """The classic console's sparkline (glyphs="solid"): only solid blocks, no dithered shades (ClearType fringes those with colour):+ a thin dim ▄ for the lowest quarter, ▄ for the middle, █ for the top."""+ vals = values[-width:]+ present = [v for v in vals if v is not None]+ if not present:+ return Text(" " * width)+ out = Text(" " * (width - len(vals)))+ low = min(present) if lo is None else lo+ high = max(present) if hi is None else hi+ if high - low < 1e-9:+ high = low + 1.0+ for v in vals:+ if v is None:+ out.append(" ")+ continue+ f = (v - low) / (high - low)+ if f < 0.25:+ out.append("▄", style=SOLID_TRACK)+ elif f < 0.6:+ out.append("▄")+ else:+ out.append("█")+ return out+++def spark(values: list[float | None], width: int, glyphs: str, lo: float | None = None, hi: float | None = None) -> str | Text:+ """One row of block characters for the last `width` samples; blanks where a sample is missing; ASCII ramp when `glyphs` is ascii,+ solid blocks (a Text) in the classic console's solid look."""+ if glyphs == "solid":+ return solid_spark(values, width, lo, hi)ramp = ".:-=+*#@" if glyphs == "ascii" else "▁▂▃▄▅▆▇█"vals = values[-width:]present = [v for v in vals if v is not None]@@ -156,8 +221,13 @@ def spark(values: list[float | None], width: int, glyphs: str, lo: float | Nonedef bar(frac: float | None, width: int, glyphs: str, color: str, empty: str = GREY) -> Text:- full, hollow = ("#", ".") if glyphs == "ascii" else ("█", "░")t = Text(no_wrap=True)+ if glyphs == "solid": # solid █ and a thin ▄ track: no dithered shades in the classic console+ n = 0 if frac is None else int(round(max(0.0, min(1.0, frac)) * width))+ t.append("█" * n, style=color)+ t.append("▄" * (width - n), style=SOLID_TRACK)+ return t+ full, hollow = ("#", ".") if glyphs == "ascii" else ("█", "░")if frac is None:t.append(hollow * width, style=GREY)return t@@ -197,19 +267,48 @@ def _tile(title: str, big: str, sub: str, series: str, width: int, *, accent: stbody = Text(no_wrap=True, overflow="crop")body.append(big + "\n", style=big_style)body.append(sub + "\n", style="dim")- body.append(series, style=accent)+ if isinstance(series, Text): # the solid look's sparkline carries its own styles+ styled = Text(style=accent)+ styled.append_text(series)+ body.append_text(styled)+ else:+ body.append(series, style=accent)return Panel(body, title=Text(title, style="dim"), title_align="left", box=box_style, padding=(0, 1), width=width,border_style="dim")+def _cards_strip(cards: list[dict], glyphs: str, accent: str, ascii_mode: bool) -> Text:+ """One line per card (up to 4): a small load bar, load %, memory, temperature and power; "+ N more cards" beyond that."""+ t = Text(no_wrap=True, overflow="crop")+ t.append("Cards" + chr(10), style=f"bold {accent}")+ shown = cards[:4]+ names = [short_gpu(c.get("name")) for c in shown]+ pad = min(16, max(len(n) for n in names))+ for c, name in zip(shown, names):+ util = c["util"]+ used, total = c["mem_used"], c["mem_total"]+ t.append(f"GPU {c['index'] if c['index'] is not None else '?'} {name[:pad]:<{pad}} ")+ t.append_text(bar((util / 100.0) if util is not None else None, 10, glyphs, accent))+ mem = f"{fmt(used, 1)} / {fmt(total, 0)} GB" if used is not None and total is not None else "-- GB"+ temp = f"{fmt(c['temp'])} {'C' if ascii_mode else '°C'}"+ t.append(f" {fmt(util):>3} % {mem:<14} {temp:>6} {fmt(c['power']):>4} W" + chr(10))+ if len(cards) > 4:+ t.append(f"+ {len(cards) - 4} more cards: press 5" + chr(10), style="dim")+ return t++def render(model: dict, *, width: int, height: int, connection: str, connection_state: str = "connected", frozen: bool = False,glyphs: str = "unicode", color: bool = True, theme: str = "dark", connect: bool = False, view_label: str = "Overview",- now: float | None = None) -> Group:+ now: float | None = None, bullet: str = "●") -> Group:now = time.time() if now is None else nowascii_mode = glyphs == "ascii"- box_style = box.SQUARE if ascii_mode else box.ROUNDED+ solid = glyphs == "solid" # the classic Windows console without Cascadia Mono: solid blocks, square boxes, palette colours+ box_style = box.SQUARE if (ascii_mode or solid) else box.ROUNDEDaccent = ("#0c8a60" if theme == "light" else ACCENT) if color else "default"- plain = (lambda s: "default") if not color else (lambda s: s)+ blue, amber, red = BLUE, AMBER, RED+ if solid and color:+ accent, blue, amber, red = SOLID_ACCENT, SOLID_BLUE, SOLID_AMBER, SOLID_RED+ plain = (lambda s: "default") if not color else (lambda s: {BLUE: blue, AMBER: amber, RED: red}.get(s, s))state = model["state"]state_color = plain({"Idle": "default", "Reading": BLUE, "Generating": accent, "Queued": AMBER, "Error": RED}[state])age = None if model.get("sampled_at") is None else now - model["sampled_at"]@@ -229,7 +328,7 @@ def render(model: dict, *, width: int, height: int, connection: str, connection_label = f"{model.get('model') or ''} {k(ctx_max) if ctx_max else ''}".strip()head.append(label, style="bold")right = Text()- right.append(("● " if not ascii_mode else "* ") + model["phase_text"] + (f" · {pct}%" if pct is not None and state in ("Reading", "Generating") else ""),+ right.append((bullet + " " if not ascii_mode else "* ") + model["phase_text"] + (f" · {pct}%" if pct is not None and state in ("Reading", "Generating") else ""),style=state_color if state != "Idle" else "dim")right.append(" ")right.append(f"[{marker}]", style=f"bold {accent}" if marker == "LIVE" else "bold yellow")@@ -260,24 +359,29 @@ def render(model: dict, *, width: int, height: int, connection: str, connection_# ---- tilesg = model["gpu"]+ cards = g.get("cards") or []+ ncards = len(cards)tile_w = max(18, (min(width, 110) - 3) // 4)inner = tile_w - 4spd, spd_note, spd_hist = model["speed"]util_scale = dict(lo=0, hi=100)tiles1 = [_tile("Speed", f"{fmt(spd, 1)} tok/s" if spd is not None else "-- tok/s", spd_note, spark(spd_hist, inner, glyphs), tile_w, accent=accent, box_style=box_style),- _tile("GPU load", f"{fmt(g['util'])} %", short_gpu(g["name"]) if g["count"] in (None, 1) else f"{short_gpu(g['name'])} +{int(g['count']) - 1}",+ _tile("GPU load", f"{fmt(g['util'])} %", f"busiest of {ncards} cards" if ncards else+ short_gpu(g["name"]) if g["count"] in (None, 1) else f"{short_gpu(g['name'])} +{int(g['count']) - 1}",spark(g["util_hist"], inner, glyphs, **util_scale), tile_w, accent=accent, box_style=box_style),_tile("VRAM", f"{fmt(g['vram_used'], 1)} / {fmt(g['vram_total'], 0)} GB",- (f"{int(model['experts']['slots']):,} experts cached" if model["experts"]["slots"] is not None else "graphics memory"),+ (f"all {ncards} cards" if ncards else+ f"{int(model['experts']['slots']):,} experts cached" if model["experts"]["slots"] is not None else "graphics memory"),spark(g["vram_hist"], inner, glyphs, lo=0, hi=g["vram_total"]), tile_w, accent=accent, box_style=box_style),- _tile("GPU temp", f"{fmt(g['temp'])} °C" if not ascii_mode else f"{fmt(g['temp'])} C", "",+ _tile("GPU temp", f"{fmt(g['temp'])} °C" if not ascii_mode else f"{fmt(g['temp'])} C", "hottest card" if ncards else "",spark(g["temp_hist"], inner, glyphs, lo=20, hi=100), tile_w, accent=plain(AMBER) if color else "default", box_style=box_style),]c, d = model["cpu"], model["disk"]gen = f"Gen{int(g['pcie_gen'])}" if g["pcie_gen"] else "PCIe"link = f"{gen} x{int(g['pcie_width'])}" if g["pcie_width"] else gen- cpu_sub = (f"{int(c['cores'])} cores · {int(c['threads'])} threads" if c["cores"] and c["threads"] else+ cpu_sub = (f"{int(c['sockets'])} CPUs · {int(c['cores'])} cores" if c.get("sockets") and c["sockets"] > 1 and c["cores"] else+ f"{int(c['cores'])} cores · {int(c['threads'])} threads" if c["cores"] and c["threads"] elsef"{int(c['threads'])} threads" if c["threads"] else "")tiles2 = [_tile("Power", f"{fmt(g['power'])} W", f"of {fmt(g['power_limit'])} W limit" if g["power_limit"] else "", spark(g["power_hist"], inner, glyphs, lo=0),@@ -321,7 +425,8 @@ def render(model: dict, *, width: int, height: int, connection: str, connection_for col, just in (("TIME", "left"), ("STATUS", "left"), ("PROMPT", "right"), ("REUSED", "right"), ("OUTPUT", "right"), ("TOK/S", "right"),("DURATION", "right")):req.add_column(col, justify=just, no_wrap=True)- show = max(2, min(6, height - 20))+ strip_rows = (1 + min(ncards, 4) + (1 if ncards > 4 else 0) + 1) if ncards else 0+ show = max(2, min(6, height - 20 - strip_rows))for r in model["recent"][:show]:stamp = time.strftime("%H:%M:%S", time.localtime(r["time"])) if r["time"] else "--"req.add_row(stamp, Text(r["state"], style=plain(accent) if r["state"] == "Done" else plain(RED if r["state"] == "Error" else AMBER)),@@ -335,5 +440,8 @@ def render(model: dict, *, width: int, height: int, connection: str, connection_bottom.add_row(Group(*lines), right)hint = Text(("1-7 views" if connect else "1-6 views") + " / filter Space freeze r refresh t theme b open in browser ? help q quit", style="dim")- parts: list[Any] = [head, tabs, rule, st, state_bar, Text(""), row(tiles1), row(tiles2), bottom, Text(""), hint]+ parts: list[Any] = [head, tabs, rule, st, state_bar, Text(""), row(tiles1), row(tiles2)]+ if ncards:+ parts += [Text(""), _cards_strip(cards, glyphs, accent, ascii_mode)]+ parts += [bottom, Text(""), hint]return Group(*parts)diff --git a/strata_cli/render.py b/strata_cli/render.pyindex 6663d46ef..b81df7ae9 100644--- a/strata_cli/render.py+++ b/strata_cli/render.py@@ -224,7 +224,9 @@ def _device(row: dict, width: int) -> str:mem = f"{number(used / 2**30 if isinstance(used, (int, float)) else None, '', 1)}/{number(total / 2**30 if isinstance(total, (int, float)) else None, ' GiB', 1)}"if width < 80:return _line(f"{label:<7} {mem:<17} util {number(row.get('util'), '%')}", width)- return _line(f"{label:<7} {field(row.get('name'), 18)} {mem:<17} {number(row.get('util'), '%'):>5} {number(row.get('temp'), ' C'):>6} {number(row.get('power'), ' W'):>7}", width)+ from strata_cli.overview import short_gpu # "NVIDIA GeForce RTX 3090" -> "RTX 3090": the maker's prefix used to cut the model off+ name = short_gpu(row.get("name")) if row.get("name") else None+ return _line(f"{label:<7} {field(name, 20)} {mem:<17} {number(row.get('util'), '%'):>5} {number(row.get('temp'), ' C'):>6} {number(row.get('power'), ' W'):>7}", width)def _device_stage(topology: dict, index: Any, width: int) -> str:diff --git a/tests/terminal/test_cpu_topology.py b/tests/terminal/test_cpu_topology.pynew file mode 100644index 000000000..a1c54d8e6--- /dev/null+++ b/tests/terminal/test_cpu_topology.py@@ -0,0 +1,61 @@+"""serve/telemetry.py `_cpu_topology`: how many CPU sockets and NUMA nodes the computer has (for "2 CPUs · 64 cores" in the monitor)."""++from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++from serve import telemetry+++def fake_sysfs(root: Path, packages: list[int], nodes: int) -> None:+ for i, pkg in enumerate(packages):+ d = root / "cpu" / f"cpu{i}" / "topology"+ d.mkdir(parents=True)+ (d / "physical_package_id").write_text(f"{pkg}\n")+ (root / "cpu" / "cpufreq").mkdir() # not a cpuN folder: never counted+ for n in range(nodes):+ (root / "node" / f"node{n}").mkdir(parents=True)+++class Topology(unittest.TestCase):+ def read(self, root):+ with mock.patch.object(telemetry.os, "name", "posix"), mock.patch.object(telemetry.sys, "platform", "linux"):+ return telemetry._cpu_topology(str(root))++ def test_two_sockets_two_numa_nodes(self):+ with tempfile.TemporaryDirectory() as tmp:+ fake_sysfs(Path(tmp), [0, 0, 0, 0, 1, 1, 1, 1], 2) # 8 logical CPUs on 2 packages+ self.assertEqual(self.read(tmp), (2, 2))++ def test_one_socket(self):+ with tempfile.TemporaryDirectory() as tmp:+ fake_sysfs(Path(tmp), [0, 0, 0, 0], 1)+ self.assertEqual(self.read(tmp), (1, 1))++ def test_one_socket_with_several_memory_nodes(self): # e.g. an EPYC with NPS4: one package, four nodes+ with tempfile.TemporaryDirectory() as tmp:+ fake_sysfs(Path(tmp), [0] * 8, 4)+ self.assertEqual(self.read(tmp), (1, 4))++ def test_nothing_readable_is_none_not_a_guess(self):+ with tempfile.TemporaryDirectory() as tmp:+ self.assertEqual(self.read(tmp), (None, None))++ def test_this_computer_answers_in_numbers(self):+ sockets, numa = telemetry._cpu_topology()+ self.assertTrue(sockets is None or sockets >= 1)+ self.assertTrue(numa is None or numa >= 1)++ def test_the_hardware_info_carries_them(self):+ src = (Path(telemetry.__file__)).read_text(encoding="utf-8")+ self.assertIn('"sockets"', src)+ self.assertIn('"numa_nodes"', src)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/terminal/test_monitor_classic.py b/tests/terminal/test_monitor_classic.pynew file mode 100644index 000000000..39057d64d--- /dev/null+++ b/tests/terminal/test_monitor_classic.py@@ -0,0 +1,232 @@+"""The monitor in the classic Windows console (Cascadia Mono switch, the solid look, the tip) and with several cards / CPUs."""++from __future__ import annotations++import io+import os+import time+import unittest+from unittest import mock++from rich.console import Console++from strata_cli import consoleinfo, monitor, overview+from tests.terminal.test_overview import GIB, metrics++TIP = "For the full look, use Windows Terminal (built into Windows 11)"+++def draw(model, width=110, height=40, **kw) -> str:+ c = Console(width=width + 2, record=True, file=io.StringIO(), force_terminal=False, legacy_windows=False)+ c.print(overview.render(model, width=width, height=height, connection="http://127.0.0.1:8080", **kw))+ return c.export_text()+++def three_cards(sockets=2):+ m = metrics("generating")+ cards = [{"index": i, "name": "NVIDIA GeForce RTX 3090", "util": u, "mem_used": used * GIB, "mem_total": 24 * GIB, "temp": t, "power": p, "power_limit": 350}+ for i, (u, used, t, p) in enumerate(((88, 22.1, 61, 236), (71, 21.4, 58, 201), (64, 20.8, 55, 188)))]+ m["hardware"]["gpus"] = cards+ m["hardware_static"].update({"gpu_name": "NVIDIA GeForce RTX 3090", "gpu_count": 3, "cores": 64, "threads": 128, "sockets": sockets, "numa_nodes": 2})+ return m+++class WhichLook(unittest.TestCase):+ def setUp(self):+ consoleinfo.forget_style()+ self.addCleanup(consoleinfo.forget_style)++ def test_decide_style_by_the_facts(self):+ d = consoleinfo.decide_style(legacy=False, cascadia_ok=False, font=None)+ self.assertEqual((d["mode"], d["tip"]), ("none", None)) # Windows Terminal, Linux, macOS: nothing changes+ d = consoleinfo.decide_style(legacy=True, cascadia_ok=True, font="Cascadia Mono")+ self.assertEqual((d["mode"], d["tip"]), ("full", TIP)) # the font was switched: the full Unicode look, the tip anyway+ d = consoleinfo.decide_style(legacy=True, cascadia_ok=False, font="Consolas")+ self.assertEqual((d["mode"], d["bullet"], d["tip"]), ("solid", "●", TIP))+ d = consoleinfo.decide_style(legacy=True, cascadia_ok=False, font="Lucida Console")+ self.assertEqual((d["mode"], d["bullet"]), ("solid", "•")) # Lucida has no ●+ self.assertEqual(consoleinfo.decide_style(legacy=True, cascadia_ok=False, font=None)["bullet"], "•")++ def test_classic_style_switches_the_font_once_when_cascadia_is_installed(self):+ with mock.patch.object(consoleinfo, "legacy_console", return_value=True), mock.patch.object(consoleinfo.os, "name", "nt"), \+ mock.patch.dict(os.environ, {"STRATA_GLYPHS": ""}), mock.patch.object(consoleinfo, "cascadia_installed", return_value=True), \+ mock.patch.object(consoleinfo, "console_font", side_effect=["Consolas", "Cascadia Mono"]), \+ mock.patch.object(consoleinfo, "switch_font", return_value=True) as sw:+ s = consoleinfo.classic_style()+ self.assertEqual(s["mode"], "full")+ sw.assert_called_once_with("Cascadia Mono")+ consoleinfo.classic_style()+ sw.assert_called_once() # cached: the font API is not called again++ def test_without_cascadia_or_when_the_switch_fails_the_solid_look_with_the_font_it_has(self):+ for installed, switched in ((False, False), (True, False)):+ consoleinfo.forget_style()+ with mock.patch.object(consoleinfo, "legacy_console", return_value=True), mock.patch.object(consoleinfo.os, "name", "nt"), \+ mock.patch.dict(os.environ, {"STRATA_GLYPHS": ""}), mock.patch.object(consoleinfo, "cascadia_installed", return_value=installed), \+ mock.patch.object(consoleinfo, "console_font", return_value="Lucida Console"), \+ mock.patch.object(consoleinfo, "switch_font", return_value=switched):+ s = consoleinfo.classic_style()+ self.assertEqual((s["mode"], s["bullet"]), ("solid", "•"))++ def test_never_in_windows_terminal_linux_or_mac(self):+ with mock.patch.object(consoleinfo, "legacy_console", return_value=False), mock.patch.object(consoleinfo, "switch_font") as sw:+ self.assertEqual(consoleinfo.classic_style()["mode"], "none")+ sw.assert_not_called()+ env = {k: v for k, v in os.environ.items() if k not in ("WT_SESSION", "TERM_PROGRAM", "STRATA_GLYPHS")}+ env["WT_SESSION"] = "x"+ with mock.patch.dict(os.environ, env, clear=True), mock.patch.object(consoleinfo.os, "name", "nt"), mock.patch.object(consoleinfo.sys, "platform", "win32"):+ self.assertFalse(consoleinfo.legacy_console()) # Windows Terminal+ with mock.patch.dict(os.environ, {}, clear=True), mock.patch.object(consoleinfo.os, "name", "posix"), mock.patch.object(consoleinfo.sys, "platform", "linux"):+ self.assertFalse(consoleinfo.legacy_console())+ with mock.patch.object(consoleinfo.os, "name", "posix"):+ self.assertIsNone(consoleinfo.console_font())+ self.assertFalse(consoleinfo.switch_font())+ self.assertFalse(consoleinfo.cascadia_installed())++ def test_choose_glyphs(self):+ with mock.patch.object(consoleinfo, "legacy_console", return_value=True), mock.patch.object(consoleinfo, "classic_style", return_value={"mode": "full"}):+ self.assertEqual(monitor.choose_glyphs("auto", "utf-8", "xterm"), "unicode")+ with mock.patch.object(consoleinfo, "legacy_console", return_value=True), mock.patch.object(consoleinfo, "classic_style", return_value={"mode": "solid"}):+ self.assertEqual(monitor.choose_glyphs("auto", "utf-8", None), "solid")+ with mock.patch.dict(os.environ, {"STRATA_GLYPHS": "ascii"}):+ self.assertEqual(monitor.choose_glyphs("auto", "utf-8", None), "ascii") # forced ASCII stays ASCII+ self.assertEqual(monitor.choose_glyphs("unicode", "utf-8", None), "unicode") # an explicit --glyphs wins+ with mock.patch.object(consoleinfo, "legacy_console", return_value=False):+ self.assertEqual(monitor.choose_glyphs("auto", "utf-8", "xterm"), "unicode")+++class SolidLook(unittest.TestCase):+ def test_solid_blocks_only_no_dithered_shades_and_no_eighth_blocks(self):+ text = draw(overview.build(metrics("generating")), glyphs="solid")+ for ch in "░▒▓▁▂▃▅▆▇╭╮╰╯":+ self.assertNotIn(ch, text, ch)+ for ch in "█▄┌┐└┘":+ self.assertIn(ch, text, ch)++ def test_bars_use_a_thin_track_and_boxes_are_square(self):+ bar = overview.bar(0.25, 20, "solid", "bright_green")+ self.assertEqual(bar.plain, "█" * 5 + "▄" * 15)+ self.assertEqual(overview.bar(None, 4, "solid", "x").plain, "▄▄▄▄")+ self.assertEqual(overview.spark([0, 50, 100], 3, "solid", lo=0, hi=100).plain, "▄▄█")++ def test_the_16_palette_names_not_hex_colours(self):+ group = overview.render(overview.build(metrics("generating")), width=110, height=40, connection="x", glyphs="solid")+ c = Console(width=112, record=True, file=io.StringIO(), force_terminal=True, color_system="standard", legacy_windows=False)+ c.print(group)+ out = c.export_text(styles=True)+ self.assertNotIn("38;2;", out) # no 24-bit colours: conhost maps them to cyan or black++ def test_the_bullet_follows_the_font(self):+ m = overview.build(metrics("generating"))+ self.assertIn("● Generating", draw(m, glyphs="solid", bullet="●"))+ self.assertIn("• Generating", draw(m, glyphs="solid", bullet="•"))++ def test_the_other_looks_are_unchanged(self):+ m = overview.build(metrics("generating"))+ self.assertIn("╭", draw(m, glyphs="unicode"))+ self.assertNotIn("╭", draw(m, glyphs="ascii"))+++class SeveralCards(unittest.TestCase):+ def test_one_card_looks_exactly_as_before(self):+ base = metrics("generating")+ one = metrics("generating")+ one["hardware"]["gpus"] = [{"index": 0, "name": "NVIDIA GeForce RTX 5070", "util": 88, "mem_used": 11.2 * GIB, "mem_total": 12 * GIB, "temp": 54, "power": 114}]+ for glyphs in ("unicode", "ascii", "solid"):+ self.assertEqual(draw(overview.build(base), glyphs=glyphs, now=1.0), draw(overview.build(one), glyphs=glyphs, now=1.0), glyphs)+ self.assertNotIn("Cards", draw(overview.build(base)))++ def test_the_tiles_say_it_for_the_whole_computer(self):+ m = overview.build(three_cards())+ g = m["gpu"]+ self.assertEqual((g["util"], g["temp"], g["count"]), (88.0, 61.0, 3.0)) # the busiest, the hottest+ self.assertAlmostEqual(g["vram_used"], 64.3, places=1)+ self.assertEqual(g["vram_total"], 72.0) # all cards+ self.assertEqual((g["power"], g["power_limit"]), (625.0, 1050.0))+ text = draw(m)+ for want in ("busiest of 3 cards", "all 3 cards", "hottest card", "64.3 / 72 GB", "625 W", "of 1,050 W limit", "61 °C"):+ self.assertIn(want, text, want)+ self.assertNotIn("+2", text) # no more "RTX 3090 +2"++ def test_the_cards_strip_one_line_per_card(self):+ text = draw(overview.build(three_cards()))+ lines = [ln for ln in text.splitlines() if ln.startswith("GPU ")]+ self.assertEqual(len(lines), 3)+ self.assertIn("Cards", text)+ for want, line in zip(("88 %", "71 %", "64 %"), lines):+ self.assertIn(want, line)+ self.assertIn("22.1 / 24 GB", lines[0])+ self.assertIn("61 °C", lines[0])+ self.assertIn("236 W", lines[0])+ self.assertIn("RTX 3090", lines[0])++ def test_up_to_four_cards_then_a_pointer_to_view_5(self):+ m = three_cards()+ m["hardware"]["gpus"] += [dict(m["hardware"]["gpus"][0], index=i) for i in (3, 4, 5)]+ text = draw(overview.build(m), height=44)+ self.assertEqual(len([ln for ln in text.splitlines() if ln.startswith("GPU ")]), 4)+ self.assertIn("+ 2 more cards: press 5", text)++ def test_the_cpu_tile_says_how_many_cpus(self):+ self.assertIn("2 CPUs · 64 cores", draw(overview.build(three_cards(sockets=2))))+ one = draw(overview.build(three_cards(sockets=1)))+ self.assertIn("64 cores · 128 threads", one)+ self.assertNotIn("CPUs", one)+ self.assertIn("6 cores · 12 threads", draw(overview.build(metrics("generating")))) # no socket count reported: as before++ def test_a_missing_reading_stays_missing(self):+ m = three_cards()+ for c in m["hardware"]["gpus"]:+ c["temp"] = None+ c["power"] = None+ g = overview.build(m)["gpu"]+ self.assertIsNone(g["temp"])+ self.assertIsNone(g["power"])+ self.assertIn("-- °C", draw(overview.build(m)))++ def test_it_fits_the_width_and_the_classic_looks_too(self):+ for glyphs in ("unicode", "ascii", "solid"):+ for ln in draw(overview.build(three_cards()), glyphs=glyphs, width=100).splitlines():+ self.assertLessEqual(len(ln.rstrip()), 102, (glyphs, ln))+++class FooterAndViews(unittest.TestCase):+ def screen_text(self, classic):+ import asyncio+ from tests.terminal.test_overview import Source++ async def go():+ consoleinfo.forget_style()+ style = consoleinfo.decide_style(legacy=bool(classic), cascadia_ok=classic == "full", font="Consolas")+ with mock.patch.object(consoleinfo, "legacy_console", return_value=bool(classic)), mock.patch.object(consoleinfo, "classic_style", return_value=style):+ app = monitor.MonitorApp(Source(three_cards()), None, interval=30)+ async with app.run_test(size=(120, 40)) as pilot:+ await pilot.pause(0.5)+ return "\n".join(s.text for s in app.screen._compositor.render_strips())+ try:+ return asyncio.run(go())+ finally:+ consoleinfo.forget_style()++ def test_the_tip_is_in_the_classic_console_only(self):+ self.assertIn(TIP, self.screen_text("solid"))+ self.assertIn(TIP, self.screen_text("full")) # also when the font was switched: one line, always+ self.assertNotIn(TIP, self.screen_text(None)) # Windows Terminal, Linux, macOS++ def test_the_monitor_draws_the_several_cards_in_every_look(self):+ for classic in ("solid", "full", None):+ shown = self.screen_text(classic)+ self.assertIn("busiest of 3 cards", shown, classic)+ self.assertIn("Cards", shown, classic)+ self.assertIn("2 CPUs", shown, classic)++ def test_view_5_shows_the_whole_card_name(self):+ from strata_cli.render import _device+ row = {"index": 1, "name": "NVIDIA GeForce RTX 3090", "mem_used": 21.4 * GIB, "mem_total": 24 * GIB, "util": 71, "temp": 58, "power": 201}+ line = _device(row, 100)+ self.assertIn("RTX 3090", line)+ self.assertNotIn("NVIDIA", line)+++if __name__ == "__main__":+ unittest.main()