""" live_stream.py — the live token-streaming bus. While a chat run is in flight, the model wrappers push the incremental text they generate onto this module-global bus. The running WS stream drains the bus on the SAME live timer that already forwards `[Tag]` log lines, and the client receives the deltas as `live` WS events. The chat UI then shows the model's ACTUAL generated text growing in real time — the raw stream the terminal sees — instead of nothing until the step/answer completes. Design notes: - Single global bus, one chat run at a time (the UI gates sends on `busy`). - Run-scoped: ``begin_run()`` clears stale frames and marks the bus active; everything pushed before a run's ``end_run()`` is ignored. Wrappers check ``bus.running`` and keep their ORIGINAL non-streaming path otherwise, so a model call outside a WS chat run (STT report analysis, memory compaction, …) behaves exactly as before. - Generation-scoped: each model call calls ``begin_generation()`` (emits a RESET frame so the UI clears the previous live bubble) then pushes text deltas, then ``end_generation()``. ``drain()`` returns the collapsed view: a single ``(reset, text)`` pair covering everything since the last drain — text after the LAST reset, since intermediate generations' text is never shown live anyway (their complete result lands via `update`/`final` WS events and replaces the transient live bubble). """ import threading class LiveGenerationBus: """Thread-safe buffer for incremental generated text, drained by the WS run. See the module docstring for the reset/generation semantics.""" def __init__(self): self._lock = threading.Lock() self._running = False # a WS chat run is active self._gen_active = False # a model call is currently streaming self._frames = [] # ("reset",) / ("text", str) in arrival order @property def running(self) -> bool: """True while a WS chat run owns the bus (streaming is enabled).""" with self._lock: return self._running def begin_run(self): """Start a chat run: drop stale frames and enable streaming.""" with self._lock: self._running = True self._gen_active = False self._frames = [] def end_run(self): """Finish a chat run: stop accepting pushes (nothing left to show).""" with self._lock: self._running = False self._gen_active = False self._frames = [] def begin_generation(self): """A new model call is generating: emit a RESET so the UI clears the previous live bubble (the next drain's ``reset`` is True).""" with self._lock: if not self._running: return self._gen_active = True self._frames.append(("reset", "")) def end_generation(self): """The model call finished its stream (no more in-progress text).""" with self._lock: self._gen_active = False def push(self, text: str): """A text delta from the generating model. Dropped when no run or no generation is active (a wrapper writing outside its own epoch).""" if not text: return with self._lock: if self._running and self._gen_active: self._frames.append(("text", text)) def drain(self) -> tuple: """Return ``(reset, text)`` for everything since the last drain: ``reset`` True when at least one generation began, ``text`` = the deltas AFTER the LAST reset marker (earlier generations' deltas are dropped — their complete results arrive via update/final anyway). Clears the buffer so the next drain returns only new deltas.""" with self._lock: frames = self._frames self._frames = [] reset = False text = [] for kind, value in frames: if kind == "reset": reset = True text = [] else: text.append(value) return reset, "".join(text) _bus = LiveGenerationBus() def get_bus() -> LiveGenerationBus: """The app-wide live-streaming bus (thread-safe).""" return _bus