Skip to content

Prefetch library browse content after profile selection - #33

Merged
Quick104 merged 2 commits into
mainfrom
feature/prefetch-library-browse
Jun 30, 2026
Merged

Quick104 merged 2 commits into
mainfrom
feature/prefetch-library-browse

Conversation

@Quick104

@Quick104 Quick104 commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Prefetch authenticated startup content beyond home sections, including recommendations, user libraries, and the active library landing page.
  • Share fetch/cache paths for recommendations, libraries, library sections, and first-page browse results to avoid duplicate requests.
  • Hydrate iOS and tvOS library views from cached prefetched content and prefetch artwork for faster first paint.

Testing

  • Not run; PR content generated from the provided commit and diff.

Summary by CodeRabbit

  • New Features

    • Expanded background prefetching for improved startup and browsing: recommendations, user libraries, library sections, and the first browse page.
    • Switching libraries now proactively refreshes the associated landing content and related sections.
  • Bug Fixes

    • Improved cache reuse across browse and library views, including faster hydration from cached library section data.
    • Profile changes now preload authenticated content more consistently after selection.
  • Chores

    • Reset/cleanup of prefetch state is now more thorough during server switches and cache-wipe flows.

- Share startup prefetch paths for recommendations, libraries, and library sections
- Reuse cached library sections and first browse pages across iOS and tvOS
@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

StartupContentPrefetcher adds shared prefetch paths for recommendations, user libraries, library sections, and browse first pages. Browse, recommendations, profile selection, tvOS, and cache reset flows now call these shared methods and updated cache keys instead of direct fetch-and-cache code.

Changes

Authenticated Content Prefetch Expansion

Layer / File(s) Summary
Cache keys and prefetcher state
iosApp/iosApp/Networking/ResponseCache.swift, iosApp/iosApp/Startup/StartupContentPrefetcher.swift
Adds CacheKey.librarySections(_:), extends per-profile invalidation to library: entries, and introduces generation-scoped task and cancellation state in StartupContentPrefetcher.
Prefetch and fetch implementations
iosApp/iosApp/Startup/StartupContentPrefetcher.swift
Adds recommendations, user libraries, library sections, and browse first-page fetch paths, plus artwork warming helpers for section and browse responses.
Authenticated startup and profile selection
iosApp/iosApp/Startup/StartupContentPrefetcher.swift, iosApp/iosApp/Screens/Profiles/ProfileSelectionViewModel.swift
Routes authenticated startup prefetching through active-library selection, and changes profile selection flows to call prefetchAuthenticatedContent() after switching profiles.
Browse screens use shared prefetches
iosApp/iosApp/Screens/Browse/BrowseView.swift, iosApp/iosApp/Screens/Browse/BrowseViewModel.swift, iosApp/iosApp/Screens/Browse/LibrariesTabView.swift
Browse library title loading, library section loading, library selection, cached library hydration, and browse pagination switch to StartupContentPrefetcher and the new library sections cache key.
Recommendations and tvOS callers
iosApp/iosApp/Screens/Recommendations/RecommendationsViewModel.swift, iosApp/iosApp/tvOS/Navigation/TVMainTabView.swift, iosApp/iosApp/tvOS/Screens/Libraries/TVLibraryBrowseView.swift
Recommendations loading switches to the shared recommendations fetch, and tvOS library loading and browse content loading switch to StartupContentPrefetcher-backed library fetches with cached section hydration.
Startup and cache reset hooks
iosApp/iosApp/Networking/ServerRegistry.swift, iosApp/iosApp/Screens/Auth/AuthService.swift
Server switching and auth cache clearing now reset startup prefetch state through the new profile-scoped and global reset methods.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.15% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is clear and relevant to the PR’s main theme of prefetching library content after profile selection, though it understates the broader startup caching changes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/prefetch-library-browse

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 601d3b03c8

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@coderabbitai

coderabbitai Bot commented Jun 30, 2026

Copy link
Copy Markdown

Caution

Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted.

Error details
{}

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
iosApp/iosApp/Startup/StartupContentPrefetcher.swift (1)

249-260: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Match fallback library ordering to the UI ordering.

When no stored library id exists, this returns API order, while tvOS tabs sort by sortOrder then id; prefetch can warm the wrong landing page.

