Repository navigation
Stop the playback before the system sleeps, and show the cached home shelves at once - #19
Conversation
pine kept playing through a suspend. After the wake, mpv played on from the old position, and the next 30 s sync sent that position to the server. Audiobookshelf saves a sync with no time check, so the sync replaced newer progress from another device. The new package internal/systemsleep holds a logind sleep delay inhibitor. On PrepareForSleep, main sends SystemSleepMsg, and the model stops the playback with stopPlayback. The inhibitor is released when the stop commands end (tea.Sequence), or after 10 s. After the wake, pine stays stopped, and the next play takes the position of the server. The position upload before the sleep is best effort: NetworkManager can take the network down first, and the position since the last sync is then lost. Without a system bus (macOS, Windows), pine logs that the monitor is off and runs as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
At each start that found an expired cache entry, the home screen showed skeleton rows until the server answered. In the log of a real setup, 28 of 31 starts waited 50 to 294 ms (once 1069 ms), and the 3 starts from the cache took 9 to 18 ms. At start and on a tab switch, the home screen now also runs a load that reads only the local cache, expired entries included, and sends no request (cache.CachedOnly, Store.GetStale). The answer of the server for the same load replaces it. A cached answer that comes after the answer of the server is dropped. EvictExpired now deletes an entry 30 days after it expires, not at once. Before, a sync tick during playback deleted the entries that a start would show. A failed load keeps the shown shelves of the selected library and goes to the log. Playback still starts from the position of the server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Thelost77
left a comment
There was a problem hiding this comment.
Automated review (Cursor review agent) of the sleep stop and the cached home shelves. 6 inline findings: 1 High, 3 Medium, 2 Low.
Outside the diff
- Medium —
internal/app/model.go:471: home results never open login.case home.PersonalizedMsgforwards to the home model withoutcheckUnauthorized. Combined with the 401 finding inline, a 401 on the home load neither shows an error nor opens login. Checkmsg.Errhere before updating the home model. - Low —
internal/app/playback.go:979: stop still deletes the shelves the cache should show.evictProgressCachesdeletesPersonalizedKeyon every stop, including quit (Cleanup) and the new sleep stop. So after a normal listen the next cold start has no personalized row and waits on the server again. Leaving the row until it expires would letGetStaleshow it.
Checked, not a bug
tea.Sequence(stopCmd, release)in bubbletea 1.3.10 waits for the nestedBatchMsg, so the inhibitor is released after the close, progress update andQuit.runCmdToEndmatches.- Inhibitor lifecycle: fd is taken out of
Monitorbefore release,sync.Oncecovers timer andprepare, a wake before release takes a new inhibitor without closing it twice,Conn.Closeends the loop. No double release or fd leak found. - No OS build tag needed on
systemsleep.go;GOOS=windows/darwinvet passes.
Checks: gofmt clean, go vet pass (linux/windows/darwin), build pass, PINE_REQUIRE_DBUS=1 go test ./... pass. libmpv tests skipped, golangci-lint not run.
| } | ||
| return nil | ||
| } | ||
| if !m.isPlaying() { |
There was a problem hiding this comment.
High — Sleep does not cancel playback that is already starting
isPlaying() is only sessionID != "", which is already false while a play or a chapter/file change is in flight: handlePlayCmd sets sessionID only on PlaySessionMsg, and restartPlaybackAt clears it before its command closes the old session and starts the next file. PlaySessionMsg has no generation, handlePlaySessionMsg always launches mpv, and stopPlayback does not bump playGeneration.
Scenario: close the lid while a book is opening, or in the gap between files of a multi-file book. This branch releases the inhibitor immediately, and the in-flight command then starts a session. After wake pine is playing again, and the next sync can overwrite newer progress from another device. The same applies on the tea.Sequence branch if a PlaySessionMsg from an earlier seek is still running.
Fix: stamp each play command with a generation, bump it in handleSystemSleep on both branches, and make handlePlaySessionMsg close a stale session instead of launching. Quit mpv on the early-release branch too. Tests only cover a fully started session and the idle case.
There was a problem hiding this comment.
Fixed in 20ca554 (do not play a session asked for before the system sleeps). handleSystemSleep raises sleepEpoch. Each of the 7 commands that ask for a play session stamps PlaySessionMsg.SleepEpoch when it is created, and Update closes a session of an earlier epoch (closeRestoredSessionCmd) and does not play it. A change of the track keeps itemID with no session, so the sleep then also stops and quits mpv. TestSystemSleepDropsPlaySessionAskedBeforeSleep covers the start, the change of the track, and the restore. All three cases failed before the fix.
| logger.Debug("STALE: discarding personalized msg of an earlier load", "msgLib", msg.LibraryID) | ||
| return m, nil | ||
| } | ||
| if msg.cached && !m.loading { |
There was a problem hiding this comment.
Medium — A fast load error drops the cached shelves
The cached answer is applied only while m.loading is still true, but any applied answer (including a failure) sets loading = false first. The keep-shelves branch only helps when the cached message landed first.
Scenario: start pine with the server down. A refused connection / ENETUNREACH often returns before the SQLite reads, the error is applied, and the cached PersonalizedMsg that arrives next is discarded — the view shows the error text. That's exactly the offline start this change aims to fix. TestFailedLoadKeepsCachedShelves only covers cache-first ordering.
Fix: on a server error, remember this generation hasn't succeeded yet and still apply a later cached message for it; show the error only if the cached command produced nothing.
There was a problem hiding this comment.
Fixed in 1d555a7 (show the cached shelves after a fast server error). A cached answer is now dropped only after the server answered the same load with no error (serverAnswered, reset for each new load). TestServerErrorBeforeCachedAnswerShowsCachedShelves sends the error first and failed before the fix.
| } | ||
| // The shelves of the selected library stay when a later load fails, | ||
| // for example a start with no network after the cached answer. | ||
| if msg.Err != nil && m.contentLibrary != "" && m.contentLibrary == m.SelectedLibraryID() { |
There was a problem hiding this comment.
Medium — A 401 is swallowed once shelves are on screen
The error from GetLibraries/GetPersonalized is wrapped with %w, so abs.IsHTTPStatus(err, 401) would match, but this branch doesn't check. It also skips m.err, so the view never shows Error: ....
Scenario: warm cache + expired token, nothing to restore. Cached shelves render, server answers 401, shelves stay, login isn't opened — only a log line. Before this PR the 401 replaced the shelves with the error.
Fix: keep shelves for network errors, but for unauthorized set the error and let the root redirect to login (see also the review summary: the root home.PersonalizedMsg case never calls checkUnauthorized).
There was a problem hiding this comment.
Fixed in 9ebbca3 (open the login screen on a 401 from the home load). The root home.PersonalizedMsg case now calls checkUnauthorized before the home screen gets the message, so a 401 opens the login screen, and the home screen keeps its shelves only for other errors. TestHomeLoadUnauthorizedOpensLogin failed before the fix.
| // Init returns the initial command that fetches personalized data. | ||
| func (m Model) Init() tea.Cmd { | ||
| return tea.Batch(m.fetchPersonalizedCmd(false), m.loadingRevealCmd()) | ||
| return tea.Batch(m.fetchPersonalizedCmd(false, true), m.fetchPersonalizedCmd(false, false), m.loadingRevealCmd()) |
There was a problem hiding this comment.
Medium — A stale cached library list makes the server answer look stale
At startup the cached load (GetStale) and the server load (Get) both fetch libraries when m.libraries is empty. With the 24 h libraries TTL expired and the server list changed (library added/removed/reordered), the local cache read usually lands first, sets m.libraries and contentLibrary to the old first library, and the server message then hits the mismatch guard (LibraryID differs, refreshed false) and is dropped for the whole session. Tab switches are fine since both reuse the in-memory list.
Fix: don't let a cached message arm that guard — apply the non-cached message of the same generation even if its library id differs, or don't replace m.libraries from a cached message.
There was a problem hiding this comment.
Fixed in fb450ba (apply the server answer when the cached library list is old). A load that reads the library list now has refreshed, as RefreshCmd has, so its answer replaces the list and selects the library by its ID. TestServerAnswerReplacesAnOldCachedLibraryList uses a real cache with an old list and a new first library on the server. It failed before the fix.
|
|
||
| // GetStale is Get that also reads an expired entry. | ||
| func (s *Store) GetStale(key string, dest any) (bool, error) { | ||
| return s.get(`SELECT data FROM api_cache WHERE cache_key = ?`, key, dest) |
There was a problem hiding this comment.
Low — GetStale ignores the 30-day bound
keepExpired is documented as how long an expired entry stays readable, but GetStale selects by key only; only EvictExpired (run from the playback sync tick) enforces it. If pine stays closed >30 days after expiry without playing, an offline start still renders that row.
Fix: use the same datetime('now', '-' || ? || ' seconds') predicate here as EvictExpired.
There was a problem hiding this comment.
Fixed in f505b82 (read an expired entry only until keepExpired). GetStale now uses the same keepExpired predicate as EvictExpired. TestStore_GetStaleSkipsAnEntryPastKeepExpired failed before the fix.
| func (m *Monitor) inhibit() { | ||
| var fd dbus.UnixFD | ||
| err := m.conn.Object(logindName, logindPath). | ||
| Call(managerIface+".Inhibit", 0, "sleep", m.who, inhibitReason, "delay"). |
There was a problem hiding this comment.
Low — Inhibit has no deadline
Call(..., 0, ...) uses context.Background(). Start runs inhibit on the main goroutine before RunProgram, so a system bus that accepts the connection but never answers blocks startup (TUI never appears). After wake the same call blocks the signal loop, so a following PrepareForSleep(true) waits with no delay lock held.
Fix: use a context with a few-second timeout; on timeout log and continue without an inhibitor, as a refused Inhibit already does.
There was a problem hiding this comment.
Fixed in 71fd206 (wait at most 3 s for an answer to Inhibit). inhibit uses CallWithContext with a 3 s timeout. Without an answer, it logs a warning and runs with no inhibitor, as for a refusal. TestStartDoesNotWaitForAnInhibitWithNoAnswer uses a fake logind that does not answer. It failed before the fix.
A sleep during a start or a change of the track released logind at once, because the model had no session yet. The command then got its session, and pine played after the wake. handleSystemSleep now raises sleepEpoch. Each command that asks for a play session stamps the PlaySessionMsg with the epoch of its creation, and Update closes a session of an earlier epoch and does not play it. A change of the track keeps itemID with no session, so the sleep also stops the playback and quits mpv then. Review finding (High) on pull request 19. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Inhibit call had no deadline. Start runs it before the program starts, so a system bus that does not answer delayed the TUI. After a wake, the same call held the signal loop. The call now has a 3 s timeout. Without an answer, the monitor logs a warning and runs with no inhibitor, as it does when logind refuses one. Review finding (Low) on pull request 19. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
GetStale read an entry of any age. Only EvictExpired, which runs on a sync tick during playback, applied the 30-day limit. A start with no network after a long break with no playback could show very old shelves. GetStale now reads only an entry that expired less than keepExpired ago. Review finding (Low) on pull request 19. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each stop, a quit included, deleted the personalized entry of the library. After a normal listening session, the next start had no cached shelves and waited for the server again. The new Store.Expire makes an entry expired now. evictProgressCaches expires the home shelves with it: Get misses them, so the next load asks the server, and GetStale still shows them at the next start. Review finding (Low, outside the diff) on pull request 19. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The root model gave home.PersonalizedMsg to the home screen without a check for 401. Since the home screen keeps its shelves on a failed load, an expired token showed old shelves and only a log line. The root model now checks the error with checkUnauthorized, as it does for the other loads, and opens the login screen. Review finding (Medium, inline and outside the diff) on pull request 19. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The cached answer applied only while the load was still in progress. A server error sets the load to done, so an error that came first (for example a start with no network, where the connection fails at once) dropped the cached answer, and the error text showed. The home screen now drops a cached answer only after the server answered the same load with no error (serverAnswered). A new load resets the flag. Review finding (Medium) on pull request 19. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
At the start, both loads read the library list. The cached answer set the old list and its first library. If the server had a different first library, its answer did not match the selected library and was dropped for the session. A load that reads the library list now has refreshed set, as a refresh has. Its answer replaces the list and selects the library by its ID. Review finding (Medium) on pull request 19. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
The two findings outside the diff in the review are fixed:
Local checks after all fixes: |
Two changes from a comparison of pine with Spotifast. Each number is one commit.
Changes
Stop the playback before the system sleeps (7a0e550).
Before, pine kept playing through a suspend. After the wake, mpv played on from the old position, and the next 30 s sync sent that position to the server. Audiobookshelf saves a sync with no time check (
PlaybackSessionManager.jslines 387-400 at v2.37.1), so the sync replaced newer progress from another device.The new package
internal/systemsleepholds a logind sleep delay inhibitor. OnPrepareForSleep, the model stops the playback withstopPlayback. The inhibitor is released after the stop commands end (tea.Sequence), or after 10 s. After the wake, pine stays stopped, and the next play takes the position of the server.Without a system bus (macOS, Windows), pine logs that the monitor is off and runs as before.
Show the cached home shelves at once, then refresh them (32832a8).
Before, each start with an expired cache entry showed skeleton rows until the server answered. In the log of one real setup, 28 of 31 starts waited 50 to 294 ms (once 1069 ms). The 3 starts from the cache took 9 to 18 ms.
At start and on a tab switch, the home screen now also runs a load that reads only the local cache, expired entries included, and sends no request (
cache.CachedOnly,Store.GetStale). The answer of the server replaces it, and a cached answer that comes after the answer of the server is dropped.EvictExpirednow deletes an entry 30 days after it expires. Before, a sync tick during playback deleted the entries that a start would show.Changes of behavior that a user can see
Review fixes
The review on this pull request had 8 findings. Each one was reproduced with a failing test before its fix. Each number is one commit.
Inhibitwaits at most 3 s, so a system bus that does not answer does not delay the start (71fd206).GetStalereads an entry only until 30 days after it expired (f505b82).Tests
internal/systemsleep/systemsleep_linux_test.goruns a fake logind on a private D-Bus bus. Each inhibitor is the write end of a pipe, so the test sees the release as EOF. The tests check the release afterprepare, the release after the timeout, and the new inhibitor after the wake.TestSystemSleepStopsPlaybackBeforeReleasechecks that the server gets the close of the session before the release.TestSystemSleepWithoutPlaybackReleaseschecks the release when nothing plays.TestClient_CachedOnly,TestStore_GetStaleReadsExpiredRow, and the changedTestStore_EvictExpiredcheck the cache.TestCachedOnlyLoadReadsExpiredRowsWithoutRequest,TestServerAnswerBeforeCachedAnswerWins, andTestFailedLoadKeepsCachedShelvescheck the home screen.TestSystemSleepDropsPlaySessionAskedBeforeSleep(start, change of the track, restore),TestStartDoesNotWaitForAnInhibitWithNoAnswer,TestStore_GetStaleSkipsAnEntryPastKeepExpired,TestStore_ExpireKeepsTheEntryForGetStale,TestStopKeepsHomeShelvesForTheNextStart,TestHomeLoadUnauthorizedOpensLogin,TestServerErrorBeforeCachedAnswerShowsCachedShelves, andTestServerAnswerReplacesAnOldCachedLibraryList. Each one failed before its fix.Local results on Linux:
A temporary program ran
systemsleep.Startagainst the real logind.systemd-inhibit --listshowed the inhibitor while it ran, and did not show it afterClose.Not tested
pine.logmust havesystem sleep: stopping playback.pine.logmust showpersonalized: showing the cached shelvesbefore thepersonalizedrequest.GOOS=darwinandGOOS=windowsgo vet ./...pass, so the code and the tests compile there. CI runs the tests on these systems.🤖 Generated with Claude Code