From 5111f79940922d0461e625eeeba83b9b1a0f7bfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wiktor=20Zi=C4=99bka?= Date: Tue, 17 Nov 2026 10:44:23 +0100 Subject: [PATCH 01/14] fix(palette): open the library of the screen Go Library opened the library that the library screen showed last, or the first library of the server. The library screen shows no Go Library, because the entry opened the same screen again. --- internal/app/model.go | 6 +++- internal/app/model_test.go | 64 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/internal/app/model.go b/internal/app/model.go index 1fcc184..b4fe2d0 100644 --- a/internal/app/model.go +++ b/internal/app/model.go @@ -1234,7 +1234,9 @@ func (m Model) buildStaticPaletteItems() (player, nav []components.PaletteItem) nav = []components.PaletteItem{ {Label: "Navigation", IsHeader: true}, {Label: "Go Home", Action: components.ActionGoHome}, - {Label: "Go Library", Action: components.ActionGoLibrary}, + } + if m.screen != ScreenLibrary { + nav = append(nav, components.PaletteItem{Label: "Go Library", Action: components.ActionGoLibrary}) } // Only a book library has series. The series list is the target of the entry. if libID, mediaType := m.currentLibraryForSearch(); mediaType == "book" && m.screen != ScreenSeriesList { @@ -1341,6 +1343,8 @@ func (m Model) handlePaletteAction(action components.PaletteAction, payload, lib case components.ActionGoHome: return m.navigate(ScreenHome) case components.ActionGoLibrary: + libID, _ := m.currentLibraryForSearch() + m.library.Configure(libID, m.home.Libraries()) return m.navigate(ScreenLibrary) case components.ActionShowSessions: if entry, ok := data.(detail.AddToQueueCmd); ok { diff --git a/internal/app/model_test.go b/internal/app/model_test.go index 762f972..7d1d932 100644 --- a/internal/app/model_test.go +++ b/internal/app/model_test.go @@ -2558,6 +2558,70 @@ func TestPaletteBrowseSeriesOpensBookLibraryOfScreen(t *testing.T) { } } +// TestPaletteGoLibraryOpensLibraryOfScreen verifies that Go Library of the +// palette opens the library of the current screen, also before the library +// screen opens for the first time. The library screen shows no Go Library. +func TestPaletteGoLibraryOpensLibraryOfScreen(t *testing.T) { + // The home screen shows the first library. + libs := []abs.Library{ + {ID: "lib-a", Name: "A", MediaType: "book"}, + {ID: "lib-b", Name: "B", MediaType: "book"}, + } + book := abs.LibraryItem{ID: "b-1", LibraryID: "lib-b", MediaType: "book"} + + tests := []struct { + name string + setup func(m *Model) + wantLib string + }{ + {"home on a book library", func(m *Model) { m.screen = ScreenHome }, "lib-a"}, + {"detail of a book of a different library", func(m *Model) { + m.detail = detail.New(m.styles, book) + m.screen = ScreenDetail + }, "lib-b"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m := newTestModelAuthenticated() + m.home, _ = m.home.Update(home.PersonalizedMsg{Libraries: libs}) + tt.setup(&m) + + var goLibrary *components.PaletteItem + _, nav := m.buildStaticPaletteItems() + for _, item := range nav { + if item.Action == components.ActionGoLibrary { + goLibrary = &item + } + } + if goLibrary == nil { + t.Fatal("the palette has no Go Library") + } + m, _ = m.handlePaletteAction(goLibrary.Action, goLibrary.Payload, goLibrary.LibraryID, goLibrary.ItemID, goLibrary.Data) + if m.screen != ScreenLibrary { + t.Errorf("screen = %v, want the library", m.screen) + } + if got := m.library.SelectedLibraryID(); got != tt.wantLib { + t.Errorf("library = %q, want %q", got, tt.wantLib) + } + }) + } + + t.Run("library screen", func(t *testing.T) { + m := newTestModelAuthenticated() + m.home, _ = m.home.Update(home.PersonalizedMsg{Libraries: libs}) + m.library.Configure("lib-b", libs) + m.screen = ScreenLibrary + + _, nav := m.buildStaticPaletteItems() + for _, item := range nav { + if item.Action == components.ActionGoLibrary { + t.Error("the library screen has Go Library") + } + } + }) +} + // TestPaletteSpeedActions verifies that Speed Up of the palette does not lower // a speed above the range of the palette, and Speed Down does not raise a speed // below it: the speed keys and MPRIS can set such a speed. MPRIS gets the new From 3acd8b36f622482bfe5328983b854f567dbccdeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wiktor=20Zi=C4=99bka?= Date: Tue, 17 Nov 2026 10:47:54 +0100 Subject: [PATCH 02/14] fix(app): reload the open screens after a scan A scan reloaded only home and the library screen, so an open series list, series, or detail screen kept the data from before the scan. A load of the series list or of a series now reaches its screen also behind the active screen. --- internal/app/e2e_helpers_test.go | 19 +++++++++++++++ internal/app/e2e_test.go | 41 ++++++++++++++++++++++++++++++++ internal/app/model.go | 34 +++++++++++++++++++++++++- internal/app/model_test.go | 33 +++++++++++++++++++++++++ internal/app/navigation.go | 7 ++++++ 5 files changed, 133 insertions(+), 1 deletion(-) diff --git a/internal/app/e2e_helpers_test.go b/internal/app/e2e_helpers_test.go index cb7d258..1893a9d 100644 --- a/internal/app/e2e_helpers_test.go +++ b/internal/app/e2e_helpers_test.go @@ -94,6 +94,13 @@ func testPodcastItem(id, title string) abs.LibraryItem { } } +// testSeries is the series of the book library of the mock server. A scan of +// the library finds testScannedSeries. +var ( + testSeries = abs.Series{ID: "ser-001", Name: "Dystopias", LibraryID: "lib-001"} + testScannedSeries = abs.Series{ID: "ser-002", Name: "Utopias", LibraryID: "lib-001"} +) + func testBookmark(title string, seconds float64) abs.Bookmark { return abs.Bookmark{ Title: title, @@ -325,6 +332,18 @@ func newFullMockABSServer(log *apiLog, state *e2eServerState) *httptest.Server { } _ = json.NewEncoder(w).Encode(resp) + // --- Series of the book library --- + case r.Method == http.MethodGet && r.URL.Path == "/api/libraries/lib-001/series": + results := []abs.Series{testSeries} + if state.getLastScan() != 0 { + results = append(results, testScannedSeries) + } + resp := abs.LibrarySeriesResponse{Results: results, Total: len(results), Limit: 50} + _ = json.NewEncoder(w).Encode(resp) + + case r.Method == http.MethodGet && r.URL.Path == "/api/libraries/lib-001/series/"+testSeries.ID: + _ = json.NewEncoder(w).Encode(testSeries) + // --- Library items (books) --- case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/api/libraries/lib-001/items"): resp := abs.LibraryItemsResponse{ diff --git a/internal/app/e2e_test.go b/internal/app/e2e_test.go index 119d9cc..e00bbda 100644 --- a/internal/app/e2e_test.go +++ b/internal/app/e2e_test.go @@ -2687,3 +2687,44 @@ func TestE2E_PaletteScanLibraryReloadsAfterTheScan(t *testing.T) { t.Errorf("home loads = %d, want more than %d after the scan", got, loads) } } + +// TestE2E_PaletteScanLibraryReloadsSeriesScreens verifies that a scan loads +// the series screen of the library again, and the series list in the back +// stack. The series list shows the series that the scan finds. +func TestE2E_PaletteScanLibraryReloadsSeriesScreens(t *testing.T) { + log := &apiLog{} + state := &e2eServerState{bookmarks: make(map[string][]abs.Bookmark)} + srv := newFullMockABSServer(log, state) + defer srv.Close() + + m := newE2EModelAuthenticated(srv, &mockPlayer{}) + m = e2eSetSize(m, 120, 40) + m, cmd := feedCmd(m, m.home.Init()) + m = feedCmdChain(m, cmd, 5) + res, cmd := m.Update(library.NavigateSeriesListMsg{LibraryID: "lib-001", LibraryName: "Audiobooks"}) + m = res.(Model) + m, _ = feedCmd(m, cmd) + m, cmd = e2ePressSpecial(m, tea.KeyEnter) + m = feedCmdChain(m, cmd, 3) + assertScreen(t, m, ScreenSeries) + seriesPath := "/api/libraries/lib-001/series/" + testSeries.ID + loads := log.count(http.MethodGet, seriesPath) + + res, _ = m.Update(tea.KeyMsg{Type: tea.KeyCtrlP}) + m = res.(Model) + m = e2eTypeString(m, "scan") + m, _ = e2ePressSpecial(m, tea.KeyEnter) + m, scanCmd := e2ePressSpecial(m, tea.KeyEnter) + m, reloadCmd := feedCmdWithin(m, scanCmd, slowCmdWait) + if got := log.count(http.MethodPost, "/api/libraries/lib-001/scan"); got != 1 { + t.Fatalf("scan requests = %d, want 1", got) + } + m = feedCmdChain(m, reloadCmd, 5) + + if got := log.count(http.MethodGet, seriesPath); got <= loads { + t.Errorf("series loads = %d, want more than %d after the scan", got, loads) + } + if !strings.Contains(m.seriesList.View(), testScannedSeries.Name) { + t.Errorf("the series list does not show %q after the scan", testScannedSeries.Name) + } +} diff --git a/internal/app/model.go b/internal/app/model.go index b4fe2d0..6430cd3 100644 --- a/internal/app/model.go +++ b/internal/app/model.go @@ -589,6 +589,18 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case serieslist.BackMsg: return m.back() + // A load reaches its screen also behind the active screen: a scan loads + // the screens in the back stack again. + case serieslist.LoadedMsg: + var cmd tea.Cmd + m.seriesList, cmd = m.seriesList.Update(msg) + return m, cmd + + case series.LoadedMsg: + var cmd tea.Cmd + m.series, cmd = m.series.Update(msg) + return m, cmd + case detail.MarkFinishedCmd: return m.handleMarkFinished(msg) @@ -630,7 +642,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if m.searchCache != nil { m.searchCache.Invalidate(msg.LibraryID) } - return m, tea.Batch(m.home.ReloadCmd(), m.library.ReloadCmd(), m.prewarmCacheCmd()) + return m, tea.Batch(m.home.ReloadCmd(), m.library.ReloadCmd(), m.prewarmCacheCmd(), m.reloadOpenScreensCmd(msg.LibraryID)) case detail.SeekToBookmarkCmd: return m.handleSeekToBookmark(msg) @@ -1694,6 +1706,26 @@ func (m Model) scanLibraryCmd() tea.Cmd { } } +// reloadOpenScreensCmd loads the open series list, series screen, and detail +// screen of a library again. With an empty libraryID, it loads them for each +// library. +func (m Model) reloadOpenScreensCmd(libraryID string) tea.Cmd { + inLibrary := func(id string) bool { + return libraryID == "" || id == libraryID + } + var cmds []tea.Cmd + if m.screenOpen(ScreenSeriesList) && inLibrary(m.seriesList.SelectedLibraryID()) { + cmds = append(cmds, m.seriesList.Init()) + } + if m.screenOpen(ScreenSeries) && inLibrary(m.series.LibraryID()) { + cmds = append(cmds, m.series.Init()) + } + if item := m.detail.Item(); m.screenOpen(ScreenDetail) && inLibrary(item.LibraryID) { + cmds = append(cmds, m.detailLoadCmds(item, nil)...) + } + return tea.Batch(cmds...) +} + func (m Model) handleDeleteItem(cmd detail.DeleteItemCmd) (Model, tea.Cmd) { if m.client == nil { return m, nil diff --git a/internal/app/model_test.go b/internal/app/model_test.go index 7d1d932..972fb42 100644 --- a/internal/app/model_test.go +++ b/internal/app/model_test.go @@ -2622,6 +2622,39 @@ func TestPaletteGoLibraryOpensLibraryOfScreen(t *testing.T) { }) } +// TestSeriesLoadedMsgReachesScreenBehindActiveScreen verifies that a load of +// the series list or of a series reaches its screen model also when a +// different screen is active: a scan loads the screens in the back stack again. +func TestSeriesLoadedMsgReachesScreenBehindActiveScreen(t *testing.T) { + t.Run("series list behind the series screen", func(t *testing.T) { + m := newTestModelAuthenticated() + m.seriesList = serieslist.New(m.styles, m.client, "lib-a", "A") + m.series = series.New(m.styles, m.client, "lib-a", "ser-1", "") + m.backStack = []Screen{ScreenHome, ScreenSeriesList} + m.screen = ScreenSeries + + res, _ := m.Update(serieslist.LoadedMsg{Results: []abs.Series{{ID: "ser-1", Name: "Dune"}}, Total: 1}) + m = res.(Model) + if m.seriesList.Loading() { + t.Error("the series list did not get the loaded page") + } + }) + + t.Run("series behind the detail screen", func(t *testing.T) { + m := newTestModelAuthenticated() + m.series = series.New(m.styles, m.client, "lib-a", "ser-1", "") + m.detail = detail.New(m.styles, abs.LibraryItem{ID: "b-1", LibraryID: "lib-a", MediaType: "book"}) + m.backStack = []Screen{ScreenHome, ScreenSeries} + m.screen = ScreenDetail + + res, _ := m.Update(series.LoadedMsg{Contents: abs.SeriesContents{Series: abs.Series{ID: "ser-1", Name: "Dune"}}}) + m = res.(Model) + if m.series.Loading() { + t.Error("the series screen did not get the loaded series") + } + }) +} + // TestPaletteSpeedActions verifies that Speed Up of the palette does not lower // a speed above the range of the palette, and Speed Down does not raise a speed // below it: the speed keys and MPRIS can set such a speed. MPRIS gets the new diff --git a/internal/app/navigation.go b/internal/app/navigation.go index 2488ce8..2a6a02c 100644 --- a/internal/app/navigation.go +++ b/internal/app/navigation.go @@ -1,6 +1,8 @@ package app import ( + "slices" + "github.com/Thelost77/pine/internal/logger" tea "github.com/charmbracelet/bubbletea" ) @@ -41,6 +43,11 @@ func (m Model) BackStack() []Screen { return cp } +// screenOpen reports whether s is the active screen or is in the back stack. +func (m Model) screenOpen(s Screen) bool { + return m.screen == s || slices.Contains(m.backStack, s) +} + // screenHeight returns the available height for screen content. func (m Model) screenHeight() int { h := m.height - headerHeight From 404310cff30205b7de460260287678a8d880ab48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wiktor=20Zi=C4=99bka?= Date: Tue, 17 Nov 2026 10:50:54 +0100 Subject: [PATCH 03/14] feat(palette): show a box while a scan runs A scan can take minutes, and pine showed nothing until its end. A second Scan Library while a scan runs does nothing. --- internal/app/e2e_test.go | 4 ++++ internal/app/messages.go | 4 +++- internal/app/model.go | 47 +++++++++++++++++++++++++++++++++---- internal/app/model_test.go | 39 ++++++++++++++++++++++++++++++ internal/app/render.go | 37 +++++++++++++++++++++++++++++ internal/app/render_test.go | 32 +++++++++++++++++++++++++ 6 files changed, 157 insertions(+), 6 deletions(-) diff --git a/internal/app/e2e_test.go b/internal/app/e2e_test.go index e00bbda..8eda4d1 100644 --- a/internal/app/e2e_test.go +++ b/internal/app/e2e_test.go @@ -2674,6 +2674,7 @@ func TestE2E_PaletteScanLibraryReloadsAfterTheScan(t *testing.T) { if scanCmd == nil { t.Fatal("Scan Library returns no command") } + assertViewContains(t, m, "Scanning Audiobooks") m, reloadCmd := feedCmdWithin(m, scanCmd, slowCmdWait) if got := log.count(http.MethodPost, "/api/libraries/lib-001/scan"); got != 1 { @@ -2682,6 +2683,9 @@ func TestE2E_PaletteScanLibraryReloadsAfterTheScan(t *testing.T) { if m.err.HasError() { t.Fatalf("error after the scan: %v", m.err.Error()) } + if strings.Contains(m.View(), "Scanning") { + t.Error("the view shows the scan box after the end of the scan") + } feedCmdChain(m, reloadCmd, 5) if got := log.count(http.MethodGet, "/api/libraries/lib-001/personalized"); got <= loads { t.Errorf("home loads = %d, want more than %d after the scan", got, loads) diff --git a/internal/app/messages.go b/internal/app/messages.go index 60e009b..31c7c87 100644 --- a/internal/app/messages.go +++ b/internal/app/messages.go @@ -158,9 +158,11 @@ type SeriesContinueMsg struct { } // LibraryScannedMsg is sent after the end of a scan of a library on the -// server. The screens then load the data of the library again. +// server. The screens then load the data of the library again. Err is the +// error of a scan that failed. type LibraryScannedMsg struct { LibraryID string + Err error } // PrewarmDoneMsg is sent after cache pre-warming completes. No action needed, diff --git a/internal/app/model.go b/internal/app/model.go index 6430cd3..2508888 100644 --- a/internal/app/model.go +++ b/internal/app/model.go @@ -27,6 +27,7 @@ import ( "github.com/Thelost77/pine/internal/ui" "github.com/Thelost77/pine/internal/ui/components" "github.com/charmbracelet/bubbles/key" + "github.com/charmbracelet/bubbles/spinner" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" ) @@ -107,6 +108,11 @@ type Model struct { palette components.Palette + // scanStatus is the text of the box of a running scan. It is empty when + // no scan runs. + scanStatus string + scanSpinner spinner.Model + lastPlayedTitle string lastPlayedTrackID string lastPlayedAuthors []string @@ -158,6 +164,7 @@ func NewWithPlayer(cfg config.Config, store *db.Store, client *cache.Client, cac mprisLink: &mprisLink{}, mprisState: &MprisState{}, palette: palette, + scanSpinner: spinner.New(spinner.WithSpinner(spinner.MiniDot), spinner.WithStyle(styles.Accent)), } } @@ -637,6 +644,10 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, tea.Batch(m.home.ReloadCmd(), m.library.ReloadCmd(), m.prewarmCacheCmd()) case LibraryScannedMsg: + m.scanStatus = "" + if msg.Err != nil { + return m.Update(components.ErrMsg{Err: msg.Err}) + } m.home.InvalidateLibrary(msg.LibraryID) m.library.InvalidateLibrary(msg.LibraryID) if m.searchCache != nil { @@ -644,6 +655,15 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } return m, tea.Batch(m.home.ReloadCmd(), m.library.ReloadCmd(), m.prewarmCacheCmd(), m.reloadOpenScreensCmd(msg.LibraryID)) + case spinner.TickMsg: + // The ticks end with the scan. + if m.scanStatus == "" { + return m, nil + } + var cmd tea.Cmd + m.scanSpinner, cmd = m.scanSpinner.Update(msg) + return m, cmd + case detail.SeekToBookmarkCmd: return m.handleSeekToBookmark(msg) @@ -1250,14 +1270,19 @@ func (m Model) buildStaticPaletteItems() (player, nav []components.PaletteItem) if m.screen != ScreenLibrary { nav = append(nav, components.PaletteItem{Label: "Go Library", Action: components.ActionGoLibrary}) } + libID, mediaType := m.currentLibraryForSearch() // Only a book library has series. The series list is the target of the entry. - if libID, mediaType := m.currentLibraryForSearch(); mediaType == "book" && m.screen != ScreenSeriesList { + if mediaType == "book" && m.screen != ScreenSeriesList { nav = append(nav, components.PaletteItem{Label: "Browse Series", Action: components.ActionBrowseSeries, LibraryID: libID, Payload: m.libraryName(libID)}) } + scanLabel := "Scan Library" + if name := m.libraryName(libID); name != "" { + scanLabel += ": " + name + } nav = append(nav, components.PaletteItem{Label: "Listening History", Action: components.ActionShowSessions}, components.PaletteItem{Label: "Library", IsHeader: true}, - components.PaletteItem{Label: "Scan Library", Action: components.ActionScanLibrary}, + components.PaletteItem{Label: scanLabel, Action: components.ActionScanLibrary}, ) if !m.isPlaying() { @@ -1658,7 +1683,19 @@ func (m Model) handlePaletteAction(action components.PaletteAction, payload, lib case components.ActionSwitchLibrary: return m, nil case components.ActionScanLibrary: - return m, m.scanLibraryCmd() + scanCmd := m.scanLibraryCmd() + if m.scanStatus != "" || scanCmd == nil { + return m, nil + } + libID, _ := m.currentLibraryForSearch() + name := m.libraryName(libID) + if name == "" { + name = "library" + } + m.scanStatus = "Scanning " + name + "…" + // The tick is first, because feedCmdWithin of the tests runs each + // command of a batch and gives the command of the last one. + return m, tea.Batch(m.scanSpinner.Tick, scanCmd) case components.ActionDeleteItem: if msg, ok := data.(detail.ShowDeleteConfirmMsg); ok && m.screen == ScreenDetail { m.detail, _ = m.detail.Update(msg) @@ -1686,7 +1723,7 @@ func (m Model) prewarmCacheCmd() tea.Cmd { // scanLibraryCmd scans the library of the current screen on the server. At the // end of the scan, the cache client clears the cache, and LibraryScannedMsg -// loads the screens again. +// closes the scan box and loads the screens again, or shows the error. func (m Model) scanLibraryCmd() tea.Cmd { libraryID, _ := m.currentLibraryForSearch() if m.client == nil || libraryID == "" { @@ -1700,7 +1737,7 @@ func (m Model) scanLibraryCmd() tea.Cmd { if abs.IsHTTPStatus(err, http.StatusForbidden) { err = fmt.Errorf("ABS user does not have the admin permission to scan: %w", err) } - return components.ErrMsg{Err: fmt.Errorf("failed to scan library: %w", err)} + return LibraryScannedMsg{LibraryID: libraryID, Err: fmt.Errorf("failed to scan library: %w", err)} } return LibraryScannedMsg{LibraryID: libraryID} } diff --git a/internal/app/model_test.go b/internal/app/model_test.go index 972fb42..ed66479 100644 --- a/internal/app/model_test.go +++ b/internal/app/model_test.go @@ -2655,6 +2655,45 @@ func TestSeriesLoadedMsgReachesScreenBehindActiveScreen(t *testing.T) { }) } +// TestPaletteScanLibraryShowsScanBox verifies that Scan Library shows the box +// of the scan, that a second Scan Library does nothing while the scan runs, +// and that the end of a scan that failed closes the box and shows the error. +func TestPaletteScanLibraryShowsScanBox(t *testing.T) { + m := newTestModelAuthenticated() + m.home, _ = m.home.Update(home.PersonalizedMsg{Libraries: []abs.Library{{ID: "lib-a", Name: "A", MediaType: "book"}}}) + + var scan *components.PaletteItem + _, nav := m.buildStaticPaletteItems() + for _, item := range nav { + if item.Action == components.ActionScanLibrary { + scan = &item + } + } + if scan == nil || scan.Label != "Scan Library: A" { + t.Fatalf("Scan Library entry = %+v, want the label %q", scan, "Scan Library: A") + } + + m, cmd := m.handlePaletteAction(components.ActionScanLibrary, "", "", "", nil) + if cmd == nil { + t.Fatal("Scan Library returns no command") + } + if m.scanStatus != "Scanning A…" { + t.Errorf("scan status = %q, want %q", m.scanStatus, "Scanning A…") + } + if _, cmd := m.handlePaletteAction(components.ActionScanLibrary, "", "", "", nil); cmd != nil { + t.Error("a second Scan Library returns a command while a scan runs") + } + + res, _ := m.Update(LibraryScannedMsg{LibraryID: "lib-a", Err: errors.New("failed to scan library: boom")}) + m = res.(Model) + if m.scanStatus != "" { + t.Errorf("scan status = %q after the scan failed, want none", m.scanStatus) + } + if !m.err.HasError() { + t.Error("no error banner after the scan failed") + } +} + // TestPaletteSpeedActions verifies that Speed Up of the palette does not lower // a speed above the range of the palette, and Speed Down does not raise a speed // below it: the speed keys and MPRIS can set such a speed. MPRIS gets the new diff --git a/internal/app/render.go b/internal/app/render.go index 04f60ea..df70165 100644 --- a/internal/app/render.go +++ b/internal/app/render.go @@ -53,6 +53,9 @@ func (m Model) View() string { content = m.overlayDetailConfirmModal(content) } + // The palette covers the scan box. + content = m.overlayScanBox(content) + if m.palette.Visible() { content = m.overlayPaletteModal(content) } @@ -378,6 +381,40 @@ func (m Model) overlayChapterModal(content string) string { return strings.Join(baseLines, "\n") } +// overlayScanBox shows the box of a running scan at the right edge, below the +// header. +func (m Model) overlayScanBox(content string) string { + if m.scanStatus == "" { + return content + } + overlay := m.styles.Border.Render(m.scanSpinner.View() + " " + m.scanStatus) + if m.width <= 0 || m.height <= 0 { + return lipgloss.JoinVertical(lipgloss.Left, content, "", overlay) + } + + w := normalizeViewWidth(m.width) + baseLines := normalizeOverlayCanvas(content, w, m.height) + overlayLines := strings.Split(overlay, "\n") + overlayWidth := lipgloss.Width(overlay) + if overlayWidth <= 0 || len(overlayLines) == 0 { + return content + } + + x := max(0, w-overlayWidth) + y := headerHeight + for i, line := range overlayLines { + if y+i >= len(baseLines) { + break + } + lineWidth := lipgloss.Width(line) + left := ansi.Truncate(baseLines[y+i], x, "") + right := ansi.TruncateLeft(baseLines[y+i], x+lineWidth, "") + baseLines[y+i] = left + line + right + } + + return strings.Join(baseLines, "\n") +} + func (m Model) viewChapterOverlay() string { if !m.chapterOverlayVisible { return "" diff --git a/internal/app/render_test.go b/internal/app/render_test.go index dc23da6..a3bf259 100644 --- a/internal/app/render_test.go +++ b/internal/app/render_test.go @@ -10,6 +10,7 @@ import ( "github.com/Thelost77/pine/internal/screens/library" "github.com/Thelost77/pine/internal/screens/metadataedit" tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" ) func TestViewRendersChapterOverlay(t *testing.T) { @@ -360,3 +361,34 @@ func TestViewHidesCaptionWithoutCues(t *testing.T) { t.Fatal("View() showed caption text without cues") } } + +// TestViewShowsScanBox verifies that the view shows the box of a running scan +// at the right edge below the header, and no box when no scan runs. +func TestViewShowsScanBox(t *testing.T) { + m := newTestModelAuthenticated() + m.width = 100 + m.height = 30 + m.propagateSize() + if containsString(m.View(), "Scanning") { + t.Fatal("the view shows a scan box with no scan") + } + + m.scanStatus = "Scanning Audiobooks…" + lines := strings.Split(m.View(), "\n") + row := -1 + for i, line := range lines { + if strings.Contains(line, m.scanStatus) { + row = i + break + } + } + if row < 0 { + t.Fatalf("the view does not show the scan status\n%s", strings.Join(lines, "\n")) + } + if row < headerHeight { + t.Errorf("the scan status is on the line %d, in the header", row) + } + if line := strings.TrimRight(ansi.Strip(lines[row]), " "); !strings.HasSuffix(line, "│") || ansi.StringWidth(line) != normalizeViewWidth(m.width) { + t.Errorf("the scan box is not at the right edge: %q", line) + } +} From c5d73c2c6868ef0ef84c06f52748c8de65a2bb89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wiktor=20Zi=C4=99bka?= Date: Tue, 17 Nov 2026 10:53:09 +0100 Subject: [PATCH 04/14] feat(palette): add a refresh entry The cache keeps the library list for 24 hours and the lists for 15 minutes, so a change on the server that pine does not make showed late. Refresh clears the local cache and loads the screens again. --- AGENTS.md | 2 +- README.md | 1 + internal/app/e2e_test.go | 50 +++++++++++++++++++++++++++++++ internal/app/messages.go | 4 +++ internal/app/model.go | 18 +++++++++++ internal/cache/client.go | 18 +++++------ internal/screens/home/model.go | 7 +++++ internal/ui/components/palette.go | 1 + 8 files changed, 91 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b0668ca..b4e027e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -95,7 +95,7 @@ The Architecture Map below describes pine and the shared packages. | File | Responsibility | |------|---------------| -| `client.go` | Cached wrapper around `abs.Client`: serves cache hits instantly. On a miss, it fetches from the API in the command of the caller and stores the result. Each cached method calls `cached(c, key, ttl, fetch)`, which returns the data of the server. A cache read or write error goes to the log and does not fail the request. A fetch that started before an invalidation does not store its value (`generation`, under `mu`). `invalidate` calls `OnInvalidate` also when the store is nil. | +| `client.go` | Cached wrapper around `abs.Client`: serves cache hits instantly. On a miss, it fetches from the API in the command of the caller and stores the result. Each cached method calls `cached(c, key, ttl, fetch)`, which returns the data of the server. A cache read or write error goes to the log and does not fail the request. A fetch that started before an invalidation does not store its value (`generation`, under `mu`). `Invalidate` calls `OnInvalidate` also when the store is nil. | | `keys.go` | The names of all cache keys. Code outside the package uses `ItemKey`, `PersonalizedKey`, `SeriesContentsKey`, `BookmarksKey`, and `SearchSnapshotKey`, not key strings. A key has no account, so a login (`LoginSuccessMsg`) clears the persistent cache with `ClearAll`. | | `store.go` | SQLite-backed cache persistence and `ClearAll`. Each key in the database has the prefix `keyVersion` (`v1-`). Raise it when the type of a cached value changes. | diff --git a/README.md b/README.md index b995a25..baf2e01 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ The remaining sections describe pine. For spruce, see [docs/spruce/README.md](do - Multiple library support with tab switching - Delete books and podcast episodes from the server - Scan a library on the server from the command palette (admin users only), then reload the lists when the scan ends +- Refresh from the command palette: clear the local cache, then load the screens and the library list again - Keyboard-driven navigation - Configurable colors and keys, with the Everforest dark theme as the default - Session restore — pick up where you left off diff --git a/internal/app/e2e_test.go b/internal/app/e2e_test.go index 8eda4d1..0db88cf 100644 --- a/internal/app/e2e_test.go +++ b/internal/app/e2e_test.go @@ -2732,3 +2732,53 @@ func TestE2E_PaletteScanLibraryReloadsSeriesScreens(t *testing.T) { t.Errorf("the series list does not show %q after the scan", testScannedSeries.Name) } } + +// TestE2E_PaletteRefreshLoadsLibrariesAgain verifies that the palette entry +// Refresh clears the persistent cache, and reads the library list and the home +// shelves from the server again. +func TestE2E_PaletteRefreshLoadsLibrariesAgain(t *testing.T) { + log := &apiLog{} + state := &e2eServerState{bookmarks: make(map[string][]abs.Bookmark)} + srv := newFullMockABSServer(log, state) + defer srv.Close() + libraryLoads := func() int { + n := 0 + for _, r := range log.get() { + if r.Method == http.MethodGet && r.Path == "/api/libraries" { + n++ + } + } + return n + } + + store, err := db.Open(t.TempDir() + "/test.db") + if err != nil { + t.Fatalf("failed to open test db: %v", err) + } + defer func() { _ = store.Close() }() + cacheStore := cache.NewStore(store) + client := cache.NewClient(abs.NewClient(srv.URL, "jwt-token-e2e"), cacheStore) + m := NewWithPlayer(config.Default(), nil, client, cacheStore, &mockPlayer{}) + m = e2eSetSize(m, 120, 40) + m, _ = feedCmdWithin(m, m.home.Init(), slowCmdWait) + libraries := libraryLoads() + shelves := log.count(http.MethodGet, "/api/libraries/lib-001/personalized") + + res, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlP}) + m = res.(Model) + m = e2eTypeString(m, "refresh") + m, _ = e2ePressSpecial(m, tea.KeyEnter) + m, refreshCmd := e2ePressSpecial(m, tea.KeyEnter) + if refreshCmd == nil { + t.Fatal("Refresh returns no command") + } + m, reloadCmd := feedCmdWithin(m, refreshCmd, slowCmdWait) + feedCmdWithin(m, reloadCmd, slowCmdWait) + + if got := libraryLoads(); got <= libraries { + t.Errorf("library list loads = %d, want more than %d after Refresh", got, libraries) + } + if got := log.count(http.MethodGet, "/api/libraries/lib-001/personalized"); got <= shelves { + t.Errorf("home loads = %d, want more than %d after Refresh", got, shelves) + } +} diff --git a/internal/app/messages.go b/internal/app/messages.go index 31c7c87..8b5bdc9 100644 --- a/internal/app/messages.go +++ b/internal/app/messages.go @@ -165,6 +165,10 @@ type LibraryScannedMsg struct { Err error } +// CacheClearedMsg is sent after the palette entry Refresh clears the cache. +// The screens and the library list then load again. +type CacheClearedMsg struct{} + // PrewarmDoneMsg is sent after cache pre-warming completes. No action needed, // just used to keep the command chain alive. type PrewarmDoneMsg struct{} diff --git a/internal/app/model.go b/internal/app/model.go index 2508888..e73511d 100644 --- a/internal/app/model.go +++ b/internal/app/model.go @@ -655,6 +655,14 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } return m, tea.Batch(m.home.ReloadCmd(), m.library.ReloadCmd(), m.prewarmCacheCmd(), m.reloadOpenScreensCmd(msg.LibraryID)) + case CacheClearedMsg: + for _, lib := range m.home.Libraries() { + m.library.InvalidateLibrary(lib.ID) + } + // The warm-up of the search index starts with home.PersonalizedMsg. + cmd := tea.Batch(m.home.RefreshCmd(), m.library.ReloadCmd(), m.reloadOpenScreensCmd("")) + return m, cmd + case spinner.TickMsg: // The ticks end with the scan. if m.scanStatus == "" { @@ -1283,6 +1291,7 @@ func (m Model) buildStaticPaletteItems() (player, nav []components.PaletteItem) components.PaletteItem{Label: "Listening History", Action: components.ActionShowSessions}, components.PaletteItem{Label: "Library", IsHeader: true}, components.PaletteItem{Label: scanLabel, Action: components.ActionScanLibrary}, + components.PaletteItem{Label: "Refresh", Action: components.ActionRefresh}, ) if !m.isPlaying() { @@ -1696,6 +1705,15 @@ func (m Model) handlePaletteAction(action components.PaletteAction, payload, lib // The tick is first, because feedCmdWithin of the tests runs each // command of a batch and gives the command of the last one. return m, tea.Batch(m.scanSpinner.Tick, scanCmd) + case components.ActionRefresh: + if m.client == nil { + return m, nil + } + client := m.client + return m, func() tea.Msg { + client.Invalidate() + return CacheClearedMsg{} + } case components.ActionDeleteItem: if msg, ok := data.(detail.ShowDeleteConfirmMsg); ok && m.screen == ScreenDetail { m.detail, _ = m.detail.Update(msg) diff --git a/internal/cache/client.go b/internal/cache/client.go index 138271b..f1a6876 100644 --- a/internal/cache/client.go +++ b/internal/cache/client.go @@ -26,9 +26,9 @@ type Client struct { store *Store OnInvalidate func() - // generation counts the calls of invalidate. cached does not store the + // generation counts the calls of Invalidate. cached does not store the // value of a fetch that started in an earlier generation, because the - // value can be from before the change. invalidate holds mu while it + // value can be from before the change. Invalidate holds mu while it // clears the store, and cached holds it while it checks the generation // and stores the value, so no old value comes after the clear. mu sync.RWMutex @@ -155,10 +155,10 @@ func (c *Client) GetBookmarks(ctx context.Context, itemID string) ([]abs.Bookmar }) } -// invalidate wipes the persistent cache after a change on the server, and +// Invalidate wipes the persistent cache after a change on the server, and // tells the in-memory caches (the search cache) to drop their snapshots. A // change is rare, so it clears each key. -func (c *Client) invalidate() { +func (c *Client) Invalidate() { if c.store != nil { c.mu.Lock() c.generation++ @@ -178,7 +178,7 @@ func (c *Client) ScanLibrary(ctx context.Context, libraryID string) error { if err := c.Client.ScanLibrary(ctx, libraryID); err != nil { return err } - c.invalidate() + c.Invalidate() return nil } @@ -187,7 +187,7 @@ func (c *Client) DeleteItem(ctx context.Context, itemID string, hardDelete bool) if err := c.Client.DeleteItem(ctx, itemID, hardDelete); err != nil { return err } - c.invalidate() + c.Invalidate() return nil } @@ -196,7 +196,7 @@ func (c *Client) DeleteEpisode(ctx context.Context, podcastID string, episodeID if err := c.Client.DeleteEpisode(ctx, podcastID, episodeID, hardDelete); err != nil { return err } - c.invalidate() + c.Invalidate() return nil } @@ -206,7 +206,7 @@ func (c *Client) UpdateLibraryItemMedia(ctx context.Context, itemID string, req if err != nil { return nil, err } - c.invalidate() + c.Invalidate() return updated, nil } @@ -216,6 +216,6 @@ func (c *Client) UpdatePodcastEpisode(ctx context.Context, itemID, episodeID str if err != nil { return nil, err } - c.invalidate() + c.Invalidate() return updated, nil } diff --git a/internal/screens/home/model.go b/internal/screens/home/model.go index e2d5223..b7094b2 100644 --- a/internal/screens/home/model.go +++ b/internal/screens/home/model.go @@ -543,6 +543,13 @@ func (m *Model) ReloadCmd() tea.Cmd { return tea.Batch(m.fetchPersonalizedCmd(), m.loadingRevealCmd()) } +// RefreshCmd reads the library list from the client again, and loads the +// shelves of the current library. +func (m *Model) RefreshCmd() tea.Cmd { + m.libraries = nil + return m.ReloadCmd() +} + // Libraries returns the available libraries. func (m Model) Libraries() []abs.Library { return m.libraries diff --git a/internal/ui/components/palette.go b/internal/ui/components/palette.go index 5d98c66..ee5f72f 100644 --- a/internal/ui/components/palette.go +++ b/internal/ui/components/palette.go @@ -66,6 +66,7 @@ const ( ActionToggleCaptions ActionShowSessions ActionScanLibrary + ActionRefresh ) type PaletteItem struct { From 7fe2a496b6618c95b8900d3e1cb9d1b0e9d33ce1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wiktor=20Zi=C4=99bka?= Date: Tue, 17 Nov 2026 10:54:27 +0100 Subject: [PATCH 05/14] fix(series): sort the series list by name With no sort, ABS gives the series in no defined order. Each row shows the number of books of the series in place of the word "Series". The cached series lists have no books, so the cache key version is v2. --- AGENTS.md | 2 +- internal/abs/libraries.go | 2 ++ internal/abs/libraries_test.go | 9 ++++++++- internal/abs/types.go | 21 ++++++++++++++------- internal/cache/store.go | 2 +- internal/cache/store_test.go | 8 ++++---- internal/screens/serieslist/model.go | 8 ++++++-- internal/screens/serieslist/model_test.go | 17 +++++++++++++++++ 8 files changed, 53 insertions(+), 16 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b4e027e..8dbf7e9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -97,7 +97,7 @@ The Architecture Map below describes pine and the shared packages. |------|---------------| | `client.go` | Cached wrapper around `abs.Client`: serves cache hits instantly. On a miss, it fetches from the API in the command of the caller and stores the result. Each cached method calls `cached(c, key, ttl, fetch)`, which returns the data of the server. A cache read or write error goes to the log and does not fail the request. A fetch that started before an invalidation does not store its value (`generation`, under `mu`). `Invalidate` calls `OnInvalidate` also when the store is nil. | | `keys.go` | The names of all cache keys. Code outside the package uses `ItemKey`, `PersonalizedKey`, `SeriesContentsKey`, `BookmarksKey`, and `SearchSnapshotKey`, not key strings. A key has no account, so a login (`LoginSuccessMsg`) clears the persistent cache with `ClearAll`. | -| `store.go` | SQLite-backed cache persistence and `ClearAll`. Each key in the database has the prefix `keyVersion` (`v1-`). Raise it when the type of a cached value changes. | +| `store.go` | SQLite-backed cache persistence and `ClearAll`. Each key in the database has the prefix `keyVersion` (`v2-`). Raise it when the type of a cached value changes. | ### MPRIS (internal/mpris/, shared) diff --git a/internal/abs/libraries.go b/internal/abs/libraries.go index ef49ea6..2c4ac06 100644 --- a/internal/abs/libraries.go +++ b/internal/abs/libraries.go @@ -222,6 +222,8 @@ func (c *Client) GetLibrarySeries(ctx context.Context, libraryID string, page, l query := url.Values{} query.Set("page", strconv.Itoa(page)) query.Set("limit", strconv.Itoa(limit)) + // With no sort, ABS gives the series in no defined order. + query.Set("sort", "name") path := fmt.Sprintf("/api/libraries/%s/series?%s", libraryID, query.Encode()) data, err := c.do(ctx, http.MethodGet, path, nil) if err != nil { diff --git a/internal/abs/libraries_test.go b/internal/abs/libraries_test.go index 46fadbd..a750d8f 100644 --- a/internal/abs/libraries_test.go +++ b/internal/abs/libraries_test.go @@ -371,13 +371,17 @@ func TestGetLibrarySeriesHTTP(t *testing.T) { if got := r.URL.Query().Get("limit"); got != "50" { t.Errorf("limit = %q, want 50", got) } + if got := r.URL.Query().Get("sort"); got != "name" { + t.Errorf("sort = %q, want name", got) + } w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{ "results": [ { "id": "series-expanse", "name": "The Expanse", - "libraryId": "lib-books-001" + "libraryId": "lib-books-001", + "books": [{"id": "book-1"}, {"id": "book-2"}] } ], "total": 1, @@ -402,6 +406,9 @@ func TestGetLibrarySeriesHTTP(t *testing.T) { if resp.Results[0].ID != "series-expanse" { t.Fatalf("series ID = %q, want series-expanse", resp.Results[0].ID) } + if got := len(resp.Results[0].Books); got != 2 { + t.Fatalf("books = %d, want 2", got) + } } func TestGetSeriesContentsHTTP(t *testing.T) { diff --git a/internal/abs/types.go b/internal/abs/types.go index 4bc9daf..ae6a126 100644 --- a/internal/abs/types.go +++ b/internal/abs/types.go @@ -225,14 +225,21 @@ type SeriesSequence struct { Sequence string `json:"sequence,omitempty"` } -// Series contains series metadata returned by ABS. +// Series contains series metadata returned by ABS. Only the series list of a +// library has the books. type Series struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description,omitempty"` - LibraryID string `json:"libraryId,omitempty"` - AddedAt int64 `json:"addedAt,omitempty"` - UpdatedAt int64 `json:"updatedAt,omitempty"` + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description,omitempty"` + LibraryID string `json:"libraryId,omitempty"` + AddedAt int64 `json:"addedAt,omitempty"` + UpdatedAt int64 `json:"updatedAt,omitempty"` + Books []SeriesBook `json:"books,omitempty"` +} + +// SeriesBook is a book in the series list of a library. +type SeriesBook struct { + ID string `json:"id"` } // SeriesContents combines series metadata with the library items in that series. diff --git a/internal/cache/store.go b/internal/cache/store.go index e43a3eb..72e4bdb 100644 --- a/internal/cache/store.go +++ b/internal/cache/store.go @@ -14,7 +14,7 @@ import ( // keyVersion is the prefix of each key in the database. Raise it when the // type of a cached value changes: the store then does not read the old rows, // and EvictExpired deletes them when they expire. -const keyVersion = "v1-" +const keyVersion = "v2-" // Store provides generic get/put/delete/evict operations over a SQLite table. type Store struct { diff --git a/internal/cache/store_test.go b/internal/cache/store_test.go index 3414bcd..c5ae926 100644 --- a/internal/cache/store_test.go +++ b/internal/cache/store_test.go @@ -92,14 +92,14 @@ func TestStore_KeysHaveVersion(t *testing.T) { if err := s.Put("k", "value", time.Minute); err != nil { t.Fatalf("Put error: %v", err) } - if n := rows("v1-k"); n != 1 { - t.Fatalf("rows with key v1-k = %d, want 1", n) + if n := rows("v2-k"); n != 1 { + t.Fatalf("rows with key v2-k = %d, want 1", n) } if err := s.Delete("k"); err != nil { t.Fatalf("Delete error: %v", err) } - if n := rows("v1-k"); n != 0 { - t.Fatalf("rows with key v1-k after Delete = %d, want 0", n) + if n := rows("v2-k"); n != 0 { + t.Fatalf("rows with key v2-k after Delete = %d, want 0", n) } // A row of an older pine, with no version and data that does not decode. diff --git a/internal/screens/serieslist/model.go b/internal/screens/serieslist/model.go index ec19f47..fd9ed0d 100644 --- a/internal/screens/serieslist/model.go +++ b/internal/screens/serieslist/model.go @@ -230,10 +230,14 @@ func (i seriesListItem) Title() string { } func (i seriesListItem) Description() string { + books := fmt.Sprintf("%d books", len(i.series.Books)) + if len(i.series.Books) == 1 { + books = "1 book" + } if strings.TrimSpace(i.series.Description) != "" { - return i.series.Description + return books + " · " + i.series.Description } - return "Series" + return books } func (i seriesListItem) FilterValue() string { diff --git a/internal/screens/serieslist/model_test.go b/internal/screens/serieslist/model_test.go index 23dc91f..fe993f4 100644 --- a/internal/screens/serieslist/model_test.go +++ b/internal/screens/serieslist/model_test.go @@ -82,3 +82,20 @@ func TestEnterNavigatesToSeries(t *testing.T) { t.Fatalf("series ID = %q, want series-expanse", navMsg.SeriesID) } } + +// TestViewShowsNumberOfBooks verifies that a row shows the number of books of +// the series, and the description after it. +func TestViewShowsNumberOfBooks(t *testing.T) { + m := newTestModel() + m, _ = m.Update(LoadedMsg{Results: []abs.Series{ + {ID: "series-dune", Name: "Dune", Books: []abs.SeriesBook{{ID: "b1"}, {ID: "b2"}}}, + {ID: "series-expanse", Name: "The Expanse", Description: "Space opera", Books: []abs.SeriesBook{{ID: "b3"}}}, + }, Total: 2, Page: 0}) + + v := m.View() + for _, want := range []string{"2 books", "1 book · Space opera"} { + if !strings.Contains(v, want) { + t.Errorf("expected view to contain %q\n%s", want, v) + } + } +} From 12c7abeee1088735171d64cdc0683657d8cda5fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wiktor=20Zi=C4=99bka?= Date: Tue, 17 Nov 2026 10:58:02 +0100 Subject: [PATCH 06/14] feat(palette): search each library The palette searched only the library of the current screen, so a book of a different library was not found. The matches of the current library come first, and the matches of each other library are below a header with its name. --- AGENTS.md | 2 +- internal/app/e2e_test.go | 59 +++++++++++++++++++++ internal/app/model.go | 111 ++++++++++++++++++++++++--------------- 3 files changed, 130 insertions(+), 42 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 8dbf7e9..9643b20 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -89,7 +89,7 @@ The Architecture Map below describes pine and the shared packages. | `serieslist` | model.go | Paginated series browser (50/page), infinite scroll. | | `series` | model.go | Books within a series, sorted by sequence number. Highlights current item, prefixes finished books with ✓. | | `sessions` | model.go | Listening sessions of a book, a podcast episode, or all items (50 newest). Each row shows the end position, the device, and the time of the last sync. Enter sends `PlayFromMsg`. | -| `search` | cache.go | No longer a standalone screen. Fuzzy-search cache used by the command palette and shared with the library view. Builds full library snapshots (all items fetched, normalized, tokenized) with background pre-warm. `Search` answers only from a ready snapshot in memory or in SQLite. On a miss, it returns no results and builds the snapshot in the background, so the palette does not wait for the network in `Update`. When the palette opens and the snapshot of its library is not ready, `openGlobalPalette` returns `PrebuildCmd`. On `CacheReadyMsg` for that library, `Palette.Refresh` applies the query again and shows the results. An invalidation removes the builds in flight, so a build that started before a change stores nothing. | +| `search` | cache.go | No longer a standalone screen. Fuzzy-search cache used by the command palette and shared with the library view. Builds full library snapshots (all items fetched, normalized, tokenized) with background pre-warm of each library (`prewarmCacheCmd`). `Search` answers only from a ready snapshot in memory or in SQLite. On a miss, it returns no results and builds the snapshot in the background, so the palette does not wait for the network in `Update`. The palette searches the library of the current screen first, then each other library below a header with its name (`contentSearchFunc`). While the snapshot of a library is not ready, the last row is the header `Building index…`. When the palette opens, `openGlobalPalette` returns `PrebuildCmd` for each library with no ready snapshot. On each `CacheReadyMsg`, `Palette.Refresh` applies the query again and shows the results. An invalidation removes the builds in flight, so a build that started before a change stores nothing. | ### Cache (internal/cache/) diff --git a/internal/app/e2e_test.go b/internal/app/e2e_test.go index 0db88cf..46a69c1 100644 --- a/internal/app/e2e_test.go +++ b/internal/app/e2e_test.go @@ -2573,6 +2573,65 @@ func TestE2E_PaletteShowsResultsWhenSnapshotIsBuilt(t *testing.T) { } } +// TestE2E_PaletteSearchesEachLibrary verifies that the palette search shows +// the matches of the current library first, then the matches of each other +// library below a header with its name. +func TestE2E_PaletteSearchesEachLibrary(t *testing.T) { + log := &apiLog{} + state := &e2eServerState{bookmarks: make(map[string][]abs.Bookmark)} + srv := newFullMockABSServer(log, state) + defer srv.Close() + + m := newE2EModelAuthenticated(srv, &mockPlayer{}) + m = e2eSetSize(m, 120, 40) + m, cmd := feedCmd(m, m.home.Init()) + m = feedCmdChain(m, cmd, 5) + for _, lib := range m.home.Libraries() { + if err := m.searchCache.Prepare(context.Background(), lib.ID, lib.MediaType); err != nil { + t.Fatalf("Prepare(%s) error: %v", lib.ID, err) + } + } + + res, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlP}) + m = res.(Model) + m = e2eTypeString(m, "test") + view := m.palette.View() + book := strings.Index(view, "The Great Gatsby") + header := strings.Index(view, "PODCASTS") + podcast := strings.Index(view, "Tech Talk Daily") + if book < 0 || header < 0 || podcast < 0 || book > header || header > podcast { + t.Errorf("the palette does not show the book, then the header of the podcast library, then the podcast\n%s", view) + } +} + +// TestE2E_PaletteSearchShowsIndexBuild verifies that the palette search shows +// a row while the index of a library is not ready. +func TestE2E_PaletteSearchShowsIndexBuild(t *testing.T) { + log := &apiLog{} + state := &e2eServerState{bookmarks: make(map[string][]abs.Bookmark)} + srv := newFullMockABSServer(log, state) + defer srv.Close() + + m := newE2EModelAuthenticated(srv, &mockPlayer{}) + m, cmd := feedCmd(m, m.home.Init()) + m = feedCmdChain(m, cmd, 5) + if err := m.searchCache.Prepare(context.Background(), "lib-001", "book"); err != nil { + t.Fatalf("Prepare() error: %v", err) + } + m.searchCache.Invalidate("lib-pods") + + items := m.contentSearchFunc()("test") + if len(items) == 0 { + t.Fatal("the search found no item") + } + if last := items[len(items)-1]; !last.IsHeader || last.Label != "Building index…" { + t.Errorf("last row = %+v, want the header Building index…", last) + } + if items[0].IsHeader { + t.Errorf("first row = %+v, want an item of the current library", items[0]) + } +} + // TestE2E_MetadataSaveBuildsSearchSnapshot verifies that a metadata save // builds the search snapshot again: the save clears the snapshots. func TestE2E_MetadataSaveBuildsSearchSnapshot(t *testing.T) { diff --git a/internal/app/model.go b/internal/app/model.go index e73511d..7859993 100644 --- a/internal/app/model.go +++ b/internal/app/model.go @@ -826,11 +826,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, cmd case search.CacheReadyMsg: - // The palette shows the results of its query when the snapshot of its - // library is ready. - if libID, _ := m.currentLibraryForSearch(); msg.LibraryID == libID { - m.palette.Refresh() - } + // The palette searches each library, so it shows the results of its + // query again when the snapshot of a library is ready. + m.palette.Refresh() return m.updateScreen(msg) case SleepTimerExpiredMsg: @@ -1177,9 +1175,9 @@ func (m Model) checkUnauthorized(err error) (Model, tea.Cmd, bool) { } // openGlobalPalette opens the palette. The search of the palette answers only -// from a snapshot that is ready, so if the snapshot of the library is not -// ready, it returns a command that builds it. CacheReadyMsg then shows the -// results of the query. +// from a snapshot that is ready, so it returns a command that builds the +// snapshot of each library that has none. CacheReadyMsg then shows the results +// of the query. func (m *Model) openGlobalPalette() tea.Cmd { playerItems, navItems := m.buildStaticPaletteItems() contextItems := m.buildContextPaletteItems() @@ -1191,45 +1189,76 @@ func (m *Model) openGlobalPalette() tea.Cmd { items = append(items, navItems...) m.palette.Open(items, m.contentSearchFunc()) - libID, libMediaType := m.currentLibraryForSearch() - if m.searchCache == nil || libID == "" { + if m.searchCache == nil { return nil } - if _, ok := m.searchCache.TryGetAll(libID, libMediaType); ok { - return nil + var cmds []tea.Cmd + for _, lib := range m.searchLibraries() { + if _, ok := m.searchCache.TryGetAll(lib.ID, lib.MediaType); !ok { + cmds = append(cmds, m.searchCache.PrebuildCmd(lib.ID, lib.MediaType)) + } + } + return tea.Batch(cmds...) +} + +// searchLibraries returns the libraries of the palette search: the library of +// the current screen first, then the other libraries. +func (m Model) searchLibraries() []abs.Library { + libID, libMediaType := m.currentLibraryForSearch() + var libs []abs.Library + if libID != "" { + libs = append(libs, abs.Library{ID: libID, Name: m.libraryName(libID), MediaType: libMediaType}) + } + for _, lib := range m.home.Libraries() { + if lib.ID != libID { + libs = append(libs, lib) + } } - return m.searchCache.PrebuildCmd(libID, libMediaType) + return libs } +// contentSearchFunc searches the library of the current screen first, then +// each other library. The items of a different library are below a header with +// its name. A row at the end shows that an index is not ready. func (m Model) contentSearchFunc() components.SearchFunc { return func(query string) []components.PaletteItem { if m.searchCache == nil { return nil } - libID, libMediaType := m.currentLibraryForSearch() - if libID == "" { - return nil - } + currentID, _ := m.currentLibraryForSearch() ctx := context.Background() - results, err := m.searchCache.Search(ctx, libID, libMediaType, query) - if err != nil || len(results) == 0 { - return nil - } - items := make([]components.PaletteItem, 0, len(results)) - for _, res := range results { - label := res.Media.Metadata.Title - if res.MediaType == "podcast" && res.RecentEpisode != nil { - label = res.RecentEpisode.Title + " — " + res.Media.Metadata.Title + var items []components.PaletteItem + building := false + for _, lib := range m.searchLibraries() { + if _, ok := m.searchCache.TryGetAll(lib.ID, lib.MediaType); !ok { + building = true } - itemCopy := res - items = append(items, components.PaletteItem{ - Label: label, - Action: components.ActionContentNavigate, - PlayAction: components.ActionPlayDirect, - LibraryID: res.LibraryID, - ItemID: res.ID, - Data: itemCopy, - }) + // With no ready index, Search builds it in the background. + results, err := m.searchCache.Search(ctx, lib.ID, lib.MediaType, query) + if err != nil || len(results) == 0 { + continue + } + if lib.ID != currentID { + items = append(items, components.PaletteItem{Label: lib.Name, IsHeader: true}) + } + for _, res := range results { + label := res.Media.Metadata.Title + if res.MediaType == "podcast" && res.RecentEpisode != nil { + label = res.RecentEpisode.Title + " — " + res.Media.Metadata.Title + } + itemCopy := res + items = append(items, components.PaletteItem{ + Label: label, + Action: components.ActionContentNavigate, + PlayAction: components.ActionPlayDirect, + LibraryID: res.LibraryID, + ItemID: res.ID, + Data: itemCopy, + }) + } + } + if building { + items = append(items, components.PaletteItem{Label: "Building index…", IsHeader: true}) } return items } @@ -1723,18 +1752,18 @@ func (m Model) handlePaletteAction(action components.PaletteAction, payload, lib return m, nil } +// prewarmCacheCmd builds the search snapshot of each library, the library of +// the current screen first. func (m Model) prewarmCacheCmd() tea.Cmd { + cache := m.searchCache + libs := m.searchLibraries() return func() tea.Msg { - cache := m.searchCache if cache == nil { return PrewarmDoneMsg{} } - libID := m.home.SelectedLibraryID() - libMediaType := m.home.SelectedLibraryMediaType() - if libID == "" { - return PrewarmDoneMsg{} + for _, lib := range libs { + _ = cache.Prepare(context.Background(), lib.ID, lib.MediaType) } - _ = cache.Prepare(context.Background(), libID, libMediaType) return PrewarmDoneMsg{} } } From d5de770064ad89b3527ed3248645c6e5a3f63825 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wiktor=20Zi=C4=99bka?= Date: Tue, 17 Nov 2026 10:59:15 +0100 Subject: [PATCH 07/14] fix(abs): check the longest item for audio The check read the first 10 items, so a library with ebooks first and audiobooks later was hidden, and an empty book library was hidden too. The longest item has audio if any item has. --- AGENTS.md | 2 +- internal/abs/filter_test.go | 27 +++++++++++++++ internal/abs/libraries.go | 67 ++++++++++++++++++------------------- 3 files changed, 60 insertions(+), 36 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9643b20..82218ac 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -116,7 +116,7 @@ The server is written from the MPRIS 2.2 specification. The Go MPRIS server libr |------|---------------| | `client.go` | HTTP client with 10s timeout, 50MB response limit, auth header, request logging. `NewClient` removes the spaces and the trailing slashes of the server address. `HTTPStatusError` keeps at most 500 bytes of the response body. A log line or a request error shows `SessionTag` (a short hash) in place of a play session ID. | | `types.go` | All ABS data types. Custom UnmarshalJSON for MediaMetadata.Series (handles both object and array). | -| `libraries.go` | GetLibraries, GetPersonalized, GetLibraryItems (paginated), GetLibraryItemsBatch (10 concurrent), GetLibrarySeries, GetSeriesContents, FilterAudioLibraries (sample-based audio detection), ScanLibrary (`POST /api/libraries/{id}/scan`). The server answers the scan request before the scan, so ScanLibrary reads `lastScan` of `GET /api/libraries/{id}` until it changes. The cache client clears the cache after the scan, and `LibraryScannedMsg` loads the home screen and the library screen again. | +| `libraries.go` | GetLibraries, GetPersonalized, GetLibraryItems (paginated), GetLibraryItemsBatch (10 concurrent), GetLibrarySeries, GetSeriesContents, FilterAudioLibraries (keeps a book library when its longest item, `sort=media.duration` and `desc=1`, has audio, or when it has no items), ScanLibrary (`POST /api/libraries/{id}/scan`). The server answers the scan request before the scan, so ScanLibrary reads `lastScan` of `GET /api/libraries/{id}` until it changes. The cache client clears the cache after the scan, and `LibraryScannedMsg` loads the home screen and the library screen again. | | `playback.go` | StartPlaySession, StartEpisodePlaySession, SyncSession, CloseSession, CloseSessionNoSync (sends no position) | | `progress.go`, `me.go` | UpdateProgress, UpdatePosition (no `isFinished` key), GetMediaProgress (ABS gives no bookmarks with the progress), GetMe (user + all media progress). UpdateProgress and UpdatePosition take an episode ID for a podcast episode. | | `sessions.go` | GetListeningSessions (`GET /api/me/listening-sessions`), GetItemListeningSessions (`GET /api/me/item/listening-sessions/{id}[/{episodeId}]`) | diff --git a/internal/abs/filter_test.go b/internal/abs/filter_test.go index 7fbe551..2d4155c 100644 --- a/internal/abs/filter_test.go +++ b/internal/abs/filter_test.go @@ -22,11 +22,22 @@ func TestFilterAudioLibraries_KeepsPodcasts(t *testing.T) { } } +// TestFilterAudioLibraries_KeepsAudiobooks verifies that the check reads one +// item, the longest, and keeps the library when that item has audio. func TestFilterAudioLibraries_KeepsAudiobooks(t *testing.T) { dur := 55908.0 numFiles := 138 numTracks := 138 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/libraries/audio-lib/items" { + t.Errorf("path = %q, want /api/libraries/audio-lib/items", r.URL.Path) + } + query := r.URL.Query() + for key, want := range map[string]string{"limit": "1", "sort": "media.duration", "desc": "1"} { + if got := query.Get(key); got != want { + t.Errorf("%s = %q, want %q", key, got, want) + } + } resp := LibraryItemsResponse{ Results: []LibraryItem{{ ID: "item-1", @@ -124,3 +135,19 @@ func TestFilterAudioLibraries_DetectsAudioByNumAudioFiles(t *testing.T) { t.Fatal("expected library with numAudioFiles>0 to be kept") } } + +// TestFilterAudioLibraries_KeepsEmptyLibrary verifies that a book library with +// no items stays in the list: it can get audiobooks later. +func TestFilterAudioLibraries_KeepsEmptyLibrary(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(LibraryItemsResponse{Results: []LibraryItem{}, Total: 0}) + })) + defer srv.Close() + + c := NewClient(srv.URL, "tok") + libs := []Library{{ID: "new-lib", Name: "New", MediaType: "book"}} + result := c.FilterAudioLibraries(context.Background(), libs) + if len(result) != 1 { + t.Fatalf("expected the empty library to be kept, got %d libraries", len(result)) + } +} diff --git a/internal/abs/libraries.go b/internal/abs/libraries.go index 2c4ac06..67595f5 100644 --- a/internal/abs/libraries.go +++ b/internal/abs/libraries.go @@ -214,7 +214,7 @@ func strPtr(s string) *string { // GetLibraryItems returns a paginated list of items in a library. func (c *Client) GetLibraryItems(ctx context.Context, libraryID string, page, limit int) (*LibraryItemsResponse, error) { - return c.getLibraryItems(ctx, libraryID, page, limit, "") + return c.getLibraryItems(ctx, libraryID, page, limit, nil) } // GetLibrarySeries returns a paginated list of series in a library. @@ -237,12 +237,12 @@ func (c *Client) GetLibrarySeries(ctx context.Context, libraryID string, page, l return &resp, nil } -func (c *Client) getLibraryItems(ctx context.Context, libraryID string, page, limit int, filter string) (*LibraryItemsResponse, error) { +func (c *Client) getLibraryItems(ctx context.Context, libraryID string, page, limit int, extra url.Values) (*LibraryItemsResponse, error) { query := url.Values{} query.Set("page", strconv.Itoa(page)) query.Set("limit", strconv.Itoa(limit)) - if filter != "" { - query.Set("filter", filter) + for key, values := range extra { + query[key] = values } path := fmt.Sprintf("/api/libraries/%s/items?%s", libraryID, query.Encode()) data, err := c.do(ctx, http.MethodGet, path, nil) @@ -346,7 +346,7 @@ func (c *Client) GetSeriesContents(ctx context.Context, libraryID, seriesID stri items := make([]LibraryItem, 0) for page := 0; ; page++ { - resp, err := c.getLibraryItems(ctx, libraryID, page, seriesPageLimit, "series."+encodeLibraryFilterValue(seriesID)) + resp, err := c.getLibraryItems(ctx, libraryID, page, seriesPageLimit, url.Values{"filter": {"series." + encodeLibraryFilterValue(seriesID)}}) if err != nil { return nil, fmt.Errorf("get series items: %w", err) } @@ -452,11 +452,9 @@ func encodeLibraryFilterValue(value string) string { return base64.StdEncoding.EncodeToString([]byte(value)) } -const audioCheckSampleSize = 10 - // FilterAudioLibraries filters out "book" type libraries that contain no audio content -// (ebooks without audio). Podcasts are always kept. For book libraries, it samples -// items and checks if any has Duration > 0 to determine if it's an audio library. +// (ebooks without audio). Podcasts are always kept. A book library is kept if its +// longest item has audio, or if it has no items. // Audio checks for book libraries run in parallel. A failed check goes to the log, // and the library is kept. func (c *Client) FilterAudioLibraries(ctx context.Context, libs []Library) []Library { @@ -514,38 +512,37 @@ func (c *Client) FilterAudioLibraries(ctx context.Context, libs []Library) []Lib return result } -// libraryHasAudio checks if a "book" type library contains any audio items -// by sampling items and checking if any has Duration > 0. -// -// This function assumes libraries contain homogeneous content (all audiobooks or all ebooks). -// If a library contains mixed content, the sampling may not detect audio content if it falls -// outside the sampled range. In practice, ABS typically separates audiobooks and ebooks -// into distinct libraries, so this is not expected to be an issue. +// libraryHasAudio checks if a "book" type library contains audio. It reads the +// item with the longest duration, because an ebook has no duration. A library +// with no items gives true: it can get audiobooks later. func (c *Client) libraryHasAudio(ctx context.Context, libraryID string) (bool, error) { - resp, err := c.GetLibraryItems(ctx, libraryID, 0, audioCheckSampleSize) + resp, err := c.getLibraryItems(ctx, libraryID, 0, 1, url.Values{"sort": {"media.duration"}, "desc": {"1"}}) if err != nil { return false, err } + if len(resp.Results) == 0 { + logger.Debug("library has no items", "libraryID", libraryID) + return true, nil + } - for i, item := range resp.Results { - if item.Media.Duration != nil && *item.Media.Duration > 0 { - logger.Debug("library audio detected", "libraryID", libraryID, "sampleSize", len(resp.Results), "sampleIndex", i, "signal", "media.duration") - return true, nil - } - if item.Media.Metadata.Duration != nil && *item.Media.Metadata.Duration > 0 { - logger.Debug("library audio detected", "libraryID", libraryID, "sampleSize", len(resp.Results), "sampleIndex", i, "signal", "metadata.duration") - return true, nil - } - if item.Media.NumAudioFiles != nil && *item.Media.NumAudioFiles > 0 { - logger.Debug("library audio detected", "libraryID", libraryID, "sampleSize", len(resp.Results), "sampleIndex", i, "signal", "numAudioFiles") - return true, nil - } - if item.Media.NumTracks != nil && *item.Media.NumTracks > 0 { - logger.Debug("library audio detected", "libraryID", libraryID, "sampleSize", len(resp.Results), "sampleIndex", i, "signal", "numTracks") - return true, nil - } + item := resp.Results[0] + if item.Media.Duration != nil && *item.Media.Duration > 0 { + logger.Debug("library audio detected", "libraryID", libraryID, "signal", "media.duration") + return true, nil + } + if item.Media.Metadata.Duration != nil && *item.Media.Metadata.Duration > 0 { + logger.Debug("library audio detected", "libraryID", libraryID, "signal", "metadata.duration") + return true, nil + } + if item.Media.NumAudioFiles != nil && *item.Media.NumAudioFiles > 0 { + logger.Debug("library audio detected", "libraryID", libraryID, "signal", "numAudioFiles") + return true, nil + } + if item.Media.NumTracks != nil && *item.Media.NumTracks > 0 { + logger.Debug("library audio detected", "libraryID", libraryID, "signal", "numTracks") + return true, nil } - logger.Debug("library audio not detected in sample", "libraryID", libraryID, "sampleSize", len(resp.Results)) + logger.Debug("library audio not detected", "libraryID", libraryID) return false, nil } From d689d873b7e173100a3c4e880c46609340cbe4b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wiktor=20Zi=C4=99bka?= Date: Tue, 17 Nov 2026 11:05:31 +0100 Subject: [PATCH 08/14] fix(app): keep the scan box off the error banner - The box covered the right end of a long error. It goes one row down while the banner shows, and it is 3 rows high, not 5. - AGENTS.md describes the reload after a scan, the refresh, the scan box, and the series list as they are. --- AGENTS.md | 9 ++++++--- internal/app/render.go | 7 +++++-- internal/app/render_test.go | 25 +++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 82218ac..5df0c56 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,7 +56,7 @@ The Architecture Map below describes pine and the shared packages. | `model.go` | Root Model struct, Update dispatcher, sleep timer, chapter overlay, command palette, 401 handling | | `playback.go` | Playback lifecycle: handlePlayCmd → handlePlaySessionMsg → handlePlayerReady → handlePositionMsg → handleSyncTick → stopPlayback → Cleanup. Track rollover for multi-track books. Session restore on startup. | | `navigation.go` | Screen routing via back stack, propagateSize (sets all 8 screen models), initScreen, updateScreen dispatch | -| `render.go` | View composition: header + error banner + screen + hints + player footer + chapter overlay modal + confirmation overlay | +| `render.go` | View composition: header + error banner + screen + hints + player footer + chapter overlay modal + confirmation overlay + scan box (`overlayScanBox`, at the right edge below the header and the error banner) | | `bookmarks.go` | Bookmark CRUD, chapter next/prev, seek logic (in-track vs cross-track), fetchBookmarksCmd/fetchEpisodesCmd/fetchBookDetailCmd | | `metadata.go` | Metadata editor save flow: server PATCH, cache eviction, search snapshot prewarm, detail refresh | | `messages.go` | Screen enum, PlaySessionMsg, PlaySessionData, QueueEntry, all root-level message types | @@ -86,7 +86,7 @@ The Architecture Map below describes pine and the shared packages. | `library` | model.go, view.go | Paginated item list (50/page), infinite scroll prefetch at 80%, per-library page cache shared with search cache. Library switching with tab. | | `detail` | model.go, view.go | Viewport-scrollable content: description, series row, episodes list (podcasts), bookmarks list, inline bookmark editing, item deletion. Tab cycles focus between sections. | | `metadataedit` | model.go, view.go | Inline metadata editor for books and podcast episodes. | -| `serieslist` | model.go | Paginated series browser (50/page), infinite scroll. | +| `serieslist` | model.go | Paginated series browser (50/page), infinite scroll. The server sorts the series by name. Each row shows the number of books. | | `series` | model.go | Books within a series, sorted by sequence number. Highlights current item, prefixes finished books with ✓. | | `sessions` | model.go | Listening sessions of a book, a podcast episode, or all items (50 newest). Each row shows the end position, the device, and the time of the last sync. Enter sends `PlayFromMsg`. | | `search` | cache.go | No longer a standalone screen. Fuzzy-search cache used by the command palette and shared with the library view. Builds full library snapshots (all items fetched, normalized, tokenized) with background pre-warm of each library (`prewarmCacheCmd`). `Search` answers only from a ready snapshot in memory or in SQLite. On a miss, it returns no results and builds the snapshot in the background, so the palette does not wait for the network in `Update`. The palette searches the library of the current screen first, then each other library below a header with its name (`contentSearchFunc`). While the snapshot of a library is not ready, the last row is the header `Building index…`. When the palette opens, `openGlobalPalette` returns `PrebuildCmd` for each library with no ready snapshot. On each `CacheReadyMsg`, `Palette.Refresh` applies the query again and shows the results. An invalidation removes the builds in flight, so a build that started before a change stores nothing. | @@ -116,7 +116,7 @@ The server is written from the MPRIS 2.2 specification. The Go MPRIS server libr |------|---------------| | `client.go` | HTTP client with 10s timeout, 50MB response limit, auth header, request logging. `NewClient` removes the spaces and the trailing slashes of the server address. `HTTPStatusError` keeps at most 500 bytes of the response body. A log line or a request error shows `SessionTag` (a short hash) in place of a play session ID. | | `types.go` | All ABS data types. Custom UnmarshalJSON for MediaMetadata.Series (handles both object and array). | -| `libraries.go` | GetLibraries, GetPersonalized, GetLibraryItems (paginated), GetLibraryItemsBatch (10 concurrent), GetLibrarySeries, GetSeriesContents, FilterAudioLibraries (keeps a book library when its longest item, `sort=media.duration` and `desc=1`, has audio, or when it has no items), ScanLibrary (`POST /api/libraries/{id}/scan`). The server answers the scan request before the scan, so ScanLibrary reads `lastScan` of `GET /api/libraries/{id}` until it changes. The cache client clears the cache after the scan, and `LibraryScannedMsg` loads the home screen and the library screen again. | +| `libraries.go` | GetLibraries, GetPersonalized, GetLibraryItems (paginated), GetLibraryItemsBatch (10 concurrent), GetLibrarySeries, GetSeriesContents, FilterAudioLibraries (keeps a book library when its longest item, `sort=media.duration` and `desc=1`, has audio, or when it has no items), ScanLibrary (`POST /api/libraries/{id}/scan`). The server answers the scan request before the scan, so ScanLibrary reads `lastScan` of `GET /api/libraries/{id}` until it changes. The cache client clears the cache after the scan. `LibraryScannedMsg` then loads the home screen and the library screen again, and the open series list, series screen, and detail screen of that library (`reloadOpenScreensCmd`). | | `playback.go` | StartPlaySession, StartEpisodePlaySession, SyncSession, CloseSession, CloseSessionNoSync (sends no position) | | `progress.go`, `me.go` | UpdateProgress, UpdatePosition (no `isFinished` key), GetMediaProgress (ABS gives no bookmarks with the progress), GetMe (user + all media progress). UpdateProgress and UpdatePosition take an episode ID for a podcast episode. | | `sessions.go` | GetListeningSessions (`GET /api/me/listening-sessions`), GetItemListeningSessions (`GET /api/me/item/listening-sessions/{id}[/{episodeId}]`) | @@ -147,6 +147,9 @@ Styles from theme config. Format helpers (timestamps, durations). `RunProgram` r - The `main` of pine and the `main` of spruce run the program with `ui.RunProgram`, which quits the program at SIGHUP, the close of the terminal, so that `Cleanup` runs. Bubble Tea quits the program at SIGTERM. - `ctrl+p` opens the global command palette from each screen, but not while a text input or a dialog gets the keys - The palette shows `Browse Series` in its Navigation group on each screen whose library is a book library, but not on the series list. `buildStaticPaletteItems` adds the entry for the library that `currentLibraryForSearch` returns, which is also the library that the palette searches. Do not add a `Browse Series` entry to the palette actions of a screen. +- The palette entries `Go Library`, `Scan Library`, and `Refresh` use the library of the current screen (`currentLibraryForSearch`). While a scan runs, `scanStatus` holds the text of the scan box, and `Scan Library` does nothing. +- `Refresh` clears the cache in a command (`cache.Client.Invalidate`). `CacheClearedMsg` then loads the library list and the home screen (`home.RefreshCmd`), the library screen, and the open series list, series screen, and detail screen again. +- `serieslist.LoadedMsg` and `series.LoadedMsg` go to their own screen model, also when that screen is behind the active screen, because a scan and `Refresh` load the screens of the back stack again. - A text input or a confirmation dialog of a screen gets each key, except ctrl+c. `capturesKeys` in `playback.go` is true for the login screen, the metadata editor, a list filter, and the bookmark title editor. It is also true for the confirmation dialog of the detail screen. `Update` in `model.go` then gives the key to the screen, before the global keys, the chapter overlay, the error banner, and the playback keys. The help overlay and the command palette get the keys first while they are open. If you add a text input or a dialog to a screen, add it to `capturesKeys`. - Duration from ABS takes precedence over mpv-reported duration (streaming content reports 0) - Each launch makes a new mpv handle, which plays at the speed 1.0. `handlePlayerReady` sets the speed of the model in the new player. diff --git a/internal/app/render.go b/internal/app/render.go index df70165..8a9f9cb 100644 --- a/internal/app/render.go +++ b/internal/app/render.go @@ -382,12 +382,12 @@ func (m Model) overlayChapterModal(content string) string { } // overlayScanBox shows the box of a running scan at the right edge, below the -// header. +// header and the error banner. func (m Model) overlayScanBox(content string) string { if m.scanStatus == "" { return content } - overlay := m.styles.Border.Render(m.scanSpinner.View() + " " + m.scanStatus) + overlay := m.styles.Border.Padding(0, 1).Render(m.scanSpinner.View() + " " + m.scanStatus) if m.width <= 0 || m.height <= 0 { return lipgloss.JoinVertical(lipgloss.Left, content, "", overlay) } @@ -402,6 +402,9 @@ func (m Model) overlayScanBox(content string) string { x := max(0, w-overlayWidth) y := headerHeight + if m.err.HasError() { + y++ + } for i, line := range overlayLines { if y+i >= len(baseLines) { break diff --git a/internal/app/render_test.go b/internal/app/render_test.go index a3bf259..abf7c1c 100644 --- a/internal/app/render_test.go +++ b/internal/app/render_test.go @@ -1,6 +1,7 @@ package app import ( + "errors" "strings" "testing" @@ -392,3 +393,27 @@ func TestViewShowsScanBox(t *testing.T) { t.Errorf("the scan box is not at the right edge: %q", line) } } + +// TestScanBoxDoesNotCoverErrorBanner verifies that the box of a running scan +// is below the error banner, so that the end of a long error stays visible. +func TestScanBoxDoesNotCoverErrorBanner(t *testing.T) { + m := newTestModelAuthenticated() + result, _ := m.Update(tea.WindowSizeMsg{Width: 100, Height: 30}) + m = result.(Model) + m.scanStatus = "Scanning Audiobooks…" + _ = m.err.SetError(errors.New(strings.Repeat("long error ", 20))) + m.propagateSize() + + banner := "" + for _, line := range strings.Split(ansi.Strip(m.View()), "\n") { + if strings.Contains(line, "⚠") { + banner = line + } + } + if banner == "" { + t.Fatal("the view shows no error banner") + } + if strings.ContainsAny(banner, "╭│╰") { + t.Errorf("the scan box covers the error banner: %q", banner) + } +} From ff969032233411f6161bc1c3d72f63b136493ace Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wiktor=20Zi=C4=99bka?= Date: Tue, 17 Nov 2026 11:46:36 +0100 Subject: [PATCH 09/14] fix(app): draw the scan box below the overlays The box covered the top right part of a high chapter overlay. --- internal/app/render.go | 7 ++++--- internal/app/render_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/internal/app/render.go b/internal/app/render.go index 8a9f9cb..6392a88 100644 --- a/internal/app/render.go +++ b/internal/app/render.go @@ -45,6 +45,10 @@ func (m Model) View() string { content = strings.Join(normalizeOverlayCanvas(content, w, m.height), "\n") } + // The chapter overlay, the confirmation dialog, and the palette cover the + // scan box. + content = m.overlayScanBox(content) + if m.chapterOverlayVisible { content = m.overlayChapterModal(content) } @@ -53,9 +57,6 @@ func (m Model) View() string { content = m.overlayDetailConfirmModal(content) } - // The palette covers the scan box. - content = m.overlayScanBox(content) - if m.palette.Visible() { content = m.overlayPaletteModal(content) } diff --git a/internal/app/render_test.go b/internal/app/render_test.go index abf7c1c..addbae1 100644 --- a/internal/app/render_test.go +++ b/internal/app/render_test.go @@ -2,6 +2,7 @@ package app import ( "errors" + "fmt" "strings" "testing" @@ -394,6 +395,31 @@ func TestViewShowsScanBox(t *testing.T) { } } +// TestScanBoxDoesNotCoverChapterOverlay verifies that the chapter overlay +// covers the box of a running scan, and not the reverse. +func TestScanBoxDoesNotCoverChapterOverlay(t *testing.T) { + m := newPlaybackTestModel() + m.width = 100 + m.height = 30 + m.sessionID = "sess-123" + m.player.Title = "Test Book" + m.player.Playing = true + for i := 0; i < 25; i++ { + m.chapters = append(m.chapters, abs.Chapter{ID: i, Start: float64(i * 60), End: float64(i*60 + 60), Title: fmt.Sprintf("Chapter %d", i+1)}) + } + m.chapterOverlayVisible = true + + // The footer covers the last lines of a high overlay, also with no scan. + noScan := ansi.Strip(m.View()) + m.scanStatus = "Scanning Audiobooks…" + view := ansi.Strip(m.View()) + for _, line := range strings.Split(ansi.Strip(m.viewChapterOverlay()), "\n") { + if strings.Contains(noScan, line) && !strings.Contains(view, line) { + t.Fatalf("the scan box covers the line %q of the chapter overlay", line) + } + } +} + // TestScanBoxDoesNotCoverErrorBanner verifies that the box of a running scan // is below the error banner, so that the end of a long error stays visible. func TestScanBoxDoesNotCoverErrorBanner(t *testing.T) { From 84633e13c4e32ca45dc8b4c1f88e2db2e4b5fe5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wiktor=20Zi=C4=99bka?= Date: Tue, 17 Nov 2026 11:47:27 +0100 Subject: [PATCH 10/14] fix(palette): keep the selection on refresh Each library whose index became ready moved the highlight back to the first result. --- internal/ui/components/palette.go | 12 +++++++++ internal/ui/components/palette_test.go | 34 ++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/internal/ui/components/palette.go b/internal/ui/components/palette.go index ee5f72f..2e104f9 100644 --- a/internal/ui/components/palette.go +++ b/internal/ui/components/palette.go @@ -216,11 +216,23 @@ func (p *Palette) Close() { // Refresh applies the query again, for results that the search function did // not have at the last change of the query. With no query, it does nothing. +// The selected item stays selected while it is in the list. func (p *Palette) Refresh() { if !p.visible || strings.TrimSpace(p.input.Value()) == "" { return } + sel, hadSelection := p.list.SelectedItem().(PaletteItem) p.applyFilter(p.input.Value()) + if !hadSelection || sel.IsHeader { + return + } + for i, item := range p.list.Items() { + pi, ok := item.(PaletteItem) + if ok && !pi.IsHeader && pi.Action == sel.Action && pi.ItemID == sel.ItemID && pi.LibraryID == sel.LibraryID && pi.Label == sel.Label { + p.list.Select(i) + return + } + } } func (p *Palette) Visible() bool { diff --git a/internal/ui/components/palette_test.go b/internal/ui/components/palette_test.go index 5da8293..ce7fc16 100644 --- a/internal/ui/components/palette_test.go +++ b/internal/ui/components/palette_test.go @@ -217,6 +217,40 @@ func TestPaletteSearchFunctionCalled(t *testing.T) { } } +// TestPaletteRefreshKeepsTheSelectedItem verifies that Refresh keeps the +// selected item while it is in the list, and selects the first item when it is +// not. Results that come later then do not move the selection. +func TestPaletteRefreshKeepsTheSelectedItem(t *testing.T) { + p := NewPalette() + results := []PaletteItem{ + {Label: "Dune", Action: ActionContentNavigate, ItemID: "dune-1"}, + {Label: "Dune Messiah", Action: ActionContentNavigate, ItemID: "dune-2"}, + } + p.Open(nil, func(string) []PaletteItem { return results }) + p.input.SetValue("dune") + p.applyFilter("dune") + for i, item := range p.list.Items() { + if pi, ok := item.(PaletteItem); ok && pi.ItemID == "dune-2" { + p.list.Select(i) + } + } + + results = append(results, + PaletteItem{Label: "Podcasts", IsHeader: true}, + PaletteItem{Label: "Dune Talk", Action: ActionContentNavigate, ItemID: "pod-1"}, + ) + p.Refresh() + if sel, _ := p.list.SelectedItem().(PaletteItem); sel.ItemID != "dune-2" { + t.Errorf("selected item = %q, want dune-2", sel.ItemID) + } + + results = []PaletteItem{{Label: "Dune Talk", Action: ActionContentNavigate, ItemID: "pod-1"}} + p.Refresh() + if sel, _ := p.list.SelectedItem().(PaletteItem); sel.ItemID != "pod-1" { + t.Errorf("selected item = %q, want pod-1", sel.ItemID) + } +} + func TestPaletteViewWhenNotVisible(t *testing.T) { p := NewPalette() if v := p.View(); v != "" { From e4888cc201fa8bc00664c883ea31713a9bd4768c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wiktor=20Zi=C4=99bka?= Date: Tue, 17 Nov 2026 11:50:08 +0100 Subject: [PATCH 11/14] fix(app): keep detail state on a reload - A reload during a bookmark title edit loaded the bookmarks, and that load closes the editor. The reload skips them during an edit. - A second load of the episodes moved the selection back to the recent episode. It keeps the selected episode. --- internal/app/bookmarks.go | 20 +++++++++------- internal/app/e2e_test.go | 16 +++++++++++++ internal/app/model.go | 6 ++++- internal/screens/detail/model.go | 26 ++++++++++++++------- internal/screens/detail/model_test.go | 33 +++++++++++++++++++++++++++ 5 files changed, 84 insertions(+), 17 deletions(-) diff --git a/internal/app/bookmarks.go b/internal/app/bookmarks.go index 570b9c0..b21106f 100644 --- a/internal/app/bookmarks.go +++ b/internal/app/bookmarks.go @@ -225,14 +225,18 @@ func (m Model) fetchBookDetailCmd(item abs.LibraryItem) tea.Cmd { } func (m Model) detailLoadCmds(item abs.LibraryItem, navCmd tea.Cmd) []tea.Cmd { - cmds := []tea.Cmd{navCmd, m.fetchBookmarksCmd(item.ID)} - if item.MediaType == "podcast" { - return append(cmds, m.fetchEpisodesCmd(item.ID)) - } - if item.MediaType == "book" { - return append(cmds, m.fetchBookDetailCmd(item)) - } - return cmds + return []tea.Cmd{navCmd, m.fetchBookmarksCmd(item.ID), m.detailItemCmd(item)} +} + +// detailItemCmd loads the episodes of a podcast or the full item of a book. +func (m Model) detailItemCmd(item abs.LibraryItem) tea.Cmd { + switch item.MediaType { + case "podcast": + return m.fetchEpisodesCmd(item.ID) + case "book": + return m.fetchBookDetailCmd(item) + } + return nil } // nextChapter returns the start time of the next chapter after current position (book-global). diff --git a/internal/app/e2e_test.go b/internal/app/e2e_test.go index 46a69c1..b60925b 100644 --- a/internal/app/e2e_test.go +++ b/internal/app/e2e_test.go @@ -880,6 +880,22 @@ func e2eSaveBookmarkTitle(m Model, state *e2eServerState) string { return state.getBookmarks("item-001")[0].Title } +// TestE2E_ScanDuringBookmarkTitleEditKeepsTheEdit verifies that the reload of +// the detail screen after a scan does not close the bookmark title editor. +func TestE2E_ScanDuringBookmarkTitleEditKeepsTheEdit(t *testing.T) { + m, _ := e2eDetailWithBookmark(t) + m, _ = e2ePressKey(m, 'e') + if !m.detail.EditingBookmark() { + t.Fatal("the bookmark editor did not open") + } + + res, cmd := m.Update(LibraryScannedMsg{LibraryID: m.detail.Item().LibraryID}) + m, _ = feedCmdWithin(res.(Model), cmd, slowCmdWait) + if !m.detail.EditingBookmark() { + t.Error("the reload after the scan closed the bookmark editor") + } +} + // TestE2E_BookmarkTitleEditGetsEachKey verifies that the bookmark title editor // gets each key during a playback. Outside the editor, these keys have a // global function or a playback function. diff --git a/internal/app/model.go b/internal/app/model.go index 7859993..762feda 100644 --- a/internal/app/model.go +++ b/internal/app/model.go @@ -1805,7 +1805,11 @@ func (m Model) reloadOpenScreensCmd(libraryID string) tea.Cmd { cmds = append(cmds, m.series.Init()) } if item := m.detail.Item(); m.screenOpen(ScreenDetail) && inLibrary(item.LibraryID) { - cmds = append(cmds, m.detailLoadCmds(item, nil)...) + cmds = append(cmds, m.detailItemCmd(item)) + // A load of the bookmarks closes the bookmark title editor. + if !m.detail.EditingBookmark() { + cmds = append(cmds, m.fetchBookmarksCmd(item.ID)) + } } return tea.Batch(cmds...) } diff --git a/internal/screens/detail/model.go b/internal/screens/detail/model.go index 36a9315..5083b96 100644 --- a/internal/screens/detail/model.go +++ b/internal/screens/detail/model.go @@ -232,6 +232,7 @@ type Model struct { bookmarkEditErr string bookmarkInput textinput.Model episodes []abs.PodcastEpisode + episodesLoaded bool selectedEpisode int focusEpisodes bool // finishedEpisodes holds the result of each mark of an episode on this @@ -351,8 +352,15 @@ func (m Model) ItemID() string { return m.item.ID } -// SetEpisodes updates the episode list and refreshes the viewport content. +// SetEpisodes updates the episode list and refreshes the viewport content. The +// first load selects the recent episode. A later load keeps the selected +// episode while it is in the list. func (m *Model) SetEpisodes(episodes []abs.PodcastEpisode) { + selectedID := "" + if m.episodesLoaded && m.selectedEpisode < len(m.episodes) { + selectedID = m.episodes[m.selectedEpisode].ID + } + m.episodesLoaded = true slices.SortFunc(episodes, func(a, b abs.PodcastEpisode) int { aIdx, bIdx := 0, 0 if a.Index != nil { @@ -364,13 +372,15 @@ func (m *Model) SetEpisodes(episodes []abs.PodcastEpisode) { return aIdx - bIdx }) m.episodes = episodes - if m.item.RecentEpisode != nil { - for i, episode := range episodes { - if episode.ID == m.item.RecentEpisode.ID { - m.selectedEpisode = i - break - } - } + selected := -1 + if selectedID != "" { + selected = slices.IndexFunc(episodes, func(e abs.PodcastEpisode) bool { return e.ID == selectedID }) + } + if selected < 0 && m.item.RecentEpisode != nil { + selected = slices.IndexFunc(episodes, func(e abs.PodcastEpisode) bool { return e.ID == m.item.RecentEpisode.ID }) + } + if selected >= 0 { + m.selectedEpisode = selected } if m.selectedEpisode >= len(episodes) { m.selectedEpisode = max(0, len(episodes)-1) diff --git a/internal/screens/detail/model_test.go b/internal/screens/detail/model_test.go index 8e2ef08..e6b1fbc 100644 --- a/internal/screens/detail/model_test.go +++ b/internal/screens/detail/model_test.go @@ -1046,6 +1046,39 @@ func TestMarkFinishedEpisodeKeepsResultPerEpisode(t *testing.T) { } } +// TestSetEpisodes_KeepsSelectedEpisodeOnReload verifies that a second load of +// the episodes keeps the episode that the user selected. The recent episode is +// only the selection of the first load. +func TestSetEpisodes_KeepsSelectedEpisodeOnReload(t *testing.T) { + item := abs.LibraryItem{ + ID: "pod-001", + MediaType: "podcast", + RecentEpisode: &abs.PodcastEpisode{ID: "ep-2"}, + } + episodes := func() []abs.PodcastEpisode { + return []abs.PodcastEpisode{ + {ID: "ep-1", Title: "Episode One"}, + {ID: "ep-2", Title: "Episode Two"}, + {ID: "ep-3", Title: "Episode Three"}, + } + } + + m := New(ui.DefaultStyles(), item) + m.SetEpisodes(episodes()) + m.selectedEpisode = 2 + + m.SetEpisodes(episodes()) + if m.SelectedEpisode() != 2 { + t.Errorf("selected episode after a reload = %d, want 2", m.SelectedEpisode()) + } + + // The selected episode is not in the new list: the recent episode. + m.SetEpisodes(episodes()[:2]) + if m.SelectedEpisode() != 1 { + t.Errorf("selected episode after its removal = %d, want 1", m.SelectedEpisode()) + } +} + func TestSetEpisodes_PreservesRecentEpisodeSelection(t *testing.T) { styles := ui.DefaultStyles() item := abs.LibraryItem{ From da7004dfd7c54a2fc5f73865faba1b320f30df92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wiktor=20Zi=C4=99bka?= Date: Tue, 17 Nov 2026 11:53:06 +0100 Subject: [PATCH 12/14] fix(series): drop the answer of an earlier load A reload after a scan or a refresh did not mark the series list as loading, and a load message had no ID. A load of a next page from before the reload then put an old page after the new first page, and a late answer filled the screen of a different series. - serieslist.LoadedMsg has the library ID and a generation, and series.LoadedMsg has the series ID. A screen drops a mismatch. - The series list reloads with ReloadCmd, which raises the generation and blocks the load of a next page. --- AGENTS.md | 2 +- internal/app/model.go | 7 +-- internal/app/model_test.go | 50 +++++++++++++++--- internal/screens/series/model.go | 17 +++--- internal/screens/series/model_test.go | 22 +++++--- internal/screens/serieslist/model.go | 44 +++++++++++----- internal/screens/serieslist/model_test.go | 63 ++++++++++++++++++++--- 7 files changed, 162 insertions(+), 43 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5df0c56..1c24b2b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -149,7 +149,7 @@ Styles from theme config. Format helpers (timestamps, durations). `RunProgram` r - The palette shows `Browse Series` in its Navigation group on each screen whose library is a book library, but not on the series list. `buildStaticPaletteItems` adds the entry for the library that `currentLibraryForSearch` returns, which is also the library that the palette searches. Do not add a `Browse Series` entry to the palette actions of a screen. - The palette entries `Go Library`, `Scan Library`, and `Refresh` use the library of the current screen (`currentLibraryForSearch`). While a scan runs, `scanStatus` holds the text of the scan box, and `Scan Library` does nothing. - `Refresh` clears the cache in a command (`cache.Client.Invalidate`). `CacheClearedMsg` then loads the library list and the home screen (`home.RefreshCmd`), the library screen, and the open series list, series screen, and detail screen again. -- `serieslist.LoadedMsg` and `series.LoadedMsg` go to their own screen model, also when that screen is behind the active screen, because a scan and `Refresh` load the screens of the back stack again. +- `serieslist.LoadedMsg` and `series.LoadedMsg` go to their own screen model, also when that screen is behind the active screen, because a scan and `Refresh` load the screens of the back stack again. `serieslist.LoadedMsg` has the library ID and the generation of its load, and `series.LoadedMsg` has the series ID. A screen drops a message that does not match. A reload of the series list uses `ReloadCmd`, which raises the generation and blocks the load of a next page. - A text input or a confirmation dialog of a screen gets each key, except ctrl+c. `capturesKeys` in `playback.go` is true for the login screen, the metadata editor, a list filter, and the bookmark title editor. It is also true for the confirmation dialog of the detail screen. `Update` in `model.go` then gives the key to the screen, before the global keys, the chapter overlay, the error banner, and the playback keys. The help overlay and the command palette get the keys first while they are open. If you add a text input or a dialog to a screen, add it to `capturesKeys`. - Duration from ABS takes precedence over mpv-reported duration (streaming content reports 0) - Each launch makes a new mpv handle, which plays at the speed 1.0. `handlePlayerReady` sets the speed of the model in the new player. diff --git a/internal/app/model.go b/internal/app/model.go index 762feda..6a771f5 100644 --- a/internal/app/model.go +++ b/internal/app/model.go @@ -653,7 +653,8 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if m.searchCache != nil { m.searchCache.Invalidate(msg.LibraryID) } - return m, tea.Batch(m.home.ReloadCmd(), m.library.ReloadCmd(), m.prewarmCacheCmd(), m.reloadOpenScreensCmd(msg.LibraryID)) + cmd := tea.Batch(m.home.ReloadCmd(), m.library.ReloadCmd(), m.prewarmCacheCmd(), m.reloadOpenScreensCmd(msg.LibraryID)) + return m, cmd case CacheClearedMsg: for _, lib := range m.home.Libraries() { @@ -1793,13 +1794,13 @@ func (m Model) scanLibraryCmd() tea.Cmd { // reloadOpenScreensCmd loads the open series list, series screen, and detail // screen of a library again. With an empty libraryID, it loads them for each // library. -func (m Model) reloadOpenScreensCmd(libraryID string) tea.Cmd { +func (m *Model) reloadOpenScreensCmd(libraryID string) tea.Cmd { inLibrary := func(id string) bool { return libraryID == "" || id == libraryID } var cmds []tea.Cmd if m.screenOpen(ScreenSeriesList) && inLibrary(m.seriesList.SelectedLibraryID()) { - cmds = append(cmds, m.seriesList.Init()) + cmds = append(cmds, m.seriesList.ReloadCmd()) } if m.screenOpen(ScreenSeries) && inLibrary(m.series.LibraryID()) { cmds = append(cmds, m.series.Init()) diff --git a/internal/app/model_test.go b/internal/app/model_test.go index ed66479..92b34da 100644 --- a/internal/app/model_test.go +++ b/internal/app/model_test.go @@ -2622,6 +2622,35 @@ func TestPaletteGoLibraryOpensLibraryOfScreen(t *testing.T) { }) } +// TestScanReloadBlocksNextPageOfSeriesList verifies that the reload after a +// scan marks the open series list as loading, so that the list starts no load +// of a next page that can mix an old page into the new list. +func TestScanReloadBlocksNextPageOfSeriesList(t *testing.T) { + m := newTestModelAuthenticated() + m.seriesList = serieslist.New(m.styles, m.client, "lib-a", "A") + m.seriesList, _ = m.seriesList.Update(serieslist.LoadedMsg{LibraryID: "lib-a", Results: []abs.Series{{ID: "ser-1", Name: "Dune"}}, Total: 120}) + m.backStack = []Screen{ScreenHome} + m.screen = ScreenSeriesList + if m.seriesList.Loading() { + t.Fatal("the series list loads before the scan") + } + + res, _ := m.Update(LibraryScannedMsg{LibraryID: "lib-a"}) + m = res.(Model) + if !m.seriesList.Loading() { + t.Error("the series list does not load after the scan") + } + + // The answer of a load from before the scan does not change the list. + res, _ = m.Update(serieslist.LoadedMsg{LibraryID: "lib-a", Results: []abs.Series{{ID: "ser-9", Name: "Old Page"}}, Total: 120, Page: 1}) + m = res.(Model) + m.width, m.height = 100, 30 + m.propagateSize() + if containsString(m.seriesList.View(), "Old Page") { + t.Error("the series list shows a page of a load from before the scan") + } +} + // TestSeriesLoadedMsgReachesScreenBehindActiveScreen verifies that a load of // the series list or of a series reaches its screen model also when a // different screen is active: a scan loads the screens in the back stack again. @@ -2633,10 +2662,13 @@ func TestSeriesLoadedMsgReachesScreenBehindActiveScreen(t *testing.T) { m.backStack = []Screen{ScreenHome, ScreenSeriesList} m.screen = ScreenSeries - res, _ := m.Update(serieslist.LoadedMsg{Results: []abs.Series{{ID: "ser-1", Name: "Dune"}}, Total: 1}) + m.width, m.height = 100, 30 + m.propagateSize() + + res, _ := m.Update(serieslist.LoadedMsg{LibraryID: "lib-a", Results: []abs.Series{{ID: "ser-1", Name: "Dune"}}, Total: 1}) m = res.(Model) - if m.seriesList.Loading() { - t.Error("the series list did not get the loaded page") + if m.seriesList.Loading() || !containsString(m.seriesList.View(), "Dune") { + t.Errorf("the series list did not get the loaded page\n%s", m.seriesList.View()) } }) @@ -2647,10 +2679,16 @@ func TestSeriesLoadedMsgReachesScreenBehindActiveScreen(t *testing.T) { m.backStack = []Screen{ScreenHome, ScreenSeries} m.screen = ScreenDetail - res, _ := m.Update(series.LoadedMsg{Contents: abs.SeriesContents{Series: abs.Series{ID: "ser-1", Name: "Dune"}}}) + m.width, m.height = 100, 30 + m.propagateSize() + + res, _ := m.Update(series.LoadedMsg{SeriesID: "ser-1", Contents: abs.SeriesContents{ + Series: abs.Series{ID: "ser-1", Name: "Dune"}, + Items: []abs.LibraryItem{{ID: "b-1", Media: abs.Media{Metadata: abs.MediaMetadata{Title: "Dune Messiah"}}}}, + }}) m = res.(Model) - if m.series.Loading() { - t.Error("the series screen did not get the loaded series") + if m.series.Loading() || !containsString(m.series.View(), "Dune Messiah") { + t.Errorf("the series screen did not get the loaded series\n%s", m.series.View()) } }) } diff --git a/internal/screens/series/model.go b/internal/screens/series/model.go index 3f047a6..fa306ac 100644 --- a/internal/screens/series/model.go +++ b/internal/screens/series/model.go @@ -14,10 +14,12 @@ import ( tea "github.com/charmbracelet/bubbletea" ) -// LoadedMsg carries a loaded series payload. +// LoadedMsg carries a loaded series payload. SeriesID names the series of the +// load, so that the screen drops the answer for a different series. type LoadedMsg struct { Contents abs.SeriesContents Err error + SeriesID string } // NavigateDetailMsg requests opening a book from the series list. @@ -107,6 +109,9 @@ func (m Model) Init() tea.Cmd { func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { switch msg := msg.(type) { case LoadedMsg: + if msg.SeriesID != m.seriesID { + return m, nil + } m.loading = false m.err = msg.Err if msg.Err != nil { @@ -191,23 +196,23 @@ func (m Model) SelectedItemID() string { } func (m Model) fetchSeriesCmd() tea.Cmd { + seriesID := m.seriesID if m.client == nil { return func() tea.Msg { - return LoadedMsg{Err: fmt.Errorf("not authenticated")} + return LoadedMsg{SeriesID: seriesID, Err: fmt.Errorf("not authenticated")} } } client := m.client libraryID := m.libraryID - seriesID := m.seriesID return func() tea.Msg { contents, err := client.GetSeriesContents(context.Background(), libraryID, seriesID) if err != nil { - return LoadedMsg{Err: fmt.Errorf("fetch series: %w", err)} + return LoadedMsg{SeriesID: seriesID, Err: fmt.Errorf("fetch series: %w", err)} } if contents == nil { - return LoadedMsg{Err: fmt.Errorf("series not found")} + return LoadedMsg{SeriesID: seriesID, Err: fmt.Errorf("series not found")} } - return LoadedMsg{Contents: *contents} + return LoadedMsg{SeriesID: seriesID, Contents: *contents} } } diff --git a/internal/screens/series/model_test.go b/internal/screens/series/model_test.go index b571ba5..6229490 100644 --- a/internal/screens/series/model_test.go +++ b/internal/screens/series/model_test.go @@ -99,7 +99,7 @@ func TestNewStartsWithSkeletonRows(t *testing.T) { func TestSeriesLoadedMsgPopulatesListAndSelectsCurrentItem(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Contents: sampleSeriesContents()}) + m, _ = m.Update(LoadedMsg{SeriesID: "series-expanse", Contents: sampleSeriesContents()}) if m.Loading() { t.Fatal("expected loading to be false after series load") @@ -111,7 +111,7 @@ func TestSeriesLoadedMsgPopulatesListAndSelectsCurrentItem(t *testing.T) { func TestView_ShowsSeriesNameAndBooks(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Contents: sampleSeriesContents()}) + m, _ = m.Update(LoadedMsg{SeriesID: "series-expanse", Contents: sampleSeriesContents()}) v := m.View() for _, want := range []string{"The Expanse", "Leviathan Wakes", "Caliban's War"} { @@ -126,7 +126,7 @@ func TestViewShowsFinishedMarkerOnlyForFinishedBooks(t *testing.T) { contents.Items[0].UserMediaProgress = &abs.UserMediaProgress{Progress: 1.0, IsFinished: true} m := newTestModel() - m, _ = m.Update(LoadedMsg{Contents: contents}) + m, _ = m.Update(LoadedMsg{SeriesID: "series-expanse", Contents: contents}) v := m.View() if !strings.Contains(v, "✓ Leviathan Wakes") { @@ -155,7 +155,7 @@ func TestLoadingSkeletonsDoNotRenderSelectedHighlight(t *testing.T) { func TestEnterKey_NavigatesToSelectedBook(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Contents: sampleSeriesContents()}) + m, _ = m.Update(LoadedMsg{SeriesID: "series-expanse", Contents: sampleSeriesContents()}) _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) if cmd == nil { @@ -173,7 +173,7 @@ func TestEnterKey_NavigatesToSelectedBook(t *testing.T) { func TestHLPageAcrossSeries(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Contents: sampleLongSeriesContents(30)}) + m, _ = m.Update(LoadedMsg{SeriesID: "series-expanse", Contents: sampleLongSeriesContents(30)}) before := m.list.GlobalIndex() m, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'L'}}) @@ -190,7 +190,7 @@ func TestHLPageAcrossSeries(t *testing.T) { func TestHLFallsBackToExtremes(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Contents: sampleLongSeriesContents(30)}) + m, _ = m.Update(LoadedMsg{SeriesID: "series-expanse", Contents: sampleLongSeriesContents(30)}) for i := 0; i < 5; i++ { m, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'L'}}) @@ -206,3 +206,13 @@ func TestHLFallsBackToExtremes(t *testing.T) { t.Fatalf("H at start should jump to first row: got %d want 0", got) } } + +// TestLoadedMsgOfOtherSeriesIsDropped verifies that the screen drops the +// answer of a load for a different series. +func TestLoadedMsgOfOtherSeriesIsDropped(t *testing.T) { + m := newTestModel() + m, _ = m.Update(LoadedMsg{SeriesID: "series-dune", Contents: sampleSeriesContents()}) + if len(m.series.Items) != 0 || !m.Loading() { + t.Errorf("the screen shows %d books of a different series", len(m.series.Items)) + } +} diff --git a/internal/screens/serieslist/model.go b/internal/screens/serieslist/model.go index fd9ed0d..80cfcf0 100644 --- a/internal/screens/serieslist/model.go +++ b/internal/screens/serieslist/model.go @@ -19,12 +19,16 @@ const pageLimit = 50 // thresholdPercent is the fraction of loaded items at which a prefetch fires. const thresholdPercent = 0.8 -// LoadedMsg carries a loaded page of series. +// LoadedMsg carries a loaded page of series. LibraryID and Generation name the +// load, so that the screen drops the answer of an earlier load and the answer +// for a different library. type LoadedMsg struct { - Results []abs.Series - Total int - Page int - Err error + Results []abs.Series + Total int + Page int + Err error + LibraryID string + Generation int } // NavigateSeriesMsg requests opening a specific series detail view. @@ -70,6 +74,7 @@ type Model struct { page int total int loading bool + generation int err error } @@ -109,10 +114,21 @@ func (m Model) Init() tea.Cmd { return m.fetchSeriesCmd(0) } +// ReloadCmd loads the first page again. The rows stay until that page comes. +// The screen drops the answer of each load that started before the reload, +// and it starts no load of a next page during the reload. +func (m *Model) ReloadCmd() tea.Cmd { + m.generation++ + return m.fetchSeriesCmd(0) +} + // Update handles messages for the series browser. func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { switch msg := msg.(type) { case LoadedMsg: + if msg.LibraryID != m.libraryID || msg.Generation != m.generation { + return m, nil + } m.loading = false if msg.Err != nil { m.err = msg.Err @@ -193,23 +209,23 @@ func (m *Model) maybePrefetch() tea.Cmd { } func (m *Model) fetchSeriesCmd(page int) tea.Cmd { + msg := LoadedMsg{LibraryID: m.libraryID, Generation: m.generation} if m.client == nil { - return func() tea.Msg { - return LoadedMsg{Err: fmt.Errorf("not authenticated")} - } + msg.Err = fmt.Errorf("not authenticated") + return func() tea.Msg { return msg } } m.loading = true client := m.client - libraryID := m.libraryID return func() tea.Msg { - resp, err := client.GetLibrarySeries(context.Background(), libraryID, page, pageLimit) + resp, err := client.GetLibrarySeries(context.Background(), msg.LibraryID, page, pageLimit) if err != nil { - return LoadedMsg{Err: fmt.Errorf("fetch series: %w", err)} + msg.Err = fmt.Errorf("fetch series: %w", err) + return msg } - if resp == nil { - return LoadedMsg{} + if resp != nil { + msg.Results, msg.Total, msg.Page = resp.Results, resp.Total, resp.Page } - return LoadedMsg{Results: resp.Results, Total: resp.Total, Page: resp.Page} + return msg } } diff --git a/internal/screens/serieslist/model_test.go b/internal/screens/serieslist/model_test.go index fe993f4..31e92cd 100644 --- a/internal/screens/serieslist/model_test.go +++ b/internal/screens/serieslist/model_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/Thelost77/pine/internal/abs" + "github.com/Thelost77/pine/internal/cache" "github.com/Thelost77/pine/internal/ui" tea "github.com/charmbracelet/bubbletea" ) @@ -26,7 +27,7 @@ func sampleSeries() []abs.Series { func TestLoadedMsgPopulatesList(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Results: sampleSeries(), Total: 2, Page: 0}) + m, _ = m.Update(LoadedMsg{LibraryID: "lib-books-001", Results: sampleSeries(), Total: 2, Page: 0}) if m.Loading() { t.Fatal("expected loading to be false after load") @@ -38,9 +39,9 @@ func TestLoadedMsgPopulatesList(t *testing.T) { func TestLoadedMsgClearsEarlierError(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Results: sampleSeries(), Total: 4, Page: 0}) - m, _ = m.Update(LoadedMsg{Err: errors.New("network error")}) - m, _ = m.Update(LoadedMsg{Results: []abs.Series{{ID: "series-foundation", Name: "Foundation"}}, Total: 4, Page: 1}) + m, _ = m.Update(LoadedMsg{LibraryID: "lib-books-001", Results: sampleSeries(), Total: 4, Page: 0}) + m, _ = m.Update(LoadedMsg{LibraryID: "lib-books-001", Err: errors.New("network error")}) + m, _ = m.Update(LoadedMsg{LibraryID: "lib-books-001", Results: []abs.Series{{ID: "series-foundation", Name: "Foundation"}}, Total: 4, Page: 1}) if m.err != nil { t.Fatalf("err = %v after a successful load, want nil", m.err) @@ -52,7 +53,7 @@ func TestLoadedMsgClearsEarlierError(t *testing.T) { func TestViewShowsSeriesNames(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Results: sampleSeries(), Total: 2, Page: 0}) + m, _ = m.Update(LoadedMsg{LibraryID: "lib-books-001", Results: sampleSeries(), Total: 2, Page: 0}) v := m.View() for _, want := range []string{"Series", "The Expanse", "Dune"} { @@ -64,7 +65,7 @@ func TestViewShowsSeriesNames(t *testing.T) { func TestEnterNavigatesToSeries(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Results: sampleSeries(), Total: 2, Page: 0}) + m, _ = m.Update(LoadedMsg{LibraryID: "lib-books-001", Results: sampleSeries(), Total: 2, Page: 0}) _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) if cmd == nil { @@ -87,7 +88,7 @@ func TestEnterNavigatesToSeries(t *testing.T) { // the series, and the description after it. func TestViewShowsNumberOfBooks(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Results: []abs.Series{ + m, _ = m.Update(LoadedMsg{LibraryID: "lib-books-001", Results: []abs.Series{ {ID: "series-dune", Name: "Dune", Books: []abs.SeriesBook{{ID: "b1"}, {ID: "b2"}}}, {ID: "series-expanse", Name: "The Expanse", Description: "Space opera", Books: []abs.SeriesBook{{ID: "b3"}}}, }, Total: 2, Page: 0}) @@ -99,3 +100,51 @@ func TestViewShowsNumberOfBooks(t *testing.T) { } } } + +func seriesNames(m Model) string { + names := make([]string, len(m.series)) + for i, s := range m.series { + names[i] = s.Name + } + return strings.Join(names, ",") +} + +// TestReloadDropsAnswerOfEarlierLoad verifies that a reload replaces the list +// with the new first page. The answer of a load of a next page that started +// before the reload must not add an old page to the new list. +func TestReloadDropsAnswerOfEarlierLoad(t *testing.T) { + const lib = "lib-books-001" + m := New(ui.DefaultStyles(), cache.NewClient(abs.NewClient("http://test", "tok"), nil), lib, "Books") + m.SetSize(80, 24) + page := func(names ...string) []abs.Series { + series := make([]abs.Series, len(names)) + for i, name := range names { + series[i] = abs.Series{ID: "series-" + name, Name: name} + } + return series + } + m, _ = m.Update(LoadedMsg{LibraryID: lib, Results: page("A", "B"), Total: 6, Page: 0}) + m, _ = m.Update(LoadedMsg{LibraryID: lib, Results: page("C", "D"), Total: 6, Page: 1}) + late := LoadedMsg{LibraryID: lib, Results: page("E", "F"), Total: 6, Page: 2} + + _ = m.ReloadCmd() + if !m.Loading() { + t.Error("the list does not load during a reload, so it can start a load of a next page") + } + m, _ = m.Update(LoadedMsg{LibraryID: lib, Generation: m.generation, Results: page("A", "B2"), Total: 6, Page: 0}) + m, _ = m.Update(late) + + if got := seriesNames(m); got != "A,B2" { + t.Errorf("series = %s, want A,B2", got) + } +} + +// TestLoadedMsgOfOtherLibraryIsDropped verifies that the list drops the answer +// of a load for a different library. +func TestLoadedMsgOfOtherLibraryIsDropped(t *testing.T) { + m := newTestModel() + m, _ = m.Update(LoadedMsg{LibraryID: "lib-other", Results: sampleSeries(), Total: 2, Page: 0}) + if got := seriesNames(m); got != "" { + t.Errorf("series = %s, want none", got) + } +} From f0f118c42e533cb6eb9fdb7b7e581ef3c82981ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wiktor=20Zi=C4=99bka?= Date: Tue, 17 Nov 2026 11:56:11 +0100 Subject: [PATCH 13/14] fix(home): drop the answer of an earlier load Refresh set the library list to nil, which turned off the check for an old answer. An old answer for one library then showed below the name of a different library, and it replaced the new shelves. - A PersonalizedMsg has the generation of its load, and the screen drops an earlier one. - The library list stays during a refresh. The answer selects the same library by its ID, not by its position. --- AGENTS.md | 3 +- internal/screens/home/model.go | 86 +++++++++++++++++---------- internal/screens/home/model_test.go | 92 ++++++++++++++++++++++++++++- 3 files changed, 149 insertions(+), 32 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1c24b2b..ffa0528 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -148,7 +148,8 @@ Styles from theme config. Format helpers (timestamps, durations). `RunProgram` r - `ctrl+p` opens the global command palette from each screen, but not while a text input or a dialog gets the keys - The palette shows `Browse Series` in its Navigation group on each screen whose library is a book library, but not on the series list. `buildStaticPaletteItems` adds the entry for the library that `currentLibraryForSearch` returns, which is also the library that the palette searches. Do not add a `Browse Series` entry to the palette actions of a screen. - The palette entries `Go Library`, `Scan Library`, and `Refresh` use the library of the current screen (`currentLibraryForSearch`). While a scan runs, `scanStatus` holds the text of the scan box, and `Scan Library` does nothing. -- `Refresh` clears the cache in a command (`cache.Client.Invalidate`). `CacheClearedMsg` then loads the library list and the home screen (`home.RefreshCmd`), the library screen, and the open series list, series screen, and detail screen again. +- `Refresh` clears the cache in a command (`cache.Client.Invalidate`). `CacheClearedMsg` then loads the library list and the home screen (`home.RefreshCmd`), the library screen, and the open series list, series screen, and detail screen again. The library list stays on the home model until the answer comes, and the answer selects the same library by its ID. +- A `home.PersonalizedMsg` has the generation of its load (`loadingGen`). The home screen drops the answer of an earlier load. - `serieslist.LoadedMsg` and `series.LoadedMsg` go to their own screen model, also when that screen is behind the active screen, because a scan and `Refresh` load the screens of the back stack again. `serieslist.LoadedMsg` has the library ID and the generation of its load, and `series.LoadedMsg` has the series ID. A screen drops a message that does not match. A reload of the series list uses `ReloadCmd`, which raises the generation and blocks the load of a next page. - A text input or a confirmation dialog of a screen gets each key, except ctrl+c. `capturesKeys` in `playback.go` is true for the login screen, the metadata editor, a list filter, and the bookmark title editor. It is also true for the confirmation dialog of the detail screen. `Update` in `model.go` then gives the key to the screen, before the global keys, the chapter overlay, the error banner, and the playback keys. The help overlay and the command palette get the keys first while they are open. If you add a text input or a dialog to a screen, add it to `capturesKeys`. - Duration from ABS takes precedence over mpv-reported duration (streaming content reports 0) diff --git a/internal/screens/home/model.go b/internal/screens/home/model.go index b7094b2..e491527 100644 --- a/internal/screens/home/model.go +++ b/internal/screens/home/model.go @@ -3,6 +3,7 @@ package home import ( "context" "fmt" + "slices" "strings" "time" @@ -27,6 +28,13 @@ type PersonalizedMsg struct { Libraries []abs.Library LibraryID string Err error + + // generation is the loadingGen of the load. The screen drops the answer + // of an earlier load. + generation uint64 + // refreshed is true when the load read the library list again. Libraries + // is then the new list, and LibraryID is the library to select in it. + refreshed bool } type rowKind int @@ -197,15 +205,20 @@ func (m *Model) SetSize(width, height int) { // Init returns the initial command that fetches personalized data. func (m Model) Init() tea.Cmd { - return tea.Batch(m.fetchPersonalizedCmd(), m.loadingRevealCmd()) + return tea.Batch(m.fetchPersonalizedCmd(false), m.loadingRevealCmd()) } // Update handles messages for the home screen. func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { switch msg := msg.(type) { case PersonalizedMsg: + if msg.generation != m.loadingGen { + logger.Debug("STALE: discarding personalized msg of an earlier load", "msgLib", msg.LibraryID) + return m, nil + } currentLib := m.SelectedLibraryID() - if msg.LibraryID != "" && currentLib != "" && msg.LibraryID != currentLib { + // The answer of a refresh selects its library in the new library list. + if !msg.refreshed && msg.LibraryID != "" && currentLib != "" && msg.LibraryID != currentLib { logger.Debug("STALE: discarding personalized msg", "msgLib", msg.LibraryID, "currentLib", currentLib) return m, nil } @@ -219,7 +232,10 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { return m, nil } m.err = nil - if len(msg.Libraries) > 0 { + if msg.refreshed { + m.libraries = msg.Libraries + m.selectedLibrary = max(0, slices.IndexFunc(m.libraries, func(lib abs.Library) bool { return lib.ID == msg.LibraryID })) + } else if len(msg.Libraries) > 0 { logger.Debug("personalized: updating libraries", "count", len(msg.Libraries)) m.libraries = msg.Libraries } @@ -297,7 +313,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { // Keep current content visible briefly; show skeletons only if // the fetch outlives the reveal delay. m.refreshListRows() - return m, tea.Batch(m.fetchPersonalizedCmd(), m.loadingRevealCmd()) + return m, tea.Batch(m.fetchPersonalizedCmd(false), m.loadingRevealCmd()) } return m, nil case key.Matches(msg, m.keys.PageDown): @@ -324,15 +340,20 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { } // fetchPersonalizedCmd creates a command that fetches personalized shelves. -func (m *Model) fetchPersonalizedCmd() tea.Cmd { +// With refreshLibraries, the command also reads the library list again, and +// it loads the shelves of the selected library by its ID. +func (m *Model) fetchPersonalizedCmd(refreshLibraries bool) tea.Cmd { + msg := PersonalizedMsg{generation: m.loadingGen, refreshed: refreshLibraries} if m.client == nil { - return func() tea.Msg { - return PersonalizedMsg{Err: fmt.Errorf("not authenticated")} - } + msg.Err = fmt.Errorf("not authenticated") + return func() tea.Msg { return msg } } client := m.client selectedIdx := m.selectedLibrary existingLibs := m.libraries + if refreshLibraries { + existingLibs = nil + } currentLibID := m.SelectedLibraryID() return func() tea.Msg { libs := existingLibs @@ -341,47 +362,48 @@ func (m *Model) fetchPersonalizedCmd() tea.Cmd { var err error libs, err = client.GetLibraries(context.Background()) if err != nil { - return PersonalizedMsg{Err: fmt.Errorf("fetch libraries: %w", err)} + msg.Err = fmt.Errorf("fetch libraries: %w", err) + return msg } libs = client.FilterAudioLibraries(context.Background(), libs) } + msg.Libraries = libs if len(libs) == 0 { - return PersonalizedMsg{Items: nil, Libraries: libs, LibraryID: currentLibID} + msg.LibraryID = currentLibID + return msg } idx := selectedIdx + if refreshLibraries { + idx = max(0, slices.IndexFunc(libs, func(lib abs.Library) bool { return lib.ID == currentLibID })) + } if idx >= len(libs) { idx = 0 } + msg.LibraryID = libs[idx].ID sections, err := client.GetPersonalized(context.Background(), libs[idx].ID) if err != nil { - return PersonalizedMsg{Err: fmt.Errorf("fetch personalized: %w", err), Libraries: libs, LibraryID: libs[idx].ID} + msg.Err = fmt.Errorf("fetch personalized: %w", err) + return msg } - var continueListening []abs.LibraryItem - var recentlyAdded []abs.LibraryItem for _, section := range sections { switch section.ID { case "continue-listening": - continueListening = section.Entities + msg.Items = section.Entities case "recently-added": - recentlyAdded = section.Entities + msg.RecentlyAdded = section.Entities } } if libs[idx].MediaType == "podcast" { if eps, err := client.GetRecentEpisodes(context.Background(), libs[idx].ID, recentlyAddedLimit); err == nil { - recentlyAdded = eps + msg.RecentlyAdded = eps } } - return PersonalizedMsg{ - Items: continueListening, - RecentlyAdded: recentlyAdded, - Libraries: libs, - LibraryID: libs[idx].ID, - } + return msg } } @@ -536,18 +558,22 @@ func removeEpisodeFromItems(items []abs.LibraryItem, itemID, episodeID string) ( // ReloadCmd forces a fresh data fetch for the current library. func (m *Model) ReloadCmd() tea.Cmd { - m.loading = true - m.loadingVisible = false - m.loadingGen++ - m.refreshListRows() - return tea.Batch(m.fetchPersonalizedCmd(), m.loadingRevealCmd()) + return m.reloadCmd(false) } // RefreshCmd reads the library list from the client again, and loads the -// shelves of the current library. +// shelves of the selected library. The library list and the selected library +// stay on the model until the answer comes. func (m *Model) RefreshCmd() tea.Cmd { - m.libraries = nil - return m.ReloadCmd() + return m.reloadCmd(true) +} + +func (m *Model) reloadCmd(refreshLibraries bool) tea.Cmd { + m.loading = true + m.loadingVisible = false + m.loadingGen++ + m.refreshListRows() + return tea.Batch(m.fetchPersonalizedCmd(refreshLibraries), m.loadingRevealCmd()) } // Libraries returns the available libraries. diff --git a/internal/screens/home/model_test.go b/internal/screens/home/model_test.go index f8674d7..edd5f5d 100644 --- a/internal/screens/home/model_test.go +++ b/internal/screens/home/model_test.go @@ -837,7 +837,7 @@ func TestFetchPersonalizedPodcastLibraryUsesRecentEpisodes(t *testing.T) { m.libraries = []abs.Library{{ID: "lib-pod", Name: "Podcasts", MediaType: "podcast"}} m.selectedLibrary = 0 - cmd := m.fetchPersonalizedCmd() + cmd := m.fetchPersonalizedCmd(false) msg := cmd() pMsg, ok := msg.(PersonalizedMsg) if !ok { @@ -881,3 +881,93 @@ func TestListItemFilterValue_PodcastEpisode(t *testing.T) { t.Errorf("FilterValue() = %q, want it to contain 'daily news'", fv) } } + +func refreshTestLibraries() []abs.Library { + return []abs.Library{ + {ID: "lib-1", Name: "One", MediaType: "podcast"}, + {ID: "lib-2", Name: "Two", MediaType: "podcast"}, + } +} + +// TestRefreshDropsAnswerOfEarlierLoad verifies that the answer of a load from +// before a refresh does not replace the answer of the refresh. +func TestRefreshDropsAnswerOfEarlierLoad(t *testing.T) { + libs := refreshTestLibraries() + item := func(id string) []abs.LibraryItem { + return []abs.LibraryItem{{ID: id, LibraryID: "lib-1", MediaType: "podcast"}} + } + m := newTestModel() + m, _ = m.Update(PersonalizedMsg{Libraries: libs, LibraryID: "lib-1", Items: item("old")}) + early := PersonalizedMsg{Libraries: libs, LibraryID: "lib-1", Items: item("early"), generation: m.loadingGen} + + _ = m.RefreshCmd() + if got := m.SelectedLibraryID(); got != "lib-1" { + t.Fatalf("selected library during the refresh = %q, want lib-1", got) + } + m, _ = m.Update(PersonalizedMsg{Libraries: libs, LibraryID: "lib-1", Items: item("new"), generation: m.loadingGen, refreshed: true}) + m, _ = m.Update(early) + + if len(m.items) != 1 || m.items[0].ID != "new" { + t.Errorf("items = %+v, want the item of the refresh", m.items) + } +} + +// TestRefreshKeepsSelectedLibraryByID verifies that the answer of a refresh +// selects the same library in the new library list, and the first library +// when the new list does not have it. +func TestRefreshKeepsSelectedLibraryByID(t *testing.T) { + libs := refreshTestLibraries() + m := newTestModel() + m, _ = m.Update(PersonalizedMsg{Libraries: libs, LibraryID: "lib-1"}) + m.selectedLibrary = 1 + + _ = m.RefreshCmd() + newLibs := append([]abs.Library{{ID: "lib-0", Name: "Zero", MediaType: "podcast"}}, libs...) + m, _ = m.Update(PersonalizedMsg{Libraries: newLibs, LibraryID: "lib-2", generation: m.loadingGen, refreshed: true}) + if got := m.SelectedLibraryID(); got != "lib-2" { + t.Errorf("selected library = %q, want lib-2", got) + } + + _ = m.RefreshCmd() + m, _ = m.Update(PersonalizedMsg{Libraries: libs[:1], LibraryID: "lib-1", generation: m.loadingGen, refreshed: true}) + if got := m.SelectedLibraryID(); got != "lib-1" || m.loading { + t.Errorf("selected library = %q, loading = %v, want lib-1 and no load", got, m.loading) + } +} + +// TestRefreshLoadsShelvesOfSelectedLibraryByID verifies that the command of a +// refresh reads the library list again and loads the shelves of the selected +// library, also when its position in the new list is different. +func TestRefreshLoadsShelvesOfSelectedLibraryByID(t *testing.T) { + var shelves []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.URL.Path == "/api/libraries": + _ = json.NewEncoder(w).Encode(map[string]any{ + "libraries": append([]abs.Library{{ID: "lib-0", Name: "Zero", MediaType: "podcast"}}, refreshTestLibraries()...), + }) + case strings.HasSuffix(r.URL.Path, "/personalized"): + shelves = append(shelves, r.URL.Path) + _ = json.NewEncoder(w).Encode([]abs.PersonalizedResponse{}) + default: + _ = json.NewEncoder(w).Encode(map[string]any{"episodes": []any{}}) + } + })) + defer srv.Close() + + m := New(ui.DefaultStyles(), cache.NewClient(abs.NewClient(srv.URL, "tok"), nil)) + m.libraries = refreshTestLibraries() + m.selectedLibrary = 1 + + msg, ok := m.fetchPersonalizedCmd(true)().(PersonalizedMsg) + if !ok { + t.Fatal("the command gives no PersonalizedMsg") + } + if msg.LibraryID != "lib-2" || len(msg.Libraries) != 3 { + t.Errorf("library = %q with %d libraries, want lib-2 with 3 libraries", msg.LibraryID, len(msg.Libraries)) + } + if len(shelves) != 1 || shelves[0] != "/api/libraries/lib-2/personalized" { + t.Errorf("shelves requests = %v, want only lib-2", shelves) + } +} From 692e43b5252ceb1d3adda4ec63e99d1e7357370f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wiktor=20Zi=C4=99bka?= Date: Tue, 17 Nov 2026 11:58:05 +0100 Subject: [PATCH 14/14] fix(palette): use the library of the sessions item On the sessions screen of an item, Go Library, Scan Library, Browse Series, and the search used the library of the home screen, which can be a different library. --- AGENTS.md | 2 +- internal/app/model.go | 16 ++++++++++++++-- internal/app/model_test.go | 9 +++++++++ internal/app/sessions.go | 6 +++--- internal/app/sessions_test.go | 22 ++++++++++++++++++++++ internal/screens/sessions/model.go | 10 +++++++++- 6 files changed, 58 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ffa0528..b6f064d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -147,7 +147,7 @@ Styles from theme config. Format helpers (timestamps, durations). `RunProgram` r - The `main` of pine and the `main` of spruce run the program with `ui.RunProgram`, which quits the program at SIGHUP, the close of the terminal, so that `Cleanup` runs. Bubble Tea quits the program at SIGTERM. - `ctrl+p` opens the global command palette from each screen, but not while a text input or a dialog gets the keys - The palette shows `Browse Series` in its Navigation group on each screen whose library is a book library, but not on the series list. `buildStaticPaletteItems` adds the entry for the library that `currentLibraryForSearch` returns, which is also the library that the palette searches. Do not add a `Browse Series` entry to the palette actions of a screen. -- The palette entries `Go Library`, `Scan Library`, and `Refresh` use the library of the current screen (`currentLibraryForSearch`). While a scan runs, `scanStatus` holds the text of the scan box, and `Scan Library` does nothing. +- The palette entries `Go Library` and `Scan Library` use the library of the current screen (`currentLibraryForSearch`). The sessions screen of an item uses the library of that item (`sessions.Target.LibraryID`). The sessions of all items use the library of the home screen. While a scan runs, `scanStatus` holds the text of the scan box, and `Scan Library` does nothing. - `Refresh` clears the cache in a command (`cache.Client.Invalidate`). `CacheClearedMsg` then loads the library list and the home screen (`home.RefreshCmd`), the library screen, and the open series list, series screen, and detail screen again. The library list stays on the home model until the answer comes, and the answer selects the same library by its ID. - A `home.PersonalizedMsg` has the generation of its load (`loadingGen`). The home screen drops the answer of an earlier load. - `serieslist.LoadedMsg` and `series.LoadedMsg` go to their own screen model, also when that screen is behind the active screen, because a scan and `Refresh` load the screens of the back stack again. `serieslist.LoadedMsg` has the library ID and the generation of its load, and `series.LoadedMsg` has the series ID. A screen drops a message that does not match. A reload of the series list uses `ReloadCmd`, which raises the generation and blocks the load of a next page. diff --git a/internal/app/model.go b/internal/app/model.go index 6a771f5..3a5d12b 100644 --- a/internal/app/model.go +++ b/internal/app/model.go @@ -1283,6 +1283,12 @@ func (m Model) currentLibraryForSearch() (libID, libMediaType string) { return item.LibraryID, item.MediaType } return m.home.SelectedLibraryID(), m.home.SelectedLibraryMediaType() + case ScreenSessions: + // The sessions of all items have no library. + if lib, ok := m.libraryByID(m.sessions.LibraryID()); ok { + return lib.ID, lib.MediaType + } + return m.home.SelectedLibraryID(), m.home.SelectedLibraryMediaType() case ScreenHome: return m.home.SelectedLibraryID(), m.home.SelectedLibraryMediaType() default: @@ -1292,12 +1298,18 @@ func (m Model) currentLibraryForSearch() (libID, libMediaType string) { // libraryName returns the name of a library, or an empty string. func (m Model) libraryName(id string) string { + lib, _ := m.libraryByID(id) + return lib.Name +} + +// libraryByID returns a library of the library list of the home screen. +func (m Model) libraryByID(id string) (abs.Library, bool) { for _, lib := range m.home.Libraries() { if lib.ID == id { - return lib.Name + return lib, true } } - return "" + return abs.Library{}, false } func (m Model) buildStaticPaletteItems() (player, nav []components.PaletteItem) { diff --git a/internal/app/model_test.go b/internal/app/model_test.go index 92b34da..c42813c 100644 --- a/internal/app/model_test.go +++ b/internal/app/model_test.go @@ -24,6 +24,7 @@ import ( "github.com/Thelost77/pine/internal/screens/metadataedit" "github.com/Thelost77/pine/internal/screens/series" "github.com/Thelost77/pine/internal/screens/serieslist" + "github.com/Thelost77/pine/internal/screens/sessions" "github.com/Thelost77/pine/internal/ui" "github.com/Thelost77/pine/internal/ui/components" tea "github.com/charmbracelet/bubbletea" @@ -2517,6 +2518,14 @@ func TestPaletteBrowseSeriesOpensBookLibraryOfScreen(t *testing.T) { m.seriesList = serieslist.New(m.styles, m.client, "lib-a", "A") m.screen = ScreenSeriesList }, "", ""}, + {"sessions of a book", homeOnPodcasts, func(m *Model) { + m.sessions = sessions.New(m.styles, m.client, sessions.Target{ItemID: "b-1", LibraryID: "lib-b"}, "") + m.screen = ScreenSessions + }, "lib-b", "B"}, + {"sessions of all items", homeOnBooks, func(m *Model) { + m.sessions = sessions.New(m.styles, m.client, sessions.Target{}, "") + m.screen = ScreenSessions + }, "lib-a", "A"}, } for _, tt := range tests { diff --git a/internal/app/sessions.go b/internal/app/sessions.go index 8b8561d..12e6965 100644 --- a/internal/app/sessions.go +++ b/internal/app/sessions.go @@ -26,7 +26,7 @@ func (m Model) handleSessionsKey() (Model, tea.Cmd) { } return m.openSessions(sessionsTarget(item, episode)) case m.isPlaying(): - return m.openSessions(sessions.Target{ItemID: m.itemID, EpisodeID: m.episodeID, Title: m.player.Title}) + return m.openSessions(sessions.Target{ItemID: m.itemID, EpisodeID: m.episodeID, Title: m.player.Title, LibraryID: m.playbackLibraryID}) } return m.openSessions(sessions.Target{}) } @@ -44,9 +44,9 @@ func (m Model) openSessions(target sessions.Target) (Model, tea.Cmd) { func sessionsTarget(item abs.LibraryItem, episode *abs.PodcastEpisode) sessions.Target { if episode != nil { - return sessions.Target{ItemID: item.ID, EpisodeID: episode.ID, Title: episode.Title} + return sessions.Target{ItemID: item.ID, EpisodeID: episode.ID, Title: episode.Title, LibraryID: item.LibraryID} } - return sessions.Target{ItemID: item.ID, Title: item.Media.Metadata.Title} + return sessions.Target{ItemID: item.ID, Title: item.Media.Metadata.Title, LibraryID: item.LibraryID} } // handlePlayFromSession leaves the sessions screen and plays the item of a diff --git a/internal/app/sessions_test.go b/internal/app/sessions_test.go index 843fc92..a3f411e 100644 --- a/internal/app/sessions_test.go +++ b/internal/app/sessions_test.go @@ -181,3 +181,25 @@ func TestPaletteListeningSessionsOfDetailTarget(t *testing.T) { _, _ = feedCmd(m, cmd) assertAPICallMade(t, log, "GET", "/api/me/item/listening-sessions/pod-001/pod-001-ep-001") } + +// TestSessionsTargetHasLibraryOfItem verifies that the sessions of an item +// keep the library of the item, so that the palette of the sessions screen +// uses that library and not the library of the home screen. +func TestSessionsTargetHasLibraryOfItem(t *testing.T) { + item := abs.LibraryItem{ID: "b-1", LibraryID: "lib-b"} + if got := sessionsTarget(item, nil).LibraryID; got != "lib-b" { + t.Errorf("library of a book target = %q, want lib-b", got) + } + if got := sessionsTarget(item, &abs.PodcastEpisode{ID: "ep-1"}).LibraryID; got != "lib-b" { + t.Errorf("library of an episode target = %q, want lib-b", got) + } + + m := newTestModelAuthenticated() + m.sessionID = "sess-1" + m.itemID = "b-1" + m.playbackLibraryID = "lib-b" + m, _ = m.handleSessionsKey() + if got := m.sessions.LibraryID(); got != "lib-b" { + t.Errorf("library of the item that plays = %q, want lib-b", got) + } +} diff --git a/internal/screens/sessions/model.go b/internal/screens/sessions/model.go index 224c196..f2e6597 100644 --- a/internal/screens/sessions/model.go +++ b/internal/screens/sessions/model.go @@ -19,11 +19,13 @@ import ( const pageSize = 50 // Target is the book or the podcast episode whose sessions the screen shows. -// The zero Target shows the sessions of all items. +// The zero Target shows the sessions of all items. LibraryID is the library of +// the item. type Target struct { ItemID string EpisodeID string Title string + LibraryID string } // LoadedMsg carries the sessions of a target. @@ -191,6 +193,12 @@ func (m *Model) SetSize(width, height int) { } // IsFiltering reports whether the filter input is active. +// LibraryID returns the library of the target item. It is empty for the +// sessions of all items. +func (m Model) LibraryID() string { + return m.target.LibraryID +} + func (m Model) IsFiltering() bool { return m.list.FilterState() == list.Filtering }