Skip to content

Commit 8c5d750

Browse files
committed
Abort stale row streams with generation counter
Prevent outdated background stream tasks from mutating the table when a new load begins. Adds a _load_gen attribute, increments it at the start of _stream_rows, captures the generation locally, and aborts the streaming loop or individual call_from_thread callbacks if the generation no longer matches. This avoids race conditions and stale UI updates when successive queries or loads occur.
1 parent 2b695df commit 8c5d750

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

src/lore/tui.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,7 @@ class LoreApp(App):
502502

503503
_query: reactive[str] = reactive("")
504504
_all_memories: list[dict] = []
505+
_load_gen: int = 0
505506

506507
def __init__(self, root: Path) -> None:
507508
super().__init__()
@@ -580,6 +581,8 @@ def _populate(self, memories: list[dict], animate: bool = False) -> None:
580581
@work(thread=True)
581582
def _stream_rows(self, memories: list[dict]) -> None:
582583
"""Animate rows trickling in one-by-one like a terminal readout."""
584+
self._load_gen += 1
585+
gen = self._load_gen
583586
q = self._query.lower()
584587
visible = [
585588
m for m in memories
@@ -592,6 +595,8 @@ def _stream_rows(self, memories: list[dict]) -> None:
592595
# clear first
593596
self.call_from_thread(lambda: self.query_one(self._TABLE, DataTable).clear())
594597
for i, m in enumerate(visible):
598+
if self._load_gen != gen:
599+
return
595600
cat = m.get("category", "")
596601
content = m.get("content", "")
597602
tags = ", ".join(m.get("tags", []))
@@ -604,7 +609,10 @@ def _stream_rows(self, memories: list[dict]) -> None:
604609
)
605610
mem_id = m.get("id")
606611
self.call_from_thread(
607-
lambda r=row, k=mem_id: self.query_one(self._TABLE, DataTable).add_row(*r, key=k)
612+
lambda r=row, k=mem_id, g=gen: (
613+
self.query_one(self._TABLE, DataTable).add_row(*r, key=k)
614+
if self._load_gen == g else None
615+
)
608616
)
609617
# stagger — faster as it loads
610618
delay = max(0.03, 0.12 - i * 0.008)

0 commit comments

Comments
 (0)