Skip to content
2 changes: 1 addition & 1 deletion .claude/skills/project-architecture/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ Storage goes through `AppSettings.Storage`, an `internal static IPreferences` de

**List screens:** Cache each Library list in-memory with a timestamp. Show cached list immediately, refresh in background when stale (>5 min) or user pulls to refresh. Preserve expanded section states and scroll position when returning from details.

**API:** Use cancellation tokens per navigation context. Duplicate in-flight character/staff reads are coalesced and cached by `CachingAniListClient`. Rate-limit handling is centralized in `AniListRateLimitHandler` (serialized requests, `Retry-After`-aware bounded retry, `ApiErrorKind.RateLimited` when exhausted) — do **not** add per-call **429/rate-limit** retry loops. Separately, `AniListClient.SendAsync` does a single short-delay retry for *transient* failures only (`Network`, `Authentication`, `Unknown` — e.g. AniList's sporadic `400 "Invalid token"`); it deliberately excludes `RateLimited` (the handler owns that), `NotFound` (deterministic), and `ServiceOutage`. A recovered blip stays a `Warning` breadcrumb and isn't reported to the outage tracker. Character/staff detail lists are lazily paged with server-side sort (`PaginatedSection<T>`); a character's voice actors are deduped/grouped by `VoiceActorAggregator` walking a fixed popularity cursor independent of the Appears-In sort.
**API:** Use cancellation tokens per navigation context. Duplicate in-flight character/staff reads are coalesced and cached by `CachingAniListClient`. Rate-limit handling is centralized in `AniListRateLimitHandler` (serialized requests, `Retry-After`-aware bounded retry, `ApiErrorKind.RateLimited` when exhausted) — do **not** add per-call **429/rate-limit** retry loops. Separately, `AniListClient.SendAsync` does a single short-delay retry for *transient* failures only (`Network`, `Authentication`, `Unknown` — e.g. AniList's sporadic `400 "Invalid token"`); it deliberately excludes `RateLimited` (the handler owns that), `NotFound` (usually deterministic — but see #158: the error card still offers a manual Retry, because we could not tell a real 404 from a transient failure misfiled as one), and `ServiceOutage`. A recovered blip stays a `Warning` breadcrumb and isn't reported to the outage tracker. Character/staff detail lists are lazily paged with server-side sort (`PaginatedSection<T>`); a character's voice actors are deduped/grouped by `VoiceActorAggregator` walking a fixed popularity cursor independent of the Appears-In sort.

**API — `pageInfo` counts are unreliable (AniList quirk):** AniList documents that `pageInfo.total` and `pageInfo.lastPage` are **not accurate** ("limited due to performance issues") — `total` only matches reality when every item fits on the requested page, otherwise it returns a bogus/capped value (e.g. **500** for any studio's `media` past one page, even tiny ones). **Only `hasNextPage` is trustworthy.** So `PaginatedSection`/paging keys off `hasNextPage` (+ `currentPage` for seeding) and never `total`/`lastPage`. Do **not** surface a server "N total" count (we tried a studio "N productions" badge and it showed 500 for everyone). The `PageInfo` model therefore carries only `HasNextPage` + `CurrentPage` (no `total`/`lastPage`), and queries don't request them. Refs: [PageInfo](https://docs.anilist.co/reference/object/pageinfo), [Pagination](https://docs.anilist.co/guide/graphql/pagination).

Expand Down
6 changes: 5 additions & 1 deletion AGENTS.md

Large diffs are not rendered by default.

Binary file modified screenshots/anime_library.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/browse.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/character_details.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/discover.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/manga_library.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/one_piece_details.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/search.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/settings.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/staff_details.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/studio_details.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
17 changes: 14 additions & 3 deletions src/AniSprinkles.Core/PageModels/DetailsPageModelBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,8 @@ protected async Task LoadCoreAsync(int id)
var isNotFound = apiEx?.Kind == ApiErrorKind.NotFound;
if (isNotFound)
{
// NotFound is non-retryable and intentionally kept out of Sentry — log at Warning so it stays a breadcrumb.
// Still logged at Warning rather than Error — a missing entry is an expected outcome,
// not a fault in this app. What changed in #158 is everything after this line.
Logger.LogWarning(
ex,
"NAVTRACE {TracePrefix} not found on AniList in {ElapsedMs}ms ({EntityNoun} {Id})",
Expand All @@ -361,12 +362,22 @@ protected async Task LoadCoreAsync(int id)
TracePrefix, stopwatch.ElapsedMilliseconds, EntityNoun, id);
}

// NotFound is treated exactly like every other failure from here on (#158). It used to
// get neither a retry nor a details string, and ErrorStateView gates its Copy/Share/Report
// actions on that string — so the error a user is least able to explain was the only one
// they could neither retry nor send. The asymmetry decides it: a genuine 404 costs one
// user-initiated request when they tap Retry, while a misclassified transient used to
// cost them the entire page with no recourse.
//
// Routing it through Record also means NotFound now reaches Sentry. That is deliberate —
// the frequency data is the thing we were missing — and can be fingerprinted down later
// if it proves noisy.
var (title, subtitle) = DescribeError(ex);
ShowError(
title,
subtitle,
canRetry: !isNotFound,
details: isNotFound ? string.Empty : _errorReportService.Record(ex, $"Load {EntityNoun} details"),
canRetry: true,
details: _errorReportService.Record(ex, $"Load {EntityNoun} details"),
iconGlyph: apiEx?.IconGlyph);
}
finally
Expand Down
172 changes: 172 additions & 0 deletions src/AniSprinkles.Core/PageModels/DiagnosticsReportCoordinator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
using AniSprinkles.Services;
using AniSprinkles.Services.Abstractions;
using Microsoft.Extensions.Logging;

namespace AniSprinkles.PageModels;

/// <summary>
/// The whole send-a-diagnostic-report flow, in one place so both entry points behave identically:
/// the Settings card and the Report action on any error card (#112).
/// <para>
/// Order matters and is the point of the type. Disclose first — the user sees what is about to leave
/// their device before anything is collected, not after. Then snapshot, build, redact, send, and say
/// what happened. Sentry is silent to the sender, so the popup and the confirmation are the only
/// things telling the user their report exists.
/// </para>
/// </summary>
public sealed class DiagnosticsReportCoordinator
{
/// <summary>
/// What the popup promises. Kept here rather than in the popup's XAML so the promise and the
/// thing that fulfils it live in one file and are asserted together — a disclosure that drifts
/// from what is actually collected is worse than no disclosure, because it is trusted.
/// </summary>
public const string DisclosureSummary =
"This sends the last 5 minutes of app activity: the screens you opened, the AniList ids they "
+ "were for, the requests the app made and how they failed, plus your app version and device "
+ "model. Your AniList login is never included.";

/// <summary>Shown after a successful send. Names the thing the popup promised, so the two read
/// back against each other rather than the user having to take "sent" on faith.</summary>
public const string SentMessage = "Diagnostics sent — last 5 minutes of activity.";

/// <summary>Shown when nothing left the device. Never silently swallowed: a report the user
/// believes they filed and did not is worse than a visible failure.</summary>
public const string FailedMessage = "Couldn't send diagnostics. Check your connection and try again.";

/// <summary>
/// Shown by an entry point that could not even reach this coordinator — i.e. the DI container
/// was unavailable. Lives here with the other two so all three read as one voice, even though
/// nothing in this class can show it: by definition that path never got this far.
/// </summary>
public const string UnavailableMessage = "Diagnostics aren't available right now.";

private readonly DiagnosticsLogBuffer _buffer;
private readonly DiagnosticsSessionLog _sessionLog;
private readonly IDiagnosticsSink _sink;
private readonly IDialogService _dialogs;
private readonly IUserFeedback _feedback;
private readonly IAppEnvironment _environment;
private readonly IAuthService _authService;
private readonly TimeProvider _timeProvider;
private readonly ILogger<DiagnosticsReportCoordinator> _logger;

public DiagnosticsReportCoordinator(
DiagnosticsLogBuffer buffer,
DiagnosticsSessionLog sessionLog,
IDiagnosticsSink sink,
IDialogService dialogs,
IUserFeedback feedback,
IAppEnvironment environment,
IAuthService authService,
TimeProvider timeProvider,
ILogger<DiagnosticsReportCoordinator> logger)
{
_buffer = buffer;
_sessionLog = sessionLog;
_sink = sink;
_dialogs = dialogs;
_feedback = feedback;
_environment = environment;
_authService = authService;
_timeProvider = timeProvider;
_logger = logger;
}

/// <summary>
/// True while a report is being assembled or sent. Guards against a double tap producing two
/// events for one intent — the send is slow enough (it waits for the Sentry flush) that a second
/// press is easy.
/// </summary>
public bool IsBusy { get; private set; }

/// <summary>
/// Runs the flow. Returns <c>true</c> only when a report actually reached Sentry — cancelling at
/// the popup returns <c>false</c>, as does a failed send, so a caller that disables its button
/// after a successful report does not disable it on a cancel.
/// </summary>
public async Task<bool> ReportAsync(CancellationToken cancellationToken = default)
{
if (IsBusy)
{
return false;
}

IsBusy = true;
try
{
var choice = await _dialogs.ShowDiagnosticsReportAsync(DisclosureSummary).ConfigureAwait(true);
if (choice is null)
{
_logger.LogInformation("Diagnostic report cancelled at the disclosure.");
return false;
}

// Snapshotted only after consent. Collecting first and discarding on cancel would work
// just as well technically, and would make the disclosure a formality rather than a gate.
var current = _buffer.Snapshot();
var previous = _sessionLog.Load();

var report = DiagnosticsReportBuilder.Build(
await BuildContextAsync(cancellationToken).ConfigureAwait(true),
_timeProvider.GetUtcNow(),
previous,
current,
choice.Value.Description);

var sent = await _sink.SendAsync(report, choice.Value.Description, cancellationToken).ConfigureAwait(true);

if (sent)
{
// Only once it is genuinely gone. Clearing on a failed send would throw away the
// previous session's lines — the ones a crash flush existed to preserve — and the
// retry would carry less than the attempt that failed.
_sessionLog.Clear();

// Confirmed branch only, matching how the other repeatable user actions breadcrumb.
// Its value is on *later* events: "this user had already reported something" is real
// context, and a cancel breadcrumb would only add buffer noise.
SentrySdk.AddBreadcrumb("Diagnostic report sent", "state", "user");
}

await _feedback.ShowSnackbarAsync(sent ? SentMessage : FailedMessage).ConfigureAwait(true);
return sent;
}
catch (Exception ex)
{
// This runs off a button the user pressed because something was already wrong. The
// reporting path throwing on top of that is the worst outcome available, so it is caught
// here and told to the user rather than raised.
_logger.LogError(ex, "Diagnostic report flow failed.");
await _feedback.ShowSnackbarAsync(FailedMessage).ConfigureAwait(true);
return false;
}
finally
{
IsBusy = false;
}
}

private async Task<DiagnosticsContext> BuildContextAsync(CancellationToken cancellationToken)
{
var isSignedIn = false;
try
{
isSignedIn = !string.IsNullOrWhiteSpace(
await _authService.GetAccessTokenAsync(cancellationToken).ConfigureAwait(true));
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// A header field is not worth losing the report over — secure storage can fail, and if it
// just did, that is itself something the log will show.
_logger.LogWarning(ex, "Could not determine sign-in state for the diagnostic report.");
}

return new DiagnosticsContext(
_environment.AppVersion,
_environment.BuildConfiguration,
_environment.Device,
_environment.OsVersion,
isSignedIn);
}
}
26 changes: 26 additions & 0 deletions src/AniSprinkles.Core/Services/Abstractions/IAppEnvironment.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
namespace AniSprinkles.Services.Abstractions;

/// <summary>
/// The handful of environment facts a diagnostic report needs in its header (#112).
/// <para>
/// A seam because every one of these comes from MAUI Essentials — <c>AppInfo</c>, <c>DeviceInfo</c> —
/// which throw rather than degrade on the plain <c>net10.0</c> test TFM. Reading them straight from a
/// page model would make the whole report flow untestable.
/// </para>
/// </summary>
public interface IAppEnvironment
{
/// <summary>Version and build, e.g. <c>0.13.0 (142)</c>.</summary>
string AppVersion { get; }

/// <summary><c>Debug</c> or <c>Release</c>. Load on this repo's behaviour genuinely diverges
/// between the two — log levels, CI stubs, fault injection — so a report that does not say which
/// one it came from is missing a fact the reader would otherwise have to guess.</summary>
string BuildConfiguration { get; }

/// <summary>Manufacturer and model, e.g. <c>Google Pixel 7</c>.</summary>
string Device { get; }

/// <summary>Platform and version, e.g. <c>Android 15</c>.</summary>
string OsVersion { get; }
}
20 changes: 20 additions & 0 deletions src/AniSprinkles.Core/Services/Abstractions/IDiagnosticsSink.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
namespace AniSprinkles.Services.Abstractions;

/// <summary>
/// Where a finished diagnostic report is sent (#112).
/// <para>
/// A seam for the same reason <see cref="IDialogService"/> is one, and with a sharper edge: an
/// uninitialised <c>SentrySdk</c> does not throw, it silently discards. A page model calling it
/// directly would no-op in a test and read as a pass, so "the report was sent" would never actually
/// be asserted anywhere.
/// </para>
/// </summary>
public interface IDiagnosticsSink
{
/// <summary>
/// Sends <paramref name="report"/>, with <paramref name="description"/> attached as the user's own
/// account of what happened when they gave one. Returns whether it was accepted for delivery.
/// Never throws — a failed send is reported to the user, not raised.
/// </summary>
Task<bool> SendAsync(string report, string? description, CancellationToken cancellationToken = default);
}
19 changes: 19 additions & 0 deletions src/AniSprinkles.Core/Services/Abstractions/IDialogService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ private MoveToListChoice(MediaListStatus? status, bool isRemove)
public static MoveToListChoice Remove { get; } = new(status: null, isRemove: true);
}

/// <summary>
/// What the user chose in the send-diagnostics sheet (#112). Reaching this at all means they pressed
/// Send; <see cref="Description"/> is what they typed, which is optional — requiring text would be
/// friction for someone who only wants the log attached.
/// </summary>
public readonly record struct DiagnosticsReportChoice(string? Description);

/// <summary>
/// Modal user interaction — confirmations, prompts, and the bottom-sheet pickers. Abstracted for the
/// same reason as <see cref="INavigationService"/> and <see cref="IUserFeedback"/>: the concrete
Expand Down Expand Up @@ -76,6 +83,18 @@ Task<bool> ConfirmAsync(
bool isDestructive = false,
string? iconGlyph = null);

/// <summary>
/// The send-diagnostics sheet (#112): states what <paramref name="summary"/> says is about to be
/// collected, and offers an optional box for what the user was doing. Returns <c>null</c> if they
/// cancelled or dismissed it.
/// <para>
/// A choice rather than a nullable string because "cancelled" and "sent without a note" are
/// different answers that a <c>string?</c> would flatten into the same <c>null</c> — and one of
/// them must not send anything.
/// </para>
/// </summary>
Task<DiagnosticsReportChoice?> ShowDiagnosticsReportAsync(string summary);

/// <summary>
/// Single-line text prompt. Returns <c>null</c> if the user cancelled.
/// </summary>
Expand Down
12 changes: 9 additions & 3 deletions src/AniSprinkles.Core/Services/AniListApiException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,17 @@ public enum ApiErrorKind
RateLimited,

/// <summary>
/// AniList returned 404 (or a "Not Found" GraphQL error) for a media/character/staff id we
/// AniList returned 404, or a GraphQL error whose entire message is "Not Found", for an id we
/// requested — the id did not resolve. This can be an AniList-side dangling reference (an id from
/// a relation, recommendation, or list entry that no longer exists) or a type-constrained lookup
/// (e.g. a non-anime id passed to <c>Media(id:, type: ANIME)</c>). Either way the result won't
/// change on a retry, so it is treated as non-retryable and is not reported to Sentry.
/// (e.g. a non-anime id passed to <c>Media(id:, type: ANIME)</c>).
/// <para>
/// Usually the result won't change on a retry — but it is still offered, and still reported
/// (#158). We could not previously tell a genuine 404 from a transient failure misfiled as one,
/// because this was the single kind that produced neither a Sentry event nor a shareable report,
/// so there was nothing to tell them apart with. See <see cref="AniListErrorClassifier"/> for the
/// matching rule that stopped arbitrary server text landing here.
/// </para>
/// </summary>
NotFound,
}
Expand Down
Loading
Loading