Skip to content

Token load races, display-setting re-rendering, and settings-save durability (#119, #127, #128) - #133

Merged
zhollis21 merged 10 commits into
mainfrom
feature/119-127-128-settings-and-token-consistency
Aug 25, 2026
Merged

zhollis21 merged 10 commits into
mainfrom
feature/119-127-128-settings-and-token-consistency

Conversation

@zhollis21

@zhollis21 zhollis21 commented Aug 25, 2026 •

Copy link
Copy Markdown
Owner

Three issues that turned out to share a theme: state the app holds locally getting
quietly overwritten, or quietly not applied, because nothing re-evaluated it.

Each is its own commit. 915 unit tests, zero warnings on Debug, CI and ErrorSim builds.

#119 — token load races

AuthService is a singleton and its token load had no synchronization. Since #116 that
load treats an unreadable token as "signed out", which is right for one caller and
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. AuthService keeps WebAuthenticator and the Android cookie
store — the half that pinned it to a project tests/ cannot reference. IAuthService is
unchanged, so the CI and ErrorSim stubs need no edits.

Two corrections to the fix proposed on the issue, both surfaced by writing the tests first:

  • The double-check is on a _loaded flag, not on AccessToken is not null. The token is
    also null for a signed-out user, so a null re-test stays true for the second caller and
    both read — failing the issue's own first acceptance criterion.
  • Reading into locals is not an alternative to the gate but part of the fix. The token was
    published one line before the expiry was read, so a concurrent caller could see a token
    whose ExpiresAt had not loaded — and a null expiry reads as "not expired".

#127 — display settings not re-rendering

Title language and score format feed computed properties, and nothing re-evaluated them,
so bound labels kept the old text. These change how already-fetched items render rather
than which items exist, so it is a re-projection rather than a refetch — 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. A new carousel item type showing a media title must implement
it
, or its cards render stale titles forever with nothing to catch it.

This shipped broken and was caught on device. Tab-root pages use OnAppearing; the five
pushed pages get none when their tab becomes current again, because Shell gives a page in a
backgrounded navigation stack no appearing/disappearing on a tab switch. Measured over two
tab round-trips: OnAppearing 1 (initial navigation only), OnDisappearing 0,
OnNavigatedTo 3. They now use OnNavigatedTo.

The tests had driven the page model through LoadAsync — precisely the call the real app
never makes on a tab return — so they passed while the feature was dead. They now go
through the real entry point. See #131; no test layer we currently have could have caught it.

#128 — settings changes discarded on a failed save

c4a2830 kept a locally changed DisplayAdultContent ahead of the server until confirmed,
but scoped to that one field. Every other setting still reverted on the next visit to
Settings, with nothing said — the setting called out as the worst case had become the only
one protected.

The guard now covers every user-editable setting, split by owner: the three AppSettings
holds keep their markers there because MyAnimePageModel calls SyncFromViewer directly,
and the rest live on the page model. Per-type notification toggles use a set of unconfirmed
types rather than one flag, so a change made elsewhere still arrives for every type the user
did not touch.

Dirty-tracking is baselined against the server so an unsent change stays dirty and the next
flush re-sends it. A successful save clears markers for the values it actually carried,
compared field by field — the user can change a setting mid-flight, and clearing that one
would discard a change the server never saw.

Two silent drops alongside: a save arriving while another was in flight was dropped rather
than coalesced, and the failure snackbar offered Retry even for ServiceOutage.

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
scheduled — the switch read off while notifications kept arriving.

Verified on device

Against the real API, on an emulator signed in to a real account:

Check Result
Flush on tab-away UpdateUser 33ms after the tab tap, not the 1.5s debounce
Real failure classification Network failure → Network, one 750ms retry, then surfaced
Snackbar "No Internet Connection" with Retry — correct for a retryable kind
Persistence Local value written to real SharedPreferences through a failed save
Revert guard Successful viewer fetch reporting the stale value → local value held
Recovery Unsent change re-sent on the next tab-away → HTTP 200
WorkManager cancel Job actually removed from dumpsys jobscheduler, not merely called
Airing else-branch Fires on a plain refresh with airing off, no toggle involved
#127 re-rendering Confirmed by hand on all four detail pages

Not covered on device, and why: ServiceOutage suppressing Retry (cannot force a real
outage without a proxy; unit-covered), the per-type marker scoping, and save coalescing —
all pure state-machine logic reached through triggers now measured firing. Surviving a
process kill is out of scope by design; the marker is in-memory, so a restart takes the
server's value.

Fixed after the first CI run

Test isolation. SettingsPageModelTests failed on CI expecting Point10Decimal and getting
Point100, while passing locally every run. The pending-upstream markers this PR adds are
process-wide statics and TestDataBuilder.ResetAppSettings() reset the four value properties
without touching them, so a test that changed a setting left a marker armed and the next test's
SyncFromViewer kept the stale local value. Whether it bites depends purely on ordering within the
shared AppSettings collection, which went one way on Linux CI and another locally.
ResetAppSettings() now goes through AppSettings.Clear(), and a regression test arms all three
markers and asserts a following SyncFromViewer still follows the server.

Warnings. 15 xUnit1051 warnings in TokenStoreTests — calls accepting a CancellationToken
should pass TestContext.Current.CancellationToken. They were invisible because the zero-warning
checks only ever covered the app project, which does not compile tests/. AGENTS.md now lists all
five build targets and calls out both traps.

Review feedback. FakeSecureTokenStorage guarded its read-tracking state but not the backing
dictionary; everything now goes through the same lock. No test actually raced on it — writes land
while the reader is parked and the release is ordered after — but the safety was incidental rather
than enforced, in the one fake whose job is making concurrency deterministic. And AuthService
logged absent (no token in SecureStorage) for a state that also covers "the read threw", so it now
says absent (no usable token); the failed read still logs its own Error line with the cause.

Follow-ups filed

Closes #119
Closes #127
Closes #128

Zach Hollis added 4 commits August 24, 2026 20:19
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.
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).
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.
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.
Copilot AI lite review requested due to automatic review settings August 25, 2026 00:21

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

The new concurrency-focused FakeSecureTokenStorage uses an unsynchronized Dictionary for reads/writes under concurrent access, risking flaky/undefined behavior in the very tests meant to validate the single-flight fix.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

This PR addresses three related correctness/durability gaps where locally held state could be overwritten or not re-applied: (1) OAuth token load races in a singleton AuthService (#119), (2) display-setting changes not re-rendering already-fetched content (#127), and (3) settings changes being silently discarded/reverted after failed saves and dropped save requests while a save is in flight (#128). The changes align with the repo’s Core-vs-MAUI separation by moving testable logic into AniSprinkles.Core and keeping platform-bound adapters in src/AniSprinkles.

Changes:

  • Introduces a Core TokenStore behind an ISecureTokenStorage seam to single-flight secure-token loads and prevent concurrent-load clobbering (#119).
  • Adds display-setting “snapshot + re-projection” infrastructure (DisplaySettingsSnapshot, IDisplayProjection, TitleProjectionWatcher) and hooks it into tab-root + pushed-page lifecycles without refetching (#127).
  • Generalizes “pending local value” durability across settings, coalesces mid-flight save requests, and routes save-failure snackbars through a shared helper that suppresses Retry for outages (#128).
File summaries
File Description
tests/AniSprinkles.UnitTests/TokenStoreTests.cs Adds concurrency and correctness tests covering single-flight load, cancellation behavior, and expiry handling for TokenStore (#119).
tests/AniSprinkles.UnitTests/TestDataBuilder.cs Extends test data builder to optionally seed English titles for display-projection tests (#127).
tests/AniSprinkles.UnitTests/SettingsSaveDurabilityTests.cs Adds unit tests for settings pending-marker durability, retry affordance, save coalescing, and WorkManager cancel-on-off behavior (#128).
tests/AniSprinkles.UnitTests/Fakes/RecordingUserFeedback.cs Records snackbar dwell duration to assert the 20s settings-save failure behavior (#128).
tests/AniSprinkles.UnitTests/Fakes/FakeSecureTokenStorage.cs Introduces a controllable ISecureTokenStorage fake to observe/read/hold/fail secure storage reads in concurrency tests (#119).
tests/AniSprinkles.UnitTests/DisplaySettingsReprojectionTests.cs Adds tests validating snapshot diffing and re-projection notifications without extra AniList fetches (#127).
src/AniSprinkles/Services/Maui/MauiSecureTokenStorage.cs Implements ISecureTokenStorage via SecureStorage.Default (platform adapter) (#119).
src/AniSprinkles/Services/AuthService.cs Refactors auth to delegate token state/loading/expiry checks to Core TokenStore (#119).
src/AniSprinkles/Pages/StudioDetailsPage.xaml.cs Hooks pushed-page display refresh into OnNavigatedTo so re-projection runs on tab return (#127).
src/AniSprinkles/Pages/StaffDetailsPage.xaml.cs Hooks pushed-page display refresh into OnNavigatedTo so re-projection runs on tab return (#127).
src/AniSprinkles/Pages/MediaDetailsPage.xaml.cs Hooks pushed-page display refresh into OnNavigatedTo so re-projection runs on tab return (#127).
src/AniSprinkles/Pages/MediaBrowsePage.xaml.cs Hooks pushed-page display refresh into OnNavigatedTo so re-projection runs on tab return (#127).
src/AniSprinkles/Pages/CharacterDetailsPage.xaml.cs Hooks pushed-page display refresh into OnNavigatedTo so re-projection runs on tab return (#127).
src/AniSprinkles/MauiProgram.cs Registers ISecureTokenStorage and TokenStore as singletons to preserve single-flight semantics (#119).
src/AniSprinkles.Core/Utilities/PendingValue.cs Adds a reusable “local value outranks server until confirmed” resolver for pending settings (#128).
src/AniSprinkles.Core/Utilities/DisplaySettingsSnapshot.cs Introduces a comparable snapshot of display settings that drive re-render vs section reorder logic (#127).
src/AniSprinkles.Core/Utilities/AppSettings.Storage.cs Generalizes pending markers to title language + score format, adds commit helpers, and confirms-saved clearing (#128).
src/AniSprinkles.Core/Services/TokenStore.cs Adds Core token store with single-flight load gate, atomic publish, and expiry classification (#119).
src/AniSprinkles.Core/Services/Abstractions/UserFeedbackExtensions.cs Adds snackbar duration override and keeps outage behavior (no Retry) centralized (#128).
src/AniSprinkles.Core/Services/Abstractions/ISecureTokenStorage.cs Adds a Core abstraction for secure-token persistence to keep TokenStore testable (#119).
src/AniSprinkles.Core/PageModels/TitleProjectionWatcher.cs Adds a lightweight watcher to re-project only title-language-sensitive card surfaces (#127).
src/AniSprinkles.Core/PageModels/StudioDetailsPageModel.cs Wires details-page projection enumeration for studio production cards (#127).
src/AniSprinkles.Core/PageModels/SearchPageModel.cs Re-projects existing search results on title-language change without re-querying (#127).
src/AniSprinkles.Core/PageModels/MyAnimePageModel.cs Re-projects library sections (and re-sorts/reorders where needed) inside freshness short-circuits (#127).
src/AniSprinkles.Core/PageModels/MediaListSectionsMerger.cs Adds in-place section reordering to apply server-provided section order without a refetch (#127).
src/AniSprinkles.Core/PageModels/MediaDetailsPageModel.cs Wires details-page projections + rating-control re-render notifications on display-setting changes (#127).
src/AniSprinkles.Core/PageModels/MediaBrowsePageModel.cs Re-projects View All cards on title-language changes on revisit paths and tab returns (#127).
src/AniSprinkles.Core/PageModels/DiscoverPageModel.cs Re-projects discover row cards on title-language change even when TTL cache short-circuits fetches (#127).
src/AniSprinkles.Core/PageModels/DetailsPageModelBase.cs Adds shared display-settings snapshot + re-projection plumbing for all details page models (#127).
src/AniSprinkles.Core/PageModels/CharacterDetailsPageModel.cs Wires details-page projection enumeration for character appearances cards (#127).
src/AniSprinkles.Core/PageModels/StaffDetailsPageModel.cs Wires details-page projection enumeration for voice/production role cards (#127).
src/AniSprinkles.Core/PageModels/SettingsPageModel.cs Implements generalized pending-marker durability, save coalescing, and outage-aware retry snackbar behavior (#128).
src/AniSprinkles.Core/Models/StudioMediaEdge.cs Implements IDisplayProjection and re-raises Node to refresh nested title bindings (#127).
src/AniSprinkles.Core/Models/StaffMediaEdge.cs Implements IDisplayProjection and re-raises Node to refresh nested title bindings (#127).
src/AniSprinkles.Core/Models/StaffCharacterEdge.cs Makes edge observable and implements IDisplayProjection by re-raising Media (#127).
src/AniSprinkles.Core/Models/MediaRelationEdge.cs Makes edge observable and implements IDisplayProjection by re-raising Node (#127).
src/AniSprinkles.Core/Models/MediaRecommendationNode.cs Makes node observable and implements IDisplayProjection by re-raising MediaRecommendation (#127).
src/AniSprinkles.Core/Models/MediaListEntry.cs Implements IDisplayProjection to re-raise nested title + score-format dependent members (#127).
src/AniSprinkles.Core/Models/IDisplayProjection.cs Introduces the projection contract used to force re-binding of computed display properties (#127).
src/AniSprinkles.Core/Models/CharacterMediaEdge.cs Implements IDisplayProjection and re-raises Node to refresh nested title bindings (#127).
src/AniSprinkles.Core/Models/BrowseMediaItem.cs Implements IDisplayProjection and re-raises Node to refresh nested title bindings (#127).
AGENTS.md Updates project guidance with new lifecycle and settings durability rules introduced by this PR.
.claude/skills/project-architecture/SKILL.md Updates architecture reference to include ISecureTokenStorage + TokenStore singleton lifetimes (#119).
Review details

Suppressed comments (3)

tests/AniSprinkles.UnitTests/Fakes/FakeSecureTokenStorage.cs:124

  • FakeSecureTokenStorage reads from the backing Dictionary without a lock; since the storage fake is exercised via concurrent TokenStore.GetAsync calls, protect this read with _sync (or switch _values to a thread-safe collection) to avoid undefined behavior in concurrency tests.
    tests/AniSprinkles.UnitTests/Fakes/FakeSecureTokenStorage.cs:131
  • FakeSecureTokenStorage.SetAsync and Remove both mutate the backing Dictionary without a lock. Since this fake is intended for concurrency tests, guard these mutations with _sync so future read/write overlaps don't introduce flaky test failures.
    tests/AniSprinkles.UnitTests/Fakes/FakeSecureTokenStorage.cs:133
  • FakeSecureTokenStorage.Remove mutates the backing Dictionary without taking _sync, which can lead to undefined behavior if a future test exercises a remove during concurrent reads. Lock this mutation for consistency with the rest of the fake's synchronization.
  • Files reviewed: 43/43 changed files
  • Comments generated: 2
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Zach Hollis and others added 2 commits August 24, 2026 23:06
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.
@github-actions

github-actions Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

📱 UI Screenshots

✅ Authenticated UI — screenshots rendered via compile-time CI stub services with hardcoded data. No OAuth token required.

View Workflow Run →

Library Discover View All (Browse) Search One Piece Details Toei Animation (Studio) Luffy (Character) Mayumi Tanaka (Staff) Settings
Library Discover View All (Browse) Search One Piece Details Toei Animation (Studio) Luffy (Character) Mayumi Tanaka (Staff) Settings

Zach Hollis and others added 4 commits August 24, 2026 23:41
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.
#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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

The changes are consistent with repo architecture, include targeted unit coverage for the reported failure modes, and the diff shows no remaining correctness or API-contract issues in the modified regions.

Review details
  • Files reviewed: 44/53 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@zhollis21
zhollis21 merged commit fe4dbad into main Aug 25, 2026
4 checks passed
@zhollis21
zhollis21 deleted the feature/119-127-128-settings-and-token-consistency branch August 25, 2026 12:44
zhollis21 added a commit that referenced this pull request Nov 19, 2026
…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>
zhollis21 added a commit that referenced this pull request Nov 22, 2026
…page (#227) (#231)

* Keep moves, adds and removals straight under fixture replay (#221)

- The adult canary rides the first recorded list, which on the test
  account is Completed, and it rode it as CURRENT. Replay reads a list's
  status off its entries, so Completed read as Watching: a title moved to
  Completed vanished, and one moved to Watching was filed under Completed.
  The canary now takes the status of the list it joins.
- A title added from Up Next had no recorded Media, so its card rendered
  blank. Replay now remembers the related titles a MediaRelations read
  showed and borrows the media block from there.
- A title added during replay could not be removed: its made-up entry id
  never reached the entry-id map, which list reads fill before saved
  entries go back in. Saves now record it.

* Add UI journeys for list edits, Up Next, Shell tabs and every pushed page (#227)

Nine journeys replace checks that were done by hand:
- TabReturnJourneys: the title language after a tab return on the
  character, staff, studio and View All pages (#133 checked these by hand).
- NavigationJourneys: #177's ANIME / MANGA strip over a pushed details
  page, judged by the details title not moving down, and #200's re-tap
  that pops to the root and then scrolls to the top.
- ListEditJourneys: long-press Move to Paused and back; Mark as completed
  into Up Next, adding the pick to Watching; the details dropdown's
  Completed into Up Next and Not now. These write list data, so they skip
  unless the app replays fixtures, which a Debug build now reports through
  a preference written at launch. Each puts back what it moved.

The harness gains a real long press and drag, Back-key recovery from a
left-open popup, a reset that returns the Library to the top, and lookups
that ignore the Manga tab's views, which the agent reports visible with
zero bounds once that tab has been opened.

AutomationIds on the long-press menu, Move to sheet, status dropdown,
rating prompt, Up Next sheet, confirm dialog, Library sections and the
View All, staff and studio titles. CI's journey floor rises to 12.

* Set the section states journeys rely on, and skip Up Next journeys when it is off

Review feedback on #231:

- Library sections keep their expanded state for the launch, so the Move
  journey timed out when Paused was already open: the moved card stayed
  laid out. Journeys now read a section's state from its header chevron,
  set the ones they rely on and put them back in teardown, rather than
  toggling blind.
- A collapsed Settings section was invisible to the old check, which asked
  whether a chip was visible: a chip keeps its own IsVisible, and its last
  bounds, while its section is shut. Settings sections are now judged by
  their content border, for Up Next's chips and Display Preferences'
  alike, and opened when shut.
- Both Up Next journeys skip when Up Next is turned off, before they change
  anything; the details-dropdown one used to time out with ONE PIECE left
  completed.
- The re-tap journey's title lookup now ignores the Manga tab's zero-bounds
  views, which could stand in for the Anime card.

* Reset journeys to the Anime list with Watching open, whatever state they find

Copilot's second review of #231:

- Re-tapping the Library tab never changes the Anime/Manga sub-tab, so a
  run that started on Manga tested the Manga list and the list-edit
  journeys timed out looking for Watching. The reset now touches the Anime
  tab (skipped on MAUI 11's Shell handlers, which show the agent no native
  views).
- With every section collapsed there are no cards, and the reset waited
  for one. It waits for the list instead, and the shared Journey setup
  opens Watching, which most journeys need, recording each section's state
  and putting it back in teardown.
- The Up Next guard read an unset preference as turned off: the agent
  reports an unset bool as exists=false, value=false. Unset now means on.

Sword Art Online still comes back from the Up Next journey at 24/25, not
0/25; whether a completed title should reset to 0 is recorded on #222.

* Clear a leftover Library filter, and make the re-tap journey scroll in any view mode

Copilot's third review of #231:

- The Library search text lasts the launch. A leftover filter hid titles
  and turned section counts into "1/4", which the list-edit journeys could
  not read. Shared setup now clears it through the agent and puts it back
  in teardown.
- In Compact view, Watching's four rows and the shut headers fit on one
  screen, so the re-tap journey had nothing to scroll. It now opens the
  other populated sections first; teardown shuts them again.
- The pop check only asserted the list was not back at the top. It now
  records a settled on-screen title and requires the same title at the same
  position after the pop.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants