Skip to content

Stop the playback before the system sleeps, and show the cached home shelves at once - #19

Merged
Thelost77 merged 9 commits into
mainfrom
feat/sleep-stop-and-cached-home
Nov 19, 2026
Merged

Thelost77 merged 9 commits into
mainfrom
feat/sleep-stop-and-cached-home

Conversation

@Thelost77

@Thelost77 Thelost77 commented Nov 19, 2026 •

Copy link
Copy Markdown
Owner

Two changes from a comparison of pine with Spotifast. Each number is one commit.

Changes

  1. 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.js lines 387-400 at v2.37.1), so the sync replaced newer progress from another device.
    The new package internal/systemsleep holds a logind sleep delay inhibitor. On PrepareForSleep, the model stops the playback with stopPlayback. 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.

  2. 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.
    EvictExpired now 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

  • On Linux with logind, a book that plays stops before a suspend. pine does not continue after the wake.
  • The position upload before a suspend is best effort. On the test machine, NetworkManager disconnected the Wi-Fi 74 ms after the sleep signal. If the network is down first, the progress since the last sync (at most 30 s) is lost.
  • The home screen shows the last shelves at once, also when they are old (at most 30 days after they expired). A failed load keeps the shelves of the selected library and writes the error to the log. Before, the error text replaced the shelves.
  • A 401 from the home load opens the login screen. Before this pull request, it showed the error text on the home screen.
  • A stop expires the home shelves instead of deleting them, so the next start can show them.

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.

  1. A sleep during a start or a change of the track no longer lets the new session play after the wake. Each play request carries a sleep epoch, and pine closes a session from before the sleep (20ca554).
  2. Inhibit waits at most 3 s, so a system bus that does not answer does not delay the start (71fd206).
  3. GetStale reads an entry only until 30 days after it expired (f505b82).
  4. A stop expires the home shelves instead of deleting them (a2d277a).
  5. A 401 from the home load opens the login screen (9ebbca3).
  6. A fast server error no longer drops the cached shelves that come after it (1d555a7).
  7. At the start, the server answer applies also when the cached library list is old (fb450ba).

Tests

  • internal/systemsleep/systemsleep_linux_test.go runs 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 after prepare, the release after the timeout, and the new inhibitor after the wake.
  • TestSystemSleepStopsPlaybackBeforeRelease checks that the server gets the close of the session before the release. TestSystemSleepWithoutPlaybackReleases checks the release when nothing plays.
  • TestClient_CachedOnly, TestStore_GetStaleReadsExpiredRow, and the changed TestStore_EvictExpired check the cache.
  • TestCachedOnlyLoadReadsExpiredRowsWithoutRequest, TestServerAnswerBeforeCachedAnswerWins, and TestFailedLoadKeepsCachedShelves check the home screen.
  • Each new test fails when its guard is removed from the code. The check was done by hand, and the code was restored.
  • The review fixes add TestSystemSleepDropsPlaySessionAskedBeforeSleep (start, change of the track, restore), TestStartDoesNotWaitForAnInhibitWithNoAnswer, TestStore_GetStaleSkipsAnEntryPastKeepExpired, TestStore_ExpireKeepsTheEntryForGetStale, TestStopKeepsHomeShelvesForTheNextStart, TestHomeLoadUnauthorizedOpensLogin, TestServerErrorBeforeCachedAnswerShowsCachedShelves, and TestServerAnswerReplacesAnOldCachedLibraryList. Each one failed before its fix.

Local results on Linux:

gofmt -l .                                                     # no file
go vet ./...                                                   # ok
golangci-lint run                                              # 0 issues (v2.14.0)
PINE_REQUIRE_LIBMPV=1 PINE_REQUIRE_DBUS=1 go test ./... -count=1  # 1056 passed
go test -race ./... -count=1                                   # 1056 passed
go list -deps ./cmd/spruce | grep systemsleep                  # no output

A temporary program ran systemsleep.Start against the real logind. systemd-inhibit --list showed the inhibitor while it ran, and did not show it after Close.

Not tested

  • A real suspend with pine playing. To check it: play a book, close the lid for one minute, and open it. pine must be stopped and silent, and pine.log must have system sleep: stopping playback.
  • A real start of pine with expired cache entries. To check it: start pine more than 5 minutes after the last start. The shelves must show with no skeleton rows, and pine.log must show personalized: showing the cached shelves before the personalized request.
  • macOS and Windows. GOOS=darwin and GOOS=windows go vet ./... pass, so the code and the tests compile there. CI runs the tests on these systems.

🤖 Generated with Claude Code

Wiktor Ziębka and others added 2 commits November 19, 2026 12:38
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 Thelost77 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.PersonalizedMsg forwards to the home model without checkUnauthorized. Combined with the 401 finding inline, a 401 on the home load neither shows an error nor opens login. Check msg.Err here before updating the home model.
  • Low — internal/app/playback.go:979: stop still deletes the shelves the cache should show. evictProgressCaches deletes PersonalizedKey on 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 let GetStale show it.

Checked, not a bug

  • tea.Sequence(stopCmd, release) in bubbletea 1.3.10 waits for the nested BatchMsg, so the inhibitor is released after the close, progress update and Quit. runCmdToEnd matches.
  • Inhibitor lifecycle: fd is taken out of Monitor before release, sync.Once covers timer and prepare, a wake before release takes a new inhibitor without closing it twice, Conn.Close ends the loop. No double release or fd leak found.
  • No OS build tag needed on systemsleep.go; GOOS=windows/darwin vet 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.

Comment thread internal/app/playback.go Outdated
}
return nil
}
if !m.isPlaying() {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread internal/screens/home/model.go Outdated
logger.Debug("STALE: discarding personalized msg of an earlier load", "msgLib", msg.LibraryID)
return m, nil
}
if msg.cached && !m.loading {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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() {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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())

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread internal/cache/store.go Outdated

// 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)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread internal/systemsleep/systemsleep.go Outdated
func (m *Monitor) inhibit() {
var fd dbus.UnixFD
err := m.conn.Object(logindName, logindPath).
Call(managerIface+".Inhibit", 0, "sleep", m.who, inhibitReason, "delay").

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Wiktor Ziębka and others added 7 commits November 19, 2026 13:07
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>
@Thelost77

Copy link
Copy Markdown
Owner Author

The two findings outside the diff in the review are fixed:

  • Medium, the root home.PersonalizedMsg case had no checkUnauthorized: fixed in 9ebbca3 (open the login screen on a 401 from the home load).
  • Low, a stop deleted the home shelves that the next start should show: fixed in a2d277a (expire the home shelves on a stop instead of deleting them). The new Store.Expire makes the entry expired now, so Get misses it and GetStale still reads it. TestStopKeepsHomeShelvesForTheNextStart failed before the fix.

Local checks after all fixes: gofmt clean, go vet on Linux, macOS, and Windows, golangci-lint 0 issues, PINE_REQUIRE_LIBMPV=1 PINE_REQUIRE_DBUS=1 go test ./... and go test -race ./... 1056 passed.

@Thelost77
Thelost77 merged commit 225a73c into main Nov 19, 2026
10 of 12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant