anamnesis-cli 0.1.0__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 (49) hide show
  1. anamnesis/__init__.py +0 -0
  2. anamnesis/cli/__init__.py +0 -0
  3. anamnesis/cli/__main__.py +551 -0
  4. anamnesis/cli/app.py +567 -0
  5. anamnesis/cli/app.tcss +160 -0
  6. anamnesis/cli/archive_view.py +211 -0
  7. anamnesis/cli/commands.py +57 -0
  8. anamnesis/cli/look.py +176 -0
  9. anamnesis/cli/node_cmd.py +453 -0
  10. anamnesis/cli/setup_cmd.py +173 -0
  11. anamnesis/cli/widgets.py +225 -0
  12. anamnesis/config.py +109 -0
  13. anamnesis/connect.py +343 -0
  14. anamnesis/core/__init__.py +0 -0
  15. anamnesis/core/db.py +563 -0
  16. anamnesis/core/devices.py +639 -0
  17. anamnesis/core/formatting.py +51 -0
  18. anamnesis/core/memory.py +290 -0
  19. anamnesis/core/models.py +76 -0
  20. anamnesis/core/vector.py +289 -0
  21. anamnesis/ingest/__init__.py +1 -0
  22. anamnesis/ingest/base.py +74 -0
  23. anamnesis/ingest/claude_code.py +85 -0
  24. anamnesis/ingest/clean.py +54 -0
  25. anamnesis/ingest/codex.py +136 -0
  26. anamnesis/ingest/cursor.py +166 -0
  27. anamnesis/ingest/exports.py +269 -0
  28. anamnesis/ingest/gemini_cli.py +156 -0
  29. anamnesis/ingest/runner.py +194 -0
  30. anamnesis/memory_mcp/__init__.py +1 -0
  31. anamnesis/memory_mcp/__main__.py +3 -0
  32. anamnesis/memory_mcp/server.py +208 -0
  33. anamnesis/node/__init__.py +1 -0
  34. anamnesis/node/app.py +476 -0
  35. anamnesis/node/auth.py +405 -0
  36. anamnesis/retention.py +75 -0
  37. anamnesis/web/__init__.py +0 -0
  38. anamnesis/web/__main__.py +21 -0
  39. anamnesis/web/main.py +265 -0
  40. anamnesis/web/static/app.js +380 -0
  41. anamnesis/web/static/index.html +48 -0
  42. anamnesis/web/static/markdown.js +79 -0
  43. anamnesis/web/static/style.css +143 -0
  44. anamnesis_cli-0.1.0.dist-info/METADATA +287 -0
  45. anamnesis_cli-0.1.0.dist-info/RECORD +49 -0
  46. anamnesis_cli-0.1.0.dist-info/WHEEL +5 -0
  47. anamnesis_cli-0.1.0.dist-info/entry_points.txt +4 -0
  48. anamnesis_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
  49. anamnesis_cli-0.1.0.dist-info/top_level.txt +1 -0
anamnesis/cli/app.py ADDED
@@ -0,0 +1,567 @@
1
+ """Anamnesis Textual TUI: a browser for the shared memory.
2
+
3
+ Sidebar of conversations from every tool, a read-only conversation view, and one input line:
4
+ plain text searches all memory, slash commands browse and manage it. All data access goes
5
+ through `MemoryService`; this module only handles presentation and input.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+ import time
13
+ from datetime import datetime
14
+
15
+ from textual import on, work
16
+ from textual.app import App, ComposeResult
17
+ from textual.binding import Binding
18
+ from textual.containers import Horizontal, Vertical, VerticalScroll
19
+ from textual.widget import Widget
20
+ from textual.widgets import Footer, Input, Label, ListView, Static
21
+
22
+ from anamnesis.cli.commands import Command, CommandError, help_text, is_command, parse_command
23
+ from anamnesis.cli.look import (
24
+ BLURRED,
25
+ MUTED,
26
+ RUST,
27
+ fuzzy_score,
28
+ pill,
29
+ project_name,
30
+ relative_time,
31
+ snippet,
32
+ )
33
+ from anamnesis.cli.widgets import (
34
+ MARKDOWN_STYLES,
35
+ THEME,
36
+ MessageView,
37
+ SearchResultsView,
38
+ ThreadItem,
39
+ )
40
+ from anamnesis.config import Settings, load_settings
41
+ from anamnesis.core.db import ThreadNotFoundError
42
+ from anamnesis.core.memory import MemoryService
43
+ from anamnesis.core.models import SOURCE_LABELS, Message, SearchHit, Thread
44
+
45
+ log = logging.getLogger(__name__)
46
+
47
+ # A conversation opens with its latest PAGE messages; earlier ones load as you scroll up.
48
+ PAGE = 40
49
+ DELETE_CONFIRM_SECONDS = 10.0
50
+ EMPTY_HINT = (
51
+ "Nothing in memory yet.\n\n"
52
+ "Run /sync to import your Claude Code, Codex, Gemini CLI and Cursor history, or\n"
53
+ "`anam import <export.zip>` for ChatGPT, claude.ai and Gemini exports.\n\n"
54
+ "/help for commands"
55
+ )
56
+
57
+
58
+ class AnamnesisApp(App[None]):
59
+ TITLE = "Anamnesis"
60
+ CSS_PATH = "app.tcss"
61
+ BINDINGS = [
62
+ Binding("ctrl+l", "focus_threads", "Conversations"),
63
+ Binding("ctrl+f", "focus_prompt", "Search"),
64
+ Binding("escape", "focus_prompt", "Search", show=False),
65
+ Binding("ctrl+q", "quit", "Quit"),
66
+ ]
67
+
68
+ def __init__(self, settings: Settings | None = None, service: MemoryService | None = None):
69
+ super().__init__()
70
+ self.register_theme(THEME)
71
+ self.theme = THEME.name
72
+ self.console.push_theme(MARKDOWN_STYLES) # Rich's Markdown colors, in our palette
73
+ self.settings = settings or load_settings()
74
+ self.service: MemoryService | None = service
75
+ self._owns_service = service is None
76
+ self.thread_id: str | None = None
77
+ self._thread_source: str | None = None
78
+ self._displayed: set[int] = set()
79
+ self._cursor = 0
80
+ self._threads_sig: tuple[int, float, int] | None = None
81
+ # Serializes sidebar rebuilds: the poller and a sync can both trigger one.
82
+ self._threads_lock = asyncio.Lock()
83
+ self._polling = False
84
+ self._listing: list[str] = []
85
+ self._delete_armed_at = 0.0
86
+ self._oldest_shown: int | None = None # id of the oldest rendered message
87
+ self._has_earlier = False
88
+ self._loading_earlier = False
89
+ self._filter = "" # fuzzy filter typed in the search box
90
+
91
+ # ---------- layout ----------
92
+
93
+ def compose(self) -> ComposeResult:
94
+ with Horizontal(id="topbar"):
95
+ yield Label(pill("ANAMNESIS"), id="brand")
96
+ yield Static("Loading memory…", id="status")
97
+ with Horizontal(id="body"):
98
+ with Vertical(id="sidebar") as sidebar:
99
+ sidebar.border_title = "Conversations"
100
+ yield ThreadList(id="threads")
101
+ with Vertical(id="main"):
102
+ prompt = Input(placeholder="Loading…", id="prompt", disabled=True)
103
+ prompt.border_title = "Search"
104
+ yield prompt
105
+ yield ConversationView(id="view")
106
+ yield Footer()
107
+
108
+ @property
109
+ def view(self) -> VerticalScroll:
110
+ return self.query_one("#view", VerticalScroll)
111
+
112
+ @property
113
+ def svc(self) -> MemoryService:
114
+ if self.service is None:
115
+ raise RuntimeError("Service not ready")
116
+ return self.service
117
+
118
+ # ---------- startup / shutdown ----------
119
+
120
+ def on_mount(self) -> None:
121
+ self.watch(self.view, "scroll_y", self._scrolled, init=False)
122
+ self.watch(self.screen, "focused", self._focus_moved)
123
+ self._initialize()
124
+
125
+ def _focus_moved(self, focused: Widget | None) -> None:
126
+ """Light up the panel that has focus.
127
+
128
+ Done with inline styles rather than CSS `:focus-within`: that pseudo-class makes Textual
129
+ restyle the panel's whole subtree on every focus change, which made Tab visibly slow.
130
+ """
131
+ for panel in (self.query_one("#sidebar"), self.view):
132
+ active = focused is not None and panel in focused.ancestors_with_self
133
+ panel.styles.border = ("round", RUST if active else BLURRED)
134
+ if panel.id == "sidebar":
135
+ panel.styles.border_title_color = RUST if active else MUTED
136
+
137
+ def _scrolled(self, y: float) -> None:
138
+ if y <= 1 and self._has_earlier and not self._loading_earlier:
139
+ self.run_worker(self._load_earlier(), group="earlier", exclusive=True)
140
+
141
+ @work(exclusive=True, group="init")
142
+ async def _initialize(self) -> None:
143
+ if self.service is None:
144
+ try:
145
+ self.service = await MemoryService.create(self.settings, defer_index=True)
146
+ except Exception as e:
147
+ log.exception("startup failed")
148
+ self.query_one("#status", Static).update(f"Startup failed: {e}")
149
+ return
150
+ await self._update_status()
151
+
152
+ threads = await self._refresh_threads()
153
+ if threads:
154
+ await self._open_thread(threads[0].id)
155
+ else:
156
+ self._show_empty()
157
+ prompt = self.query_one("#prompt", Input)
158
+ prompt.disabled = False
159
+ prompt.placeholder = "Search everything you've discussed with any AI tool · /help"
160
+ prompt.focus()
161
+ self.set_interval(self.settings.sync_interval, self._poll)
162
+ if self.settings.memory_sync:
163
+ self._memory_sync_loop()
164
+
165
+ @work(exclusive=True, group="memory-sync")
166
+ async def _memory_sync_loop(self) -> None:
167
+ """Keep importing other tools' history while the TUI is open (new threads appear live)."""
168
+ from anamnesis.ingest.runner import watch
169
+
170
+ await watch(self.svc, interval=self.settings.memory_sync_interval)
171
+
172
+ @work(exclusive=True, group="memory-sync-now")
173
+ async def _memory_sync_now(self) -> None:
174
+ from anamnesis.ingest.runner import sync_once
175
+
176
+ try:
177
+ report = await sync_once(self.svc)
178
+ except Exception as e:
179
+ log.exception("manual sync failed")
180
+ await self._note(f"Sync failed: {e}", "error")
181
+ return
182
+ if report.messages_added:
183
+ per = ", ".join(f"{SOURCE_LABELS.get(k, k)}: {v}" for k, v in report.by_source.items())
184
+ await self._note(f"Imported {report.messages_added} new messages ({per}).")
185
+ else:
186
+ await self._note("Memory is up to date (or another Anamnesis process is syncing).")
187
+ if self.is_running:
188
+ await self._refresh_threads()
189
+
190
+ async def on_unmount(self) -> None:
191
+ if self._owns_service and self.service is not None:
192
+ await self.service.close()
193
+
194
+ # ---------- status / helpers ----------
195
+
196
+ async def _update_status(self) -> None:
197
+ if self.service is None:
198
+ return
199
+ counts = await self.svc.source_counts()
200
+ mode = "semantic search" if self.svc.semantic else "keyword search only"
201
+ n, k = sum(counts.values()), len(counts)
202
+ self.query_one("#status", Static).update(
203
+ f"{n} conversation{'s' if n != 1 else ''} · {k} tool{'s' if k != 1 else ''} · {mode}"
204
+ )
205
+
206
+ def _show_empty(self) -> None:
207
+ self.view.remove_children()
208
+ self.view.mount(Static(EMPTY_HINT, id="empty"))
209
+ self._set_title(None)
210
+
211
+ async def _mount(self, view: MessageView) -> None:
212
+ for empty in self.view.query("#empty"):
213
+ await empty.remove()
214
+ await self.view.mount(view)
215
+ self.view.scroll_end(animate=False)
216
+
217
+ async def _mount_message(self, msg: Message, source: str | None = None) -> None:
218
+ self._displayed.add(msg.id)
219
+ await self._mount(MessageView.from_message(msg, source))
220
+
221
+ async def _note(self, markdown: str, kind: str = "note") -> None:
222
+ header = "Anamnesis" if kind == "note" else "Error"
223
+ color = RUST if kind == "note" else "#e5534b"
224
+ await self._mount(MessageView(kind, header, markdown, color=color))
225
+
226
+ # ---------- threads ----------
227
+
228
+ async def _refresh_threads(self) -> list[Thread]:
229
+ async with self._threads_lock:
230
+ return await self._rebuild_threads()
231
+
232
+ async def _rebuild_threads(self) -> list[Thread]:
233
+ svc = self.svc
234
+ self._threads_sig = await svc.threads_signature()
235
+ threads = await svc.list_threads()
236
+ total = len(threads)
237
+ if self._filter:
238
+ scored = [(fuzzy_score(self._filter, _haystack(t)), t) for t in threads]
239
+ ranked = sorted(
240
+ ((sc, t) for sc, t in scored if sc is not None),
241
+ key=lambda st: (-st[0], -st[1].updated_at),
242
+ )
243
+ threads = [t for _, t in ranked]
244
+ lv = self.query_one("#threads", ListView)
245
+ items = list(lv.query(ThreadItem))
246
+ if [i.thread_id for i in items] == [t.id for t in threads]:
247
+ # Same conversations in the same order (the usual case while you work): update the
248
+ # rows in place instead of rebuilding the list, and leave your cursor alone.
249
+ for item, t in zip(items, threads, strict=True):
250
+ item.update(t)
251
+ else:
252
+ highlighted = lv.highlighted_child
253
+ keep = highlighted.thread_id if isinstance(highlighted, ThreadItem) else None
254
+ await lv.clear()
255
+ await lv.extend(ThreadItem(t) for t in threads)
256
+ self._mark_current()
257
+ if keep is not None and lv.has_focus: # you were browsing: stay on that row
258
+ for i, t in enumerate(threads):
259
+ if t.id == keep:
260
+ lv.index = i
261
+ self.query_one("#sidebar").border_subtitle = (
262
+ f"{len(threads)} of {total}" if self._filter else str(total)
263
+ )
264
+ if (
265
+ not self._filter
266
+ and self.thread_id is not None
267
+ and all(t.id != self.thread_id for t in threads)
268
+ ):
269
+ # Current thread was deleted (possibly from another client).
270
+ self.thread_id = None
271
+ self._show_empty()
272
+ else:
273
+ for t in threads:
274
+ if t.id == self.thread_id:
275
+ self._set_title(t)
276
+ await self._update_status()
277
+ return threads
278
+
279
+ def _set_title(self, thread: Thread | None) -> None:
280
+ view = self.view
281
+ if thread is None:
282
+ self.sub_title = ""
283
+ view.border_title = view.border_subtitle = ""
284
+ return
285
+ self.sub_title = _subtitle(thread)
286
+ view.border_title = thread.title
287
+ meta = [SOURCE_LABELS.get(thread.source, thread.source), project_name(thread.project)]
288
+ view.border_subtitle = " · ".join(m for m in meta if m)
289
+
290
+ def _mark_current(self) -> None:
291
+ lv = self.query_one("#threads", ListView)
292
+ for i, item in enumerate(lv.query(ThreadItem)):
293
+ current = item.thread_id == self.thread_id
294
+ item.set_class(current, "current")
295
+ if current:
296
+ lv.index = i
297
+
298
+ async def _open_thread(self, thread_id: str) -> None:
299
+ svc = self.svc
300
+ try:
301
+ thread = await svc.get_thread(thread_id)
302
+ except ThreadNotFoundError:
303
+ await self._refresh_threads()
304
+ return
305
+ self.thread_id = thread.id
306
+ self._thread_source = thread.source
307
+ self._set_title(thread)
308
+ self._mark_current() # highlight immediately, before the (slower) message render
309
+ self._cursor = max(self._cursor, await svc.latest_message_id())
310
+ msgs = await svc.messages(thread.id, limit=PAGE)
311
+ await self.view.remove_children()
312
+ self._displayed = set()
313
+ self._oldest_shown = msgs[0].id if msgs else None
314
+ self._has_earlier = len(msgs) == PAGE
315
+ if self._has_earlier:
316
+ await self.view.mount(Static("↑ Earlier messages load as you scroll up", id="earlier"))
317
+ await self.view.mount_all(MessageView.from_message(m, thread.source) for m in msgs)
318
+ self._displayed.update(m.id for m in msgs)
319
+ if not msgs:
320
+ self.view.mount(Static("(no messages)", id="empty"))
321
+ self.view.scroll_end(animate=False)
322
+ self.call_after_refresh(self._fill_view)
323
+
324
+ def _fill_view(self) -> None:
325
+ """Short messages may not fill the panel, so there's nothing to scroll: load more now."""
326
+ if self._has_earlier and self.view.max_scroll_y == 0:
327
+ self.run_worker(self._load_earlier(), group="earlier", exclusive=True)
328
+
329
+ async def _load_earlier(self) -> None:
330
+ if self._loading_earlier or not self._has_earlier or self.thread_id is None:
331
+ return
332
+ self._loading_earlier = True
333
+ try:
334
+ thread_id, source = self.thread_id, self._thread_source
335
+ msgs = await self.svc.messages(thread_id, limit=PAGE, before=self._oldest_shown)
336
+ if thread_id != self.thread_id: # another conversation was opened meanwhile
337
+ return
338
+ self._has_earlier = len(msgs) == PAGE
339
+ anchor = next(iter(self.view.query(MessageView)), None)
340
+ if msgs and anchor is not None:
341
+ self._oldest_shown = msgs[0].id
342
+ views = [MessageView.from_message(m, source) for m in msgs]
343
+ await self.view.mount_all(views, before=anchor)
344
+ self._displayed.update(m.id for m in msgs)
345
+ if not self._has_earlier:
346
+ for hint in self.view.query("#earlier"):
347
+ await hint.remove()
348
+ if anchor is not None: # keep the message you were reading in place
349
+ self.view.scroll_to_widget(anchor, top=True, animate=False)
350
+ finally:
351
+ self._loading_earlier = False
352
+ self.call_after_refresh(self._fill_view)
353
+
354
+ # ---------- live updates (background imports, other devices, the web UI) ----------
355
+
356
+ async def _poll(self) -> None:
357
+ if self.service is None or self._polling:
358
+ return
359
+ self._polling = True
360
+ try:
361
+ if await self.svc.threads_signature() != self._threads_sig:
362
+ await self._refresh_threads()
363
+ await self._sync_messages()
364
+ except Exception:
365
+ log.exception("refresh failed")
366
+ finally:
367
+ self._polling = False
368
+
369
+ async def _sync_messages(self) -> None:
370
+ if self.thread_id is None:
371
+ return
372
+ for msg in await self.svc.messages_after(self._cursor):
373
+ self._cursor = max(self._cursor, msg.id)
374
+ if msg.thread_id == self.thread_id and msg.id not in self._displayed:
375
+ await self._mount_message(msg, self._thread_source)
376
+
377
+ # ---------- input ----------
378
+
379
+ @on(Input.Changed, "#prompt")
380
+ def _typed(self, event: Input.Changed) -> None:
381
+ """Typing filters the conversation list live (fuzzy, on title, project and tool)."""
382
+ text = event.value.strip()
383
+ wanted = "" if text.startswith("/") else text
384
+ if wanted != self._filter and self.service is not None:
385
+ self._filter = wanted
386
+ self._apply_filter()
387
+
388
+ @work(exclusive=True, group="filter")
389
+ async def _apply_filter(self) -> None:
390
+ await self._refresh_threads()
391
+ lv = self.query_one("#threads", ListView)
392
+ if self._filter and len(lv):
393
+ lv.index = 0
394
+
395
+ @on(Input.Submitted, "#prompt")
396
+ async def _submitted(self, event: Input.Submitted) -> None:
397
+ text = event.value.strip()
398
+ if not text or self.service is None:
399
+ return
400
+ event.input.value = ""
401
+ try:
402
+ cmd = parse_command(text) if is_command(text) else Command("search", text)
403
+ await self._run_command(cmd)
404
+ except CommandError as e:
405
+ await self._note(str(e), "error")
406
+
407
+ # ---------- commands ----------
408
+
409
+ async def _run_command(self, cmd: Command) -> None:
410
+ svc = self.svc
411
+ if cmd.name == "help":
412
+ await self._note(help_text())
413
+ elif cmd.name == "quit":
414
+ self.exit()
415
+ elif cmd.name == "history":
416
+ source = cmd.arg.strip().lower() or None
417
+ threads = await svc.list_threads(limit=30, source=source)
418
+ self._listing = [t.id for t in threads]
419
+ if not threads:
420
+ await self._note("No conversations" + (f" from `{source}`." if source else " yet."))
421
+ return
422
+ lines = [
423
+ f"{i}. **{t.title}** — {SOURCE_LABELS.get(t.source, t.source)} · "
424
+ f"{datetime.fromtimestamp(t.updated_at):%Y-%m-%d %H:%M}"
425
+ for i, t in enumerate(threads, 1)
426
+ ]
427
+ await self._note(
428
+ "**Recent conversations** (open with `/open N`)\n\n" + "\n".join(lines)
429
+ )
430
+ elif cmd.name == "sync":
431
+ await self._note("Importing new history from your AI tools…")
432
+ self._memory_sync_now()
433
+ elif cmd.name == "search":
434
+ hits = await svc.search(cmd.arg, k=10)
435
+ if not hits:
436
+ await self._note(f"No results for _{cmd.arg}_.")
437
+ return
438
+ best: dict[str, SearchHit] = {} # one result per conversation, its best message
439
+ for h in hits:
440
+ best.setdefault(h.thread_id, h)
441
+ self._listing = list(best)
442
+ rows, lines = [], []
443
+ for i, h in enumerate(best.values(), 1):
444
+ where = SOURCE_LABELS.get(h.source or "", h.source or "")
445
+ when = relative_time(h.created_at) if h.created_at else ""
446
+ meta = " · ".join(p for p in (where, project_name(h.project), when) if p)
447
+ rows.append((h.source or "", h.thread_title or "Untitled", meta, h.content))
448
+ lines.append(f"{i}. **{h.thread_title}** · {meta}: {snippet(h.content, [])}")
449
+ markdown = f"**Search: {cmd.arg}** (open with `/open N`)\n\n" + "\n".join(lines)
450
+ results = SearchResultsView(cmd.arg, rows, markdown)
451
+ await self._mount(results)
452
+ # After layout, so the first result (not the end of the list) is in view.
453
+ self.call_after_refresh(self.view.scroll_to_widget, results, top=True, animate=False)
454
+ elif cmd.name == "open":
455
+ n = int(cmd.arg)
456
+ if not 1 <= n <= len(self._listing):
457
+ raise CommandError("No such item — search or run /history first.")
458
+ await self._open_thread(self._listing[n - 1])
459
+ elif cmd.name == "rename":
460
+ if self.thread_id is None:
461
+ raise CommandError("No conversation open.")
462
+ await svc.rename_thread(self.thread_id, cmd.arg)
463
+ await self._refresh_threads()
464
+ elif cmd.name == "delete":
465
+ if self.thread_id is None:
466
+ raise CommandError("No conversation open.")
467
+ if time.monotonic() - self._delete_armed_at > DELETE_CONFIRM_SECONDS:
468
+ self._delete_armed_at = time.monotonic()
469
+ await self._note(
470
+ "Run `/delete` again within 10s to permanently delete this conversation "
471
+ "from memory."
472
+ )
473
+ return
474
+ self._delete_armed_at = 0.0
475
+ await svc.delete_thread(self.thread_id)
476
+ self.thread_id = None
477
+ threads = await self._refresh_threads()
478
+ if threads:
479
+ await self._open_thread(threads[0].id)
480
+ else:
481
+ self._show_empty()
482
+ self.notify("Conversation deleted.")
483
+
484
+ # ---------- events & actions ----------
485
+
486
+ @on(ListView.Selected, "#threads")
487
+ async def _thread_selected(self, event: ListView.Selected) -> None:
488
+ if isinstance(event.item, ThreadItem) and event.item.thread_id != self.thread_id:
489
+ await self._open_thread(event.item.thread_id)
490
+
491
+ def action_focus_threads(self) -> None:
492
+ self.query_one("#threads", ListView).focus()
493
+
494
+ def action_focus_prompt(self) -> None:
495
+ prompt = self.query_one("#prompt", Input)
496
+ if prompt.has_focus and prompt.value:
497
+ prompt.value = "" # Esc in the search box: clear the filter first
498
+ elif prompt.has_focus:
499
+ self.action_focus_threads()
500
+ else:
501
+ prompt.focus()
502
+
503
+ async def action_open_highlighted(self) -> None:
504
+ """`l` on the list: open the conversation and move into it."""
505
+ lv = self.query_one("#threads", ListView)
506
+ item = lv.highlighted_child
507
+ if isinstance(item, ThreadItem):
508
+ if item.thread_id != self.thread_id:
509
+ await self._open_thread(item.thread_id)
510
+ self.view.focus()
511
+
512
+
513
+ def _haystack(thread: Thread) -> str:
514
+ return " ".join(
515
+ (thread.title or "", project_name(thread.project), SOURCE_LABELS.get(thread.source, ""))
516
+ )
517
+
518
+
519
+ class ThreadList(ListView):
520
+ """The conversation list, with vim keys."""
521
+
522
+ BINDINGS = [
523
+ Binding("j", "cursor_down", "Down", show=False),
524
+ Binding("k", "cursor_up", "Up", show=False),
525
+ Binding("g", "first", "Top", show=False),
526
+ Binding("G", "last", "Bottom", show=False),
527
+ Binding("ctrl+d", "half_page(1)", "Half page down", show=False),
528
+ Binding("ctrl+u", "half_page(-1)", "Half page up", show=False),
529
+ Binding("l", "app.open_highlighted", "Open", show=False),
530
+ Binding("slash", "app.focus_prompt", "Search"),
531
+ ]
532
+
533
+ def action_first(self) -> None:
534
+ if len(self):
535
+ self.index = 0
536
+
537
+ def action_last(self) -> None:
538
+ if len(self):
539
+ self.index = len(self) - 1
540
+
541
+ def action_half_page(self, direction: int) -> None:
542
+ if len(self):
543
+ rows = max(1, self.size.height // 3 // 2) # each row is 3 lines tall
544
+ self.index = max(0, min(len(self) - 1, (self.index or 0) + direction * rows))
545
+
546
+
547
+ class ConversationView(VerticalScroll):
548
+ """The open conversation, with vim scrolling."""
549
+
550
+ BINDINGS = [
551
+ Binding("j", "scroll_down", "Down", show=False),
552
+ Binding("k", "scroll_up", "Up", show=False),
553
+ Binding("g", "scroll_home", "Top", show=False),
554
+ Binding("G", "scroll_end", "Bottom", show=False),
555
+ Binding("ctrl+d", "half_page(1)", "Half page down", show=False),
556
+ Binding("ctrl+u", "half_page(-1)", "Half page up", show=False),
557
+ Binding("h", "app.focus_threads", "Back to list", show=False),
558
+ Binding("slash", "app.focus_prompt", "Search"),
559
+ ]
560
+
561
+ def action_half_page(self, direction: int) -> None:
562
+ self.scroll_relative(y=direction * max(1, self.size.height // 2), animate=False)
563
+
564
+
565
+ def _subtitle(thread: Thread) -> str:
566
+ label = SOURCE_LABELS.get(thread.source, thread.source)
567
+ return f"{thread.title} · {label}" + (f" · {thread.project}" if thread.project else "")