spongebob-cli 0.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. spongebob/__init__.py +1 -0
  2. spongebob/__main__.py +375 -0
  3. spongebob/analyzer/__init__.py +9 -0
  4. spongebob/analyzer/__main__.py +39 -0
  5. spongebob/analyzer/analyzer.py +234 -0
  6. spongebob/bus/__init__.py +6 -0
  7. spongebob/bus/bus.py +38 -0
  8. spongebob/diagnose/__init__.py +29 -0
  9. spongebob/diagnose/__main__.py +111 -0
  10. spongebob/diagnose/adapter.py +82 -0
  11. spongebob/diagnose/models.py +79 -0
  12. spongebob/diagnose/probes.py +129 -0
  13. spongebob/engine/__init__.py +26 -0
  14. spongebob/engine/__main__.py +25 -0
  15. spongebob/engine/models.py +161 -0
  16. spongebob/engine/simulator.py +196 -0
  17. spongebob/export/__init__.py +25 -0
  18. spongebob/export/exporter.py +354 -0
  19. spongebob/meter/__init__.py +7 -0
  20. spongebob/meter/__main__.py +50 -0
  21. spongebob/meter/meter.py +140 -0
  22. spongebob/narrator/__init__.py +25 -0
  23. spongebob/narrator/narrator.py +352 -0
  24. spongebob/plugins/__init__.py +28 -0
  25. spongebob/plugins/loader.py +308 -0
  26. spongebob/plugins/models.py +47 -0
  27. spongebob/scenarios/__init__.py +25 -0
  28. spongebob/scenarios/builtin/__init__.py +1 -0
  29. spongebob/scenarios/builtin/control-line.toml +33 -0
  30. spongebob/scenarios/builtin/crowded-wifi.toml +33 -0
  31. spongebob/scenarios/builtin/flaky-last-mile.toml +33 -0
  32. spongebob/scenarios/builtin/long-haul-orbit.toml +33 -0
  33. spongebob/scenarios/builtin/overloaded-uplink.toml +35 -0
  34. spongebob/scenarios/builtin/tunnel-burst.toml +38 -0
  35. spongebob/scenarios/loader.py +205 -0
  36. spongebob/scenarios/models.py +55 -0
  37. spongebob/scenarios/runner.py +24 -0
  38. spongebob/ui/__init__.py +23 -0
  39. spongebob/ui/__main__.py +11 -0
  40. spongebob/ui/app.py +88 -0
  41. spongebob/ui/canvas.py +147 -0
  42. spongebob/ui/diagnose_screen.py +525 -0
  43. spongebob/ui/export_modal.py +158 -0
  44. spongebob/ui/menu_screen.py +159 -0
  45. spongebob/ui/replay.py +209 -0
  46. spongebob/ui/settings_screen.py +101 -0
  47. spongebob/ui/simulate_screen.py +566 -0
  48. spongebob/ui/theme.py +364 -0
  49. spongebob/ui/visualize_screen.py +411 -0
  50. spongebob_cli-0.3.2.dist-info/METADATA +78 -0
  51. spongebob_cli-0.3.2.dist-info/RECORD +54 -0
  52. spongebob_cli-0.3.2.dist-info/WHEEL +5 -0
  53. spongebob_cli-0.3.2.dist-info/entry_points.txt +2 -0
  54. spongebob_cli-0.3.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,566 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ from textual.app import ComposeResult
6
+ from textual.binding import Binding
7
+ from textual.containers import Horizontal, Vertical, VerticalScroll
8
+ from textual.screen import Screen
9
+ from textual.widgets import Button, Footer, Input, Label, Select, Static
10
+
11
+ from spongebob.analyzer import Finding, analyze
12
+ from spongebob.engine import Flow, Hop, default_path, simulate
13
+ from spongebob.export import ExportPayload, export_report
14
+ from spongebob.meter import Metrics, measure
15
+ from spongebob.narrator import MASCOT_NAME
16
+ from spongebob.scenarios import (
17
+ Scenario,
18
+ list_builtin_scenarios,
19
+ load_builtin_scenario,
20
+ load_scenario,
21
+ )
22
+ from spongebob.ui import theme
23
+ from spongebob.ui.export_modal import ExportOverwriteModal
24
+
25
+
26
+ class SimulateScreen(Screen[None]):
27
+ """Configure flow and per-hop impairments, validate live, and inspect results."""
28
+
29
+ BINDINGS = [
30
+ Binding("escape", "go_back", "Back"),
31
+ Binding("v", "open_visualize", "Visualize"),
32
+ ]
33
+
34
+ CSS = f"""
35
+ SimulateScreen {{
36
+ layout: vertical;
37
+ background: {theme.BG};
38
+ color: {theme.CREAM};
39
+ }}
40
+ #sim-layout {{
41
+ height: 1fr;
42
+ }}
43
+ #config-pane {{
44
+ width: 58%;
45
+ padding: 0 1;
46
+ }}
47
+ #path-impairment-box {{
48
+ border: solid {theme.SIGNAL_GREEN};
49
+ background: {theme.BG};
50
+ padding: 0 1;
51
+ height: auto;
52
+ margin-bottom: 1;
53
+ }}
54
+ #core-header-row {{
55
+ height: 1;
56
+ color: {theme.SIGNAL_GREEN};
57
+ text-style: bold;
58
+ }}
59
+ .core-hop-row {{
60
+ height: 1;
61
+ }}
62
+ .core-hop-name {{
63
+ width: 10;
64
+ height: 1;
65
+ color: {theme.CREAM};
66
+ text-style: bold;
67
+ }}
68
+ .core-col-hdr {{
69
+ width: 1fr;
70
+ height: 1;
71
+ color: {theme.SIGNAL_GREEN};
72
+ text-style: bold;
73
+ }}
74
+ .core-input {{
75
+ width: 1fr;
76
+ height: 1;
77
+ border: none;
78
+ padding: 0 1;
79
+ background: {theme.BG};
80
+ color: {theme.CREAM};
81
+ }}
82
+ .core-input:focus {{
83
+ background: {theme.BANNER_BLUE};
84
+ color: {theme.CREAM};
85
+ }}
86
+ #secondary-scroll {{
87
+ height: 1fr;
88
+ border: solid {theme.SIGNAL_GREEN};
89
+ padding: 0 1;
90
+ }}
91
+ #results-pane {{
92
+ width: 42%;
93
+ padding: 0 1;
94
+ border: solid {theme.SIGNAL_GREEN};
95
+ }}
96
+ .section-title {{
97
+ text-style: bold;
98
+ color: {theme.SIGNAL_GREEN};
99
+ margin-top: 1;
100
+ margin-bottom: 0;
101
+ }}
102
+ .hop-card {{
103
+ border: solid {theme.TEAL_DARK};
104
+ padding: 0 1;
105
+ margin-bottom: 1;
106
+ height: auto;
107
+ }}
108
+ .hop-header {{
109
+ text-style: bold;
110
+ color: {theme.TEAL_LIGHT};
111
+ }}
112
+ .row {{
113
+ height: auto;
114
+ margin-bottom: 0;
115
+ }}
116
+ .field {{
117
+ width: 1fr;
118
+ height: auto;
119
+ margin-right: 1;
120
+ }}
121
+ .field-label {{
122
+ color: {theme.SIGNAL_GREEN};
123
+ }}
124
+ #validation-error {{
125
+ color: {theme.CRIT_RED};
126
+ text-style: bold;
127
+ min-height: 1;
128
+ }}
129
+ #actions-row {{
130
+ height: auto;
131
+ margin-top: 0;
132
+ }}
133
+ #actions-row Button {{
134
+ margin-right: 1;
135
+ }}
136
+ #export-path, #scenario-path, #scenario-select {{
137
+ width: 1fr;
138
+ margin-right: 1;
139
+ }}
140
+ #metrics-output, #findings-output, #narrator-output {{
141
+ margin-bottom: 1;
142
+ color: {theme.CREAM};
143
+ }}
144
+ #too-small {{
145
+ width: 100%;
146
+ height: 1fr;
147
+ content-align: center middle;
148
+ color: {theme.WARN_AMBER};
149
+ text-style: bold;
150
+ display: none;
151
+ }}
152
+ """
153
+
154
+ def __init__(self) -> None:
155
+ super().__init__()
156
+ self._has_results = False
157
+ self._dirty = False
158
+ self._initial_values: dict[str | None, str] = {}
159
+ self._last_export_data: tuple[Scenario, list, Metrics, list[Finding], list] | None = None
160
+
161
+ def compose(self) -> ComposeResult:
162
+ yield theme.make_top_title("SIMULATE")
163
+ yield theme.RedTopRule(classes="red-rule")
164
+ yield Static("SIMULATE — CORE IMPAIRMENTS & FLOW", classes="screen-banner")
165
+ yield Static("Enlarge terminal (minimum 50x16 required).", id="too-small")
166
+
167
+ default_delays = {"client": "5", "router": "15", "isp": "25", "server": "5"}
168
+ default_jitters = {"client": "1", "router": "5", "isp": "8", "server": "1"}
169
+ default_losses = {"client": "0", "router": "1", "isp": "2", "server": "0"}
170
+ hop_names = [h.name for h in default_path()]
171
+
172
+ with Horizontal(id="sim-layout"):
173
+ with Vertical(id="config-pane"):
174
+ with Vertical(id="path-impairment-box"):
175
+ yield Static("PATH IMPAIRMENT", classes="box-title")
176
+ with Horizontal(id="core-header-row"):
177
+ yield Label("HOP", classes="core-hop-name")
178
+ yield Label("DELAY ms", classes="core-col-hdr")
179
+ yield Label("JITTER ms", classes="core-col-hdr")
180
+ yield Label("LOSS %", classes="core-col-hdr")
181
+ for hop_name in hop_names:
182
+ with Horizontal(classes="core-hop-row"):
183
+ yield Label(hop_name.upper(), classes="core-hop-name")
184
+ yield Input(
185
+ default_delays[hop_name],
186
+ id=f"hop-{hop_name}-delay",
187
+ classes="core-input",
188
+ )
189
+ yield Input(
190
+ default_jitters[hop_name],
191
+ id=f"hop-{hop_name}-jitter",
192
+ classes="core-input",
193
+ )
194
+ yield Input(
195
+ default_losses[hop_name],
196
+ id=f"hop-{hop_name}-loss",
197
+ classes="core-input",
198
+ )
199
+
200
+ with VerticalScroll(id="secondary-scroll"):
201
+ yield Static("LOAD SCENARIO", classes="section-title")
202
+ scenario_options: list[tuple[str, str]] = [
203
+ (name, name) for name in list_builtin_scenarios()
204
+ ]
205
+ reg = getattr(self.app, "plugin_registry", None)
206
+ if reg is not None:
207
+ for pname in sorted(reg.scenarios):
208
+ scenario_options.append((pname, pname))
209
+ with Horizontal(classes="row"):
210
+ yield Select(
211
+ scenario_options,
212
+ prompt="Select built-in / plugin",
213
+ id="scenario-select",
214
+ )
215
+ yield Input("", placeholder="or type .toml path", id="scenario-path")
216
+ yield Button("Load", id="btn-load-scenario")
217
+
218
+ yield Static("FLOW SETTINGS", classes="section-title")
219
+ with Horizontal(classes="row"):
220
+ with Vertical(classes="field"):
221
+ yield Label("PACKETS", classes="field-label")
222
+ yield Input("100", id="flow-packets")
223
+ with Vertical(classes="field"):
224
+ yield Label("INTERVAL MS", classes="field-label")
225
+ yield Input("10.0", id="flow-interval")
226
+ with Vertical(classes="field"):
227
+ yield Label("SIZE BYTES", classes="field-label")
228
+ yield Input("64", id="flow-size")
229
+ with Vertical(classes="field"):
230
+ yield Label("SEED", classes="field-label")
231
+ yield Input("42", id="flow-seed")
232
+
233
+ yield Static("BANDWIDTH CAP & BURSTY LOSS", classes="section-title")
234
+ for hop_name in hop_names:
235
+ with Vertical(classes="hop-card"):
236
+ yield Static(f"HOP: {hop_name.upper()}", classes="hop-header")
237
+ with Horizontal(classes="row"):
238
+ with Vertical(classes="field"):
239
+ yield Label("BW KBPS", classes="field-label")
240
+ yield Input("", id=f"hop-{hop_name}-bw")
241
+ with Vertical(classes="field"):
242
+ yield Label("QUEUE LIMIT", classes="field-label")
243
+ yield Input("", id=f"hop-{hop_name}-qlim")
244
+ with Vertical(classes="field"):
245
+ yield Label("LOSS MODEL", classes="field-label")
246
+ yield Select(
247
+ [("random", "random"), ("gilbert", "gilbert")],
248
+ value="random",
249
+ id=f"hop-{hop_name}-lmodel",
250
+ )
251
+ with Horizontal(classes="row"):
252
+ with Vertical(classes="field"):
253
+ yield Label("P_G2B (0-1)", classes="field-label")
254
+ yield Input("0.0", id=f"hop-{hop_name}-pg2b")
255
+ with Vertical(classes="field"):
256
+ yield Label("P_B2G (0-1)", classes="field-label")
257
+ yield Input("0.0", id=f"hop-{hop_name}-pb2g")
258
+ with Vertical(classes="field"):
259
+ yield Label("LOSS_BAD (%)", classes="field-label")
260
+ yield Input("100.0", id=f"hop-{hop_name}-lbad")
261
+
262
+ yield Static("", id="validation-error")
263
+ with Horizontal(id="actions-row"):
264
+ yield Button("Run Simulation", id="btn-run", variant="primary")
265
+ yield Button("Visualize (V)", id="btn-open-visualize", disabled=True)
266
+
267
+ with VerticalScroll(id="results-pane"):
268
+ yield Static("METRICS", classes="section-title")
269
+ yield Static("Run a simulation to view metrics.", id="metrics-output")
270
+ yield Static("FINDINGS", classes="section-title")
271
+ yield Static("No findings yet.", id="findings-output")
272
+ yield Static(MASCOT_NAME.upper(), classes="section-title")
273
+ yield Static("Narrator ready.", id="narrator-output")
274
+ yield Static("EXPORT REPORT", classes="section-title")
275
+ with Horizontal(classes="row"):
276
+ yield Input("", placeholder="report.json / .csv / .md", id="export-path")
277
+ yield Button("Export", id="btn-export", disabled=True)
278
+ yield Static("", id="export-status")
279
+ yield Static(theme.format_status_line("SIMULATE READY", 0.0), id="sim-status", classes="status-bar")
280
+ yield Footer()
281
+
282
+ def on_mount(self) -> None:
283
+ self._initial_values = {
284
+ inp.id: inp.value for inp in self.query(Input)
285
+ }
286
+ self._check_size()
287
+
288
+ def on_resize(self) -> None:
289
+ self._check_size()
290
+
291
+ def _check_size(self) -> None:
292
+ too_small = self.query_one("#too-small", Static)
293
+ layout = self.query_one("#sim-layout", Horizontal)
294
+ if self.size.width < 50 or self.size.height < 16:
295
+ too_small.styles.display = "block"
296
+ layout.styles.display = "none"
297
+ else:
298
+ too_small.styles.display = "none"
299
+ layout.styles.display = "block"
300
+
301
+ def _parse_config(self) -> tuple[Flow, list[Hop], int | None]:
302
+ packets = int(self.query_one("#flow-packets", Input).value.strip())
303
+ interval = float(self.query_one("#flow-interval", Input).value.strip())
304
+ size_bytes = int(self.query_one("#flow-size", Input).value.strip())
305
+ seed_raw = self.query_one("#flow-seed", Input).value.strip()
306
+ seed = int(seed_raw) if seed_raw else None
307
+ flow = Flow(packet_count=packets, interval_ms=interval, size_bytes=size_bytes)
308
+
309
+ hops: list[Hop] = []
310
+ for hop_name in [h.name for h in default_path()]:
311
+ delay = float(self.query_one(f"#hop-{hop_name}-delay", Input).value.strip())
312
+ jitter = float(self.query_one(f"#hop-{hop_name}-jitter", Input).value.strip())
313
+ loss = float(self.query_one(f"#hop-{hop_name}-loss", Input).value.strip())
314
+
315
+ bw_raw = self.query_one(f"#hop-{hop_name}-bw", Input).value.strip()
316
+ bw = float(bw_raw) if bw_raw else None
317
+
318
+ qlim_raw = self.query_one(f"#hop-{hop_name}-qlim", Input).value.strip()
319
+ qlim = int(qlim_raw) if qlim_raw else None
320
+
321
+ lmodel_val = self.query_one(f"#hop-{hop_name}-lmodel", Select).value
322
+ lmodel = str(lmodel_val) if lmodel_val is not None else "random"
323
+
324
+ pg2b = float(self.query_one(f"#hop-{hop_name}-pg2b", Input).value.strip())
325
+ pb2g = float(self.query_one(f"#hop-{hop_name}-pb2g", Input).value.strip())
326
+ lbad = float(self.query_one(f"#hop-{hop_name}-lbad", Input).value.strip())
327
+
328
+ hops.append(
329
+ Hop(
330
+ name=hop_name,
331
+ delay_ms=delay,
332
+ jitter_ms=jitter,
333
+ loss_pct=loss,
334
+ bandwidth_kbps=bw,
335
+ queue_limit_packets=qlim,
336
+ loss_model=lmodel, # type: ignore[arg-type]
337
+ p_good_to_bad=pg2b,
338
+ p_bad_to_good=pb2g,
339
+ loss_bad=lbad,
340
+ )
341
+ )
342
+ return flow, hops, seed
343
+
344
+ def _validate_live(self) -> tuple[Flow, list[Hop], int | None] | None:
345
+ err_widget = self.query_one("#validation-error", Static)
346
+ run_btn = self.query_one("#btn-run", Button)
347
+ try:
348
+ parsed = self._parse_config()
349
+ err_widget.update("")
350
+ run_btn.disabled = False
351
+ return parsed
352
+ except (ValueError, TypeError) as exc:
353
+ err_widget.update(f"Invalid input: {exc}")
354
+ run_btn.disabled = True
355
+ return None
356
+
357
+ def on_input_changed(self, event: Input.Changed) -> None:
358
+ if not self._dirty and event.value == self._initial_values.get(event.input.id):
359
+ return
360
+ self._dirty = True
361
+ self._validate_live()
362
+
363
+ def on_select_changed(self, event: Select.Changed) -> None:
364
+ if event.select.id == "scenario-select" and event.value not in (None, Select.BLANK):
365
+ self._load_named_scenario(str(event.value))
366
+ return
367
+ if self._initial_values:
368
+ self._dirty = True
369
+ self._validate_live()
370
+
371
+ def on_button_pressed(self, event: Button.Pressed) -> None:
372
+ if event.button.id == "btn-run":
373
+ self._run_simulation()
374
+ elif event.button.id == "btn-open-visualize":
375
+ self.action_open_visualize()
376
+ elif event.button.id == "btn-load-scenario":
377
+ self._load_typed_scenario()
378
+ elif event.button.id == "btn-export":
379
+ self._handle_export()
380
+
381
+ def _apply_scenario(self, scenario: Scenario) -> None:
382
+ self.query_one("#flow-packets", Input).value = str(scenario.flow.packet_count)
383
+ self.query_one("#flow-interval", Input).value = str(scenario.flow.interval_ms)
384
+ self.query_one("#flow-size", Input).value = str(scenario.flow.size_bytes)
385
+ self.query_one("#flow-seed", Input).value = (
386
+ "" if scenario.seed is None else str(scenario.seed)
387
+ )
388
+ by_name = {h.name: h for h in scenario.hops}
389
+ default_names = [h.name for h in default_path()]
390
+ for idx, hop_name in enumerate(default_names):
391
+ hop = by_name.get(hop_name)
392
+ if hop is None and idx < len(scenario.hops):
393
+ hop = scenario.hops[idx]
394
+ if hop is None:
395
+ continue
396
+ self.query_one(f"#hop-{hop_name}-delay", Input).value = str(hop.delay_ms)
397
+ self.query_one(f"#hop-{hop_name}-jitter", Input).value = str(hop.jitter_ms)
398
+ self.query_one(f"#hop-{hop_name}-loss", Input).value = str(hop.loss_pct)
399
+ self.query_one(f"#hop-{hop_name}-bw", Input).value = (
400
+ "" if hop.bandwidth_kbps is None else str(hop.bandwidth_kbps)
401
+ )
402
+ self.query_one(f"#hop-{hop_name}-qlim", Input).value = (
403
+ "" if hop.queue_limit_packets is None else str(hop.queue_limit_packets)
404
+ )
405
+ self.query_one(f"#hop-{hop_name}-lmodel", Select).value = hop.loss_model
406
+ self.query_one(f"#hop-{hop_name}-pg2b", Input).value = str(hop.p_good_to_bad)
407
+ self.query_one(f"#hop-{hop_name}-pb2g", Input).value = str(hop.p_bad_to_good)
408
+ self.query_one(f"#hop-{hop_name}-lbad", Input).value = str(hop.loss_bad)
409
+ self.query_one("#sim-status", Static).update(
410
+ theme.format_status_line(f"LOADED {scenario.name.upper()}", 0.0)
411
+ )
412
+
413
+ def _load_named_scenario(self, name: str) -> None:
414
+ reg = getattr(self.app, "plugin_registry", None)
415
+ try:
416
+ if reg is not None and name in reg.scenarios:
417
+ sc = reg.scenarios[name]
418
+ else:
419
+ sc = load_builtin_scenario(name)
420
+ self._apply_scenario(sc)
421
+ except Exception as exc:
422
+ self.query_one("#validation-error", Static).update(f"Scenario error: {exc}")
423
+
424
+ def _load_typed_scenario(self) -> None:
425
+ raw_path = self.query_one("#scenario-path", Input).value.strip()
426
+ if not raw_path:
427
+ self.query_one("#validation-error", Static).update("Enter a scenario .toml path.")
428
+ return
429
+ try:
430
+ sc = load_scenario(raw_path)
431
+ self._apply_scenario(sc)
432
+ self.query_one("#validation-error", Static).update("")
433
+ except Exception as exc:
434
+ self.query_one("#validation-error", Static).update(f"Scenario error: {exc}")
435
+
436
+ def _handle_export(self) -> None:
437
+ if self._last_export_data is None:
438
+ return
439
+ raw_path = self.query_one("#export-path", Input).value.strip()
440
+ status = self.query_one("#export-status", Static)
441
+ if not raw_path:
442
+ status.update("Enter an export path (.json, .csv, .md).")
443
+ return
444
+ sc, events, metrics, findings, narr_lines = self._last_export_data
445
+ payload = ExportPayload(
446
+ source="simulation",
447
+ metrics=metrics,
448
+ findings=findings,
449
+ events=events,
450
+ narrator_lines=tuple(narr_lines),
451
+ scenario=sc,
452
+ latency_kind="one_way",
453
+ include_narrator=getattr(self.app, "narrator_enabled", True),
454
+ )
455
+
456
+ def _do_write(force: bool) -> None:
457
+ try:
458
+ out = export_report(payload, raw_path, force=force)
459
+ status.update(f"Exported: {out}")
460
+ except Exception as exc:
461
+ status.update(f"Export failed: {exc}")
462
+
463
+ if Path(raw_path).exists():
464
+ self.app.push_screen(
465
+ ExportOverwriteModal(raw_path),
466
+ lambda ok: _do_write(True) if ok else status.update("Export cancelled."),
467
+ )
468
+ else:
469
+ _do_write(False)
470
+
471
+ def _run_simulation(self) -> None:
472
+ parsed = self._validate_live()
473
+ if parsed is None:
474
+ return
475
+ flow, path, seed = parsed
476
+ status = self.query_one("#sim-status", Static)
477
+ status.update(theme.format_status_line("RUNNING SIMULATION", 0.5))
478
+ events = simulate(flow=flow, path=path, seed=seed)
479
+ metrics = measure(events, packet_size_bytes=flow.size_bytes)
480
+ findings = analyze(events, path)
481
+
482
+ self.app.last_run = (path, events, metrics, findings) # type: ignore[attr-defined]
483
+ self.app.last_run_latency_kind = "one_way" # type: ignore[attr-defined]
484
+ self._has_results = True
485
+ self.query_one("#btn-open-visualize", Button).disabled = False
486
+ self.query_one("#btn-export", Button).disabled = False
487
+
488
+ narr_lines = (
489
+ self.app.narrator.narrate(findings, metrics, events, seed=seed) # type: ignore[attr-defined]
490
+ if getattr(self.app, "narrator_enabled", True)
491
+ else []
492
+ )
493
+ sc_obj = Scenario(
494
+ name="Interactive Simulation",
495
+ description="Configured in Simulate screen.",
496
+ flow=flow,
497
+ hops=tuple(path),
498
+ seed=seed,
499
+ )
500
+ self._last_export_data = (sc_obj, events, metrics, findings, narr_lines)
501
+
502
+ self._render_metrics(metrics)
503
+ self._render_findings(findings)
504
+ self._render_narrator(findings, metrics, events, seed)
505
+ status.update(theme.format_status_line("SIMULATION COMPLETE", 1.0))
506
+
507
+ def _render_metrics(self, metrics: Metrics) -> None:
508
+ if metrics.latency_ms is not None:
509
+ lat_text = (
510
+ f"min={metrics.latency_ms.min:.2f}ms "
511
+ f"avg={metrics.latency_ms.avg:.2f}ms "
512
+ f"max={metrics.latency_ms.max:.2f}ms "
513
+ f"p95={metrics.latency_ms.p95:.2f}ms"
514
+ )
515
+ else:
516
+ lat_text = "N/A"
517
+ jit_text = f"{metrics.jitter_ms:.2f}ms" if metrics.jitter_ms is not None else "N/A"
518
+ tp_text = (
519
+ f"{metrics.throughput_kbps:.2f} kbps"
520
+ if metrics.throughput_kbps is not None
521
+ else "n/a"
522
+ )
523
+ text = (
524
+ f"Sent: {metrics.sent} Delivered: {metrics.delivered} "
525
+ f"Lost: {metrics.lost} ({metrics.loss_pct:.2f}%)\n"
526
+ f"Latency: {lat_text}\n"
527
+ f"Jitter (RFC3550): {jit_text}\n"
528
+ f"Reordered: {metrics.reordered} Throughput: {tp_text}\n"
529
+ f"Loss by hop: {metrics.loss_by_hop or 'none'}"
530
+ )
531
+ self.query_one("#metrics-output", Static).update(text)
532
+
533
+ def _render_findings(self, findings: list[Finding]) -> None:
534
+ if not findings:
535
+ self.query_one("#findings-output", Static).update(
536
+ f"[{theme.SIGNAL_GREEN}]All clear: no findings.[/{theme.SIGNAL_GREEN}]"
537
+ )
538
+ return
539
+
540
+ color_map = {"critical": theme.CRIT_RED, "warn": theme.WARN_AMBER, "info": theme.TEAL_LIGHT}
541
+ lines = []
542
+ for f in findings:
543
+ color = color_map.get(f.severity, theme.CREAM)
544
+ hop_label = f.hop if f.hop is not None else "path"
545
+ lines.append(
546
+ f"[{color}][{f.severity.upper()}][/{color}] {f.code} "
547
+ f"({hop_label}): {f.value:.2f} > {f.threshold:.2f}"
548
+ )
549
+ self.query_one("#findings-output", Static).update("\n".join(lines))
550
+
551
+ def _render_narrator(
552
+ self, findings: list[Finding], metrics: Metrics, events: list, seed: int | None
553
+ ) -> None:
554
+ output = self.query_one("#narrator-output", Static)
555
+ if not getattr(self.app, "narrator_enabled", True):
556
+ output.update(f"[{theme.DIM_TEXT}]Narrator is off.[/{theme.DIM_TEXT}]")
557
+ return
558
+ lines = self.app.narrator.narrate(findings, metrics, events, seed=seed) # type: ignore[attr-defined]
559
+ output.update("\n".join(f"• {line.text}" for line in lines))
560
+
561
+ def action_open_visualize(self) -> None:
562
+ if self._has_results:
563
+ self.app.open_visualize() # type: ignore[attr-defined]
564
+
565
+ def action_go_back(self) -> None:
566
+ self.app.pop_screen()