Proposed refactor
-        let visibleLibraries = libraries.filter {
-            AppNavPreferences.shared.showAudiobooks || !$0.isAudiobookLibrary
-        }
+        let visibleLibraries = libraries
+            .filter {
+                AppNavPreferences.shared.showAudiobooks || !$0.isAudiobookLibrary
+            }
+            .sorted {
+                ($0.sortOrder ?? Int.max, $0.id) < ($1.sortOrder ?? Int.max, $1.id)
+            }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@iosApp/iosApp/Startup/StartupContentPrefetcher.swift` around lines 249 - 260,
The fallback in preferredLibrary(from:) is using the raw API order, which can
differ from the UI’s landing order. Update the fallback selection so that, when
no stored library id is present, it picks from visibleLibraries in the same
ordering used by the tabs/landing UI (sorted by sortOrder, then id). Keep the
stored-id lookup behavior unchanged, and adjust the final return path in
StartupContentPrefetcher.preferredLibrary to use that UI-consistent ordering.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@iosApp/iosApp/Networking/ResponseCache.swift`:
- Around line 99-101: The profile-scoped cache keys created by
ResponseCache.librarySections are not being invalidated on profile switches
because perProfilePrefixes does not cover the "library:" namespace. Update the
profile cache clearing logic in ResponseCache so that library section entries
are included alongside the existing perProfilePrefixes handling, ensuring stale
data from CacheKey.librarySections is removed when the active profile changes.

In `@iosApp/iosApp/Startup/StartupContentPrefetcher.swift`:
- Around line 19-22: Reset the cached in-flight task holders in
StartupContentPrefetcher when the active profile changes, because
recommendationsTask, userLibrariesTask, librarySectionsTasks, and
browseFirstPageTasks are shared across profiles and can be reused or write late
results into the next profile. Add a profile-change reset path in
StartupContentPrefetcher that clears these static task references/maps, and make
sure the existing prefetch entry points use that reset before starting or
reusing any task.
- Around line 207-210: The browse page cache is being stored through
StartupContentPrefetcher’s response caching path, but
ResponseCache.perProfilePrefixes does not treat the browse: namespace as
profile-scoped. Update the cache prefix handling in ResponseCache so browse:
entries are included in per-profile invalidation, ensuring cached page-1 results
are cleared or segregated when the active profile changes.

---

Nitpick comments:
In `@iosApp/iosApp/Startup/StartupContentPrefetcher.swift`:
- Around line 249-260: The fallback in preferredLibrary(from:) is using the raw
API order, which can differ from the UI’s landing order. Update the fallback
selection so that, when no stored library id is present, it picks from
visibleLibraries in the same ordering used by the tabs/landing UI (sorted by
sortOrder, then id). Keep the stored-id lookup behavior unchanged, and adjust
the final return path in StartupContentPrefetcher.preferredLibrary to use that
UI-consistent ordering.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4b4a9977-6933-4582-9833-18575b34e7d5

📥 Commits

Reviewing files that changed from the base of the PR and between 893b1f5 and 601d3b0.

📒 Files selected for processing (9)
  • iosApp/iosApp/Networking/ResponseCache.swift
  • iosApp/iosApp/Screens/Browse/BrowseView.swift
  • iosApp/iosApp/Screens/Browse/BrowseViewModel.swift
  • iosApp/iosApp/Screens/Browse/LibrariesTabView.swift
  • iosApp/iosApp/Screens/Profiles/ProfileSelectionViewModel.swift
  • iosApp/iosApp/Screens/Recommendations/RecommendationsViewModel.swift
  • iosApp/iosApp/Startup/StartupContentPrefetcher.swift
  • iosApp/iosApp/tvOS/Navigation/TVMainTabView.swift
  • iosApp/iosApp/tvOS/Screens/Libraries/TVLibraryBrowseView.swift

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@iosApp/iosApp/Startup/StartupContentPrefetcher.swift`:
- Around line 199-200: Capture the profileScopedGeneration in the prefetch
wrapper methods before enqueuing work, then compare it again inside the queued
task and skip execution if the generation changed. Update the
prefetchLibrarySections and prefetchBrowseFirstPage flow in
StartupContentPrefetcher so stale libraryId or browse requests cannot run after
a profile reset, and keep fetchLibrarySections/fetchBrowseFirstPage guarded by
the generation snapshot taken at scheduling time.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 16348cd4-6dff-4cbb-86d8-be5d7dc67353

📥 Commits

Reviewing files that changed from the base of the PR and between 601d3b0 and 0e9d50b.

📒 Files selected for processing (4)
  • iosApp/iosApp/Networking/ResponseCache.swift
  • iosApp/iosApp/Networking/ServerRegistry.swift
  • iosApp/iosApp/Screens/Auth/AuthService.swift
  • iosApp/iosApp/Startup/StartupContentPrefetcher.swift
🚧 Files skipped from review as they are similar to previous changes (1)
  • iosApp/iosApp/Networking/ResponseCache.swift

Comment on lines +199 to +200
static func fetchLibrarySections(libraryId: Int) async throws -> SectionsResponse {
let generation = profileScopedGeneration

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the file structure and locate the relevant symbols.
git ls-files 'iosApp/iosApp/Startup/*.swift' 'iosApp/iosApp/**/Startup*.swift' | sed -n '1,120p'
echo '---'
ast-grep outline iosApp/iosApp/Startup/StartupContentPrefetcher.swift --view expanded
echo '---'
rg -n "profileScopedGeneration|validateProfileScopedGeneration|resetProfileScopedPrefetches|resetAllPrefetches|prefetchLibrarySections|prefetchBrowseFirstPage|prefetchActiveLibraryLanding|fetchUserLibraries|prefetchLibraryLanding" iosApp/iosApp/Startup/StartupContentPrefetcher.swift

Repository: Silo-Server/silo-apple

Length of output: 4438


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n "resetProfileScopedPrefetches\(|resetAllPrefetches\(" iosApp/iosApp
echo '---'
rg -n "prefetchLibrarySections\(|prefetchBrowseFirstPage\(|prefetchActiveLibraryLanding\(" iosApp/iosApp

Repository: Silo-Server/silo-apple

Length of output: 1494


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '180,320p' iosApp/iosApp/Startup/StartupContentPrefetcher.swift | cat -n

Repository: Silo-Server/silo-apple

Length of output: 5949


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '150,280p' iosApp/iosApp/Startup/StartupContentPrefetcher.swift | cat -n

Repository: Silo-Server/silo-apple

Length of output: 5418


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '280,315p' iosApp/iosApp/Startup/StartupContentPrefetcher.swift | cat -n

Repository: Silo-Server/silo-apple

Length of output: 1590


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n "perProfilePrefixes|CacheKey|ResponseCache|clear.*browse|clear.*library|remove.*browse|remove.*library" iosApp/iosApp

Repository: Silo-Server/silo-apple

Length of output: 12300


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '76,125p' iosApp/iosApp/Networking/ResponseCache.swift | cat -n
echo '---'
sed -n '180,200p' iosApp/iosApp/Screens/Auth/AuthService.swift | cat -n
echo '---'
sed -n '260,275p' iosApp/iosApp/Screens/Auth/AuthService.swift | cat -n

Repository: Silo-Server/silo-apple

Length of output: 4486


Capture profile generation before scheduling queued prefetches. prefetchLibrarySections and prefetchBrowseFirstPage read profileScopedGeneration only inside fetch…, so a profile reset can land between scheduling and execution and let stale libraryId/browse parameters run under the new profile. Snapshot the generation in the wrappers and drop the task if it changed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@iosApp/iosApp/Startup/StartupContentPrefetcher.swift` around lines 199 - 200,
Capture the profileScopedGeneration in the prefetch wrapper methods before
enqueuing work, then compare it again inside the queued task and skip execution
if the generation changed. Update the prefetchLibrarySections and
prefetchBrowseFirstPage flow in StartupContentPrefetcher so stale libraryId or
browse requests cannot run after a profile reset, and keep
fetchLibrarySections/fetchBrowseFirstPage guarded by the generation snapshot
taken at scheduling time.

@Quick104
Quick104 merged commit 353678e into main Jun 30, 2026
1 check passed
@Quick104
Quick104 deleted the feature/prefetch-library-browse branch June 30, 2026 18:40
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