Feature: Interactive Book Selection () #20

Closed
opened 2026-06-03 18:32:38 +02:00 by AlexKucera · 0 comments
AlexKucera commented 2026-06-03 18:32:38 +02:00 (Migrated from github.com)

PRD: Interactive Book Selection (--select)

Problem Statement

Libro.fm-downloader downloads all undownloaded books from the user's library on every sync run. The only controls are --limit N (cap count) and download-history filtering (skip already-downloaded). Users with large libraries (50+ books) or limited storage have no way to choose specific titles — they must either download everything or manually craft --limit and hope the right books fall within the cap. This leads to unwanted downloads, wasted bandwidth, and storage pressure.

Solution

Add a --select CLI flag (off by default) that opens an interactive checkbox TUI before downloading. The user sees their undownloaded library as a scrollable, searchable checklist, picks the books they want, confirms the selection, and then the normal parallel download pipeline runs on just those books.

User Stories

  1. As a user with a large library, I want to pick which books to download from a visual list, so that I don't have to download 50+ audiobooks when I only want 3.
  2. As a user running the tool interactively, I want checkbox-style selection with arrow-key navigation and space to toggle, so that picking books feels natural and fast.
  3. As a user with many books, I want fuzzy search/filtering inside the selection UI, so that I can quickly find specific titles without scrolling through everything.
  4. As a cautious user, I want all books unchecked by default (opt-in), so that I don't accidentally start downloading my entire library by pressing Enter too quickly.
  5. As a user who just picked books, I want a confirmation summary showing exactly what will download before it starts, so that I can catch mistakes.
  6. As a user with series, I want to see series name and number in each row (e.g., [Dune 2]), so that I can make informed ordering decisions.
  7. As a cron user, I want --select to fail clearly if there's no terminal, so that I don't get stuck in an interactive prompt in a non-interactive context.
  8. As a user who already downloaded some books, I want those hidden from the selection list entirely, so that the UI only shows what's new.
  9. As a user whose library is fully up to date, I want the same "All caught up!" message I get today, even with --select enabled, so that behavior is consistent.
  10. As a user who changed their mind mid-selection, I want to be able to press Enter without selecting anything and exit cleanly, so that choosing nothing is always safe.
  11. As a developer extending this tool, I want selection logic isolated in its own module with a clean function signature, so that I can test it independently of CLI wiring.
  12. As a user who normally auto-downloads everything, I want --select to be off by default with no config option, so that existing scripts and cron jobs are completely unaffected.
  13. As a user who uses --limit for testing, I want to understand that --select supersedes --limit, so that there's no confusion about which filter wins.

Implementation Decisions

New dependency: questionary

The interactive TUI is powered by questionary, a mature Python library built on prompt_toolkit that provides Rich-compatible checkbox prompts with keyboard navigation and fuzzy search. It is added as a required runtime dependency in pyproject.toml alongside httpx, pyyaml, and rich.

New module: selector.py

A new librofm_downloader/selector.py module contains the selection logic. Its public interface is a single function:

select_books(books: list[Book]) -> list[Book]

This function:

  1. Formats each Book into a display string: "N. Title — First Author [Series #]" (series suffix omitted when absent)
  2. Opens a questionary checkbox prompt with those choices, all unchecked by default
  3. If the user selects zero books, prints "No books selected. Exiting." and returns an empty list
  4. If the user selects one or more books, shows a confirmation summary listing selected titles, then prompts y/N
  5. On confirmation, returns the selected Book objects in their original order
  6. On cancellation (N / Ctrl+C at confirm), returns an empty list

The module has no side effects beyond console I/O via questionary/Rich. It does not call any network APIs or touch the filesystem.

Modified module: cli.py

The run() function gains a new parameter select: bool = False. The argparse block gains a --select flag (no short form).

When select=True, the pipeline changes between step 3 (fetch_library) and step 5 (download):

Current path: fetch_library → history_filter → limit → download_all
Select path: fetch_library → history_filter → TTY_check → convert_to_Books → select_books() → download_all

Specifically:

  • After fetching the library, the same DownloadHistory check removes already-downloaded books (same logic as today)
  • If no undownloaded books remain, print "All caught up!" and exit 0 (identical to current behavior)
  • Check sys.stdout.isatty() — if False, print error message and exit 1
  • Convert remaining raw dicts to Book objects using the existing _raw_to_book() pattern from orchestrator.py
  • Call selector.select_books(books)
  • If result is empty, exit 0
  • Pass selected Books (converted back to dicts or accepted directly) into the existing download_all_books() orchestrator
  • Continue with normal progress reporting, history writing, and summary output

When select=False, behavior is 100% identical to today — no code path changes.

--limit interaction

When --select is active, --limit is explicitly ignored. A verbose-mode note documents this: "Selection mode active — --limit is superseded by manual selection." This prevents user confusion about which filter applies.

Row format specification

Each selectable row displays as:

N. Title — First Author [Series #]

Where:

  • N is the 1-based index
  • Title is the book title
  • First Author is authors[] if available, else "Unknown"
  • [Series #] suffix appears only when both series and series_num are present

Duration is intentionally excluded because the /api/v10/library endpoint does not return it; fetching per-book detail would add N API calls before the UI renders.

Confirmation dialog format

After selection but before downloads begin:

N book(s) selected for download:
 • Title One — Author One
 • Title Two — Author Two

Proceed? [y/N]

Default is No (safe). Accepts 'y' or 'Y' only; anything else (including bare Enter) cancels and exits 0.

Error handling

Condition Behavior Exit code
--select + no TTY Print error, exit 1
All books already downloaded Print "All caught up!", exit 0
Zero books selected Print "No books selected.", exit 0
User cancels confirmation (N) Exit silently 0
Ctrl+C during selection Propagate KeyboardInterrupt → cli.py handler (exit 130) 130

Testing Decisions

Testing philosophy

Tests verify external behavior (what goes in, what comes out) rather than implementation details (which questionary methods were called, exact prompt text). The selector module is tested by patching questionary's prompt functions to return controlled values without rendering a real TUI.

Modules under test

selector.py — Full unit test coverage:

  • test_select_books_returns_selected: patches questionary.checkbox to return specific choices, verifies correct Books returned in original order
  • test_select_books_empty_selection_returns_empty: user selects nothing → empty list
  • test_select_books_formatting: verifies row format includes title, author, series when present, omits series when absent
  • test_select_books_single_book: single-book library works correctly
  • test_select_books_preserves_order: selection order matches input order regardless of which checkboxes were toggled first
  • test_confirm_yes_returns_selections: confirmation accepts 'y'/'Y'
  • test_confirm_no_returns_empty: confirmation rejects anything else (default No)
  • test_format_row_with_series: row includes [Series N]
  • test_format_row_without_series: row omits series suffix
  • test_format_row_single_author: shows author name
  • test_format_row_no_authors: shows "Unknown"

cli.py — Integration tests for select-path:

  • test_select_mode_calls_selector: when select=True and books available, selector.select_books is called
  • test_select_mode_no_tty_exits: stdout not a tty → exit 1 with error message
  • test_select_mode_all_downloaded_caught_up: all books in history → "All caught up!", exit 0
  • test_select_mode_empty_selection_exits_zero: selector returns empty → exit 0
  • test_select_mode_passes_to_orchestrator: selected books flow into download_all_books correctly
  • test_select_mode_ignores_limit: --limit N with --select → limit not applied

Prior art

Test patterns follow the established conventions in this codebase:

  • test_client.py: uses httpx.MockTransport for API mocking
  • test_orchestrator.py: tests pure functions with dataclass inputs/outputs
  • test_cli.py: tests the run() function with mocked dependencies
  • All tests use pytest with pytest-mock's mocker fixture for patching

Out of Scope

  • Duration display: Would require N additional API calls to /api/v10/explore/audiobook_details/{isbn} per book before the UI renders. Not worth the latency cost.
  • Config.yaml option for select mode: Selection is a per-invocation decision, not a persistent preference. CLI-only keeps the mental model clean.
  • Non-TTY fallback mode: Degrading to numbered-list input would double the codepaths and testing surface for a scenario almost no user encounters.
  • Re-downloading already-downloaded books via selection: Already-downloaded books are filtered out before the TUI opens. Re-download would require a separate --force flag (future work).
  • Multi-select with ranges or patterns: The checkbox TUI is the selection mechanism; no need for --select 1,3,5-10 syntax.
  • Persistent selections / favorites: No saved selection lists or bookmarking. Each invocation is independent.
  • Cover art thumbnails in the selection UI: Would require fetching images and terminal image rendering support. Out of scope for v1.

Further Notes

  • This feature is documented in ADR 0006 (docs/adr/0006-select-mode-interactive-book-selection.md) which covers the full trade-off analysis including why questionary was chosen over alternatives, why non-TTY is a hard error, and why duration was omitted.
  • The domain glossary (CONTEXT.md) has been updated with a Select Mode definition and the revised Sync Run pipeline description.
  • The questionary dependency pulls in prompt_toolkit as a transitive dependency. Both are mature, widely-used libraries with active maintenance.
  • Future enhancement: a --force flag could allow re-downloading already-downloaded books through the selection UI by skipping the history-filter step when combined with --select.
# PRD: Interactive Book Selection (`--select`) ## Problem Statement Libro.fm-downloader downloads **all** undownloaded books from the user's library on every sync run. The only controls are `--limit N` (cap count) and download-history filtering (skip already-downloaded). Users with large libraries (50+ books) or limited storage have no way to choose specific titles — they must either download everything or manually craft `--limit` and hope the right books fall within the cap. This leads to unwanted downloads, wasted bandwidth, and storage pressure. ## Solution Add a `--select` CLI flag (off by default) that opens an interactive checkbox TUI before downloading. The user sees their undownloaded library as a scrollable, searchable checklist, picks the books they want, confirms the selection, and then the normal parallel download pipeline runs on just those books. ## User Stories 1. As a **user with a large library**, I want to pick which books to download from a visual list, so that I don't have to download 50+ audiobooks when I only want 3. 2. As a **user running the tool interactively**, I want checkbox-style selection with arrow-key navigation and space to toggle, so that picking books feels natural and fast. 3. As a **user with many books**, I want fuzzy search/filtering inside the selection UI, so that I can quickly find specific titles without scrolling through everything. 4. As a **cautious user**, I want all books unchecked by default (opt-in), so that I don't accidentally start downloading my entire library by pressing Enter too quickly. 5. As a **user who just picked books**, I want a confirmation summary showing exactly what will download before it starts, so that I can catch mistakes. 6. As a **user with series**, I want to see series name and number in each row (e.g., `[Dune 2]`), so that I can make informed ordering decisions. 7. As a **cron user**, I want `--select` to fail clearly if there's no terminal, so that I don't get stuck in an interactive prompt in a non-interactive context. 8. As a **user who already downloaded some books**, I want those hidden from the selection list entirely, so that the UI only shows what's new. 9. As a **user whose library is fully up to date**, I want the same "All caught up!" message I get today, even with `--select` enabled, so that behavior is consistent. 10. As a **user who changed their mind mid-selection**, I want to be able to press Enter without selecting anything and exit cleanly, so that choosing nothing is always safe. 11. As a **developer extending this tool**, I want selection logic isolated in its own module with a clean function signature, so that I can test it independently of CLI wiring. 12. As a **user who normally auto-downloads everything**, I want `--select` to be off by default with no config option, so that existing scripts and cron jobs are completely unaffected. 13. As a **user who uses `--limit` for testing**, I want to understand that `--select` supersedes `--limit`, so that there's no confusion about which filter wins. ## Implementation Decisions ### New dependency: questionary The interactive TUI is powered by **questionary**, a mature Python library built on prompt_toolkit that provides Rich-compatible checkbox prompts with keyboard navigation and fuzzy search. It is added as a required runtime dependency in `pyproject.toml` alongside httpx, pyyaml, and rich. ### New module: selector.py A new `librofm_downloader/selector.py` module contains the selection logic. Its public interface is a single function: ``` select_books(books: list[Book]) -> list[Book] ``` This function: 1. Formats each Book into a display string: `"N. Title — First Author [Series #]"` (series suffix omitted when absent) 2. Opens a questionary checkbox prompt with those choices, all unchecked by default 3. If the user selects zero books, prints "No books selected. Exiting." and returns an empty list 4. If the user selects one or more books, shows a confirmation summary listing selected titles, then prompts y/N 5. On confirmation, returns the selected Book objects in their original order 6. On cancellation (N / Ctrl+C at confirm), returns an empty list The module has no side effects beyond console I/O via questionary/Rich. It does not call any network APIs or touch the filesystem. ### Modified module: cli.py The `run()` function gains a new parameter `select: bool = False`. The argparse block gains a `--select` flag (no short form). When `select=True`, the pipeline changes between step 3 (fetch_library) and step 5 (download): **Current path:** fetch_library → history_filter → limit → download_all **Select path:** fetch_library → history_filter → TTY_check → convert_to_Books → select_books() → download_all Specifically: - After fetching the library, the same DownloadHistory check removes already-downloaded books (same logic as today) - If no undownloaded books remain, print "All caught up!" and exit 0 (identical to current behavior) - Check `sys.stdout.isatty()` — if False, print error message and exit 1 - Convert remaining raw dicts to Book objects using the existing `_raw_to_book()` pattern from orchestrator.py - Call `selector.select_books(books)` - If result is empty, exit 0 - Pass selected Books (converted back to dicts or accepted directly) into the existing `download_all_books()` orchestrator - Continue with normal progress reporting, history writing, and summary output When `select=False`, behavior is 100% identical to today — no code path changes. ### `--limit` interaction When `--select` is active, `--limit` is explicitly ignored. A verbose-mode note documents this: "Selection mode active — --limit is superseded by manual selection." This prevents user confusion about which filter applies. ### Row format specification Each selectable row displays as: ``` N. Title — First Author [Series #] ``` Where: - N is the 1-based index - Title is the book title - First Author is `authors[]` if available, else `"Unknown"` - `[Series #]` suffix appears only when both `series` and `series_num` are present Duration is intentionally excluded because the `/api/v10/library` endpoint does not return it; fetching per-book detail would add N API calls before the UI renders. ### Confirmation dialog format After selection but before downloads begin: ``` N book(s) selected for download: • Title One — Author One • Title Two — Author Two Proceed? [y/N] ``` Default is No (safe). Accepts 'y' or 'Y' only; anything else (including bare Enter) cancels and exits 0. ### Error handling | Condition | Behavior | Exit code | |---|---|---| | `--select` + no TTY | Print error, exit | 1 | | All books already downloaded | Print "All caught up!", exit | 0 | | Zero books selected | Print "No books selected.", exit | 0 | | User cancels confirmation (N) | Exit silently | 0 | | Ctrl+C during selection | Propagate KeyboardInterrupt → cli.py handler (exit 130) | 130 | ## Testing Decisions ### Testing philosophy Tests verify external behavior (what goes in, what comes out) rather than implementation details (which questionary methods were called, exact prompt text). The selector module is tested by patching questionary's prompt functions to return controlled values without rendering a real TUI. ### Modules under test **selector.py** — Full unit test coverage: - `test_select_books_returns_selected`: patches questionary.checkbox to return specific choices, verifies correct Books returned in original order - `test_select_books_empty_selection_returns_empty`: user selects nothing → empty list - `test_select_books_formatting`: verifies row format includes title, author, series when present, omits series when absent - `test_select_books_single_book`: single-book library works correctly - `test_select_books_preserves_order`: selection order matches input order regardless of which checkboxes were toggled first - `test_confirm_yes_returns_selections`: confirmation accepts 'y'/'Y' - `test_confirm_no_returns_empty`: confirmation rejects anything else (default No) - `test_format_row_with_series`: row includes `[Series N]` - `test_format_row_without_series`: row omits series suffix - `test_format_row_single_author`: shows author name - `test_format_row_no_authors`: shows "Unknown" **cli.py** — Integration tests for select-path: - `test_select_mode_calls_selector`: when select=True and books available, selector.select_books is called - `test_select_mode_no_tty_exits`: stdout not a tty → exit 1 with error message - `test_select_mode_all_downloaded_caught_up`: all books in history → "All caught up!", exit 0 - `test_select_mode_empty_selection_exits_zero`: selector returns empty → exit 0 - `test_select_mode_passes_to_orchestrator`: selected books flow into download_all_books correctly - `test_select_mode_ignores_limit`: --limit N with --select → limit not applied ### Prior art Test patterns follow the established conventions in this codebase: - `test_client.py`: uses `httpx.MockTransport` for API mocking - `test_orchestrator.py`: tests pure functions with dataclass inputs/outputs - `test_cli.py`: tests the `run()` function with mocked dependencies - All tests use `pytest` with `pytest-mock`'s `mocker` fixture for patching ## Out of Scope - **Duration display**: Would require N additional API calls to `/api/v10/explore/audiobook_details/{isbn}` per book before the UI renders. Not worth the latency cost. - **Config.yaml option for select mode**: Selection is a per-invocation decision, not a persistent preference. CLI-only keeps the mental model clean. - **Non-TTY fallback mode**: Degrading to numbered-list input would double the codepaths and testing surface for a scenario almost no user encounters. - **Re-downloading already-downloaded books via selection**: Already-downloaded books are filtered out before the TUI opens. Re-download would require a separate `--force` flag (future work). - **Multi-select with ranges or patterns**: The checkbox TUI is the selection mechanism; no need for `--select 1,3,5-10` syntax. - **Persistent selections / favorites**: No saved selection lists or bookmarking. Each invocation is independent. - **Cover art thumbnails in the selection UI**: Would require fetching images and terminal image rendering support. Out of scope for v1. ## Further Notes - This feature is documented in **ADR 0006** (`docs/adr/0006-select-mode-interactive-book-selection.md`) which covers the full trade-off analysis including why questionary was chosen over alternatives, why non-TTY is a hard error, and why duration was omitted. - The domain glossary (**CONTEXT.md**) has been updated with a **Select Mode** definition and the revised **Sync Run** pipeline description. - The `questionary` dependency pulls in `prompt_toolkit` as a transitive dependency. Both are mature, widely-used libraries with active maintenance. - Future enhancement: a `--force` flag could allow re-downloading already-downloaded books through the selection UI by skipping the history-filter step when combined with `--select`.
Sign in to join this conversation.