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,525 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from textual.app import ComposeResult
8
+ from textual.binding import Binding
9
+ from textual.containers import Center, Horizontal, Vertical, VerticalScroll
10
+ from textual.screen import ModalScreen, Screen
11
+ from textual.widgets import Button, Checkbox, Footer, Input, Label, Static
12
+ from textual.worker import Worker
13
+
14
+ from spongebob.analyzer import Finding, analyze
15
+ from spongebob.diagnose import Sample, probe_dns, probe_tcp, samples_to_events
16
+ from spongebob.diagnose.models import (
17
+ validate_port,
18
+ validate_probe_params,
19
+ validate_target,
20
+ )
21
+ from spongebob.export import ExportPayload, default_export_path, export_report
22
+ from spongebob.meter import Metrics, measure
23
+ from spongebob.narrator import MASCOT_NAME
24
+ from spongebob.ui import theme
25
+ from spongebob.ui.export_modal import DiagnoseExportModal, ExportOverwriteModal
26
+
27
+
28
+ class DiagnoseConfirmModal(ModalScreen[bool]):
29
+ """Explicit consent dialog shown before any network probe is sent."""
30
+
31
+ BINDINGS = [
32
+ Binding("escape", "cancel", "Cancel"),
33
+ Binding("y", "confirm", "Confirm"),
34
+ Binding("n", "cancel", "Cancel"),
35
+ ]
36
+
37
+ CSS = f"""
38
+ DiagnoseConfirmModal {{
39
+ align: center middle;
40
+ background: {theme.BG};
41
+ }}
42
+ #confirm-box {{
43
+ width: 58;
44
+ height: auto;
45
+ border: solid {theme.SIGNAL_GREEN};
46
+ padding: 1 2;
47
+ background: {theme.BG};
48
+ }}
49
+ #confirm-title {{
50
+ text-style: bold;
51
+ background: {theme.BANNER_BLUE};
52
+ color: {theme.CREAM};
53
+ padding: 0 1;
54
+ margin-bottom: 1;
55
+ }}
56
+ #confirm-body {{
57
+ color: {theme.CREAM};
58
+ margin-bottom: 1;
59
+ }}
60
+ #confirm-actions {{
61
+ height: auto;
62
+ }}
63
+ #confirm-actions Button {{
64
+ margin-right: 1;
65
+ }}
66
+ """
67
+
68
+ def __init__(self, host: str, port: int, count: int) -> None:
69
+ super().__init__()
70
+ self._host = host
71
+ self._port = port
72
+ self._count = count
73
+
74
+ def compose(self) -> ComposeResult:
75
+ with Center():
76
+ with Vertical(id="confirm-box"):
77
+ yield Static("CONFIRM LIVE PROBE", id="confirm-title")
78
+ yield Static(
79
+ f"This will contact {self._host}:{self._port} {self._count} times.\n"
80
+ "Nothing is saved to disk.",
81
+ id="confirm-body",
82
+ )
83
+ with Horizontal(id="confirm-actions"):
84
+ yield Button("Confirm [Y]", id="btn-confirm-yes", variant="primary")
85
+ yield Button("Cancel [N]", id="btn-confirm-no")
86
+
87
+ def on_button_pressed(self, event: Button.Pressed) -> None:
88
+ if event.button.id == "btn-confirm-yes":
89
+ self.dismiss(True)
90
+ elif event.button.id == "btn-confirm-no":
91
+ self.dismiss(False)
92
+
93
+ def action_confirm(self) -> None:
94
+ self.dismiss(True)
95
+
96
+ def action_cancel(self) -> None:
97
+ self.dismiss(False)
98
+
99
+
100
+ class DiagnoseScreen(Screen[None]):
101
+ """Configure bounded live probes, confirm consent, and inspect RTT findings."""
102
+
103
+ BINDINGS = [
104
+ Binding("escape", "go_back", "Back"),
105
+ Binding("v", "open_visualize", "Visualize"),
106
+ ]
107
+
108
+ CSS = f"""
109
+ DiagnoseScreen {{
110
+ layout: vertical;
111
+ background: {theme.BG};
112
+ color: {theme.CREAM};
113
+ }}
114
+ #diag-layout {{
115
+ height: 1fr;
116
+ }}
117
+ #diag-config-pane {{
118
+ width: 48%;
119
+ padding: 0 1;
120
+ border: solid {theme.SIGNAL_GREEN};
121
+ margin-right: 1;
122
+ }}
123
+ #diag-config-scroll {{
124
+ height: 1fr;
125
+ }}
126
+ #diag-results-pane {{
127
+ width: 52%;
128
+ padding: 0 1;
129
+ border: solid {theme.SIGNAL_GREEN};
130
+ }}
131
+ .section-title {{
132
+ text-style: bold;
133
+ color: {theme.SIGNAL_GREEN};
134
+ margin-top: 1;
135
+ margin-bottom: 0;
136
+ }}
137
+ .row {{
138
+ height: auto;
139
+ margin-bottom: 1;
140
+ }}
141
+ .field {{
142
+ width: 1fr;
143
+ height: auto;
144
+ margin-right: 1;
145
+ }}
146
+ .field-label {{
147
+ color: {theme.SIGNAL_GREEN};
148
+ }}
149
+ #validation-error {{
150
+ color: {theme.CRIT_RED};
151
+ text-style: bold;
152
+ min-height: 1;
153
+ }}
154
+ #progress-output {{
155
+ color: {theme.TEAL_LIGHT};
156
+ min-height: 1;
157
+ }}
158
+ #actions-row {{
159
+ height: auto;
160
+ margin-top: 1;
161
+ margin-bottom: 1;
162
+ }}
163
+ #actions-row Button {{
164
+ margin-right: 1;
165
+ }}
166
+ #export-path {{
167
+ width: 1fr;
168
+ margin-right: 1;
169
+ }}
170
+ #metrics-output, #findings-output, #narrator-output {{
171
+ margin-bottom: 1;
172
+ color: {theme.CREAM};
173
+ }}
174
+ #errors-output {{
175
+ color: {theme.WARN_AMBER};
176
+ margin-bottom: 1;
177
+ }}
178
+ #too-small {{
179
+ width: 100%;
180
+ height: 1fr;
181
+ content-align: center middle;
182
+ color: {theme.WARN_AMBER};
183
+ text-style: bold;
184
+ display: none;
185
+ }}
186
+ """
187
+
188
+ def __init__(self) -> None:
189
+ super().__init__()
190
+ self._has_results = False
191
+ self._active_worker: Worker[Any] | None = None
192
+ self._dirty = False
193
+ self._initial_values: dict[str | None, str] = {}
194
+ self._last_export_data: tuple[str, int, list, Metrics, list[Finding], list] | None = None
195
+
196
+ def compose(self) -> ComposeResult:
197
+ yield theme.make_top_title("DIAGNOSE")
198
+ yield theme.RedTopRule(classes="red-rule")
199
+ yield Static("DIAGNOSE — LIVE TARGET PROBE (RTT & TIMEOUTS)", classes="screen-banner")
200
+ yield Static("Enlarge terminal (minimum 50x16 required).", id="too-small")
201
+ with Horizontal(id="diag-layout"):
202
+ with Vertical(id="diag-config-pane"):
203
+ with VerticalScroll(id="diag-config-scroll"):
204
+ yield Static("TARGET PARAMETERS", classes="section-title")
205
+ with Horizontal(classes="row"):
206
+ with Vertical(classes="field"):
207
+ yield Label("HOST", classes="field-label")
208
+ yield Input("", placeholder="e.g. 127.0.0.1", id="diag-host")
209
+ with Vertical(classes="field"):
210
+ yield Label("PORT (1-65535)", classes="field-label")
211
+ yield Input("443", id="diag-port")
212
+ with Horizontal(classes="row"):
213
+ with Vertical(classes="field"):
214
+ yield Label("COUNT (1-200)", classes="field-label")
215
+ yield Input("20", id="diag-count")
216
+ with Vertical(classes="field"):
217
+ yield Label("INTERVAL MS (MIN 100)", classes="field-label")
218
+ yield Input("200", id="diag-interval")
219
+
220
+ yield Checkbox("Probe system DNS resolution first", value=False, id="diag-dns")
221
+ yield Static("", id="validation-error")
222
+ yield Static("Idle.", id="progress-output")
223
+ with Horizontal(id="actions-row"):
224
+ yield Button("Start", id="btn-start", variant="primary")
225
+ yield Button("Visualize (V)", id="btn-open-visualize", disabled=True)
226
+
227
+ with VerticalScroll(id="diag-results-pane"):
228
+ yield Static("METRICS", classes="section-title")
229
+ yield Static("Run a probe to view metrics.", id="metrics-output")
230
+ yield Static("FINDINGS", classes="section-title")
231
+ yield Static("No findings yet.", id="findings-output")
232
+ yield Static(MASCOT_NAME.upper(), classes="section-title")
233
+ yield Static("Narrator ready.", id="narrator-output")
234
+ yield Static("COULD NOT PROBE", classes="section-title")
235
+ yield Static("None.", id="errors-output")
236
+ yield Static("EXPORT REPORT", classes="section-title")
237
+ with Horizontal(classes="row"):
238
+ yield Input("", placeholder="diag.json / .csv / .md", id="export-path")
239
+ yield Button("Export", id="btn-export", disabled=True)
240
+ yield Static("", id="export-status")
241
+ yield Static(theme.format_status_line("DIAGNOSE READY", 0.0), id="diag-status", classes="status-bar")
242
+ yield Footer()
243
+
244
+ def on_mount(self) -> None:
245
+ self._initial_values = {
246
+ inp.id: inp.value for inp in self.query(Input)
247
+ }
248
+ self._check_size()
249
+
250
+ def on_resize(self) -> None:
251
+ self._check_size()
252
+
253
+ def _check_size(self) -> None:
254
+ too_small = self.query_one("#too-small", Static)
255
+ layout = self.query_one("#diag-layout", Horizontal)
256
+ if self.size.width < 50 or self.size.height < 16:
257
+ too_small.styles.display = "block"
258
+ layout.styles.display = "none"
259
+ else:
260
+ too_small.styles.display = "none"
261
+ layout.styles.display = "block"
262
+
263
+ def _parse_config(self) -> tuple[str, int, int, float, bool]:
264
+ host = validate_target(self.query_one("#diag-host", Input).value, "host")
265
+ port_raw = self.query_one("#diag-port", Input).value.strip()
266
+ count_raw = self.query_one("#diag-count", Input).value.strip()
267
+ interval_raw = self.query_one("#diag-interval", Input).value.strip()
268
+
269
+ port = validate_port(int(port_raw))
270
+ count, interval_ms, _ = validate_probe_params(
271
+ int(count_raw), float(interval_raw), 1000.0
272
+ )
273
+ include_dns = self.query_one("#diag-dns", Checkbox).value
274
+ return host, port, count, interval_ms, include_dns
275
+
276
+ def _validate_live(self) -> tuple[str, int, int, float, bool] | None:
277
+ err_widget = self.query_one("#validation-error", Static)
278
+ start_btn = self.query_one("#btn-start", Button)
279
+ try:
280
+ parsed = self._parse_config()
281
+ err_widget.update("")
282
+ start_btn.disabled = False
283
+ return parsed
284
+ except (ValueError, TypeError) as exc:
285
+ err_widget.update(f"Invalid input: {exc}")
286
+ start_btn.disabled = True
287
+ return None
288
+
289
+ def on_input_changed(self, event: Input.Changed) -> None:
290
+ if not self._dirty and event.value == self._initial_values.get(event.input.id):
291
+ return
292
+ self._dirty = True
293
+ self._validate_live()
294
+
295
+ def on_button_pressed(self, event: Button.Pressed) -> None:
296
+ if event.button.id == "btn-start":
297
+ self._prompt_and_start()
298
+ elif event.button.id == "btn-open-visualize":
299
+ self.action_open_visualize()
300
+ elif event.button.id == "btn-export":
301
+ self._handle_export()
302
+
303
+ def _handle_export(self) -> None:
304
+ if self._last_export_data is None:
305
+ return
306
+ status = self.query_one("#export-status", Static)
307
+ host, port, events, metrics, findings, narr_lines = self._last_export_data
308
+ payload = ExportPayload(
309
+ source="diagnose",
310
+ metrics=metrics,
311
+ findings=findings,
312
+ events=events,
313
+ narrator_lines=tuple(narr_lines),
314
+ latency_kind="rtt",
315
+ target_host=host,
316
+ target_port=port,
317
+ include_narrator=getattr(self.app, "narrator_enabled", True),
318
+ )
319
+
320
+ def _do_write(target_path: str, force: bool) -> None:
321
+ try:
322
+ out = export_report(payload, target_path, force=force)
323
+ status.update(f"Exported: {out}")
324
+ except Exception as exc:
325
+ status.update(f"Export failed: {exc}")
326
+
327
+ def _on_modal_result(chosen_path: str | None) -> None:
328
+ if not chosen_path:
329
+ status.update("Export cancelled.")
330
+ return
331
+ if Path(chosen_path).exists():
332
+ self.app.push_screen(
333
+ ExportOverwriteModal(chosen_path),
334
+ lambda ok: _do_write(chosen_path, True) if ok else status.update("Export cancelled."),
335
+ )
336
+ else:
337
+ _do_write(chosen_path, False)
338
+
339
+ typed = self.query_one("#export-path", Input).value.strip()
340
+ if typed:
341
+ initial_path = typed
342
+ warning = None
343
+ else:
344
+ try:
345
+ initial_path = str(default_export_path(kind="diagnose", target=host, fmt="md"))
346
+ warning = None
347
+ except Exception as exc:
348
+ initial_path = ""
349
+ warning = f"Downloads unavailable: {exc}"
350
+
351
+ self.app.push_screen(DiagnoseExportModal(initial_path, warning=warning), _on_modal_result)
352
+
353
+ def _prompt_and_start(self) -> None:
354
+ parsed = self._validate_live()
355
+ if parsed is None:
356
+ return
357
+ host, port, count, interval_ms, include_dns = parsed
358
+
359
+ def _on_confirm(confirmed: bool | None) -> None:
360
+ if not confirmed:
361
+ if self.is_mounted:
362
+ self.query_one("#progress-output", Static).update("Cancelled.")
363
+ return
364
+ self._start_worker(host, port, count, interval_ms, include_dns)
365
+
366
+ self.app.push_screen(DiagnoseConfirmModal(host, port, count), _on_confirm)
367
+
368
+ def _start_worker(
369
+ self,
370
+ host: str,
371
+ port: int,
372
+ count: int,
373
+ interval_ms: float,
374
+ include_dns: bool,
375
+ ) -> None:
376
+ self.query_one("#btn-start", Button).disabled = True
377
+ self.query_one("#progress-output", Static).update(
378
+ f"Probing {host}:{port} — sent: 0/{count}, ok: 0, timeouts: 0"
379
+ )
380
+ self.query_one("#diag-status", Static).update(
381
+ theme.format_status_line(f"PROBING {host}:{port}", 0.25)
382
+ )
383
+ self._active_worker = self.run_worker(
384
+ self._probe_worker(host, port, count, interval_ms, include_dns),
385
+ exclusive=True,
386
+ )
387
+
388
+ async def _probe_worker(
389
+ self,
390
+ host: str,
391
+ port: int,
392
+ count: int,
393
+ interval_ms: float,
394
+ include_dns: bool,
395
+ ) -> None:
396
+ try:
397
+ results: dict[str, list[Sample]] = {}
398
+ if include_dns:
399
+ results["dns"] = await probe_dns(
400
+ host, count=count, interval_ms=interval_ms, timeout_ms=1000.0
401
+ )
402
+ results[f"tcp:{host}:{port}"] = await probe_tcp(
403
+ host, port=port, count=count, interval_ms=interval_ms, timeout_ms=1000.0
404
+ )
405
+
406
+ if not self.is_mounted:
407
+ return
408
+
409
+ all_samples = [s for seg in results.values() for s in seg]
410
+ sent_n = len(all_samples)
411
+ ok_n = sum(1 for s in all_samples if s.outcome == "ok")
412
+ timeout_n = sum(1 for s in all_samples if s.outcome == "timeout")
413
+ self.query_one("#progress-output", Static).update(
414
+ f"Done — sent: {sent_n}, ok: {ok_n}, timeouts: {timeout_n}"
415
+ )
416
+ self.query_one("#diag-status", Static).update(
417
+ theme.format_status_line("PROBE COMPLETE", 1.0)
418
+ )
419
+
420
+ adapted = samples_to_events(results)
421
+ metrics = measure(adapted.events, packet_size_bytes=adapted.size_bytes)
422
+ findings = analyze(adapted.events, adapted.path, latency_kind=adapted.latency_kind)
423
+
424
+ self.app.last_run = (adapted.path, adapted.events, metrics, findings) # type: ignore[attr-defined]
425
+ self.app.last_run_latency_kind = "rtt" # type: ignore[attr-defined]
426
+ self._has_results = True
427
+ self.query_one("#btn-open-visualize", Button).disabled = False
428
+ self.query_one("#btn-export", Button).disabled = False
429
+
430
+ narr_lines = (
431
+ self.app.narrator.narrate( # type: ignore[attr-defined]
432
+ findings, metrics, adapted.events, mode="diagnose"
433
+ )
434
+ if getattr(self.app, "narrator_enabled", True)
435
+ else []
436
+ )
437
+ self._last_export_data = (
438
+ host,
439
+ port,
440
+ adapted.events,
441
+ metrics,
442
+ findings,
443
+ narr_lines,
444
+ )
445
+
446
+ self._render_metrics(metrics)
447
+ self._render_findings(findings)
448
+ self._render_narrator(findings, metrics, adapted.events)
449
+ self._render_errors(adapted.errors or {})
450
+ except asyncio.CancelledError:
451
+ return
452
+ finally:
453
+ if self.is_mounted:
454
+ self.query_one("#btn-start", Button).disabled = False
455
+
456
+ def _render_metrics(self, metrics: Metrics) -> None:
457
+ if metrics.latency_ms is not None:
458
+ lat_text = (
459
+ f"min={metrics.latency_ms.min:.2f}ms "
460
+ f"avg={metrics.latency_ms.avg:.2f}ms "
461
+ f"max={metrics.latency_ms.max:.2f}ms "
462
+ f"p95={metrics.latency_ms.p95:.2f}ms"
463
+ )
464
+ else:
465
+ lat_text = "N/A"
466
+ jit_text = f"{metrics.jitter_ms:.2f}ms" if metrics.jitter_ms is not None else "N/A"
467
+ text = (
468
+ f"Sent: {metrics.sent} Delivered: {metrics.delivered} "
469
+ f"Lost: {metrics.lost} ({metrics.loss_pct:.2f}% — timeouts approximate packet loss)\n"
470
+ f"Round-trip time: {lat_text}\n"
471
+ f"Jitter (RFC3550): {jit_text}\n"
472
+ f"Throughput: n/a\n"
473
+ f"Loss by segment: {metrics.loss_by_hop or 'none'}"
474
+ )
475
+ self.query_one("#metrics-output", Static).update(text)
476
+
477
+ def _render_findings(self, findings: list[Finding]) -> None:
478
+ if not findings:
479
+ self.query_one("#findings-output", Static).update(
480
+ f"[{theme.SIGNAL_GREEN}]All clear: no findings.[/{theme.SIGNAL_GREEN}]"
481
+ )
482
+ return
483
+
484
+ color_map = {"critical": theme.CRIT_RED, "warn": theme.WARN_AMBER, "info": theme.TEAL_LIGHT}
485
+ lines = []
486
+ for f in findings:
487
+ color = color_map.get(f.severity, theme.CREAM)
488
+ hop_label = f.hop if f.hop is not None else "path"
489
+ lines.append(
490
+ f"[{color}][{f.severity.upper()}][/{color}] {f.code} "
491
+ f"({hop_label}): {f.value:.2f} > {f.threshold:.2f}"
492
+ )
493
+ self.query_one("#findings-output", Static).update("\n".join(lines))
494
+
495
+ def _render_narrator(
496
+ self, findings: list[Finding], metrics: Metrics, events: list[Any]
497
+ ) -> None:
498
+ output = self.query_one("#narrator-output", Static)
499
+ if not getattr(self.app, "narrator_enabled", True):
500
+ output.update(f"[{theme.DIM_TEXT}]Narrator is off.[/{theme.DIM_TEXT}]")
501
+ return
502
+ lines = self.app.narrator.narrate( # type: ignore[attr-defined]
503
+ findings, metrics, events, mode="diagnose"
504
+ )
505
+ output.update("\n".join(f"• {line.text}" for line in lines))
506
+
507
+ def _render_errors(self, errors: dict[str, list[Sample]]) -> None:
508
+ output = self.query_one("#errors-output", Static)
509
+ if not errors:
510
+ output.update("None.")
511
+ return
512
+ parts = []
513
+ for seg, err_samples in errors.items():
514
+ outcomes = ", ".join(sorted({s.outcome for s in err_samples}))
515
+ parts.append(f"{seg}: {len(err_samples)} ({outcomes})")
516
+ output.update("\n".join(parts))
517
+
518
+ def action_open_visualize(self) -> None:
519
+ if self._has_results:
520
+ self.app.open_visualize() # type: ignore[attr-defined]
521
+
522
+ def action_go_back(self) -> None:
523
+ if self._active_worker is not None and not self._active_worker.is_finished:
524
+ self._active_worker.cancel()
525
+ self.app.pop_screen()
@@ -0,0 +1,158 @@
1
+ from __future__ import annotations
2
+
3
+ from textual.app import ComposeResult
4
+ from textual.binding import Binding
5
+ from textual.containers import Center, Horizontal, Vertical
6
+ from textual.screen import ModalScreen
7
+ from textual.widgets import Button, Input, Static
8
+
9
+ from spongebob.ui import theme
10
+
11
+
12
+ class ExportOverwriteModal(ModalScreen[bool]):
13
+ """Explicit confirmation dialog before overwriting an existing export file."""
14
+
15
+ BINDINGS = [
16
+ Binding("escape", "cancel", "Cancel"),
17
+ Binding("y", "confirm", "Overwrite"),
18
+ Binding("n", "cancel", "Cancel"),
19
+ ]
20
+
21
+ CSS = f"""
22
+ ExportOverwriteModal {{
23
+ align: center middle;
24
+ background: {theme.BG};
25
+ }}
26
+ #overwrite-box {{
27
+ width: 58;
28
+ height: auto;
29
+ border: solid {theme.SIGNAL_GREEN};
30
+ padding: 1 2;
31
+ background: {theme.BG};
32
+ }}
33
+ #overwrite-title {{
34
+ text-style: bold;
35
+ background: {theme.BANNER_BLUE};
36
+ color: {theme.CREAM};
37
+ padding: 0 1;
38
+ margin-bottom: 1;
39
+ }}
40
+ #overwrite-body {{
41
+ color: {theme.CREAM};
42
+ margin-bottom: 1;
43
+ }}
44
+ #overwrite-actions {{
45
+ height: auto;
46
+ }}
47
+ #overwrite-actions Button {{
48
+ margin-right: 1;
49
+ }}
50
+ """
51
+
52
+ def __init__(self, target_path: str) -> None:
53
+ super().__init__()
54
+ self._target_path = target_path
55
+
56
+ def compose(self) -> ComposeResult:
57
+ with Center():
58
+ with Vertical(id="overwrite-box"):
59
+ yield Static("OVERWRITE EXISTING FILE?", id="overwrite-title")
60
+ yield Static(
61
+ f"File already exists:\n{self._target_path}\n\nOverwrite it?",
62
+ id="overwrite-body",
63
+ )
64
+ with Horizontal(id="overwrite-actions"):
65
+ yield Button("Overwrite [Y]", id="btn-overwrite-yes", variant="primary")
66
+ yield Button("Cancel [N]", id="btn-overwrite-no")
67
+
68
+ def on_button_pressed(self, event: Button.Pressed) -> None:
69
+ if event.button.id == "btn-overwrite-yes":
70
+ self.dismiss(True)
71
+ elif event.button.id == "btn-overwrite-no":
72
+ self.dismiss(False)
73
+
74
+ def action_confirm(self) -> None:
75
+ self.dismiss(True)
76
+
77
+ def action_cancel(self) -> None:
78
+ self.dismiss(False)
79
+
80
+
81
+ class DiagnoseExportModal(ModalScreen[str | None]):
82
+ """Modal dialog prefilled with the default Downloads export path."""
83
+
84
+ BINDINGS = [
85
+ Binding("escape", "cancel", "Cancel"),
86
+ ]
87
+
88
+ CSS = f"""
89
+ DiagnoseExportModal {{
90
+ align: center middle;
91
+ background: {theme.BG};
92
+ }}
93
+ #diag-export-box {{
94
+ width: 72;
95
+ height: auto;
96
+ border: solid {theme.SIGNAL_GREEN};
97
+ padding: 1 2;
98
+ background: {theme.BG};
99
+ }}
100
+ #diag-export-title {{
101
+ text-style: bold;
102
+ background: {theme.BANNER_BLUE};
103
+ color: {theme.CREAM};
104
+ padding: 0 1;
105
+ margin-bottom: 1;
106
+ }}
107
+ #diag-export-note {{
108
+ color: {theme.CREAM};
109
+ margin-bottom: 1;
110
+ }}
111
+ #diag-export-warning {{
112
+ color: {theme.WARN_AMBER};
113
+ margin-bottom: 1;
114
+ }}
115
+ #modal-export-path {{
116
+ margin-bottom: 1;
117
+ }}
118
+ #diag-export-actions {{
119
+ height: auto;
120
+ }}
121
+ #diag-export-actions Button {{
122
+ margin-right: 1;
123
+ }}
124
+ """
125
+
126
+ def __init__(self, initial_path: str, warning: str | None = None) -> None:
127
+ super().__init__()
128
+ self._initial_path = initial_path
129
+ self._warning = warning
130
+
131
+ def compose(self) -> ComposeResult:
132
+ with Center():
133
+ with Vertical(id="diag-export-box"):
134
+ yield Static("EXPORT DIAGNOSE REPORT", id="diag-export-title")
135
+ yield Static(
136
+ "Review or edit the export path (.md, .json, or .csv). Nothing is saved until you press Save.",
137
+ id="diag-export-note",
138
+ )
139
+ if self._warning:
140
+ yield Static(self._warning, id="diag-export-warning")
141
+ yield Input(
142
+ self._initial_path,
143
+ placeholder="Enter full export path (.md / .json / .csv)",
144
+ id="modal-export-path",
145
+ )
146
+ with Horizontal(id="diag-export-actions"):
147
+ yield Button("Save", id="btn-export-save", variant="primary")
148
+ yield Button("Cancel", id="btn-export-cancel")
149
+
150
+ def on_button_pressed(self, event: Button.Pressed) -> None:
151
+ if event.button.id == "btn-export-save":
152
+ chosen = self.query_one("#modal-export-path", Input).value.strip()
153
+ self.dismiss(chosen or None)
154
+ elif event.button.id == "btn-export-cancel":
155
+ self.dismiss(None)
156
+
157
+ def action_cancel(self) -> None:
158
+ self.dismiss(None)