Repository navigation
Replace hamburger flyout with a bottom tab bar (#43) - #116
Conversation
Five tabs — Library, Discover, Search, Feed, Settings — replacing the three flyout items. Routes are unchanged (my-anime, discover, settings) and search and feed are added, so nothing that navigates had to change. The Library tab holds two ShellContents, which Shell renders as a native swipeable top strip: anime (MyAnimePage) and manga (a placeholder until #12). Both halves title the nav bar "Library" and the strip disambiguates, so the bottom tab, nav bar and strip all agree. Their rainbow accents are pinned via ConverterParameter rather than derived from the title text, so anime stays green and manga blue despite sharing a title. Selected tabs render the Filled glyph and unselected the Regular one. Shell has no per-state icon property — Android draws the bar through BottomNavigationView and Shell maps a single Icon — so AppShell swaps it on Navigated, building both ImageSources per tab once instead of allocating on every tap. Search and Feed ship as stub pages with no PageModels; phase 2 moves the search already built into Discover onto the Search tab. driver.ps1: goto is now a plain tab-label tap and works from inside a pushed details stack, search is a shortcut for it, and flyout is gone. The in-page toolbar icons lost the hamburger they used to mirror for coordinates, which the skill's gotchas now say explicitly. Verified on device: labels do not truncate at five tabs, detail-page content clears the bar without extra padding, and tab labels are real uiautomator nodes so navigation needs no coordinate tricks. The CI screenshot job still drives the flyout and is rewritten in phase 2.
Search shipped inside Discover behind a toolbar toggle (#16). The Search tab needs it standalone, so SearchPageModel takes over the debounce, the generation guarding and the paginated results, and Discover keeps only its section rows. The extraction is larger than the search block itself because search was coupled to Discover in two places that do not survive separation: - Discover's LoadAsync cleared the search whenever auth or the adult toggle flipped. SearchPageModel now runs that check against its own results in OnAppearingAsync, since there is no load here to fold it into. - Discover's long-press write-back walked Rows.Concat(SearchSection.Items) so a status chip stayed consistent wherever that media appeared. SearchPageModel carries its own EntryActionCoordinator and writes back over its results. Auth is baselined on appear rather than recorded per search: doing it inside the fetch's try meant a token refresh throwing after a good fetch would report "Search failed" for a search that had actually succeeded. Appear-time is enough, because signing in or out means visiting Settings and coming back. The page skips the deferred content host that Discover and My Anime use. That pattern keeps a heavy InitializeComponent off the UI thread during the tab transition; an Entry plus one CollectionView does not need it. The singleton keeps the query across tab switches on purpose — returning to the tab should show what you were looking at. A dedicated tab also has no section rows to fall back on, so it gains an idle prompt the Discover version never needed. CI: the screenshot job navigated by opening the flyout and, for the search icon, by mirroring the hamburger's x across the screen width because MAUI toolbar icons expose no uiautomator node. Tab labels are real nodes, so all of that collapses into goto_tab — 61 lines lighter. goto_tab deliberately propagates the tap's exit status rather than the trailing sleep's, so a missed tab skips the screenshots that depend on it instead of capturing the wrong screen.
There was a problem hiding this comment.
Pull request overview
Replaces the hamburger flyout with a five-tab bottom bar and extracts Discover’s search into a persistent Search tab.
Changes:
- Adds Library, Discover, Search, Feed, and Settings tabs.
- Moves search, pagination, and result actions into
SearchPageModel. - Updates DI, CI navigation, screenshot labels, and documentation.
Review findings:
- Moderate (2 votes): Invalidate in-flight searches when authentication or adult-setting context changes.
- Moderate (2 votes): Reset or gate pagination when the search query changes during debounce.
- Nit (3 votes): Rename CI screenshot labels from
Discover SearchtoSearch.
Reviewed changes
Copilot reviewed 26 out of 35 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Reviewed changes |
|---|---|
src/Views/DiscoverLoadedContentView.xaml.cs |
Removes embedded search handlers. |
src/Views/DiscoverLoadedContentView.xaml |
Removes embedded search UI. |
src/Pages/SettingsPage.xaml.cs |
Updates tab navigation comments. |
src/Pages/SearchPage.xaml.cs |
Adds Search lifecycle, focus, and result actions. |
src/Pages/SearchPage.xaml |
Defines the dedicated Search interface. |
src/Pages/MyMangaPage.xaml.cs |
Adds Manga placeholder page code-behind. |
src/Pages/MyMangaPage.xaml |
Adds Manga placeholder UI. |
src/Pages/MyAnimePage.xaml.cs |
Updates Library tab comments. |
src/Pages/MyAnimePage.xaml |
Updates Library title and accent. |
src/Pages/FeedPage.xaml.cs |
Adds Feed placeholder page code-behind. |
src/Pages/FeedPage.xaml |
Adds Feed placeholder UI. |
src/Pages/DiscoverPage.xaml.cs |
Updates tab lifecycle comments. |
src/Pages/DiscoverPage.xaml |
Removes the embedded search action. |
src/PageModels/SettingsPageModel.cs |
Updates tab-related documentation. |
src/PageModels/SearchPageModel.cs |
Implements extracted search, debounce, pagination, and actions. |
src/PageModels/MyAnimePageModel.cs |
Renames the page title to Library. |
src/PageModels/DiscoverPageModel.cs |
Removes Discover-owned search behavior. |
src/MauiProgram.cs |
Registers new pages and models. |
src/AppShell.xaml.cs |
Manages selected and unselected tab icons. |
src/AppShell.xaml |
Defines bottom tabs and Library sub-tabs. |
README.md |
Updates navigation documentation. |
AGENTS.md |
Updates navigation and DI guidance. |
.github/workflows/ci-build-and-preview.yml |
Updates tab navigation and screenshots. |
.claude/skills/run-anisprinkles/SKILL.md |
Documents tab-based emulator workflows. |
.claude/skills/run-anisprinkles/driver.ps1 |
Replaces flyout automation with tab navigation. |
.claude/skills/project-architecture/SKILL.md |
Documents the updated architecture. |
Suppressed comments (5)
AGENTS.md:13
- The navigation docs now describe tab PageModels, but the repository's
/ani-kickoffchecklist still says the singleton PageModels are "flyout PageModels" at.claude/skills/ani-kickoff/SKILL.md:245. That stale guidance can cause future issue planning to use the wrong navigation/lifetime terminology; update it along with the navigation documentation.
- **DI**: Services and tab PageModels (`MyAnimePageModel`, `DiscoverPageModel`, `SearchPageModel`, `SettingsPageModel`) are singleton. All Pages and details PageModels (`MediaDetailsPageModel`, `StaffDetailsPageModel`, `CharacterDetailsPageModel`, `StudioDetailsPageModel`, `MediaBrowsePageModel`) are transient. See `/project-architecture` for the full DI table and page patterns.
src/PageModels/SearchPageModel.cs:125
- This auth check is awaited by
SearchPage.OnAppearing, which isasync void, but it is not inside a catch.AuthService.GetAccessTokenAsyncdirectly awaits the SecureStorage reads, so a keystore/storage failure can escape the page lifecycle as an unhandled exception when opening the Search tab. Handle/report the auth-check failure or route it through a caught load path.
var displayAdult = AppSettings.DisplayAdultContent;
var isAuthenticated = !string.IsNullOrWhiteSpace(await _authService.GetAccessTokenAsync());
src/PageModels/SearchPageModel.cs:221
- The adult-content context is recorded from the global setting after the request completes, not from the setting/filter that was used for this request. If the user starts a search with adult content enabled, switches to Settings, and disables it while the request is in flight, an 18+ response can finish here and store
false; returning to Search then sees no adult-context change and keeps those stale results. Capture the setting/filter before the fetch, use that captured value for the request, and record the same captured value here.
_searchedWithAdultContent = AppSettings.DisplayAdultContent;
src/PageModels/SearchPageModel.cs:221
AdultFilteris evaluated before the request, but this assignment readsAppSettings.DisplayAdultContentagain after the await. If the user switches to Settings and changes the adult toggle while this request is in flight, results fetched with the old filter are recorded as having used the new filter, soOnAppearingAsyncwill not invalidate them when the user returns. Capture the filter value used for this request and record that same value after the fetch (and use it as the request argument).
_searchedWithAdultContent = AppSettings.DisplayAdultContent;
src/PageModels/SearchPageModel.cs:135
- The invalidation baseline only records whether a token exists, not which viewer it belongs to. Because this model is a singleton, a user can sign out and sign in as a different AniList account from another tab without an intermediate Search appearance;
truethen remainstrue, leaving the previous account'smediaListEntrychips (and edit values used by long-press actions) on the new account's results. Track a stable auth identity/change generation or invalidate search results whenever the token identity changes.
var authChanged = isAuthenticated != _searchedAuthenticated;
var adultChanged = displayAdult != _searchedWithAdultContent;
💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
There was a problem hiding this comment.
🟢 Approval recommended
Review details
Suppressed comments (9)
src/PageModels/SearchPageModel.cs:205
AdultFilteris evaluated from the mutable global setting both when the seed request is started and later by the paging delegate, but_searchedWithAdultContentis set from the setting only after the await. If the setting changes during an in-flight search—or before a later page—old and new filter contexts can be mixed, and completion can mark old results as fresh soOnAppearingAsyncdoes not invalidate them. Capture the filter alongside the search generation and use that captured value for every page; record the same captured value.
var (items, pageInfo) = await _aniListClient.SearchAnimePageAsync(
query, AdultFilter, page: 1, perPage: SearchPerPage, cancellationToken: token);
src/PageModels/SearchPageModel.cs:125
GetAccessTokenAsyncis awaited outside a try/catch.AuthServicereads SecureStorage here, which can throw (the Settings page already treats this probe as fallible), andSearchPage.OnAppearingisasync void, so a transient storage failure becomes an unhandled page-lifecycle exception. Handle this probe through the page's existing error/feedback path, without updating the search context when the probe fails.
var isAuthenticated = !string.IsNullOrWhiteSpace(await _authService.GetAccessTokenAsync());
src/PageModels/SearchPageModel.cs:232
- The cancellation catch only checks
_activeSearchQuery. When a new keystroke cancels an in-flight request, the replacement query has not necessarily reached the assignment above yet; if the canceled client call reports a non-cancellation exception,_activeSearchQuerystill equals the old query and this path shows "Search failed" for a request the user replaced. Checktoken.IsCancellationRequestedbefore showing the error.
if (!string.Equals(_activeSearchQuery, query, StringComparison.Ordinal))
{
return;
}
src/PageModels/SearchPageModel.cs:184
- A new qualifying query leaves the old
SearchSection(including its page cursor andHasNextPage) alive until the first-page request eventually callsSeed. If the visible collection reaches its threshold while that request is debouncing/in flight,LoadMoreAsynccan invoke the delegate after_activeSearchQueryhas switched and append page 2 of the new query to the old results. Reset the section when scheduling a new query (or otherwise bind paging to a query generation) so concurrent paging cannot mix searches.
IsSearchActive = true;
IsSearching = true;
HasNoSearchResults = false; // a previous query's empty state must not show under the new fetch
_searchDebounceCts = new CancellationTokenSource();
_ = DebouncedSearchAsync(query, _searchDebounceCts.Token);
src/PageModels/SearchPageModel.cs:237
- On a first-page failure this catch leaves
IsSearchActive=true,IsSearching=false,HasNoSearchResults=false, and the section empty, so every result/idle state is hidden and the Search tab is blank after the snackbar disappears._hasSearchedThisSessionalso remains false, so returning to the tab does not retry. Preserve a visible prior-result state with an error indicator or add a retry action/state instead of leaving the screen with no recovery path.
// Keep whatever results are showing; the snackbar is the failure signal.
var apiEx = ex as AniListApiException;
await _feedback.ShowSnackbarAsync(apiEx?.UserTitle ?? "Search failed. Please try again.");
_errorReportService.Record(ex, "Search");
src/PageModels/SearchPageModel.cs:154
- This is the only invalidation check, but
SettingsPageModelupdatesAppSettings.DisplayAdultContentonly after its 1.5-second debouncedUpdateUsersucceeds. If a user flips the toggle and immediately switches to Search, this method baselines the old value; when the save later updatesAppSettings, no event reruns the query, so existing results remain fetched under the wrong adult filter until another tab re-entry. Propagate the preference change immediately or notify this singleton when the save completes.
if (!string.IsNullOrEmpty(SearchText))
{
// Re-run the same query under the new context rather than dumping what the user typed.
var query = SearchText;
SearchText = string.Empty; // OnSearchTextChanged resets the section and cancels in-flight work
SearchText = query;
}
src/PageModels/SearchPageModel.cs:129
- The Search page auto-focuses the field, so the user can type while this first authentication baseline is still awaiting SecureStorage. If the 600 ms search completes first,
_hasSearchedThisSessionbecomes true while_searchedAuthenticatedis still its defaultfalse(the fetch intentionally never sets it); this continuation then treats a valid authenticated result as an auth change and immediately launches a duplicate search. Coordinate the first search with this baseline or snapshot the authentication context used by that search.
var isAuthenticated = !string.IsNullOrWhiteSpace(await _authService.GetAccessTokenAsync());
if (!_hasSearchedThisSession)
{
_searchedWithAdultContent = displayAdult;
src/PageModels/SearchPageModel.cs:146
- These context baselines are committed before the replacement search has succeeded, but the fetch catch deliberately keeps the previous results. If the auth/adult-invalidating fetch fails, the next appearance now sees the new baselines and skips the retry, leaving results fetched under the old viewer/filter (including adult results after turning the toggle off). Keep the old baselines until a successful replacement fetch, or retain a pending invalidation so the next appearance retries.
_searchedWithAdultContent = displayAdult;
_searchedAuthenticated = isAuthenticated;
src/Pages/MyMangaPage.xaml:7
RainbowAccentConverterhashes unknown keys, and theMangakey hashes to theRainbowGreenslot, so this placeholder gets the same green accent as Anime rather than the blue accent described for the two Library halves. Add an explicitManga→RainbowBluemapping (or use a key that is already mapped to blue) so the sharedLibrarytitle does not collapse the intended color distinction.
Shell.TitleColor="{Binding Converter={StaticResource RainbowAccentConverter}, ConverterParameter='Manga'}">
- Files reviewed: 26/35 changed files
- Comments generated: 0 new
- Review effort level: Lite
The nav title reads 'Library' now, so the PR preview table calling that screenshot 'My Anime' no longer matches what it shows. Filename stays my_anime.png so existing committed screenshots are not orphaned.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 26 out of 35 changed files in this pull request and generated no new comments.
Suppressed comments (6)
.github/workflows/ci-build-and-preview.yml:777
- The screenshot manifest still labels
screenshots/search.pngasDiscover Search, although search now lives on its own Search tab and the capture log already calls itSearch. This makes the generated PR comment misidentify the new tab; update the label here.
{ file: 'screenshots/my_anime.png', label: 'Library' },
{ file: 'screenshots/discover.png', label: 'Discover' },
{ file: 'screenshots/browse.png', label: 'View All (Browse)' },
{ file: 'screenshots/search.png', label: 'Discover Search' },
src/PageModels/SearchPageModel.cs:221
_searchedWithAdultContentis captured after the request, butAdultFilterwas evaluated before it. If the user changes the adult toggle while this request is in flight, the response is recorded as having used the new setting even though it used the old filter; returning to Search then sees noadultChangedand leaves stale adult/SFW results visible. Keep the appear-time baseline (or snapshotDisplayAdultContentbefore the call and use that same snapshot for both the request and this field).
_hasSearchedThisSession = true;
_searchedWithAdultContent = AppSettings.DisplayAdultContent;
src/PageModels/SearchPageModel.cs:125
- This auth check is outside any exception handler.
AuthService.LoadAsyncreadsSecureStoragedirectly and can throw on a keystore/storage failure; becauseSearchPageawaitsOnAppearingAsyncfromasync void OnAppearing, that exception becomes an unhandled UI exception before the search error path can run. Handle/report the auth-check failure here (the cached-settings path already does this inSettingsPageModel.LoadAsync).
var displayAdult = AppSettings.DisplayAdultContent;
var isAuthenticated = !string.IsNullOrWhiteSpace(await _authService.GetAccessTokenAsync());
src/PageModels/SearchPageModel.cs:146
- These context baselines are committed before the replacement search is even scheduled. If that refetch fails,
DebouncedSearchAsyncleaves_hasSearchedThisSessiontrue, so subsequent appearances see no auth/adult change and never retry; after the reset in this branch, the Search tab can remain empty until the user edits the query. Keep the previous baseline (or track the invalidation as pending) until the replacement search succeeds, while still updating it immediately when there is no query to refetch.
_searchedWithAdultContent = displayAdult;
_searchedAuthenticated = isAuthenticated;
src/PageModels/SearchPageModel.cs:229
- A cancelled request can still throw a non-
OperationCanceledException(for example, a transport error after cancellation). If the user re-enters the same query before that old request finishes,_activeSearchQuerymatches and this stale request reports "Search failed" and records an error for the newer search. Includetoken.IsCancellationRequestedin this guard, as the success path already does.
if (!string.Equals(_activeSearchQuery, query, StringComparison.Ordinal))
src/PageModels/SearchPageModel.cs:182
- When a new qualifying query starts, the previous
SearchSectionremains populated and can still load more. A threshold event during the debounce/fetch window can therefore invoke the paging delegate with the old_activeSearchQuery(or the new query before its first page has seeded), producing a request for the wrong query and stale rows. Reset or otherwise generation-invalidate the section as soon as the qualifying query changes, not only when its first page returns.
IsSearchActive = true;
IsSearching = true;
HasNoSearchResults = false; // a previous query's empty state must not show under the new fetch
There was a problem hiding this comment.
🟡 Changes recommended
SearchPageModel must handle authentication-token retrieval failures to prevent UI lifecycle crashes.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (7)
.github/workflows/ci-build-and-preview.yml:777
- The search capture now comes from the dedicated Search tab, but this label still calls it
Discover Search. The generated PR comment will therefore misidentify the screenshot; rename the label toSearchhere and in the summary table below.
{ file: 'screenshots/search.png', label: 'Discover Search' },
README.md:74
- This navigation update leaves the Features section inconsistent:
README.md:30still describes debounced search as part of Discover, even though this change removes it from Discover and makes it a dedicated Search tab. Please update that feature description so the README does not direct readers to a nonexistent Discover search control.
| Navigation | Shell bottom tab bar + programmatic details routes (`media-details`, `character-details`, `staff-details`, `studio-details`) |
src/PageModels/SearchPageModel.cs:232
- When a new keystroke cancels an in-flight request,
_activeSearchQueryremains the old query until the replacement debounce fires. If the canceled request completes with a non-cancellation exception during that window, this guard still passes and showsSearch failed/records an error for a superseded request. Checktoken.IsCancellationRequestedhere as well before reporting the failure.
if (!string.Equals(_activeSearchQuery, query, StringComparison.Ordinal))
{
return;
}
src/PageModels/SearchPageModel.cs:136
- This invalidation only compares the authenticated boolean. If a user signs out and signs into a different AniList account while the Search tab is away, both values are
true, so the singleton keeps the previous account'smediaListEntrystatus chips. Track an auth identity/generation (or explicitly invalidate on sign-in/out), rather than only the boolean, before reusing these viewer-relative results.
var authChanged = isAuthenticated != _searchedAuthenticated;
var adultChanged = displayAdult != _searchedWithAdultContent;
if (!authChanged && !adultChanged)
src/PageModels/SearchPageModel.cs:221
AdultFilterwas evaluated when the request started (line 205), but this records the live setting at completion. If the user flips the adult-content setting while the request is in flight, results fetched under the old filter are stamped as the new context, soOnAppearingAsyncwill not invalidate them and the list can remain stale. Capture the request's filter context and commit that snapshot, or discard/restart when the context changes.
_hasSearchedThisSession = true;
_searchedWithAdultContent = AppSettings.DisplayAdultContent;
src/PageModels/SearchPageModel.cs:261
- This load-more operation has no cancellation token, so changing the query only cancels the first-page debounce/fetch; an in-flight page-2 request continues after
SearchSection.Reset(). Because the fetch delegate reads mutable_activeSearchQuery, it can even send a discarded page-2 request for the new query, wasting an AniList rate-limit slot. Pass a query-owned token here and cancel it on each text change.
() => SearchSection.LoadMoreAsync(),
src/PageModels/SearchPageModel.cs:131
- When the first qualifying search is still in flight,
_hasSearchedThisSessionis false, so this branch overwrites the context baselines and returns. If the user signs in or flips the adult setting on another tab before that request finishes, the uncancelled old response can seed results without list entries (or under the old adult filter), and line 221 records the new context so the next appearance will not invalidate them. Detect a context change in this branch as well and restart/cancel the active query, or otherwise associate the response with a context generation.
if (!_hasSearchedThisSession)
{
_searchedWithAdultContent = displayAdult;
_searchedAuthenticated = isAuthenticated;
return;
- Files reviewed: 26/35 changed files
- Comments generated: 1
- Review effort level: Lite
Search context is now recorded when the fetch is issued, not when it lands. Recording on success left _hasSearchedThisSession false while the first search was in flight, so a user who tabbed away, flipped the adult toggle and came back hit OnAppearingAsync's "nothing to invalidate" branch — which baselined the new context without cancelling the old request. That response then landed and was marked current, and no later appearance would invalidate it. Recording at issue time routes that user through the normal path, which cancels and re-runs. Load More is gated on !IsSearching. Between the debounce firing and page 1 landing, the previous query's items are still on screen with HasNextPage set, so scrolling to the threshold fetched page 2 of the NEW query onto the OLD results. A successful Seed bumps the section generation and discards that, but a failed page 1 never seeds and the mixed list stayed visible. AuthService.LoadAsync and the expiry-triggered SignOutAsync are guarded. SecureStorage sits on the Android keystore and can fail for reasons unrelated to us; every tab page model calls GetAccessTokenAsync from an async void OnAppearing, where nothing catches. An unreadable or un-clearable token is functionally an absent one, so both paths fall back to signed out. Explicit sign-out still surfaces its failures. CI: the preview table labelled screenshots/search.png "Discover Search", which stopped being true when search moved off Discover.
There was a problem hiding this comment.
🔵 Needs a closer look
Search query changes can retain stale pagination state when the first page request fails.
Review details
Suppressed comments (3)
Previously missed (1) — in code that hasn't changed since the last review.
src/PageModels/SearchPageModel.cs:182
- When a new qualifying query is entered, the previous
SearchSectionitems and page cursor remain in place while page 1 is debounced/fetched. If that page-1 request fails,IsSearchingis cleared infinallywithout aSeed/generation reset, so load-more becomes available and calls the delegate with_activeSearchQuery(the new query) and the old cursor, appending page N of the new query to the old results. Invalidate the old pagination on query changes or gate load-more until page 1 has successfully seeded for the current query.
IsSearchActive = true;
IsSearching = true;
HasNoSearchResults = false; // a previous query's empty state must not show under the new fetch
README.md:74
- The README feature list still says Discover includes “debounced search across all of AniList” (line 30), but this PR moves that search UI to the standalone Search tab. Please update that feature description (and mention Search separately) so the navigation change documented here is not contradicted elsewhere in the README.
| Navigation | Shell bottom tab bar + programmatic details routes (`media-details`, `character-details`, `staff-details`, `studio-details`) |
src/PageModels/SearchPageModel.cs:125
- This appear-only check can miss an adult-toggle change that completes after the tab transition.
SettingsPageModelupdatesAppSettings.DisplayAdultContentonly after its 1.5-second auto-save andUpdateUserAsyncsucceeds (SettingsPageModel.cs:458-501); if the user switches to Search before that completes, this call baselines the old value, and the later static-setting update does not trigger anotherOnAppearingAsync, leaving the old result set visible. Propagate the setting change/invalidation to this singleton (or otherwise re-run the query when the save completes), rather than relying only on the next tab appearance.
var displayAdult = AppSettings.DisplayAdultContent;
var isAuthenticated = !string.IsNullOrWhiteSpace(await _authService.GetAccessTokenAsync());
- Files reviewed: 28/37 changed files
- Comments generated: 0 new
- Review effort level: Lite
There was a problem hiding this comment.
🟡 Changes recommended
Resolve the search pagination race and preserve cancellation in AuthService.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (2)
.github/workflows/ci-build-and-preview.yml:545
- When
goto_tab "Settings"fails, this branch only emits a warning and then continues through the unconditional Settings wait/capture below. The current screen is still the details page, so the workflow can publishsettings.pngcontaining the wrong page; gate the Settings polling/capture on a successful tab switch (asDISCOVER_OPENEDdoes) or skip that artifact.
if ! goto_tab "Settings"; then
echo "::warning::Could not reach the Settings tab — Settings screenshot may be incorrect"
fi
README.md:74
- The Features section still describes debounced search as part of Discover, but this PR removes the Discover search UI and moves it to the dedicated Search tab. Update that description as well so the README does not direct users to a feature that is no longer on Discover.
| Navigation | Shell bottom tab bar + programmatic details routes (`media-details`, `character-details`, `staff-details`, `studio-details`) |
- Files reviewed: 28/37 changed files
- Comments generated: 2
- Review effort level: Lite
Same race the Search tab just had, in the two places that share DiscoverSectionFetch. PaginatedSection tracks only its own operations, so a page-model-level reload leaves the section un-busy and Load More still armed. That matters because DiscoverSectionFetch reads AppSettings.DisplayAdultContent live, per page. Scrolling a carousel during an adult-toggle refresh fetches under the NEW filter and appends onto items fetched under the OLD one, mixing 18+ results into a row that was SFW. A successful refresh re-Seeds and the generation bump discards the stray page, but a failed refresh never seeds — and Discover deliberately keeps showing content on refresh failure, so the mixed row is what the user is left looking at. MediaBrowse's page load scope does not cover this ordering either: Begin() cancels the PREVIOUS token, but a Load More started after the reload began shares the reload's token and survives it. Its guard sits in the command body rather than CanExecute because IsBusy changing does not notify the command, and folding it into the predicate risks leaving Load More stuck disabled after a reload. Also documents a driver trap that cost real time here: a plain dotnet build omits EmbedAssembliesIntoApk and leaves a ~19 MB Fast Deployment APK where the ~97 MB one was. Installing it aborts before any managed code with a bare SIGABRT and no .NET stack, which reads exactly like a crash in the change under test.
There was a problem hiding this comment.
🔵 Needs a closer look
Search can mix adult-filter contexts, and Discover’s refresh guard still leaves a pre-busy race.
Review details
Suppressed comments (2)
Previously missed (2) — in code that hasn't changed since the last review.
src/PageModels/SearchPageModel.cs:75
AdultFilteris resolved again for every paged request instead of being tied to the context that produced page 1. Settings auto-save is debounced andPopulateFromUserupdatesAppSettingsafter the user can already have returned to Search, soOnAppearingAsyncmay run before the update; existing results then remain under the old policy and Load More appends a page under the new one. In particular, turning adult content off can leave 18+ page-1 items visible and mix SFW page 2 into them. Snapshot the filter for the active query and invalidate/re-run when the persisted setting changes while this tab is visible.
(page, _, ct) => _aniListClient.SearchAnimePageAsync(_activeSearchQuery, AdultFilter, page, SearchPerPage, ct),
src/PageModels/DiscoverPageModel.cs:131
- This guard does not cover the start of a refresh:
LoadAsyncawaitsGetAccessTokenAsyncat line 172 and only setsIsBusyat line 195. While that await is suspended (notably after sign-out or during expired-token cleanup), a visible row near its threshold can still start Load More under the new viewer/filter context and append it to cached rows from the old context. If the refresh then fails, the mixed row remains—the failure mode this guard is intended to prevent. Mark the refresh as active before its first await, or coordinate paging with a refresh generation/token.
if (IsBusy)
{
return Task.CompletedTask;
- Files reviewed: 29/39 changed files
- Comments generated: 0 new
- Review effort level: Balanced
…window (#116) Two findings from Copilot's latest review, both variations on the same root cause: the adult filter is read live, per page, rather than being fixed to the result set it belongs to. Search now pins it. The toggle does not reach AppSettings when the user flips it — Settings debounces 1500 ms, saves, and only applies the value from the server response — so a user can toggle, return to Search inside that window, have OnAppearingAsync read the OLD value and find nothing to invalidate, and then have the new value land. A live read on the next page would then apply a different policy to results already on screen; turning adult content OFF is the bad direction, leaving 18+ page-1 items visible with SFW pages beneath them. The snapshot is keyed off the raw DisplayAdultContent bool, not the derived filter. The filter's own null means "adult allowed", so it cannot double as "nothing seeded yet" — a null-coalesce would have fallen back to a live read in exactly the adult-enabled case. ResetResults() clears results and snapshot together so the two cannot drift. Discover's Load More guard covered only the window after IsBusy went up, but LoadAsync awaits the auth read before setting it. A row near its threshold could pass the guard during that suspension and append a page fetched under the new context. _refreshEvaluating is raised before the first await, so the whole load is covered; LoadAsync splits into a thin guard plus LoadCoreAsync to get the try/finally without reindenting the body.
|
Both suppressed findings from the last Copilot review (the two under "Previously missed" in the review body, which produced no inline threads) are fixed in f575d36.
The filter is now pinned when page 1 is issued and reused for every later page. One detail worth recording: the snapshot is keyed off the raw
Verified on device: search seeds and pages, re-querying swaps cleanly, Discover pull-to-refresh and carousel paging both still work, and View All still loads more. Build clean at zero warnings, 391/391 tests. Process note for anyone reading later: these two arrived as suppressed comments inside the review body rather than as review threads, so they never appeared as unresolved comments and our open-comments tooling did not surface them. Worth reading the review body directly, not just the thread list. |
There was a problem hiding this comment.
🟡 Changes recommended
Delayed adult-setting propagation can leave stale or mixed-policy results, and concurrent auth loads can overwrite valid state.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
- Files reviewed: 29/39 changed files
- Comments generated: 4
- Review effort level: Balanced
* Extract AniSprinkles.Core as a sibling project (#62) The unit tests could not reach a single PageModel: tests/AniSprinkles.UnitTests link-compiled individual files out of src/, so anything touching Shell, a popup or the icon font was untestable. Every one of the six defects PR #116 found lives in exactly that code, and three of them were regressions introduced by the previous round's fix. Re-measuring the blocker first showed two of the three package restrictions the issue was written around no longer hold: Microsoft.Maui.Controls 10.0.60 and CommunityToolkit.Maui 14.2.0 both ship plain net10.0 assemblies, so Shell, Keyboard, Popup, PopupOptions and ShowPopupAsync all compile off-device. The real blockers were narrower — the icon font, the XAML popup types, and Android. Layout: src/AniSprinkles/ (net10.0-android) and src/AniSprinkles.Core/ (net10.0) are siblings. Core initially sat inside the app project's folder, where the app's default globs swept up 602 of Core's sources plus its obj/ generated assembly attributes and failed as CS0579. DefaultItemExcludes suppresses that, but siblings need no suppression at all. Core holds Models, Utilities, non-platform Services, Converters and every PageModel. It deliberately references neither CommunityToolkit.Maui nor IconFont.Maui.FluentIcons — leaving those out is what stops the new seams eroding. Three seams carry what stayed behind: - IDialogService covers the five XAML popups plus DisplayPromptAsync, implemented by MauiDialogService next to the existing MauiShellNavigationService and MauiUserFeedback. This matters beyond compilation: Shell.Current is null rather than throwing off-device, so a popup call from a PageModel silently no-ops and its test passes without exercising anything. - IExternalBrowser covers the four "view on AniList" links. - Core mirrors the 57 icon glyphs it uses into Icons/Glyphs.cs, generated by tools/generate-glyphs.cs from the package's PE metadata. The package ships platform TFMs only. Also folded in, because the move surfaced them: - OutageStateService called MainThread.IsMainThread, which throws NotImplementedInReferenceAssemblyException off-device; its catch only covered InvalidOperationException, so the comment promising an inline fallback in unit tests was never true. Now uses the injected IDispatcher. - SettingsPageModel read AppInfo.Current in a field initializer, so the type could not be constructed off-device at all. IAppInfo is injected alongside IPreferences. - Four PageModels each carried a private copy of the same toast/snackbar helpers; they now share IUserFeedback. Plain snackbars move 5s -> 4s as a result; the 20s settings save-failure and 10s permission snackbars are preserved through a new optional duration. - Browser-open failures log at Warning rather than Error, matching how MauiUserFeedback treats its own display failures, and so stop raising Sentry events for a device concern. ListEntryStatusFlow becomes an instance singleton so its confirm/rating prompts can go through IDialogService. The tap-suppression window moves to Core as LongPressTapSuppressor; the Android gesture plumbing stays in Views. The test project now project-references Core. All 391 existing tests pass unchanged; Core's internals stay internal via InternalsVisibleTo rather than being widened for tests. * Validate every icon glyph reference against the package (#117) src/AniSprinkles/AppShell.xaml shipped x:Static icons:FluentIconsRegular.Compass24 — the real member is CompassNorthwest24. x:Static is resolved by the XAML loader at runtime, so the build was completely clean and the app crashed on launch with XamlParseException. That one was lucky: AppShell loads at startup, so it failed immediately and unmissably. The same typo on a details page would build, pass tests, pass CI screenshots, and only crash when a user opened that screen. Two things are checked, both driven off the icon assembly's PE metadata: - Every x:Static icon reference in src/**/*.xaml resolves. The xmlns prefix is read from the file rather than assumed to be "icons:", so renaming it cannot quietly switch the test off. - Every constant in Core's mirrored Glyphs table still matches the package by name AND value. Mirroring those glyphs (#62) was only acceptable on the condition that drift becomes a build failure, and this is that condition. PE metadata rather than Assembly.Load: the package targets net10.0-android36.0 and will not load into a net10.0 test host. Two approaches that produced confidently wrong answers on the way here are documented at the call site — substring-matching the DLL reports Compass24 as present because CompassNorthwest24 contains it, and a regex over the #Strings heap silently misses every other name because entries share NUL delimiters. The pinned version is read from whichever project under src/ declares the package, not a hardcoded path. An unresolvable package cache skips (a fresh machine, an unrestored bump); a missing declaration throws, because that is a repo-structure problem rather than an environment gap. Empty-discovery guards keep both theories from passing vacuously. Verified by reintroducing Compass24 (fails, naming the file and suggesting CompassNorthwest24) and by tampering with a mirrored glyph value (fails, printing both escaped code points and the regeneration command). * Add PageModel state-machine tests for the #116 defects (#52 phase 1) The #62 extraction is only worth its diff if the code it unblocked is actually covered. These are the defects PR #116 found across six review rounds — none were reachable by the previous 391 tests, and none are reachable on device either: each needs a specific interleaving that the happy-path pass cannot produce. SearchPageModel: - A failed page 1 on a new query must not re-arm Load More over the previous query's results. The failure clears IsSearching in its finally (that is what stops the spinner), which used to leave the section holding the old items with HasNextPage set — so scrolling appended page 2 of the new query onto the old query's results, one list silently mixing two searches. - Load More must page under the filter page 1 used. The adult filter was read live per page, and Settings debounces 1500ms and only applies the value from the server response, so a user could toggle, return inside that window with nothing detected as changed, and have the new value land in time to page a different policy onto results already on screen. - An adult flip while the first search is still in flight must invalidate. The context used to be recorded on fetch success, so a first search in flight left "nothing searched yet" set and the flip baselined the new context WITHOUT cancelling the old request, whose response then marked itself current forever. - A superseded search resuming late must not clear its successor's spinner. DiscoverPageModel: - Load More must be refused while a refresh is still reading auth. The guard used to cover only the window after IsBusy went up, but LoadCoreAsync awaits the auth read before setting it. Each of these was confirmed to fail against the reverted fix and pass against the current code, so they catch what they claim to rather than merely passing. Also #52's own phase-1 list for MediaDetailsPageModel.LoadAsync (happy path, non-positive id, null media, NotFound hiding Retry, throw keeping Retry, reuse without a second request, in-memory list entry not clobbered) and the reachable SettingsPageModel.LoadAsync branches. SettingsPageModel's authenticated happy path is deliberately absent: it ends in AppSettings.SyncFromViewer, which persists through the static Preferences.Default and throws off-device, so the test would be asserting on the catch block. Giving AppSettings a preferences seam is the open decision on #52 and is noted there. SearchPageModel takes a TimeProvider so its 600ms debounce is deterministic under test rather than a real sleep per case; DiscoverPageModel already took one. Test classes touching the process-wide AppSettings statics now share a non-parallel collection. * Close the biggest remaining test gaps in Core (#52) An audit of the 130 types now in Core against every test file found 56 never mentioned at all. Most are DTOs and fine, but three groups were not. EntryActionCoordinator had zero coverage and is the highest-value thing #62 unblocked: every list surface (My Anime, Discover, Search, View All) routes its long-press flows through it, so one defect surfaces in four places. It was previously unreachable because each entry point opened a popup through Shell.Current, which is null rather than throwing off-device — the flow would no-op and any test of it would pass without executing a decision. Now covered: menu routing and dismissal, the flush-before-flow hook, remove-vs-move branching, rollback of status/progress/score/repeat on a failed move, retry targeting the id captured at failure time, outage suppressing the retry action, id adoption on add-to-list, and the completion flow's re-entrancy guard. Code added in this branch had none of its own. Covered now: the outage/retry rule in UserFeedbackExtensions, MoveToListChoice's two shapes, LongPressTapSuppressor, and OutageStateService — including the dispatcher fallback that replaced the MainThread call whose catch never covered what it threw. MyAnimePageModel's +1 debounce: six taps collapse to one write (the app's largest single rate-limit saving), a failure reverts to before the first tap rather than one step, switching entries flushes the previous one, and reaching a known total routes to the completion flow instead of the debounce. Takes a TimeProvider for the same reason SearchPageModel does — a real 1500 ms sleep per case is neither fast nor deterministic. Plus #52 phase 3 (converters — the Brush-vs-Color target rule that MAUI's Background/BackgroundColor precedence makes load-bearing, hash stability, format glyph mapping) and ImageUrl, where AniList returns a default.jpg placeholder rather than null and a plain null check leaves its grey graphic on screen. Every new behavioural assertion was mutation-checked: the entry-switch flush, revert depth, completion routing, remove-vs-move, the completion guard, the id-less-create throw, and the dropped-dispatch fallback were each broken in turn and confirmed to fail the intended test. Two of those mutations hung the suite rather than failing it, so both tests are now bounded with WaitAsync — a hang in CI reads as an infrastructure problem, not a regression. 680 tests, up from 603. * CI: Update UI screenshots [skip ci] * Make RecordingUserFeedback track the latest snackbar, not the latest with an action PR review (Copilot) on #123. `LastSnackbarAction` was only ever assigned, never cleared, so after a snackbar that offered no action it still held an earlier one's. The underlying mismatch: the property tracked "the most recent snackbar *that offered an action*" — a filtered subset — while `Assert.Null(LastSnackbarAction)` means "the last snackbar offered none", which is a statement about the latest event. Those only agree while at most one snackbar has been shown, which is why no existing test was wrong. It matters on retry chains, which show several. Added the behavioural test that was hiding behind it: a delete that fails, is retried, and fails again into a service outage must stop offering a retry button that cannot work. That test fails against the old double *with correct production code*, which is the whole problem — the double was answering for a snackbar that was not the one under assertion. Doc comment updated to match; the old wording described the old behaviour accurately, so changing one without the other would have swapped a latent trap for a real doc/code mismatch. Considered recording (message, action) pairs instead, which is immune to ordering entirely. Rejected: it churns all 8 assertion sites and turns `Assert.Contains("AniList is Down", feedback.Snackbars)` into a predicate lambda, for precision only needed to assert about a non-final snackbar — which splits into separate tests instead. * CI: Update UI screenshots [skip ci] --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
…I test gates (#118, #121, #122, #124) (#129) * CI: fail the build on skipped or vanished tests (#122) The skipped count was parsed into the job summary and then never acted on, so a run where 190 of 644 tests skipped was a green check with a number in a column nobody reads. That already happened once: IconGlyphReferenceTests skips gracefully when it cannot locate the icon package, and when #62 moved the app csproj out from under that lookup all 190 glyph cases turned into skips. It was caught by eye. Fail the job when any test skips, naming the project and the count, and add a floor on the summed total so tests that VANISH are caught as well as tests that skip -- the same incident also dropped the total by 231, and a stale-assembly run reported 557 against a 644-test suite. Neither shows up as a skip. Both gates only fire when the runner output actually parsed, preserving the existing rule that a format change must never fail CI on its own. The skip check guards on is_count first: in the new-runner branch S falls back to the literal "?" while PARSED is still 1, so a bare -gt would error rather than fail cleanly. Also widens the duration regex to accept seconds. It only matched "N ms", so every run slower than a second has been showing "?" in the summary table. Thresholds start at 0 skips and a floor of 830, against a measured 837 passing. * Redact bearer tokens at the source, not at the sinks (#124) ErrorReportService redacted the string it returned to the on-screen error panel -- the least sensitive sink, on the user's own device -- and handed the raw exception to the two that persist and transmit: the rotating file log and Sentry. The `summary` local was computed, redacted, and then never used, which reads like wiring that got lost rather than a deliberate choice. The vector is live. AniListClient embeds up to 500 characters of the raw response body into the exception message, so an auth-failure body echoing the credential lands in AniListApiException.Message and from there in both sinks. Redact where the text is produced instead, so the token never enters the exception and every downstream consumer is safe by construction. Three sites, not the two the issue named -- graphQl.Errors[0].Message on an HTTP 200 reaches the message the same way the 4xx branch does. Classification runs on the raw text and redaction only on what gets stored: AniListErrorClassifier matches "Invalid token" and the outage markers, none of which the bearer pattern touches today, but keeping the order explicit means a future pattern cannot silently reclassify an error as Unknown. ErrorReportService still hands the raw exception to both sinks on purpose -- rebuilding it for Sentry would cost the stack trace its grouping depends on. SentryScrubber, wired through BeforeSend, covers exceptions Sentry captures without passing through ErrorReportService at all. It materialises SentryExceptions before mutating: the property is typed IEnumerable, so a lazily-projected sequence would hand each enumeration fresh objects and a plain foreach would redact copies that are never sent. Regression tests cover all three message paths and the deferred-sequence case; each fails without the corresponding fix. * Give AppSettings an injectable preferences store (#121) AppSettings read and wrote through the static Preferences.Default, which throws NotImplementedInReferenceAssemblyException on the plain net10.0 TFM the tests build against. That made every path ending in Load/Save/Clear/SyncFromViewer untestable -- the concrete casualty being SettingsPageModel.LoadAsync's authenticated happy path, deliberately left unwritten in #62 with a comment saying why. Keep the static surface and make only the storage injectable. AppSettings stays static for a real reason: Media.DisplayTitle and MediaListEntry.ScoreDisplay consult it, and those are plain deserialized POCOs that DI never constructs. Full IAppSettings injection stays available later (#52). No MauiProgram wiring. Preferences.Default is safe as a field initializer -- verified against Microsoft.Maui.Essentials 10.0.60 that the Default getter returns an implementation off-device and only Get/Set/Remove throw -- so the initializer IS the shipping behaviour and production is unchanged. The seam stays internal; InternalsVisibleTo("AniSprinkles.UnitTests") already exists. TestDataBuilder.ResetAppSettings now installs a dictionary-backed FakePreferences and returns it. Every class that calls it is already in AppSettingsCollection, which serialises writes to these process-wide statics. Unblocks the SettingsPageModel authenticated path, the "exception with cached data stays Content" case from #52, and round-trip coverage of the persistence itself. * Commit the adult-content setting immediately, and pin paging to it (#118) DisplayAdultContent is what every browse surface filters on, but it was not written when the user flipped the toggle -- SettingsPageModel debounced 1500 ms, saved to AniList, and the value only reached AppSettings when the server response was applied. Turning 18+ content off and tabbing to a browse surface inside that window meant the surface read the old value, cache-hit, and left the 18+ results on screen until a whole tab cycle later. Commit it locally the moment the toggle flips instead. That removes the window rather than reacting to it: a browse surface can only appear after the user leaves Settings, so the invalidation checks those surfaces already have start working with no new machinery. The issue proposed a static change notification with three subscribers. Dropped: with an immediate commit there is no remaining staleness for it to fix, and MediaBrowsePageModel is registered transient, not singleton as the issue assumed -- a static event would leak one page model per View All navigation. Second defect, same root cause: DiscoverSectionFetch.PageAsync resolved the static per page, so once a commit landed while Discover was on screen the next Load More fetched under the new policy and appended onto the old one, mixing two policies into one row. The #116 guards do not cover it because no reload is involved. It now takes the seeded policy as a parameter. Library was a fourth affected surface the issue did not list, and the worst of them: its refresh short-circuit weighed only auth and a five-minute freshness window, never the setting, so tabbing away and back would not clear it either. Committing locally then exposed a further hole -- MyAnimePageModel.LoadAsync syncs preferences from the viewer, whose copy is still the old one inside the debounce, so a Library refresh reverted the toggle app-wide. Fixed from both ends: SettingsPage.OnDisappearing flushes a pending save on navigate-away (worth having regardless -- a change made and then backgrounded was previously lost with the debounce), and AppSettings shadows DisplayAdultContent from viewer syncs until the save is confirmed. The flush alone is not sufficient: Shell does not guarantee OnDisappearing precedes the next page's OnAppearing, and a save can fail, leaving the server genuinely stale. Every fix here landed test-first, each failing red for the expected reason before the change. * CI: canary fixture that fails the build if the adult filter breaks The adult-content filter was never exercised end to end. The CI stub carried no flagged fixture and ignored the isAdult argument entirely, so DiscoverSectionFetch, the browse/search queries and MediaListSectionsMerger could all have broken without changing a single screenshot -- which is exactly where #118's two bugs lived. Seed one fixture flagged IsAdult, titled "18PLUS CANARY - FILTER FAILED", into both the stub list and the browse results. It carries no adult content: the title is a marker and it has no cover image, so a leak renders the app's own placeholder next to a shouted label. The stub viewer leaves DisplayAdultContent off and nothing in CI turns it on, so every surface must filter it out. For that to mean anything the stub has to model the filter, so CIAniListClient now honours the contract the real client relies on -- false = SFW only, true = 18+ only, null = unfiltered -- across browse, search and the Discover rows. The canary lives in its own list rather than carrying a flag because RelatedMedia has no IsAdult: browse filtering is entirely server-side, so the client never receives the field, which is precisely why the stub must model it. The workflow dumps the UI after Library, Discover, View All and Search, and fails the job if the canary appears -- last, so the screenshots and logcat are still uploaded for diagnosis. An unreadable dump is a warning only; a flaky emulator must not fail the build on its own. The gate greps for a literal, so renaming the fixture would leave it matching nothing and passing forever, which is the failure #122 exists to prevent. The workflow therefore also asserts the marker still appears in CIAniListClient.cs and fails fast if it does not. Existing screenshots are unchanged: the toggle stays off, so every surface asks for isAdult false and the canary is filtered everywhere. * CI: Update UI screenshots [skip ci] * Don't treat every viewer response as confirming a pending adult-content change (#129 review) PopulateFromUser cleared the pending marker on any viewer response. That is only true for the reply to our own save: a fresh load just asks the server, which is still behind while the save is in flight and permanently behind if it failed. Worse, the guard was bypassed before it was ever consulted. PopulateFromUser assigns the bound DisplayAdultContent property, which runs the changed handler and writes straight through to AppSettings -- 23 lines before SyncFromViewer's check. So returning to Settings inside the save window stamped the server's stale value over the choice the user had just made, and the toggle flipped back on. Confirm by comparison instead. The marker now clears exactly when the server reports the value we are holding, whichever response brought it, and PopulateFromUser routes its assignment through ResolveDisplayAdultContent so the toggle and the static can never disagree. That drops ConfirmDisplayAdultContentSaved entirely -- the invariant is self-resolving. Reported by Copilot on #129. * CI: Update UI screenshots [skip ci] * Correct the bearer-regex character-class comment, and test what it claims (#129 review) The comment described the class as "the unreserved URL set plus the base64url padding a JWT can end on", which omits + and / entirely and files them under a label that does not apply -- those are standard-base64 characters, and base64url substitutes - and _ for them. The regex is right and unchanged: carrying both alphabets means a token is scrubbed whichever encoding it arrives in. Only the description was wrong, and a wrong description on a credential-scrubbing pattern invites someone to "fix" it by narrowing it. Say what the class actually covers, say why it spans both alphabets, and add a theory that exercises each so the claim is enforced rather than asserted. Reported by Copilot on #129. * CI: Update UI screenshots [skip ci] --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
#133 review) FakeSecureTokenStorage locked its read-tracking state but not the backing dictionary, which Seed, SetAsync, Remove and GetAsync all touch. No test races on it today -- the sign-in and sign-out cases write while the reader is parked on its hold and release only afterwards, and the genuinely concurrent case is two readers, which Dictionary handles. But that safety is incidental, resting on an unwritten "no test writes while a reader is unparked" rule, inside the one fake whose whole job is making concurrency deterministic. Everything now goes through the existing _sync lock, taken after the await and never across it. AuthService logged "absent (no token in SecureStorage)" for TokenState.Absent, which TokenStore also returns when the read threw. Collapsing those is deliberate (#116) because callers act identically, but the message asserted a cause it did not know, and the traces here are a documented diagnostic surface. Now "absent (no usable token)"; a failed read still logs its own Error line with the reason.
…ability (#119, #127, #128) (#133) * Single-flight the token load behind a testable seam (#119) AuthService is a singleton and its token load had no synchronization, so two callers arriving before the first load completed both entered it. Since #116 that load has a fallback catch treating an unreadable token as "signed out" -- correct for one caller, destructive for two: a caller whose read failed cleared the token a concurrent caller had already published, and anything sampling auth in between rendered a signed-in user as signed out. Token state, the load gate and the expiry check move to a Core TokenStore behind an ISecureTokenStorage seam, with MauiSecureTokenStorage alongside the other adapters in Services/Maui/. AuthService keeps the platform half -- the OAuth round trip and the Android cookie store -- which is what pinned it to the app project that tests/ cannot reference. IAuthService is unchanged, so CIAuthService and SimAuthService need no edits. Two corrections to the fix proposed on the issue, both found by the tests: - The double-check is on a separate _loaded flag, not on "is the token null?". The token is also null for a signed-out user, so a null re-test is still true for the second caller and both read -- failing the first acceptance criterion. - Both values are read into locals and published together. LoadAsync assigned the token one line before reading the expiry, so a concurrent caller could observe a token whose ExpiresAt had not loaded -- and a null expiry reads as "not expired", so it would accept a token the load was about to reject. State is guarded by a plain lock rather than the async gate, because sign-in and sign-out publish without going through the load at all; the load yields to whatever they published rather than overwriting a newer decision. The lock is never held across an await, so it cannot deadlock the UI thread SignOutAsync runs on. All three acceptance criteria are now tests. Each was written first and watched fail against a faithful port of the old behaviour. * Re-render display settings on the surfaces already showing them (#127) Title language and score format feed computed properties -- Media.DisplayTitle, MediaListEntry.ScoreDisplay, the details rating control -- and nothing re-evaluated when the user navigated back, so bound labels kept the old text indefinitely. Unlike the adult toggle (#118), these change how already-fetched items render rather than which items exist, so the answer is a re-projection, not a refetch. Each surface snapshots a DisplaySettingsSnapshot and re-projects when it moved. No AniList request is added anywhere. Media and RelatedMedia carry DisplayTitle but are plain classes and cannot raise PropertyChanged, so the observable containers implement IDisplayProjection and re-raise the property holding them (Media / Node); MAUI then re-resolves the whole binding path. A carousel item type that shows a media title must implement it or its cards render stale titles forever with nothing to catch it. The hook differs by page kind, and this is the part that shipped broken and was caught on device. Tab-root pages use OnAppearing. The five pushed pages -- the four detail pages and View All -- get no OnAppearing when their tab becomes current again, because Shell gives a page in a backgrounded navigation stack no appearing/disappearing on a tab switch. Measured across two tab round-trips: OnAppearing 1 (initial navigation only), OnDisappearing 0, OnNavigatedTo 3. They call ViewModel.RefreshDisplaySettings() from OnNavigatedTo instead. The reuse-guard call in LoadCoreAsync stays as well, since a sort popup closing does fire OnAppearing and reaches the load path; the check is idempotent so both is free. The tests drove the page model through LoadAsync, which is precisely the call the real app never makes on a tab return -- they passed while the feature was dead. They now go through RefreshDisplaySettings(). No test layer we currently have could have caught this; see #131. Also: title language moves the Title sort order, not just the text, because MediaListSection orders by DisplayTitle. Staff name language is out of scope -- it is read by nothing today (#130). * Stop discarding settings changes that failed to save (#128) c4a2830 kept a locally changed DisplayAdultContent ahead of the server until the server confirmed it. The marker was scoped to that one field, so every other setting still reverted: a failed save left the server reporting the old value, and the next visit to Settings assigned it straight back over the user's choice with nothing said. The setting called out as the worst case for this had become the only one protected. The guard now covers every user-editable setting. Title language, score format and adult content keep their markers in AppSettings, because MyAnimePageModel calls SyncFromViewer directly and has to honour them without going through the Settings page at all; staff name language, restrict-messages, activity merge time, airing notifications and the per-type notification toggles keep theirs on the page model. The per-type ones are a set of unconfirmed types rather than one flag, so a change made on another device still arrives for every type the user did not touch. AnimeSectionOrder deliberately has none -- there is no control for it, so it can only ever come from the server. Title language and score format now also commit locally the moment they are picked, the way the adult toggle does. Before, they reached AppSettings only once a save succeeded, so the choice took 1.5s to reach the rest of the app and was lost entirely if the save failed. Dirty-tracking is baselined against what the server reported rather than the resolved local value, so an unsent change leaves the page dirty and the next flush re-sends it. A successful UpdateUser clears the markers for the values it actually carried, compared field by field -- the user can change a setting while a save is in flight, and clearing that one would discard a change the server never saw. Without that, a server which quietly declined a value would leave it pending and the page permanently dirty, re-sending a rejected change on every navigate-away. Two silent drops alongside it. SaveSettingsAsync returned immediately when IsSaving without scheduling anything, so a Retry tap or a navigate-away flush landing mid-save vanished; it now coalesces into a second pass. And the failure snackbar built its own retry action instead of going through ShowFailureSnackbarAsync, so a ServiceOutage kept offering a Retry that cannot succeed for minutes or hours. Also fixes an orphaned WorkManager job, pre-existing and unrelated to saving: PopulateFromUser scheduled the airing check when the toggle landed on but never cancelled it when it landed off, so turning airing notifications off anywhere else left this device still scheduled -- the switch read off while notifications kept arriving. Verified on device against the real API: flush fires 33ms after a tab switch rather than on the debounce; a real network failure classifies as Network, retries once, then surfaces "No Internet Connection" with Retry; the local value persists to SharedPreferences through the failed save; a successful viewer fetch reporting the stale value does not revert it; the change is re-sent on the next flush; and CancelPeriodicCheck genuinely removes the job from the system scheduler. * Document the lifecycle asymmetry and the seams these changes added The Shell lifecycle note is the one that matters: OnAppearing fires on tab-root pages but not on a page pushed onto a backgrounded tab's stack, so anything that must re-evaluate when the user returns to a detail page has to hang off OnNavigatedTo. That fact cost a shipped-but-dead feature this round and no test layer can surface it, so it belongs somewhere a reader will hit before making the same assumption. See #131 and #132. Also records the generalised pending-save guard, the display re-projection contract, the airing job following the toggle in both directions, TokenStore and ISecureTokenStorage in the DI table, SecureStorage in the list of Essentials statics that throw off-device, and why ConfigureAwait(true) is written explicitly in page models -- it is the default, so it documents a requirement rather than changing behaviour. * Reset the pending markers between tests, and silence xUnit1051 Two CI failures, neither reproducible locally by running the suite. SettingsPageModelTests failed asserting Point10Decimal and getting Point100. The pending-upstream markers #128 added are process-wide statics, and TestDataBuilder.ResetAppSettings reset the four value properties without touching them. A test that changed a setting locally left a marker armed, so the NEXT test's SyncFromViewer kept the stale local value instead of taking the server's. SettingsSaveDurabilityTests sets a score format, so whether this bites depends purely on ordering within the shared collection -- it ordered that way on CI and not here. ResetAppSettings now goes through AppSettings.Clear(), which resets the markers as well, and a regression test arms all three and asserts a following SyncFromViewer still follows the server. Separately, 15 xUnit1051 warnings in TokenStoreTests: calls accepting a CancellationToken should pass TestContext.Current.CancellationToken. Missed because the local test runs were filtered for failures and errors and never for warnings -- the zero-warning checks only ever covered the app project. * CI: Update UI screenshots [skip ci] * Record that the zero-warning gate covers the test project too The claim was being checked against the app project alone, which does not compile tests/, so xUnit analyzer warnings reached a PR while the builds were reported clean. Lists all five targets, and notes the matching trap alongside it: a suite that is green locally can still fail on CI when the failure depends on ordering within the shared AppSettings collection, so process-wide state added to those statics has to be reset in TestDataBuilder.ResetAppSettings. * CI: Update UI screenshots [skip ci] * Guard the fake's dictionary, and stop the absent log asserting a cause (#133 review) FakeSecureTokenStorage locked its read-tracking state but not the backing dictionary, which Seed, SetAsync, Remove and GetAsync all touch. No test races on it today -- the sign-in and sign-out cases write while the reader is parked on its hold and release only afterwards, and the genuinely concurrent case is two readers, which Dictionary handles. But that safety is incidental, resting on an unwritten "no test writes while a reader is unparked" rule, inside the one fake whose whole job is making concurrency deterministic. Everything now goes through the existing _sync lock, taken after the await and never across it. AuthService logged "absent (no token in SecureStorage)" for TokenState.Absent, which TokenStore also returns when the read threw. Collapsing those is deliberate (#116) because callers act identically, but the message asserted a cause it did not know, and the traces here are a documented diagnostic surface. Now "absent (no usable token)"; a failed read still logs its own Error line with the reason. * CI: Update UI screenshots [skip ci] --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
…ge (#125, #132, #130) (#135) * Replace ErrorSim with runtime fault injection that composes with the CI fixtures (#125) ErrorSim could not test the thing it existed to test. It replaced the client rather than decorating it, so `FailingAniListClient` answered all 23 interface methods with `throw` and every call failed — you could never reach the screen whose error state you wanted to see. That is why the details pages' error and retry states had never been exercised on a device. Two seams instead, sharing one disarmed-by-default `FaultState`: - `FaultInjectingAniListClient` decorates whichever client DI selected, so it composes with the CI fixtures: a real screen loads and the *next* call breaks. `scope next` is what makes Retry genuinely recover. - `FaultInjectingHttpHandler` sits innermost in the pipeline, so a synthetic 429 or 503 is processed by the real `AniListRateLimitHandler`, `LoggingHandler`, `SendAsync` retry-once and `AniListErrorClassifier`. A profile names which layer it fires at; both seams share one state, so without that tag a single armed fault would fire twice for one logical call. `Delay` is independent of failure — latency with no error kind is the only way to open the cancellation and interlock windows that #116's defect family lives in. Scopes are deterministic only: a fault you cannot re-run is not a fixture. Armed over adb through an attribute-generated `BroadcastReceiver` and `driver.ps1 fault`, so changing what fails costs a broadcast rather than a ~3 minute rebuild. Everything is behind `#if DEBUG`, including the exported receiver, which is why `-p:ErrorSim=true` and its Release guard are gone. The decorator clears an outage banner it raised once a call succeeds. Caught on device: the banner is sticky and normally clears via `AniListClient`'s `ReportSuccess`, which never runs behind the fixtures, so an injected outage pinned it for the session and recovery looked broken. * Cancel in-flight work when a pushed page's tab is switched away (#132) `OnDisappearing` never fires on the five pushed pages when the tab changes, so `ViewModel.CancelInFlight()` and `_loader.OnDisappearing()` simply did not run. Tab away from a details page mid-load and the fetch, plus any Load More, ran to completion against AniList — spending rate-limit budget on a page the user had left — and `PageLoadScope` was never cancelled, making the guards written against it inert on that path. Measured on device rather than assumed. The navigation hooks are a strict superset of the appearing hooks: they fire everywhere those do, plus the two tab-switch cases where those do not. path OnAppearing OnDisappearing OnNavigatedTo OnNavigatedFrom initial navigation yes - yes - tab away (pushed page) - NO - yes tab back (pushed page) NO - yes - forward nav to sub-page - yes - yes back nav from sub-page yes - yes - sort popup open - yes - yes sort popup close yes - yes - tab-root page (Settings) yes yes yes yes So the whole lifecycle moves to `OnNavigatedTo`/`OnNavigatedFrom`, leaving the popup, forward-nav and back-nav paths behaving exactly as before. The pair has to stay together. `DeferredContentLoader.OnDisappearing` clears `_hasAppeared`, which gates both `IsCurrent` and `TrySchedule`, so moving the cleanup without a matching re-arm would latch the loader off after a single tab round-trip and leave the page on its spinner forever — worse than the bug. Verified on device with an armed delay fault: a load cancelled at 6308ms of an 8000ms delay on tab-away, and tabbing back re-armed and completed it. Tab-root pages get the full set and are unaffected, so `SettingsPage`'s pending save flush (#118, #128) still runs. * Render staff and character names from userPreferred (#130) Staff Name Language was saved to AniList and read by nothing: both accessors were `Name?.Full ?? Name?.UserPreferred ?? ...`, so `Full` always won and every staff and character name rendered identically whatever the viewer had picked. The issue proposed composing the name locally from `first`/`last`. That was implemented, then abandoned on evidence gathered against a real account: - `full` is NOT a stable western-order field. AniList resolves it server-side against the viewer setting, exactly like `userPreferred`. Staff id 113181 is "Taiki Kawakami" unauthenticated and "Kawakami Taiki" on an account set to ROMAJI. Composing Romaji Western from `full` therefore renders family-first for those users — the app could not have shown western order at all. - AniList is not internally consistent. Under ROMAJI a Latin-script name comes back as full="Bairstow Caitlyn" but userPreferred="Caitlyn Bairstow"; `userPreferred` is script-aware and `full` is not. Any local `last first` rule diverges from anilist.co for every western voice actor, and matching it would mean inventing a CJK heuristic and hoping it keeps tracking theirs. So the whole question defers to `userPreferred`, falling back to `full` then `native`. All eleven `name { ... }` selections request it — the issue named two; the other nine are every name appearing in a list rather than as a page hero, and would have been left behind by either proposed option. The cost is that `userPreferred` is fixed at fetch time, so a change needs a refetch rather than a re-projection. `IAniListClient.InvalidateEntityCache()` drops the cached character/staff/studio reads; pages reload lazily as the user navigates back to them rather than firing a burst on a settings tap. It fires for an upstream change too — the website or another device — which arrives through `PopulateFromUser`, not the changed handler. Also fixes `CIAniListClient.UpdateUserAsync`, which returned the untouched static viewer instead of echoing the request, so every Display Preferences change reverted on the next Settings load and the whole section was unverifiable in a CI build. `DisplayAdultContent` stays unechoed so the adult-content canary cannot be flipped from inside the app. The native-script subtitle under the hero is suppressed when it would just repeat the name above it, which happens once the setting is Native. * CI: Update UI screenshots [skip ci] * Document that the fault op means a different thing per layer (#125, PR review) `fault <op>` was documented everywhere as an `IAniListClient` method prefix. That is only true at the client seam. The HTTP seam parses the GraphQL `operationName` out of the request body, because that is all it can see — so `fault GetStudio ... -layer http` matched nothing and looked like a broken seam rather than a targeting mistake. Every HTTP scenario in the device pass used `op any`, which is why this was not caught during verification. No normalisation is attempted, because none would work. Stripping `Get`/`Load`/`Async` lines up `GetStudioAsync` with `Studio`, but the namespaces genuinely diverge elsewhere: `GetMyAnimeListAsync` is `MediaListCollection` over the wire and `SearchAnimePageAsync` is `Search`. Partial magic that covers most operations and silently fails on the rest is worse than none. So the rule is stated in all five places that document it (driver help, /run-anisprinkles, DEVELOPER_NOTES, AGENTS.md, and FaultProfile's XML doc), and the handler now logs `FAULT http no match` naming the operation it actually saw when an armed targeted profile misses — the failure diagnoses itself instead of looking like nothing happened. Only reachable with a targeted Http profile armed, so it cannot flood the log. Two tests pin the distinction so nobody "fixes" it by normalising one side. * CI: Update UI screenshots [skip ci] * Pin FaultState.Decide's atomicity under contention (#125, PR review) A review comment claimed `lock (_gate)` on a `System.Threading.Lock` boxes a new object per use and therefore synchronizes nothing. It does not — `Lock` is a sealed class, and C# 13 lowers `lock` on it to `using (x.EnterScope())` rather than `Monitor.Enter`. Converting one to `object`, which the comment suggested as the fix, is the case warning CS9216 exists to catch. No production change; these tests make the answer checkable rather than argued, and guard an invariant worth guarding on its own. `Decide` is a read-modify-write on the hit counter reached from the UI thread and from HTTP continuations on pool threads, and every scope's meaning rests on it being atomic: `next` must fire once however many callers race, `firstn:N` must affect exactly N. Confirmed the tests are not vacuous by removing the lock from `Decide` and re-running — `firstn` fails, because lost increments let extra callers slip under the threshold. * CI: Update UI screenshots [skip ci] --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
* Replace hamburger flyout with a bottom tab bar (#43 phase 1) Five tabs — Library, Discover, Search, Feed, Settings — replacing the three flyout items. Routes are unchanged (my-anime, discover, settings) and search and feed are added, so nothing that navigates had to change. The Library tab holds two ShellContents, which Shell renders as a native swipeable top strip: anime (MyAnimePage) and manga (a placeholder until #12). Both halves title the nav bar "Library" and the strip disambiguates, so the bottom tab, nav bar and strip all agree. Their rainbow accents are pinned via ConverterParameter rather than derived from the title text, so anime stays green and manga blue despite sharing a title. Selected tabs render the Filled glyph and unselected the Regular one. Shell has no per-state icon property — Android draws the bar through BottomNavigationView and Shell maps a single Icon — so AppShell swaps it on Navigated, building both ImageSources per tab once instead of allocating on every tap. Search and Feed ship as stub pages with no PageModels; phase 2 moves the search already built into Discover onto the Search tab. driver.ps1: goto is now a plain tab-label tap and works from inside a pushed details stack, search is a shortcut for it, and flyout is gone. The in-page toolbar icons lost the hamburger they used to mirror for coordinates, which the skill's gotchas now say explicitly. Verified on device: labels do not truncate at five tabs, detail-page content clears the bar without extra padding, and tab labels are real uiautomator nodes so navigation needs no coordinate tricks. The CI screenshot job still drives the flyout and is rewritten in phase 2. * Move search from Discover onto its own tab (#43 phase 2) Search shipped inside Discover behind a toolbar toggle (#16). The Search tab needs it standalone, so SearchPageModel takes over the debounce, the generation guarding and the paginated results, and Discover keeps only its section rows. The extraction is larger than the search block itself because search was coupled to Discover in two places that do not survive separation: - Discover's LoadAsync cleared the search whenever auth or the adult toggle flipped. SearchPageModel now runs that check against its own results in OnAppearingAsync, since there is no load here to fold it into. - Discover's long-press write-back walked Rows.Concat(SearchSection.Items) so a status chip stayed consistent wherever that media appeared. SearchPageModel carries its own EntryActionCoordinator and writes back over its results. Auth is baselined on appear rather than recorded per search: doing it inside the fetch's try meant a token refresh throwing after a good fetch would report "Search failed" for a search that had actually succeeded. Appear-time is enough, because signing in or out means visiting Settings and coming back. The page skips the deferred content host that Discover and My Anime use. That pattern keeps a heavy InitializeComponent off the UI thread during the tab transition; an Entry plus one CollectionView does not need it. The singleton keeps the query across tab switches on purpose — returning to the tab should show what you were looking at. A dedicated tab also has no section rows to fall back on, so it gains an idle prompt the Discover version never needed. CI: the screenshot job navigated by opening the flyout and, for the search icon, by mirroring the hamburger's x across the screen width because MAUI toolbar icons expose no uiautomator node. Tab labels are real nodes, so all of that collapses into goto_tab — 61 lines lighter. goto_tab deliberately propagates the tap's exit status rather than the trailing sleep's, so a missed tab skips the screenshots that depend on it instead of capturing the wrong screen. * CI: Update UI screenshots [skip ci] * CI: relabel the Library screenshot after the tab rename The nav title reads 'Library' now, so the PR preview table calling that screenshot 'My Anime' no longer matches what it shows. Filename stays my_anime.png so existing committed screenshots are not orphaned. * CI: Update UI screenshots [skip ci] * PR feedback: close three races and relabel the Search screenshot (#116) Search context is now recorded when the fetch is issued, not when it lands. Recording on success left _hasSearchedThisSession false while the first search was in flight, so a user who tabbed away, flipped the adult toggle and came back hit OnAppearingAsync's "nothing to invalidate" branch — which baselined the new context without cancelling the old request. That response then landed and was marked current, and no later appearance would invalidate it. Recording at issue time routes that user through the normal path, which cancels and re-runs. Load More is gated on !IsSearching. Between the debounce firing and page 1 landing, the previous query's items are still on screen with HasNextPage set, so scrolling to the threshold fetched page 2 of the NEW query onto the OLD results. A successful Seed bumps the section generation and discards that, but a failed page 1 never seeds and the mixed list stayed visible. AuthService.LoadAsync and the expiry-triggered SignOutAsync are guarded. SecureStorage sits on the Android keystore and can fail for reasons unrelated to us; every tab page model calls GetAccessTokenAsync from an async void OnAppearing, where nothing catches. An unreadable or un-clearable token is functionally an absent one, so both paths fall back to signed out. Explicit sign-out still surfaces its failures. CI: the preview table labelled screenshots/search.png "Discover Search", which stopped being true when search moved off Discover. * CI: Update UI screenshots [skip ci] * Gate Load More on a reload in flight for Discover and View All (#116) Same race the Search tab just had, in the two places that share DiscoverSectionFetch. PaginatedSection tracks only its own operations, so a page-model-level reload leaves the section un-busy and Load More still armed. That matters because DiscoverSectionFetch reads AppSettings.DisplayAdultContent live, per page. Scrolling a carousel during an adult-toggle refresh fetches under the NEW filter and appends onto items fetched under the OLD one, mixing 18+ results into a row that was SFW. A successful refresh re-Seeds and the generation bump discards the stray page, but a failed refresh never seeds — and Discover deliberately keeps showing content on refresh failure, so the mixed row is what the user is left looking at. MediaBrowse's page load scope does not cover this ordering either: Begin() cancels the PREVIOUS token, but a Load More started after the reload began shares the reload's token and survives it. Its guard sits in the command body rather than CanExecute because IsBusy changing does not notify the command, and folding it into the predicate risks leaving Load More stuck disabled after a reload. Also documents a driver trap that cost real time here: a plain dotnet build omits EmbedAssembliesIntoApk and leaves a ~19 MB Fast Deployment APK where the ~97 MB one was. Installing it aborts before any managed code with a bare SIGABRT and no .NET stack, which reads exactly like a crash in the change under test. * CI: Update UI screenshots [skip ci] * Reset search results on query change; rethrow cancellation in AuthService (#116) The !IsSearching gate added earlier only closed half the window. A failed page 1 never seeds, but the finally block still clears IsSearching, so Load More came back armed while the section still held the PREVIOUS query's items and HasNextPage — and _activeSearchQuery had already moved on. Scrolling then fetched page 2 of the new query onto the old results: one list silently mixing two searches, with nothing on screen to say so. Resetting the section when a qualifying query starts removes the stale items outright, so CanLoadMore stays false until a successful Seed for the current query. That makes the in-flight check redundant, so it goes. The cost is that the list blanks through the debounce instead of holding the old results; the spinner covers that gap. AuthService rethrows OperationCanceledException ahead of both broad catches. The mechanism a reviewer described does not exist today — LoadAsync never passes its token to SecureStorage, and ISecureStorage.GetAsync has no overload taking one — but the detail page models do pass a PageLoadScope token into GetAccessTokenAsync and expect navigating away to cancel rather than report "signed out" and wipe the shared auth state. The sign-out path is the more exposed of the two, since it drives the Android CookieManager through MainThread.InvokeOnMainThreadAsync. * CI: Update UI screenshots [skip ci] * Capture the auth flag at search-issue time alongside the adult flag (#116) Both halves of the search context now describe the same moment, rather than the adult flag coming from issue time and auth from whenever the page last appeared. The asymmetry was defensible — OnAppearingAsync baselines auth before any search can be issued, since the page must appear before the user can type — but it made the invariant depend on an ordering argument rather than on the code, which is the kind of thing that quietly stops being true. The read sits outside the fetch's try on purpose: that catch reports "Search failed", and a token read blowing up must not be shown to the user as a failed search. A failure keeps whatever OnAppearingAsync last recorded rather than guessing, since a wrong value either strands stale results or forces a pointless refetch. The new await is also a suspension point, so a superseded search now bails before spending the request instead of after it. * CI: Update UI screenshots [skip ci] * driver: uninstall before a doomed install, and report why one failed Cmd-Install's failure path built its diagnostic with `(AdbOut df /data) -join`, and AdbOut returns $null when the device is unreachable — so the interesting case, an install that actually failed, reported "You cannot call a method on a null-valued expression" and swallowed both the adb output and the free space. Every capture is @()-wrapped now, and the message carries what adb said. Install also checks free space up front and drops the old copy when it is short, rather than finding out through a failed install and retrying. The uninstall costs seconds; the failed install costs a full cycle. Documents the two habits that cost the most time in practice: build the Android head only through driver.ps1 build (a plain dotnet build silently swaps the deployable APK for a Fast Deployment one, and dotnet test never needs the Android head at all), and never chain a build with device driving in one shell call, where a single stalled step takes the whole timeout and the finished steps with it. * CI: Update UI screenshots [skip ci] * Route install through the serial-aware wrapper; guard the auth write (#116) Cmd-Install called `& $Adb` directly in all four places, bypassing the `Adb` wrapper that adds `-s $script:Serial` from Resolve-Target. With ANDROID_SERIAL set or two devices attached, the free-space check could read one device while the install targeted another, or adb would fail outright on "more than one device" — in a driver whose documented behaviour is that every command targets one device. One of those four calls was added by the low-space check in this PR; the other three predate it. Verified by running install with ANDROID_SERIAL set. SearchPageModel assigned _searchedAuthenticated before checking the token, so a superseded search resuming after a newer one had already recorded its context could clobber it with an older read. Narrow — the only way auth flips without leaving the tab is token expiry, and the reachable direction costs an extra refetch rather than showing stale results — but the value is now captured into a local and only written once the token is confirmed still active. The adult flag and _hasSearchedThisSession need no such guard: they are written before any await, so issue order already decides them. * CI: Update UI screenshots [skip ci] * Filter the auth cancellation rethrow to the caller's own token (#116) The rethrow added earlier was unconditional, which turned a survivable cleanup failure into a crash. Ten call sites across six page models call GetAccessTokenAsync with no token at all, from async void OnAppearing paths where nothing catches — and SignOutAsync drives the Android CookieManager through MainThread.InvokeOnMainThreadAsync, which can surface a cancellation of its own during teardown. Before the rethrow, the broad catch swallowed that. After it, the exception escaped into the UI lifecycle. Both catches now filter on cancellationToken.IsCancellationRequested, so only the caller's own cancellation propagates. The detail page models that pass a PageLoadScope token keep the behaviour the earlier review asked for; everyone else gets the failure handled locally, as before. Worth recording that the previous round's reassurance on this was wrong: the claim was that nothing could cancel these calls because they pass no token, but an unconditional rethrow does not care where the cancellation came from. * CI: Update UI screenshots [skip ci] * CI: never publish a stale screenshot; align the docs with the tab structure (#116) The screenshots directory is wiped before capture. The checkout carries the previous run's screenshots because they are committed to the branch, so any capture that failed silently left last run's PNG on disk and the publish step embedded it as current. A missing screenshot is obvious; a plausible-looking stale one is not. Search moves out of the DISCOVER_OPENED guard. It has been its own tab since phase 1, but the capture stayed nested where the flyout-era code had put it, so one failed Discover tap skipped Search too — and combined with the stale-image problem above, that published the previous run's Search screenshot as if it were this run's. goto_tab works from anywhere, so there is nothing to unwind first. The Settings capture is gated on reaching the tab, as Discover already was. On a missed tab we are still on the staff details page, and capturing anyway filed that as settings.png. The commit that added goto_tab claimed a missed tab would skip its dependent screenshots; that was only true for Discover. Docs: README labelled the plain `dotnet build` as "Debug APK", which is the exact command the driver skill now warns produces a non-installable Fast Deployment package — so the repo pointed developers at the artifact the warning is about. Both README and AGENTS now separate the compile-only build from the deployable one. README's screenshot column also still said "My Anime" over an image reading "Library", and sold search as a Discover feature rather than its own tab. * CI: Update UI screenshots [skip ci] * Pin the adult filter to the result set; close the pre-IsBusy refresh window (#116) Two findings from Copilot's latest review, both variations on the same root cause: the adult filter is read live, per page, rather than being fixed to the result set it belongs to. Search now pins it. The toggle does not reach AppSettings when the user flips it — Settings debounces 1500 ms, saves, and only applies the value from the server response — so a user can toggle, return to Search inside that window, have OnAppearingAsync read the OLD value and find nothing to invalidate, and then have the new value land. A live read on the next page would then apply a different policy to results already on screen; turning adult content OFF is the bad direction, leaving 18+ page-1 items visible with SFW pages beneath them. The snapshot is keyed off the raw DisplayAdultContent bool, not the derived filter. The filter's own null means "adult allowed", so it cannot double as "nothing seeded yet" — a null-coalesce would have fallen back to a live read in exactly the adult-enabled case. ResetResults() clears results and snapshot together so the two cannot drift. Discover's Load More guard covered only the window after IsBusy went up, but LoadAsync awaits the auth read before setting it. A row near its threshold could pass the guard during that suspension and append a page fetched under the new context. _refreshEvaluating is raised before the first await, so the whole load is covered; LoadAsync splits into a thin guard plus LoadCoreAsync to get the try/finally without reindenting the body. * CI: Update UI screenshots [skip ci] --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
* Extract AniSprinkles.Core as a sibling project (#62) The unit tests could not reach a single PageModel: tests/AniSprinkles.UnitTests link-compiled individual files out of src/, so anything touching Shell, a popup or the icon font was untestable. Every one of the six defects PR #116 found lives in exactly that code, and three of them were regressions introduced by the previous round's fix. Re-measuring the blocker first showed two of the three package restrictions the issue was written around no longer hold: Microsoft.Maui.Controls 10.0.60 and CommunityToolkit.Maui 14.2.0 both ship plain net10.0 assemblies, so Shell, Keyboard, Popup, PopupOptions and ShowPopupAsync all compile off-device. The real blockers were narrower — the icon font, the XAML popup types, and Android. Layout: src/AniSprinkles/ (net10.0-android) and src/AniSprinkles.Core/ (net10.0) are siblings. Core initially sat inside the app project's folder, where the app's default globs swept up 602 of Core's sources plus its obj/ generated assembly attributes and failed as CS0579. DefaultItemExcludes suppresses that, but siblings need no suppression at all. Core holds Models, Utilities, non-platform Services, Converters and every PageModel. It deliberately references neither CommunityToolkit.Maui nor IconFont.Maui.FluentIcons — leaving those out is what stops the new seams eroding. Three seams carry what stayed behind: - IDialogService covers the five XAML popups plus DisplayPromptAsync, implemented by MauiDialogService next to the existing MauiShellNavigationService and MauiUserFeedback. This matters beyond compilation: Shell.Current is null rather than throwing off-device, so a popup call from a PageModel silently no-ops and its test passes without exercising anything. - IExternalBrowser covers the four "view on AniList" links. - Core mirrors the 57 icon glyphs it uses into Icons/Glyphs.cs, generated by tools/generate-glyphs.cs from the package's PE metadata. The package ships platform TFMs only. Also folded in, because the move surfaced them: - OutageStateService called MainThread.IsMainThread, which throws NotImplementedInReferenceAssemblyException off-device; its catch only covered InvalidOperationException, so the comment promising an inline fallback in unit tests was never true. Now uses the injected IDispatcher. - SettingsPageModel read AppInfo.Current in a field initializer, so the type could not be constructed off-device at all. IAppInfo is injected alongside IPreferences. - Four PageModels each carried a private copy of the same toast/snackbar helpers; they now share IUserFeedback. Plain snackbars move 5s -> 4s as a result; the 20s settings save-failure and 10s permission snackbars are preserved through a new optional duration. - Browser-open failures log at Warning rather than Error, matching how MauiUserFeedback treats its own display failures, and so stop raising Sentry events for a device concern. ListEntryStatusFlow becomes an instance singleton so its confirm/rating prompts can go through IDialogService. The tap-suppression window moves to Core as LongPressTapSuppressor; the Android gesture plumbing stays in Views. The test project now project-references Core. All 391 existing tests pass unchanged; Core's internals stay internal via InternalsVisibleTo rather than being widened for tests. * Validate every icon glyph reference against the package (#117) src/AniSprinkles/AppShell.xaml shipped x:Static icons:FluentIconsRegular.Compass24 — the real member is CompassNorthwest24. x:Static is resolved by the XAML loader at runtime, so the build was completely clean and the app crashed on launch with XamlParseException. That one was lucky: AppShell loads at startup, so it failed immediately and unmissably. The same typo on a details page would build, pass tests, pass CI screenshots, and only crash when a user opened that screen. Two things are checked, both driven off the icon assembly's PE metadata: - Every x:Static icon reference in src/**/*.xaml resolves. The xmlns prefix is read from the file rather than assumed to be "icons:", so renaming it cannot quietly switch the test off. - Every constant in Core's mirrored Glyphs table still matches the package by name AND value. Mirroring those glyphs (#62) was only acceptable on the condition that drift becomes a build failure, and this is that condition. PE metadata rather than Assembly.Load: the package targets net10.0-android36.0 and will not load into a net10.0 test host. Two approaches that produced confidently wrong answers on the way here are documented at the call site — substring-matching the DLL reports Compass24 as present because CompassNorthwest24 contains it, and a regex over the #Strings heap silently misses every other name because entries share NUL delimiters. The pinned version is read from whichever project under src/ declares the package, not a hardcoded path. An unresolvable package cache skips (a fresh machine, an unrestored bump); a missing declaration throws, because that is a repo-structure problem rather than an environment gap. Empty-discovery guards keep both theories from passing vacuously. Verified by reintroducing Compass24 (fails, naming the file and suggesting CompassNorthwest24) and by tampering with a mirrored glyph value (fails, printing both escaped code points and the regeneration command). * Add PageModel state-machine tests for the #116 defects (#52 phase 1) The #62 extraction is only worth its diff if the code it unblocked is actually covered. These are the defects PR #116 found across six review rounds — none were reachable by the previous 391 tests, and none are reachable on device either: each needs a specific interleaving that the happy-path pass cannot produce. SearchPageModel: - A failed page 1 on a new query must not re-arm Load More over the previous query's results. The failure clears IsSearching in its finally (that is what stops the spinner), which used to leave the section holding the old items with HasNextPage set — so scrolling appended page 2 of the new query onto the old query's results, one list silently mixing two searches. - Load More must page under the filter page 1 used. The adult filter was read live per page, and Settings debounces 1500ms and only applies the value from the server response, so a user could toggle, return inside that window with nothing detected as changed, and have the new value land in time to page a different policy onto results already on screen. - An adult flip while the first search is still in flight must invalidate. The context used to be recorded on fetch success, so a first search in flight left "nothing searched yet" set and the flip baselined the new context WITHOUT cancelling the old request, whose response then marked itself current forever. - A superseded search resuming late must not clear its successor's spinner. DiscoverPageModel: - Load More must be refused while a refresh is still reading auth. The guard used to cover only the window after IsBusy went up, but LoadCoreAsync awaits the auth read before setting it. Each of these was confirmed to fail against the reverted fix and pass against the current code, so they catch what they claim to rather than merely passing. Also #52's own phase-1 list for MediaDetailsPageModel.LoadAsync (happy path, non-positive id, null media, NotFound hiding Retry, throw keeping Retry, reuse without a second request, in-memory list entry not clobbered) and the reachable SettingsPageModel.LoadAsync branches. SettingsPageModel's authenticated happy path is deliberately absent: it ends in AppSettings.SyncFromViewer, which persists through the static Preferences.Default and throws off-device, so the test would be asserting on the catch block. Giving AppSettings a preferences seam is the open decision on #52 and is noted there. SearchPageModel takes a TimeProvider so its 600ms debounce is deterministic under test rather than a real sleep per case; DiscoverPageModel already took one. Test classes touching the process-wide AppSettings statics now share a non-parallel collection. * Close the biggest remaining test gaps in Core (#52) An audit of the 130 types now in Core against every test file found 56 never mentioned at all. Most are DTOs and fine, but three groups were not. EntryActionCoordinator had zero coverage and is the highest-value thing #62 unblocked: every list surface (My Anime, Discover, Search, View All) routes its long-press flows through it, so one defect surfaces in four places. It was previously unreachable because each entry point opened a popup through Shell.Current, which is null rather than throwing off-device — the flow would no-op and any test of it would pass without executing a decision. Now covered: menu routing and dismissal, the flush-before-flow hook, remove-vs-move branching, rollback of status/progress/score/repeat on a failed move, retry targeting the id captured at failure time, outage suppressing the retry action, id adoption on add-to-list, and the completion flow's re-entrancy guard. Code added in this branch had none of its own. Covered now: the outage/retry rule in UserFeedbackExtensions, MoveToListChoice's two shapes, LongPressTapSuppressor, and OutageStateService — including the dispatcher fallback that replaced the MainThread call whose catch never covered what it threw. MyAnimePageModel's +1 debounce: six taps collapse to one write (the app's largest single rate-limit saving), a failure reverts to before the first tap rather than one step, switching entries flushes the previous one, and reaching a known total routes to the completion flow instead of the debounce. Takes a TimeProvider for the same reason SearchPageModel does — a real 1500 ms sleep per case is neither fast nor deterministic. Plus #52 phase 3 (converters — the Brush-vs-Color target rule that MAUI's Background/BackgroundColor precedence makes load-bearing, hash stability, format glyph mapping) and ImageUrl, where AniList returns a default.jpg placeholder rather than null and a plain null check leaves its grey graphic on screen. Every new behavioural assertion was mutation-checked: the entry-switch flush, revert depth, completion routing, remove-vs-move, the completion guard, the id-less-create throw, and the dropped-dispatch fallback were each broken in turn and confirmed to fail the intended test. Two of those mutations hung the suite rather than failing it, so both tests are now bounded with WaitAsync — a hang in CI reads as an infrastructure problem, not a regression. 680 tests, up from 603. * CI: Update UI screenshots [skip ci] * Make RecordingUserFeedback track the latest snackbar, not the latest with an action PR review (Copilot) on #123. `LastSnackbarAction` was only ever assigned, never cleared, so after a snackbar that offered no action it still held an earlier one's. The underlying mismatch: the property tracked "the most recent snackbar *that offered an action*" — a filtered subset — while `Assert.Null(LastSnackbarAction)` means "the last snackbar offered none", which is a statement about the latest event. Those only agree while at most one snackbar has been shown, which is why no existing test was wrong. It matters on retry chains, which show several. Added the behavioural test that was hiding behind it: a delete that fails, is retried, and fails again into a service outage must stop offering a retry button that cannot work. That test fails against the old double *with correct production code*, which is the whole problem — the double was answering for a snackbar that was not the one under assertion. Doc comment updated to match; the old wording described the old behaviour accurately, so changing one without the other would have swapped a latent trap for a real doc/code mismatch. Considered recording (message, action) pairs instead, which is immune to ordering entirely. Rejected: it churns all 8 assertion sites and turns `Assert.Contains("AniList is Down", feedback.Snackbars)` into a predicate lambda, for precision only needed to assert about a non-final snackbar — which splits into separate tests instead. * CI: Update UI screenshots [skip ci] --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
…I test gates (#118, #121, #122, #124) (#129) * CI: fail the build on skipped or vanished tests (#122) The skipped count was parsed into the job summary and then never acted on, so a run where 190 of 644 tests skipped was a green check with a number in a column nobody reads. That already happened once: IconGlyphReferenceTests skips gracefully when it cannot locate the icon package, and when #62 moved the app csproj out from under that lookup all 190 glyph cases turned into skips. It was caught by eye. Fail the job when any test skips, naming the project and the count, and add a floor on the summed total so tests that VANISH are caught as well as tests that skip -- the same incident also dropped the total by 231, and a stale-assembly run reported 557 against a 644-test suite. Neither shows up as a skip. Both gates only fire when the runner output actually parsed, preserving the existing rule that a format change must never fail CI on its own. The skip check guards on is_count first: in the new-runner branch S falls back to the literal "?" while PARSED is still 1, so a bare -gt would error rather than fail cleanly. Also widens the duration regex to accept seconds. It only matched "N ms", so every run slower than a second has been showing "?" in the summary table. Thresholds start at 0 skips and a floor of 830, against a measured 837 passing. * Redact bearer tokens at the source, not at the sinks (#124) ErrorReportService redacted the string it returned to the on-screen error panel -- the least sensitive sink, on the user's own device -- and handed the raw exception to the two that persist and transmit: the rotating file log and Sentry. The `summary` local was computed, redacted, and then never used, which reads like wiring that got lost rather than a deliberate choice. The vector is live. AniListClient embeds up to 500 characters of the raw response body into the exception message, so an auth-failure body echoing the credential lands in AniListApiException.Message and from there in both sinks. Redact where the text is produced instead, so the token never enters the exception and every downstream consumer is safe by construction. Three sites, not the two the issue named -- graphQl.Errors[0].Message on an HTTP 200 reaches the message the same way the 4xx branch does. Classification runs on the raw text and redaction only on what gets stored: AniListErrorClassifier matches "Invalid token" and the outage markers, none of which the bearer pattern touches today, but keeping the order explicit means a future pattern cannot silently reclassify an error as Unknown. ErrorReportService still hands the raw exception to both sinks on purpose -- rebuilding it for Sentry would cost the stack trace its grouping depends on. SentryScrubber, wired through BeforeSend, covers exceptions Sentry captures without passing through ErrorReportService at all. It materialises SentryExceptions before mutating: the property is typed IEnumerable, so a lazily-projected sequence would hand each enumeration fresh objects and a plain foreach would redact copies that are never sent. Regression tests cover all three message paths and the deferred-sequence case; each fails without the corresponding fix. * Give AppSettings an injectable preferences store (#121) AppSettings read and wrote through the static Preferences.Default, which throws NotImplementedInReferenceAssemblyException on the plain net10.0 TFM the tests build against. That made every path ending in Load/Save/Clear/SyncFromViewer untestable -- the concrete casualty being SettingsPageModel.LoadAsync's authenticated happy path, deliberately left unwritten in #62 with a comment saying why. Keep the static surface and make only the storage injectable. AppSettings stays static for a real reason: Media.DisplayTitle and MediaListEntry.ScoreDisplay consult it, and those are plain deserialized POCOs that DI never constructs. Full IAppSettings injection stays available later (#52). No MauiProgram wiring. Preferences.Default is safe as a field initializer -- verified against Microsoft.Maui.Essentials 10.0.60 that the Default getter returns an implementation off-device and only Get/Set/Remove throw -- so the initializer IS the shipping behaviour and production is unchanged. The seam stays internal; InternalsVisibleTo("AniSprinkles.UnitTests") already exists. TestDataBuilder.ResetAppSettings now installs a dictionary-backed FakePreferences and returns it. Every class that calls it is already in AppSettingsCollection, which serialises writes to these process-wide statics. Unblocks the SettingsPageModel authenticated path, the "exception with cached data stays Content" case from #52, and round-trip coverage of the persistence itself. * Commit the adult-content setting immediately, and pin paging to it (#118) DisplayAdultContent is what every browse surface filters on, but it was not written when the user flipped the toggle -- SettingsPageModel debounced 1500 ms, saved to AniList, and the value only reached AppSettings when the server response was applied. Turning 18+ content off and tabbing to a browse surface inside that window meant the surface read the old value, cache-hit, and left the 18+ results on screen until a whole tab cycle later. Commit it locally the moment the toggle flips instead. That removes the window rather than reacting to it: a browse surface can only appear after the user leaves Settings, so the invalidation checks those surfaces already have start working with no new machinery. The issue proposed a static change notification with three subscribers. Dropped: with an immediate commit there is no remaining staleness for it to fix, and MediaBrowsePageModel is registered transient, not singleton as the issue assumed -- a static event would leak one page model per View All navigation. Second defect, same root cause: DiscoverSectionFetch.PageAsync resolved the static per page, so once a commit landed while Discover was on screen the next Load More fetched under the new policy and appended onto the old one, mixing two policies into one row. The #116 guards do not cover it because no reload is involved. It now takes the seeded policy as a parameter. Library was a fourth affected surface the issue did not list, and the worst of them: its refresh short-circuit weighed only auth and a five-minute freshness window, never the setting, so tabbing away and back would not clear it either. Committing locally then exposed a further hole -- MyAnimePageModel.LoadAsync syncs preferences from the viewer, whose copy is still the old one inside the debounce, so a Library refresh reverted the toggle app-wide. Fixed from both ends: SettingsPage.OnDisappearing flushes a pending save on navigate-away (worth having regardless -- a change made and then backgrounded was previously lost with the debounce), and AppSettings shadows DisplayAdultContent from viewer syncs until the save is confirmed. The flush alone is not sufficient: Shell does not guarantee OnDisappearing precedes the next page's OnAppearing, and a save can fail, leaving the server genuinely stale. Every fix here landed test-first, each failing red for the expected reason before the change. * CI: canary fixture that fails the build if the adult filter breaks The adult-content filter was never exercised end to end. The CI stub carried no flagged fixture and ignored the isAdult argument entirely, so DiscoverSectionFetch, the browse/search queries and MediaListSectionsMerger could all have broken without changing a single screenshot -- which is exactly where #118's two bugs lived. Seed one fixture flagged IsAdult, titled "18PLUS CANARY - FILTER FAILED", into both the stub list and the browse results. It carries no adult content: the title is a marker and it has no cover image, so a leak renders the app's own placeholder next to a shouted label. The stub viewer leaves DisplayAdultContent off and nothing in CI turns it on, so every surface must filter it out. For that to mean anything the stub has to model the filter, so CIAniListClient now honours the contract the real client relies on -- false = SFW only, true = 18+ only, null = unfiltered -- across browse, search and the Discover rows. The canary lives in its own list rather than carrying a flag because RelatedMedia has no IsAdult: browse filtering is entirely server-side, so the client never receives the field, which is precisely why the stub must model it. The workflow dumps the UI after Library, Discover, View All and Search, and fails the job if the canary appears -- last, so the screenshots and logcat are still uploaded for diagnosis. An unreadable dump is a warning only; a flaky emulator must not fail the build on its own. The gate greps for a literal, so renaming the fixture would leave it matching nothing and passing forever, which is the failure #122 exists to prevent. The workflow therefore also asserts the marker still appears in CIAniListClient.cs and fails fast if it does not. Existing screenshots are unchanged: the toggle stays off, so every surface asks for isAdult false and the canary is filtered everywhere. * CI: Update UI screenshots [skip ci] * Don't treat every viewer response as confirming a pending adult-content change (#129 review) PopulateFromUser cleared the pending marker on any viewer response. That is only true for the reply to our own save: a fresh load just asks the server, which is still behind while the save is in flight and permanently behind if it failed. Worse, the guard was bypassed before it was ever consulted. PopulateFromUser assigns the bound DisplayAdultContent property, which runs the changed handler and writes straight through to AppSettings -- 23 lines before SyncFromViewer's check. So returning to Settings inside the save window stamped the server's stale value over the choice the user had just made, and the toggle flipped back on. Confirm by comparison instead. The marker now clears exactly when the server reports the value we are holding, whichever response brought it, and PopulateFromUser routes its assignment through ResolveDisplayAdultContent so the toggle and the static can never disagree. That drops ConfirmDisplayAdultContentSaved entirely -- the invariant is self-resolving. Reported by Copilot on #129. * CI: Update UI screenshots [skip ci] * Correct the bearer-regex character-class comment, and test what it claims (#129 review) The comment described the class as "the unreserved URL set plus the base64url padding a JWT can end on", which omits + and / entirely and files them under a label that does not apply -- those are standard-base64 characters, and base64url substitutes - and _ for them. The regex is right and unchanged: carrying both alphabets means a token is scrubbed whichever encoding it arrives in. Only the description was wrong, and a wrong description on a credential-scrubbing pattern invites someone to "fix" it by narrowing it. Say what the class actually covers, say why it spans both alphabets, and add a theory that exercises each so the claim is enforced rather than asserted. Reported by Copilot on #129. * CI: Update UI screenshots [skip ci] --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
…ability (#119, #127, #128) (#133) * Single-flight the token load behind a testable seam (#119) AuthService is a singleton and its token load had no synchronization, so two callers arriving before the first load completed both entered it. Since #116 that load has a fallback catch treating an unreadable token as "signed out" -- correct for one caller, destructive for two: a caller whose read failed cleared the token a concurrent caller had already published, and anything sampling auth in between rendered a signed-in user as signed out. Token state, the load gate and the expiry check move to a Core TokenStore behind an ISecureTokenStorage seam, with MauiSecureTokenStorage alongside the other adapters in Services/Maui/. AuthService keeps the platform half -- the OAuth round trip and the Android cookie store -- which is what pinned it to the app project that tests/ cannot reference. IAuthService is unchanged, so CIAuthService and SimAuthService need no edits. Two corrections to the fix proposed on the issue, both found by the tests: - The double-check is on a separate _loaded flag, not on "is the token null?". The token is also null for a signed-out user, so a null re-test is still true for the second caller and both read -- failing the first acceptance criterion. - Both values are read into locals and published together. LoadAsync assigned the token one line before reading the expiry, so a concurrent caller could observe a token whose ExpiresAt had not loaded -- and a null expiry reads as "not expired", so it would accept a token the load was about to reject. State is guarded by a plain lock rather than the async gate, because sign-in and sign-out publish without going through the load at all; the load yields to whatever they published rather than overwriting a newer decision. The lock is never held across an await, so it cannot deadlock the UI thread SignOutAsync runs on. All three acceptance criteria are now tests. Each was written first and watched fail against a faithful port of the old behaviour. * Re-render display settings on the surfaces already showing them (#127) Title language and score format feed computed properties -- Media.DisplayTitle, MediaListEntry.ScoreDisplay, the details rating control -- and nothing re-evaluated when the user navigated back, so bound labels kept the old text indefinitely. Unlike the adult toggle (#118), these change how already-fetched items render rather than which items exist, so the answer is a re-projection, not a refetch. Each surface snapshots a DisplaySettingsSnapshot and re-projects when it moved. No AniList request is added anywhere. Media and RelatedMedia carry DisplayTitle but are plain classes and cannot raise PropertyChanged, so the observable containers implement IDisplayProjection and re-raise the property holding them (Media / Node); MAUI then re-resolves the whole binding path. A carousel item type that shows a media title must implement it or its cards render stale titles forever with nothing to catch it. The hook differs by page kind, and this is the part that shipped broken and was caught on device. Tab-root pages use OnAppearing. The five pushed pages -- the four detail pages and View All -- get no OnAppearing when their tab becomes current again, because Shell gives a page in a backgrounded navigation stack no appearing/disappearing on a tab switch. Measured across two tab round-trips: OnAppearing 1 (initial navigation only), OnDisappearing 0, OnNavigatedTo 3. They call ViewModel.RefreshDisplaySettings() from OnNavigatedTo instead. The reuse-guard call in LoadCoreAsync stays as well, since a sort popup closing does fire OnAppearing and reaches the load path; the check is idempotent so both is free. The tests drove the page model through LoadAsync, which is precisely the call the real app never makes on a tab return -- they passed while the feature was dead. They now go through RefreshDisplaySettings(). No test layer we currently have could have caught this; see #131. Also: title language moves the Title sort order, not just the text, because MediaListSection orders by DisplayTitle. Staff name language is out of scope -- it is read by nothing today (#130). * Stop discarding settings changes that failed to save (#128) c4a2830 kept a locally changed DisplayAdultContent ahead of the server until the server confirmed it. The marker was scoped to that one field, so every other setting still reverted: a failed save left the server reporting the old value, and the next visit to Settings assigned it straight back over the user's choice with nothing said. The setting called out as the worst case for this had become the only one protected. The guard now covers every user-editable setting. Title language, score format and adult content keep their markers in AppSettings, because MyAnimePageModel calls SyncFromViewer directly and has to honour them without going through the Settings page at all; staff name language, restrict-messages, activity merge time, airing notifications and the per-type notification toggles keep theirs on the page model. The per-type ones are a set of unconfirmed types rather than one flag, so a change made on another device still arrives for every type the user did not touch. AnimeSectionOrder deliberately has none -- there is no control for it, so it can only ever come from the server. Title language and score format now also commit locally the moment they are picked, the way the adult toggle does. Before, they reached AppSettings only once a save succeeded, so the choice took 1.5s to reach the rest of the app and was lost entirely if the save failed. Dirty-tracking is baselined against what the server reported rather than the resolved local value, so an unsent change leaves the page dirty and the next flush re-sends it. A successful UpdateUser clears the markers for the values it actually carried, compared field by field -- the user can change a setting while a save is in flight, and clearing that one would discard a change the server never saw. Without that, a server which quietly declined a value would leave it pending and the page permanently dirty, re-sending a rejected change on every navigate-away. Two silent drops alongside it. SaveSettingsAsync returned immediately when IsSaving without scheduling anything, so a Retry tap or a navigate-away flush landing mid-save vanished; it now coalesces into a second pass. And the failure snackbar built its own retry action instead of going through ShowFailureSnackbarAsync, so a ServiceOutage kept offering a Retry that cannot succeed for minutes or hours. Also fixes an orphaned WorkManager job, pre-existing and unrelated to saving: PopulateFromUser scheduled the airing check when the toggle landed on but never cancelled it when it landed off, so turning airing notifications off anywhere else left this device still scheduled -- the switch read off while notifications kept arriving. Verified on device against the real API: flush fires 33ms after a tab switch rather than on the debounce; a real network failure classifies as Network, retries once, then surfaces "No Internet Connection" with Retry; the local value persists to SharedPreferences through the failed save; a successful viewer fetch reporting the stale value does not revert it; the change is re-sent on the next flush; and CancelPeriodicCheck genuinely removes the job from the system scheduler. * Document the lifecycle asymmetry and the seams these changes added The Shell lifecycle note is the one that matters: OnAppearing fires on tab-root pages but not on a page pushed onto a backgrounded tab's stack, so anything that must re-evaluate when the user returns to a detail page has to hang off OnNavigatedTo. That fact cost a shipped-but-dead feature this round and no test layer can surface it, so it belongs somewhere a reader will hit before making the same assumption. See #131 and #132. Also records the generalised pending-save guard, the display re-projection contract, the airing job following the toggle in both directions, TokenStore and ISecureTokenStorage in the DI table, SecureStorage in the list of Essentials statics that throw off-device, and why ConfigureAwait(true) is written explicitly in page models -- it is the default, so it documents a requirement rather than changing behaviour. * Reset the pending markers between tests, and silence xUnit1051 Two CI failures, neither reproducible locally by running the suite. SettingsPageModelTests failed asserting Point10Decimal and getting Point100. The pending-upstream markers #128 added are process-wide statics, and TestDataBuilder.ResetAppSettings reset the four value properties without touching them. A test that changed a setting locally left a marker armed, so the NEXT test's SyncFromViewer kept the stale local value instead of taking the server's. SettingsSaveDurabilityTests sets a score format, so whether this bites depends purely on ordering within the shared collection -- it ordered that way on CI and not here. ResetAppSettings now goes through AppSettings.Clear(), which resets the markers as well, and a regression test arms all three and asserts a following SyncFromViewer still follows the server. Separately, 15 xUnit1051 warnings in TokenStoreTests: calls accepting a CancellationToken should pass TestContext.Current.CancellationToken. Missed because the local test runs were filtered for failures and errors and never for warnings -- the zero-warning checks only ever covered the app project. * CI: Update UI screenshots [skip ci] * Record that the zero-warning gate covers the test project too The claim was being checked against the app project alone, which does not compile tests/, so xUnit analyzer warnings reached a PR while the builds were reported clean. Lists all five targets, and notes the matching trap alongside it: a suite that is green locally can still fail on CI when the failure depends on ordering within the shared AppSettings collection, so process-wide state added to those statics has to be reset in TestDataBuilder.ResetAppSettings. * CI: Update UI screenshots [skip ci] * Guard the fake's dictionary, and stop the absent log asserting a cause (#133 review) FakeSecureTokenStorage locked its read-tracking state but not the backing dictionary, which Seed, SetAsync, Remove and GetAsync all touch. No test races on it today -- the sign-in and sign-out cases write while the reader is parked on its hold and release only afterwards, and the genuinely concurrent case is two readers, which Dictionary handles. But that safety is incidental, resting on an unwritten "no test writes while a reader is unparked" rule, inside the one fake whose whole job is making concurrency deterministic. Everything now goes through the existing _sync lock, taken after the await and never across it. AuthService logged "absent (no token in SecureStorage)" for TokenState.Absent, which TokenStore also returns when the read threw. Collapsing those is deliberate (#116) because callers act identically, but the message asserted a cause it did not know, and the traces here are a documented diagnostic surface. Now "absent (no usable token)"; a failed read still logs its own Error line with the reason. * CI: Update UI screenshots [skip ci] --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
…ge (#125, #132, #130) (#135) * Replace ErrorSim with runtime fault injection that composes with the CI fixtures (#125) ErrorSim could not test the thing it existed to test. It replaced the client rather than decorating it, so `FailingAniListClient` answered all 23 interface methods with `throw` and every call failed — you could never reach the screen whose error state you wanted to see. That is why the details pages' error and retry states had never been exercised on a device. Two seams instead, sharing one disarmed-by-default `FaultState`: - `FaultInjectingAniListClient` decorates whichever client DI selected, so it composes with the CI fixtures: a real screen loads and the *next* call breaks. `scope next` is what makes Retry genuinely recover. - `FaultInjectingHttpHandler` sits innermost in the pipeline, so a synthetic 429 or 503 is processed by the real `AniListRateLimitHandler`, `LoggingHandler`, `SendAsync` retry-once and `AniListErrorClassifier`. A profile names which layer it fires at; both seams share one state, so without that tag a single armed fault would fire twice for one logical call. `Delay` is independent of failure — latency with no error kind is the only way to open the cancellation and interlock windows that #116's defect family lives in. Scopes are deterministic only: a fault you cannot re-run is not a fixture. Armed over adb through an attribute-generated `BroadcastReceiver` and `driver.ps1 fault`, so changing what fails costs a broadcast rather than a ~3 minute rebuild. Everything is behind `#if DEBUG`, including the exported receiver, which is why `-p:ErrorSim=true` and its Release guard are gone. The decorator clears an outage banner it raised once a call succeeds. Caught on device: the banner is sticky and normally clears via `AniListClient`'s `ReportSuccess`, which never runs behind the fixtures, so an injected outage pinned it for the session and recovery looked broken. * Cancel in-flight work when a pushed page's tab is switched away (#132) `OnDisappearing` never fires on the five pushed pages when the tab changes, so `ViewModel.CancelInFlight()` and `_loader.OnDisappearing()` simply did not run. Tab away from a details page mid-load and the fetch, plus any Load More, ran to completion against AniList — spending rate-limit budget on a page the user had left — and `PageLoadScope` was never cancelled, making the guards written against it inert on that path. Measured on device rather than assumed. The navigation hooks are a strict superset of the appearing hooks: they fire everywhere those do, plus the two tab-switch cases where those do not. path OnAppearing OnDisappearing OnNavigatedTo OnNavigatedFrom initial navigation yes - yes - tab away (pushed page) - NO - yes tab back (pushed page) NO - yes - forward nav to sub-page - yes - yes back nav from sub-page yes - yes - sort popup open - yes - yes sort popup close yes - yes - tab-root page (Settings) yes yes yes yes So the whole lifecycle moves to `OnNavigatedTo`/`OnNavigatedFrom`, leaving the popup, forward-nav and back-nav paths behaving exactly as before. The pair has to stay together. `DeferredContentLoader.OnDisappearing` clears `_hasAppeared`, which gates both `IsCurrent` and `TrySchedule`, so moving the cleanup without a matching re-arm would latch the loader off after a single tab round-trip and leave the page on its spinner forever — worse than the bug. Verified on device with an armed delay fault: a load cancelled at 6308ms of an 8000ms delay on tab-away, and tabbing back re-armed and completed it. Tab-root pages get the full set and are unaffected, so `SettingsPage`'s pending save flush (#118, #128) still runs. * Render staff and character names from userPreferred (#130) Staff Name Language was saved to AniList and read by nothing: both accessors were `Name?.Full ?? Name?.UserPreferred ?? ...`, so `Full` always won and every staff and character name rendered identically whatever the viewer had picked. The issue proposed composing the name locally from `first`/`last`. That was implemented, then abandoned on evidence gathered against a real account: - `full` is NOT a stable western-order field. AniList resolves it server-side against the viewer setting, exactly like `userPreferred`. Staff id 113181 is "Taiki Kawakami" unauthenticated and "Kawakami Taiki" on an account set to ROMAJI. Composing Romaji Western from `full` therefore renders family-first for those users — the app could not have shown western order at all. - AniList is not internally consistent. Under ROMAJI a Latin-script name comes back as full="Bairstow Caitlyn" but userPreferred="Caitlyn Bairstow"; `userPreferred` is script-aware and `full` is not. Any local `last first` rule diverges from anilist.co for every western voice actor, and matching it would mean inventing a CJK heuristic and hoping it keeps tracking theirs. So the whole question defers to `userPreferred`, falling back to `full` then `native`. All eleven `name { ... }` selections request it — the issue named two; the other nine are every name appearing in a list rather than as a page hero, and would have been left behind by either proposed option. The cost is that `userPreferred` is fixed at fetch time, so a change needs a refetch rather than a re-projection. `IAniListClient.InvalidateEntityCache()` drops the cached character/staff/studio reads; pages reload lazily as the user navigates back to them rather than firing a burst on a settings tap. It fires for an upstream change too — the website or another device — which arrives through `PopulateFromUser`, not the changed handler. Also fixes `CIAniListClient.UpdateUserAsync`, which returned the untouched static viewer instead of echoing the request, so every Display Preferences change reverted on the next Settings load and the whole section was unverifiable in a CI build. `DisplayAdultContent` stays unechoed so the adult-content canary cannot be flipped from inside the app. The native-script subtitle under the hero is suppressed when it would just repeat the name above it, which happens once the setting is Native. * CI: Update UI screenshots [skip ci] * Document that the fault op means a different thing per layer (#125, PR review) `fault <op>` was documented everywhere as an `IAniListClient` method prefix. That is only true at the client seam. The HTTP seam parses the GraphQL `operationName` out of the request body, because that is all it can see — so `fault GetStudio ... -layer http` matched nothing and looked like a broken seam rather than a targeting mistake. Every HTTP scenario in the device pass used `op any`, which is why this was not caught during verification. No normalisation is attempted, because none would work. Stripping `Get`/`Load`/`Async` lines up `GetStudioAsync` with `Studio`, but the namespaces genuinely diverge elsewhere: `GetMyAnimeListAsync` is `MediaListCollection` over the wire and `SearchAnimePageAsync` is `Search`. Partial magic that covers most operations and silently fails on the rest is worse than none. So the rule is stated in all five places that document it (driver help, /run-anisprinkles, DEVELOPER_NOTES, AGENTS.md, and FaultProfile's XML doc), and the handler now logs `FAULT http no match` naming the operation it actually saw when an armed targeted profile misses — the failure diagnoses itself instead of looking like nothing happened. Only reachable with a targeted Http profile armed, so it cannot flood the log. Two tests pin the distinction so nobody "fixes" it by normalising one side. * CI: Update UI screenshots [skip ci] * Pin FaultState.Decide's atomicity under contention (#125, PR review) A review comment claimed `lock (_gate)` on a `System.Threading.Lock` boxes a new object per use and therefore synchronizes nothing. It does not — `Lock` is a sealed class, and C# 13 lowers `lock` on it to `using (x.EnterScope())` rather than `Monitor.Enter`. Converting one to `object`, which the comment suggested as the fix, is the case warning CS9216 exists to catch. No production change; these tests make the answer checkable rather than argued, and guard an invariant worth guarding on its own. `Decide` is a read-modify-write on the hit counter reached from the UI thread and from HTTP continuations on pool threads, and every scope's meaning rests on it being atomic: `next` must fire once however many callers race, `firstn:N` must affect exactly N. Confirmed the tests are not vacuous by removing the lock from `Decide` and re-running — `firstn` fails, because lost increments let extra callers slip under the threshold. * CI: Update UI screenshots [skip ci] --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>









Closes #43.
Replaces the hamburger flyout with a five-tab bottom bar: Library · Discover · Search · Feed · Settings. Two commits, each green on its own — the tab bar first, then the search extraction.
Where this differs from the issue
The issue's tab table predates #102, which closed #15 and #16. Discover was already a real page, and search already existed inside Discover behind a toolbar toggle. So "add stub pages for Discover, Search, and Feed" became: Discover is reused as-is, Search is an extraction, and only Feed is a genuine stub. The issue body was corrected during planning.
Phase 1 — the tab bar
my-anime,discover,settings) plussearchandfeed, so nothing that navigates had to change.ShellContents (anime,manga), which Shell renders as a native swipeable top strip — no custom control. Manga is a placeholder until Manga support #12; that decision is recorded on the issue.ConverterParameterrather than derived from the title text, so Anime stays green and Manga blue despite sharing a title.BottomNavigationViewand Shell maps a singleIcon— soAppShellswaps it onNavigated, building bothImageSources per tab once rather than allocating on every tap.Phase 2 — search onto its own tab
Larger than the search block itself, because search was coupled to Discover in two places that don't survive separation:
LoadAsynccleared search whenever auth or the adult toggle flipped.SearchPageModelruns that check against its own results inOnAppearingAsync, since there's no load here to fold it into.Rows.Concat(SearchSection.Items)so a status chip stayed consistent wherever that media appeared.SearchPageModelcarries its ownEntryActionCoordinator.Auth is baselined on appear rather than per-search: recording it inside the fetch's
trymeant a token refresh throwing after a good fetch would report "Search failed" for a search that had succeeded.The page skips the deferred content host Discover and My Anime use — that pattern keeps a heavy
InitializeComponentoff the UI thread during the tab transition, and an Entry plus one CollectionView doesn't need it. The singleton keeps the query across tab switches on purpose. A dedicated tab has no rows to fall back on, so it gains an idle prompt the Discover version never needed.CI and tooling
The screenshot job navigated by opening the flyout, and located the search icon by mirroring the hamburger's x across the screen width — MAUI toolbar icons expose no uiautomator node, but the drawer toggle did. Tab labels are real nodes, so all of that collapses into
goto_tab: −61 lines, and four flaky coordinate/retry heuristics gone.goto_tabpropagates the tap's exit status rather than the trailingsleep's, so a missed tab skips its dependent screenshots instead of capturing the wrong screen.driver.ps1got the same treatment (flyoutremoved,gotois a label tap). Docs updated:AGENTS.md,README.md,project-architecture,run-anisprinkles.Verification
Zero warnings, 391/391 tests green, and driven on the emulator: all five tabs, sub-tab tap and swipe, labels not truncating, detail-page content clearing the bar, search debounce and results, search → details, and the long-press action sheet on a search result.
Worth a reviewer's attention
AGENTS.mdrecords that PageModel tests aren't possible under the link-compile setup until Extract AniSprinkles.Core class library to unblock PageModel/Services unit tests #62 lands. The debounce and generation-guard logic is the most test-worthy code here and is covered only by the device pass.x:Staticresolves at runtime and the XAML test only checks well-formedness;FluentIconsRegular.Compass24(which doesn't exist) got through zero-warning and died on startup. Not fixed here — tracked in Add a test that validates x:Static icon glyph references in XAML #117.Review feedback (054c3f6)
Three races closed and one label fixed, from Copilot's review:
_hasSearchedThisSessionfalse while the first search was in flight, so a user who tabbed away, flipped the adult toggle and returned hitOnAppearingAsync's "nothing to invalidate" branch — which baselined the new context without cancelling the old request. That response then landed and marked itself current, permanently.DiscoverPageModelnever had this bug because it captures the flag at load start; this puts Search back into the same shape.!IsSearching. Between the debounce firing and page 1 landing, the previous query's items were still on screen withHasNextPageset. A successfulSeedbumps the section generation and discards the stray page, but a failed page 1 never seeds, leaving a mixed list visible.AuthServiceis guarded, rather than the one call site flagged. The unguardedSecureStorageread is reached from 12GetAccessTokenAsynccall sites across nine page models, all fromasync void OnAppearing. Fixing it inAuthService.LoadAsynccovers them all. Sweeping also found a second hole a caller-side guard would have missed:GetAccessTokenAsynccallsSignOutAsync()on the expired-token path, which clearsSecureStorageand drives the AndroidCookieManager— also unguarded, now also handled. Both fall back to signed out; explicit sign-out still surfaces its failures.screenshots/search.pngwas still labelled "Discover Search" in the preview table.Also fixed (9a583c3): the same Load More race in Discover and in
MediaBrowsePageModel(View All). Initially deferred as out of scope, then reconsidered —DiscoverSectionFetchreadsAppSettings.DisplayAdultContentlive per page, so scrolling during an adult-toggle refresh appends new-filter items onto old-filter ones, mixing 18+ results into a row that was SFW. Discover keeps showing content when a refresh fails, so on that path the mixed row is what the user is left with. MediaBrowse'sPageLoadScopedoes not cover it either:Begin()cancels the previous token, but a Load More started after the reload began shares the reload's token.That commit also documents a driver trap in the
run-anisprinklesskill: a plaindotnet buildomitsEmbedAssembliesIntoApkand leaves a ~19 MB Fast Deployment APK where the ~97 MB one was. Installing it aborts before any managed code with a bareSIGABRTand no .NET stack, which reads exactly like a crash in the change under test.Second review round
!IsSearchinggate closed only the in-flight window — a failed page 1 still clearsIsSearchinginfinally, re-arming Load More while the section held the previous query's items. Resetting on query start keepsCanLoadMorefalse until a successfulSeedfor the current query, and makes the in-flight check redundant. Cost: the list blanks through the debounce rather than holding old results; the spinner covers it.AuthServicerethrowsOperationCanceledExceptionahead of both broad catches. The mechanism described in review doesn't exist today (LoadAsyncnever passes its token to SecureStorage, which has no overload taking one), but the unused parameter is a trap primed to make it real, and the three detail page models alreadycatch (OperationCanceledException)so propagation is what they expect.Third review round
Cmd-Installroutes every adb call through the serial-awareAdbwrapper. All four bypassed it via& $Adb, so withANDROID_SERIALset or two devices attached the free-space check could read one device while the install targeted another. Three of the four predate this PR. Verified by running install withANDROID_SERIALset.Fourth review round
GetAccessTokenAsyncwith no token fromasync voidlifecycle paths, andSignOutAsynccan surface a cancellation of its own viaMainThread.InvokeOnMainThreadAsyncduring teardown. Unfiltered, that escaped as an unhandled lifecycle failure where the broad catch previously absorbed it. Both catches now usewhen (cancellationToken.IsCancellationRequested), so detail pages passing aPageLoadScopetoken keep propagation while everyone else gets the failure handled locally.Fifth review round
screenshots/is wiped before capture. The checkout carries the previous run's PNGs (they are committed to the branch), so any failed capture left last run's image on disk and the publish step embedded it as current. Now a failed capture yields a visibly missing screenshot instead of a plausible wrong one.DISCOVER_OPENEDguard. Search has been its own tab since phase 1, but the capture stayed where the flyout-era code put it, so one failed Discover tap skipped Search too — and combined with the above, republished the previous run's Search image.settings.png— contradicting this PR's own stated guarantee.dotnet buildas "Debug APK" — the exact command that yields a non-installable Fast Deployment package. Both now separate the compile-only build from the deployable one. README's screenshot column also still read "My Anime" over a "Library" image, and sold search as a Discover feature.Sixth review round
AppSettingsimmediately — a 1500 ms debounce, a save, and only then the server response applies it. So a user could toggle, return to Search inside that window (no invalidation detected), and have the new value land in time for Load More to page a different policy onto results already on screen. Turning adult content off left 18+ page-1 items visible with SFW pages beneath.LoadAsyncawaits the auth read before raisingIsBusy, so the previous guard left that suspension open;_refreshEvaluatingis raised before the first await instead.Known limitations, tracked separately
Two findings from the last review round are deliberately not fixed here — both are pre-existing patterns this PR narrowed but did not close, and both need changes wider than a navigation PR should carry:
DiscoverSectionFetch, which still resolves the setting per page, so they can still mix. Closing it needs a commit notification onAppSettingsplus subscriptions in three page models.AuthService.LoadAsyncraces on concurrent first-token reads. The singleton has no synchronization, so if one caller's SecureStorage read succeeds while a concurrent one throws, the failing one's fallback wipes the valid token. The missing synchronization predates this PR, but the wipe does not: before the fallback catch added here, the exception propagated instead.