diff --git a/.claude/skills/project-architecture/SKILL.md b/.claude/skills/project-architecture/SKILL.md index 006812f0..b10b6f62 100644 --- a/.claude/skills/project-architecture/SKILL.md +++ b/.claude/skills/project-architecture/SKILL.md @@ -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`); 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`); 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). diff --git a/AGENTS.md b/AGENTS.md index c9c81237..46f24108 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,7 @@ - **Core references neither `CommunityToolkit.Maui` nor `IconFont.Maui.FluentIcons`**, deliberately. Popups, snackbars and toasts go through `IDialogService` / `IUserFeedback`; leaving the package out is what stops that seam eroding. Icon glyphs are mirrored into `Core/Icons/Glyphs.cs` (generated by `tools/generate-glyphs.cs`, validated against the real package by `IconGlyphReferenceTests`) because the package ships platform TFMs only. - **MVVM** via CommunityToolkit.Mvvm: PageModels extend `ObservableObject`, use `[ObservableProperty]`, `[RelayCommand]`, `[NotifyPropertyChangedFor]`. The four details page models extend `DetailsPageModelBase` instead, which supplies the shared load/error/retry/favourite/external-link spine — see `/project-architecture`. Shell bottom-tab navigation (`library` with `anime`/`manga` sub-tabs, `discover`, `search`, `feed`, `settings`) with programmatic `media-details`, `staff-details`, `character-details`, `studio-details`, and `media-browse` routes. PageModels navigate through the injected `INavigationService` (routes + lightweight query params — never full objects); persist state via the injected `IPreferences`; marshal pool-thread continuations back to the UI via the injected `IDispatcher`; read app metadata via the injected `IAppInfo`. View-facing UX calls go through Core abstractions too — `IDialogService` for confirmations, prompts and the bottom-sheet pickers, `IUserFeedback` for snackbars and toasts, `IExternalBrowser` for "view on AniList" — each implemented in `src/AniSprinkles/Services/Maui/`. A PageModel must not reach `Shell.Current`, a popup type, or an Essentials static directly: `Shell.Current` and `Application.Current` return **null** off-device rather than throwing, so such a call silently no-ops and its test passes without exercising anything. The one exception is `HapticFeedback.Default.Perform` in `EntryActionCoordinator` — it returns nothing, has no observable effect to assert, and is already wrapped in a swallowing `catch`, so a seam would buy nothing. - **DI**: Services and tab PageModels (`AnimeLibraryPageModel` and `MangaLibraryPageModel` — two singletons over one parameterized `MediaListPageModel`, #12 — plus `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. -- **Services**: `AuthService` (OAuth + SecureStorage), `AniListClient` (GraphQL + viewer ID cache), `ErrorReportService` (Sentry + `ILogger`), `SensitiveText` / `SentryScrubber` (bearer-token redaction), `FileLoggerProvider` (rotating async file log, Debug = 1 MB × 3 / Release = 256 KB × 3), `AndroidLogcatLoggerProvider` (bridges `ILogger` → `adb logcat` on Android), `LoggingHandler` (HTTP DelegatingHandler), `AiringNotificationService` (WorkManager periodic check). See `/airing-notifications` for the notification subsystem. +- **Services**: `AuthService` (OAuth + SecureStorage), `AniListClient` (GraphQL + viewer ID cache), `ErrorReportService` (Sentry + `ILogger`), `SensitiveText` / `SentryScrubber` (bearer-token redaction), `FileLoggerProvider` (rotating async file log, Debug = 1 MB × 3 / Release = 256 KB × 3), `AndroidLogcatLoggerProvider` (bridges `ILogger` → `adb logcat` on Android), `LoggingHandler` (HTTP DelegatingHandler), `AiringNotificationService` (WorkManager periodic check), `DiagnosticsLogBuffer` / `DiagnosticsSessionLog` / `DiagnosticsSessionFlusher` / `DiagnosticsReportBuilder` / `SentryDiagnosticsSink` + `DiagnosticsReportCoordinator` (user-sent diagnostic reports, #112). See `/airing-notifications` for the notification subsystem. - **Global usings** (`GlobalUsings.cs`): `Models`, `PageModels`, `Pages`, `Services`, `IconFont.Maui.FluentIcons`. `Converters` and `Utilities` require explicit `using`. - **Key NuGet packages**: `Microsoft.Maui.Controls`, `CommunityToolkit.Mvvm`, `CommunityToolkit.Maui`, `Sentry.Maui`, `Syncfusion.Maui.Toolkit`, `IconFont.Maui.FluentIcons`. @@ -32,6 +32,7 @@ - **AniList publishes no chapter schedule.** `chapters` and `volumes` are null for *every* RELEASING series (verified across One Piece, Berserk, Dandadan, Sakamoto Days), and there is no `nextAiringEpisode` equivalent to fall back on the way an airing anime has. So an ongoing manga has no cap, no progress bar, no "chapters behind" and no completion prompt — that is the common case, not an edge one. - **Rate limiting**: `AniListRateLimitHandler` (a `DelegatingHandler`) serializes all requests, reads `X-RateLimit-Remaining`/`X-RateLimit-Reset` for adaptive spacing, and does bounded `Retry-After`-aware retry on 429 (surfacing `ApiErrorKind.RateLimited` when the wait exceeds the cap or retries are exhausted). - **Transient retry**: `AniListClient.SendAsync` retries once (short delay) on plausibly transient failures — `Network`, `Authentication` (e.g. AniList's sporadic `400 "Invalid token"` on a valid token), and `Unknown` — and **not** `RateLimited` (owned by the handler above), `NotFound`, or `ServiceOutage`. A recovered blip stays a `Warning` breadcrumb and isn't reported to the outage tracker. +- **`NotFound` is no longer a dead end (#158).** It is still excluded from the *automatic* retry above, but the error card now offers Retry and produces a report like every other failure — it used to get neither, and `ErrorStateView` gates Copy/Share on that report string, so the error a user can least explain was the only one they could neither retry nor send. The classifier now matches AniList's `"Not Found."` message **exactly** rather than as a substring anywhere in server text (`AniListErrorClassifier.IsNotFoundMessage`); a substring hit turned any transient failure containing those two words into a permanent, silent dead end. One consequence to know about: `NotFound` now reaches Sentry, deliberately, because the frequency data is what was missing. Fingerprint it down if it proves noisy. - **Caching**: `CachingAniListClient` decorates `IAniListClient`, caching character/staff/studio reads for the session and coalescing concurrent same-key fetches. `InvalidateEntityCache()` drops them; `SettingsPageModel` calls it when Staff Name Language changes (#130), because names render from `userPreferred` — resolved server-side against that setting, so cached reads hold a stale rendering. Invalidate-only, no refetch: pages reload as the user navigates to them. Other reads (lists, search, media, discover/browse) pass through — broader caching is a planned follow-up. Discover sections have their own ~20-minute TTL cache inside the singleton `DiscoverPageModel` (invalidated by pull-to-refresh, an adult-toggle flip, or an auth change) because the rows carry viewer-relative `mediaListEntry` state. - **On Android a cancelled request is not an `OperationCanceledException`.** `AndroidMessageHandler` disconnects the underlying `HttpURLConnection`, so the read already in flight fails with `Java.Net.SocketException("Socket closed")` and reaches managed code as a **`System.Net.WebException`** — a type no `catch (OperationCanceledException)` in the app matches. Both HTTP boundaries therefore consult the *token*, not the exception type — but **not the same token**, and the difference is the whole trick: - `AniListClient.SendAsyncCore` holds the **caller's** token and calls `ThrowIfCancellationRequested()` before classifying, so a superseded search or a page left mid-load abandons quietly while an uncancelled socket drop still classifies as `Network`. @@ -143,7 +144,9 @@ dotnet build src/AniSprinkles/AniSprinkles.csproj -c Debug -f net10.0-android -p - Provider wiring lives in `MauiProgram.cs`. `FileLoggerProvider` runs in both Debug (1 MB × 3 at `LogLevel.Debug`) and Release (256 KB × 3 at `LogLevel.Warning`). `AndroidLogcatLoggerProvider` bridges ILogger output into `adb logcat` on Android in all build configs (`AddDebug()` does not reach logcat on .NET MAUI Android). `AddDebug()` stays Debug-only. - Exception: `Platforms/Android/MainActivity.cs` and `Platforms/Android/AiringCheckWorker.cs` call `Android.Util.Log` directly because they run before the MAUI DI container is guaranteed to be built (activity lifecycle callbacks; post-reboot WorkManager). Inline comments document this at the call sites. Do not introduce new direct-`Android.Util.Log` callers elsewhere — use ILogger. - On-device log file: `{AppDataDirectory}/logs/anisprinkles.log` (+ `.1`, `.2` archives). Pull via `adb shell run-as com.RainbowSprinkles.AniSprinkles cat files/logs/anisprinkles.log` or use `/ani-debug`. + - **`DiagnosticsLogBuffer` is a third provider, in memory, at `LogLevel.Information` in every config (#112).** It exists because the file log drops `Information` in Release, which is every trace worth sending — no `NAVTRACE`, no `PageState`, no `HTTP`. It keeps roughly the last five minutes, bounded by age *and* entry count, and touches no disk. `DiagnosticsSessionFlusher` writes a snapshot to `{AppDataDirectory}/logs/previous-session.log` from the three global exception handlers and `MainActivity.OnPause`, and clears it again on resume — but only when this process wrote it, since a file left by a process that actually died is the thing worth sending. If you change `DiagnosticsLogBuffer.DefaultRetention`, the popup's "5 minutes" copy is a lie; `DiagnosticsDisclosureTests` fails on purpose when they drift. Neither the ring nor `previous-session.log` is cleared on sign-out — a crash spanning sign-out/sign-in is worth reporting, and this is a single-user install. Revisit before first public release. - **Telemetry**: Sentry crash reporting only (`SendDefaultPii = false`, `TracesSampleRate = 0.0`, plus a `BeforeSend` redaction pass — `SendDefaultPii` governs IP/username, not message content). Use `ErrorReportService.Record()` for handled exceptions. + - **The Sentry event comes from `Record`'s `LogError`, not its `CaptureException`** — confirmed by the `mechanism: SentryLogger` tag on the events. `MinimumEventLevel` defaults to `Error`, so the `ILogger` integration captures first and gets the real id; the explicit `CaptureException` on the next line is then dropped by `DuplicateEventDetectionEventProcessor` (`DeduplicateMode` defaults to `All ^ InnerException`, which still includes `SameExceptionInstance`) and returns `SentryId.Empty`. Worse, `Hub.CaptureEvent` assigns `scope.LastEventId = id` unguarded, so that empty id **overwrites** the good one — which is why `SentrySdk.LastEventId` is also empty. Don't build anything on either value; correlate on exception text and timestamp. Do not "fix" it by swapping the two lines either: the logger-created event is the richer one (it carries the `Context` tag, the logger name and a readable message), and a bare `CaptureException` event has none of that. Cost this out before touching it — #112 tried twice and removed the feature instead. - **User prefs**: `AppSettings` (static, `Utilities/`) persists title language, score format, adult content toggle, and section order through the injectable `AppSettings.Storage` seam, which defaults to `Preferences.Default` (#121). `DisplayAdultContent` commits the instant the Settings toggle flips via `SetDisplayAdultContent`, ahead of the debounced AniList save (#118) — every browse surface filters on it and only re-checks when it appears, so a late commit left 18+ results on screen. Paging must be pinned to the value its page 1 was seeded under (`_seededDisplayAdult` in `SearchPageModel`, `DiscoverPageModel` and `MediaBrowsePageModel`; passed into `DiscoverSectionFetch.PageAsync`) rather than re-reading the static per page, or one result set can hold two policies. All four surfaces — Library included — compare it against the value their current data was built with. Title language and score format commit the same way, via `SetTitleLanguage` / `SetScoreFormat` (#128); before that they reached `AppSettings` only once a save had succeeded. A locally committed change outranks the server's copy until the server reports that same value back — for all three now, not just the adult toggle — so neither a refresh elsewhere in the app nor a return to Settings can sync the pre-change value over it; `SettingsPage.OnDisappearing` flushes any pending save so the server catches up promptly. The settings the Settings page holds on its own (staff name language, restrict-messages, activity merge time, airing notifications, and the per-type notification toggles) carry the same markers there — the per-type ones as a set of unconfirmed types, 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 come from the server. - **The airing job follows the toggle both ways.** `PopulateFromUser` schedules the WorkManager check when airing notifications land on, and cancels it when they land off. Only the enabling half was wired originally, so turning the setting off anywhere else — the AniList website, another device — left this device still scheduled, and the switch read off while notifications kept arriving. Cancelling an unscheduled job is a no-op, so the else-branch is safe on every load. - **Pushed detail pages get no lifecycle on a tab return.** `OnAppearing` / `OnDisappearing` fire on tab-*root* pages (Library, Discover, Search, Settings) when you switch tabs, but **not** on a page pushed onto a backgrounded tab's navigation stack — the four detail pages and View All (`AppShell.xaml.cs:23-27`). Verified on device: `MediaDetailsPage.OnAppearing` logged exactly once, at the initial navigation, and tabbing away and back produced nothing. **Use `OnNavigatedTo` instead** — it fires on every tab return, and pairs with `OnNavigatedFrom` on the way out; all five pushed pages call `ViewModel.RefreshDisplaySettings()` from it. Confirmed in the same device run: `OnAppearing` 1, `OnDisappearing` 0, `OnNavigatedTo` 3 across two tab round-trips. No unit test will tell you which to use — the page model behaves correctly when called, and the bug is that nothing calls it, so a test driving the page model directly passes while the feature is dead on device. Verify on device via `/run-anisprinkles`, and see #131. @@ -198,6 +201,7 @@ When presenting 2+ approaches to the user, list them clearly with tradeoffs for - **OAuth implicit grant** via `WebAuthenticator`; tokens stored in `SecureStorage`, never logged. - Bearer tokens are redacted **at the source**, not at each sink (#124). `SensitiveText.Redact` is applied in `AniListClient` to every server-derived string that becomes an exception message, so the token never enters the exception and the file log, logcat and Sentry are safe by construction. `SentryScrubber` (wired via `options.SetBeforeSend`) is the backstop for exceptions Sentry captures without going through `ErrorReportService`. Classification runs on the raw text and redaction only on what gets stored, so `AniListErrorClassifier` keeps matching "Invalid token" and the outage markers. +- **`SentryScrubber` does not walk attachments**, so it is *not* the backstop for a user-sent diagnostic report (#112) — that report goes to Sentry as an attachment, by a route `SetBeforeSend` never inspects. `DiagnosticsReportBuilder.Build` runs one `SensitiveText.Redact` pass over the whole finished report, and `SentryDiagnosticsSink` redacts the free-text description separately because it takes a third route again (`SentryFeedback`). If you add a section to that report, it inherits the pass; if you add another *sink*, it does not. - Sentry: `SendDefaultPii = false`. AniList Client ID (`35674`) is a public app identifier, not a secret. - Sign-out clears both in-memory token fields and both SecureStorage keys. - Token expiry is tracked and auto-cleared when expired (`IsExpired()` check on access). diff --git a/screenshots/anime_library.png b/screenshots/anime_library.png index dae41306..53037dd3 100644 Binary files a/screenshots/anime_library.png and b/screenshots/anime_library.png differ diff --git a/screenshots/browse.png b/screenshots/browse.png index b7e092d6..303138db 100644 Binary files a/screenshots/browse.png and b/screenshots/browse.png differ diff --git a/screenshots/character_details.png b/screenshots/character_details.png index 7a8de2ad..3354f3ed 100644 Binary files a/screenshots/character_details.png and b/screenshots/character_details.png differ diff --git a/screenshots/discover.png b/screenshots/discover.png index 95678146..076060bd 100644 Binary files a/screenshots/discover.png and b/screenshots/discover.png differ diff --git a/screenshots/manga_library.png b/screenshots/manga_library.png index 2053e49e..a63f3420 100644 Binary files a/screenshots/manga_library.png and b/screenshots/manga_library.png differ diff --git a/screenshots/one_piece_details.png b/screenshots/one_piece_details.png index 6cc212f6..6512039f 100644 Binary files a/screenshots/one_piece_details.png and b/screenshots/one_piece_details.png differ diff --git a/screenshots/search.png b/screenshots/search.png index 577301e4..3f294920 100644 Binary files a/screenshots/search.png and b/screenshots/search.png differ diff --git a/screenshots/settings.png b/screenshots/settings.png index 0237c8c5..6468d8bf 100644 Binary files a/screenshots/settings.png and b/screenshots/settings.png differ diff --git a/screenshots/staff_details.png b/screenshots/staff_details.png index 6d528a85..cc4bbb04 100644 Binary files a/screenshots/staff_details.png and b/screenshots/staff_details.png differ diff --git a/screenshots/studio_details.png b/screenshots/studio_details.png index 0f3f1897..d1198c86 100644 Binary files a/screenshots/studio_details.png and b/screenshots/studio_details.png differ diff --git a/src/AniSprinkles.Core/PageModels/DetailsPageModelBase.cs b/src/AniSprinkles.Core/PageModels/DetailsPageModelBase.cs index 22ce5cf0..ee94a27d 100644 --- a/src/AniSprinkles.Core/PageModels/DetailsPageModelBase.cs +++ b/src/AniSprinkles.Core/PageModels/DetailsPageModelBase.cs @@ -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})", @@ -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 diff --git a/src/AniSprinkles.Core/PageModels/DiagnosticsReportCoordinator.cs b/src/AniSprinkles.Core/PageModels/DiagnosticsReportCoordinator.cs new file mode 100644 index 00000000..301ea7c3 --- /dev/null +++ b/src/AniSprinkles.Core/PageModels/DiagnosticsReportCoordinator.cs @@ -0,0 +1,172 @@ +using AniSprinkles.Services; +using AniSprinkles.Services.Abstractions; +using Microsoft.Extensions.Logging; + +namespace AniSprinkles.PageModels; + +/// +/// 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). +/// +/// 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. +/// +/// +public sealed class DiagnosticsReportCoordinator +{ + /// + /// 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. + /// + 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."; + + /// 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. + public const string SentMessage = "Diagnostics sent — last 5 minutes of activity."; + + /// 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. + public const string FailedMessage = "Couldn't send diagnostics. Check your connection and try again."; + + /// + /// 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. + /// + 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 _logger; + + public DiagnosticsReportCoordinator( + DiagnosticsLogBuffer buffer, + DiagnosticsSessionLog sessionLog, + IDiagnosticsSink sink, + IDialogService dialogs, + IUserFeedback feedback, + IAppEnvironment environment, + IAuthService authService, + TimeProvider timeProvider, + ILogger logger) + { + _buffer = buffer; + _sessionLog = sessionLog; + _sink = sink; + _dialogs = dialogs; + _feedback = feedback; + _environment = environment; + _authService = authService; + _timeProvider = timeProvider; + _logger = logger; + } + + /// + /// 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. + /// + public bool IsBusy { get; private set; } + + /// + /// Runs the flow. Returns true only when a report actually reached Sentry — cancelling at + /// the popup returns false, as does a failed send, so a caller that disables its button + /// after a successful report does not disable it on a cancel. + /// + public async Task 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 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); + } +} diff --git a/src/AniSprinkles.Core/Services/Abstractions/IAppEnvironment.cs b/src/AniSprinkles.Core/Services/Abstractions/IAppEnvironment.cs new file mode 100644 index 00000000..e26f3e7d --- /dev/null +++ b/src/AniSprinkles.Core/Services/Abstractions/IAppEnvironment.cs @@ -0,0 +1,26 @@ +namespace AniSprinkles.Services.Abstractions; + +/// +/// The handful of environment facts a diagnostic report needs in its header (#112). +/// +/// A seam because every one of these comes from MAUI Essentials — AppInfo, DeviceInfo — +/// which throw rather than degrade on the plain net10.0 test TFM. Reading them straight from a +/// page model would make the whole report flow untestable. +/// +/// +public interface IAppEnvironment +{ + /// Version and build, e.g. 0.13.0 (142). + string AppVersion { get; } + + /// Debug or Release. 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. + string BuildConfiguration { get; } + + /// Manufacturer and model, e.g. Google Pixel 7. + string Device { get; } + + /// Platform and version, e.g. Android 15. + string OsVersion { get; } +} diff --git a/src/AniSprinkles.Core/Services/Abstractions/IDiagnosticsSink.cs b/src/AniSprinkles.Core/Services/Abstractions/IDiagnosticsSink.cs new file mode 100644 index 00000000..9eaf8661 --- /dev/null +++ b/src/AniSprinkles.Core/Services/Abstractions/IDiagnosticsSink.cs @@ -0,0 +1,20 @@ +namespace AniSprinkles.Services.Abstractions; + +/// +/// Where a finished diagnostic report is sent (#112). +/// +/// A seam for the same reason is one, and with a sharper edge: an +/// uninitialised SentrySdk 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. +/// +/// +public interface IDiagnosticsSink +{ + /// + /// Sends , with 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. + /// + Task SendAsync(string report, string? description, CancellationToken cancellationToken = default); +} diff --git a/src/AniSprinkles.Core/Services/Abstractions/IDialogService.cs b/src/AniSprinkles.Core/Services/Abstractions/IDialogService.cs index 2070be9e..88f379a8 100644 --- a/src/AniSprinkles.Core/Services/Abstractions/IDialogService.cs +++ b/src/AniSprinkles.Core/Services/Abstractions/IDialogService.cs @@ -23,6 +23,13 @@ private MoveToListChoice(MediaListStatus? status, bool isRemove) public static MoveToListChoice Remove { get; } = new(status: null, isRemove: true); } +/// +/// What the user chose in the send-diagnostics sheet (#112). Reaching this at all means they pressed +/// Send; is what they typed, which is optional — requiring text would be +/// friction for someone who only wants the log attached. +/// +public readonly record struct DiagnosticsReportChoice(string? Description); + /// /// Modal user interaction — confirmations, prompts, and the bottom-sheet pickers. Abstracted for the /// same reason as and : the concrete @@ -76,6 +83,18 @@ Task ConfirmAsync( bool isDestructive = false, string? iconGlyph = null); + /// + /// The send-diagnostics sheet (#112): states what says is about to be + /// collected, and offers an optional box for what the user was doing. Returns null if they + /// cancelled or dismissed it. + /// + /// A choice rather than a nullable string because "cancelled" and "sent without a note" are + /// different answers that a string? would flatten into the same null — and one of + /// them must not send anything. + /// + /// + Task ShowDiagnosticsReportAsync(string summary); + /// /// Single-line text prompt. Returns null if the user cancelled. /// diff --git a/src/AniSprinkles.Core/Services/AniListApiException.cs b/src/AniSprinkles.Core/Services/AniListApiException.cs index 49afaeca..4ed4e93c 100644 --- a/src/AniSprinkles.Core/Services/AniListApiException.cs +++ b/src/AniSprinkles.Core/Services/AniListApiException.cs @@ -13,11 +13,17 @@ public enum ApiErrorKind RateLimited, /// - /// 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 Media(id:, type: ANIME)). 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 Media(id:, type: ANIME)). + /// + /// 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 for the + /// matching rule that stopped arbitrary server text landing here. + /// /// NotFound, } diff --git a/src/AniSprinkles.Core/Services/AniListErrorClassifier.cs b/src/AniSprinkles.Core/Services/AniListErrorClassifier.cs index e760fc81..43e0ba9d 100644 --- a/src/AniSprinkles.Core/Services/AniListErrorClassifier.cs +++ b/src/AniSprinkles.Core/Services/AniListErrorClassifier.cs @@ -52,8 +52,21 @@ public static ApiErrorKind ClassifyGraphQlError(string message) return ApiErrorKind.Authentication; } - // AniList also surfaces missing ids as a GraphQL-level "Not Found." error in some responses. - if (message.Contains("Not Found", StringComparison.OrdinalIgnoreCase)) + // AniList also surfaces missing ids as a GraphQL-level "Not Found." error in some responses, + // where those words are the entire message. + // + // Matched exactly rather than as a substring (#158). What forced that was the state NotFound + // used to be in: it was then the only kind that was both non-retryable and suppressed from + // Sentry, so a substring hit anywhere in server-supplied text turned any transient failure + // containing those two words into a permanent, silent dead end. #158 removed both of those + // properties in the same change — NotFound now retries and reports like everything else — so + // the stakes here are lower than they were. + // + // The exact match still stands on its own terms, though: calling arbitrary server text a + // missing id is simply wrong, it suppresses the automatic retry in AniListClient.SendAsync, + // and it shows the user "this may have been removed from AniList" about something that was + // never missing. Unknown is the honest answer for text we don't recognise. + if (IsNotFoundMessage(message)) { return ApiErrorKind.NotFound; } @@ -61,6 +74,16 @@ public static ApiErrorKind ClassifyGraphQlError(string message) return ApiErrorKind.Unknown; } + /// + /// Whether the whole message is AniList's not-found response, allowing for the trailing period + /// it usually carries and whatever whitespace survived transport. + /// + private static bool IsNotFoundMessage(string message) + { + var trimmed = message.Trim().TrimEnd('.').Trim(); + return trimmed.Equals("Not Found", StringComparison.OrdinalIgnoreCase); + } + private static bool ContainsOutageMarker(string message) => message.Contains("temporarily disabled", StringComparison.OrdinalIgnoreCase) || message.Contains("stability issues", StringComparison.OrdinalIgnoreCase) || diff --git a/src/AniSprinkles.Core/Services/DiagnosticsLogBuffer.cs b/src/AniSprinkles.Core/Services/DiagnosticsLogBuffer.cs new file mode 100644 index 00000000..39f618e2 --- /dev/null +++ b/src/AniSprinkles.Core/Services/DiagnosticsLogBuffer.cs @@ -0,0 +1,167 @@ +using Microsoft.Extensions.Logging; + +namespace AniSprinkles.Services; + +/// +/// An in-memory ring of the last few minutes of log lines, kept so a user can send what led up to a +/// problem (#112). +/// +/// This exists because neither existing sink can answer "what was the app doing just before this +/// went wrong". The file log keeps and above in Release, which is +/// every trace worth having filtered out — no NAVTRACE, no PageState, no HTTP. +/// Logcat has all of it but lives on the far side of the app/Core boundary, in a buffer shared with +/// the rest of the system. +/// +/// +/// Nothing here touches disk. Entries are dropped once they age out or the ring fills, so an install +/// that never reports anything pays only the memory, and the window a report can cover is bounded by +/// construction rather than by how long the app happened to be running. +/// is what writes a snapshot down when the process is about to +/// be torn away. +/// +/// +[ProviderAlias("Diagnostics")] +public sealed class DiagnosticsLogBuffer : ILoggerProvider +{ + /// + /// How far back a report reaches. Five minutes is the span a user can actually narrate — "I + /// tapped into a few manga and they all failed" — and it comfortably covers the lead-up to a + /// failure they are still looking at. + /// + public static readonly TimeSpan DefaultRetention = TimeSpan.FromMinutes(5); + + /// + /// The hard ceiling on entries, independent of age. Retention alone is not a memory bound: a + /// burst — a paged list, a retry storm — can emit thousands of lines inside the window. At a + /// typical line length this caps the ring at a few hundred KB. + /// + public const int DefaultMaxEntries = 2000; + + private readonly object _lock = new(); + private readonly Queue _entries = new(); + private readonly TimeProvider _timeProvider; + private readonly TimeSpan _retention; + private readonly int _maxEntries; + private readonly LogLevel _minimumLevel; + + public DiagnosticsLogBuffer( + TimeProvider? timeProvider = null, + TimeSpan? retention = null, + int maxEntries = DefaultMaxEntries, + LogLevel minimumLevel = LogLevel.Information) + { + _timeProvider = timeProvider ?? TimeProvider.System; + _retention = retention ?? DefaultRetention; + _maxEntries = Math.Max(maxEntries, 1); + _minimumLevel = minimumLevel; + } + + public ILogger CreateLogger(string categoryName) => new BufferLogger(categoryName, this); + + /// + /// The lines currently in the window, oldest first, already formatted. Aged-out entries are + /// dropped here as well as on write — otherwise a quiet stretch would hand a report lines from + /// well outside the window it promises the user. + /// + public IReadOnlyList Snapshot() + { + lock (_lock) + { + TrimLocked(); + return _entries.Select(e => e.Line).ToArray(); + } + } + + public void Dispose() + { + // Nothing to release — the ring is plain memory, and callers may still hold loggers. + } + + private void Append(LogLevel level, string category, int eventId, string? message, Exception? exception) + { + var timestamp = _timeProvider.GetUtcNow(); + var normalizedMessage = string.IsNullOrWhiteSpace(message) + ? string.Empty + : message.Replace("\r\n", " ").Replace('\n', ' ').Replace('\r', ' '); + var exceptionText = exception is null ? string.Empty : $" | {exception}"; + + // Same shape as the file log's lines, so a reader moving between the two isn't re-learning a + // format. Note the message normalization is on literal \r and \n rather than + // Environment.NewLine: a report built on one platform can carry text produced on another, and + // a message that smuggles a newline through would be indistinguishable from a new record. + // + // A record therefore starts on its own line, but does not necessarily end on one: an appended + // exception keeps its stack trace's line breaks, deliberately and like FileLoggerProvider. + // The only thing that reads a report is a person, and a 20-frame trace folded onto one line is + // far worse for them than a wrapped one — .NET already indents continuation frames, so a + // continuation is still distinguishable from the next record at a glance. Don't tighten this + // into "one physical line per record" without a machine consumer that actually needs it. + var line = $"{timestamp:O} [{level}] {category} ({eventId}) {normalizedMessage}{exceptionText}"; + + lock (_lock) + { + _entries.Enqueue(new Entry(timestamp, line)); + TrimLocked(); + } + } + + private void TrimLocked() + { + var cutoff = _timeProvider.GetUtcNow() - _retention; + + while (_entries.Count > 0 && _entries.Peek().At < cutoff) + { + _entries.Dequeue(); + } + + while (_entries.Count > _maxEntries) + { + _entries.Dequeue(); + } + } + + private readonly record struct Entry(DateTimeOffset At, string Line); + + private sealed class BufferLogger : ILogger + { + private readonly string _categoryName; + private readonly DiagnosticsLogBuffer _owner; + + public BufferLogger(string categoryName, DiagnosticsLogBuffer owner) + { + _categoryName = categoryName; + _owner = owner; + } + + public IDisposable BeginScope(TState state) where TState : notnull => NullScope.Instance; + + public bool IsEnabled(LogLevel logLevel) + => logLevel != LogLevel.None && logLevel >= _owner._minimumLevel; + + public void Log( + LogLevel logLevel, + EventId eventId, + TState state, + Exception? exception, + Func formatter) + { + if (!IsEnabled(logLevel)) + { + return; + } + + // Formatted here rather than at snapshot time because TState may be pooled and reused the + // moment this returns — holding it to format later reads whatever the next caller put there. + _owner.Append(logLevel, _categoryName, eventId.Id, formatter(state, exception), exception); + } + + private sealed class NullScope : IDisposable + { + public static readonly NullScope Instance = new(); + + public void Dispose() + { + } + } + } +} diff --git a/src/AniSprinkles.Core/Services/DiagnosticsReportBuilder.cs b/src/AniSprinkles.Core/Services/DiagnosticsReportBuilder.cs new file mode 100644 index 00000000..6a0fe150 --- /dev/null +++ b/src/AniSprinkles.Core/Services/DiagnosticsReportBuilder.cs @@ -0,0 +1,105 @@ +using System.Text; +using AniSprinkles.Utilities; + +namespace AniSprinkles.Services; + +/// +/// The environment facts that head a diagnostic report. Passed in rather than read here so the +/// builder stays pure: every one of these comes from MAUI Essentials (AppInfo, +/// DeviceInfo), which throws off-device and would make the builder untestable. +/// +public readonly record struct DiagnosticsContext( + string AppVersion, + string BuildConfiguration, + string Device, + string OsVersion, + bool IsSignedIn); + +/// +/// Assembles the text a user sends when they report a problem (#112): a short header, whatever they +/// typed, the tail of the previous session if one was flushed, and the current in-memory ring. +/// +/// Pure and synchronous on purpose. The redaction pass below is the only thing standing between the +/// log and Sentry — SentryScrubber runs on SetBeforeSend over the +/// SentryEvent and does not walk attachments, so a token reaching the report here +/// would reach Sentry intact. Keeping the assembly pure is what lets that be tested directly. +/// +/// +public static class DiagnosticsReportBuilder +{ + /// The name the report is attached under in Sentry. + public const string AttachmentFileName = "anisprinkles-diagnostics.log"; + + /// Header for the section holding what the user typed, omitted when they typed nothing. + public const string DescriptionHeader = "── what the user was doing ──"; + + /// Header for the current in-memory ring. + public const string CurrentSessionHeader = "── this session ──"; + + /// Stands in for the ring when there is nothing in it, so an empty report cannot be + /// mistaken for a truncated one. + public const string NoActivityPlaceholder = "(no activity recorded in the window)"; + + public static string Build( + DiagnosticsContext context, + DateTimeOffset capturedAt, + IReadOnlyList previousSession, + IReadOnlyList currentSession, + string? description) + { + var builder = new StringBuilder(); + + builder.AppendLine("AniSprinkles diagnostic report"); + builder.AppendLine($"captured: {capturedAt:O}"); + builder.AppendLine($"version: {context.AppVersion} ({context.BuildConfiguration})"); + builder.AppendLine($"device: {context.Device} — {context.OsVersion}"); + // Whether they were signed in changes which code paths could even have run, and it is the one + // account fact worth stating outright rather than leaving to be inferred from AUTH traces. + builder.AppendLine($"signed in: {(context.IsSignedIn ? "yes" : "no")}"); + + // No cross-reference to the automatic exception event, deliberately. An earlier draft printed + // one, and on device it was always absent: the exception does reach Sentry, but neither + // ErrorReportService's CaptureException return value nor SentrySdk.LastEventId holds its id by + // the time a report is built. Correlating on the exception text and the timestamps below — + // both of which this report already carries in full — works, and a header field that is + // reliably empty is worse than no field at all. + + if (!string.IsNullOrWhiteSpace(description)) + { + builder.AppendLine(); + builder.AppendLine(DescriptionHeader); + builder.AppendLine(description.Trim()); + } + + if (previousSession.Count > 0) + { + builder.AppendLine(); + builder.AppendLine(DiagnosticsSessionLog.PreviousSessionHeader); + foreach (var line in previousSession) + { + builder.AppendLine(line); + } + } + + builder.AppendLine(); + builder.AppendLine(CurrentSessionHeader); + if (currentSession.Count == 0) + { + builder.AppendLine(NoActivityPlaceholder); + } + else + { + foreach (var line in currentSession) + { + builder.AppendLine(line); + } + } + + // One pass over the finished text rather than per-line, which is what makes line structure + // irrelevant to redaction. That matters because records are not strictly one line each — + // an appended stack trace keeps its breaks — but the token pattern is `Bearer\s+…`, and `\s` + // spans newlines, so a credential wrapped across a break is still matched. Scanning the whole + // string also means a section someone adds later cannot quietly skip the pass. + return SensitiveText.Redact(builder.ToString()); + } +} diff --git a/src/AniSprinkles.Core/Services/DiagnosticsSessionFlusher.cs b/src/AniSprinkles.Core/Services/DiagnosticsSessionFlusher.cs new file mode 100644 index 00000000..a21abfcd --- /dev/null +++ b/src/AniSprinkles.Core/Services/DiagnosticsSessionFlusher.cs @@ -0,0 +1,67 @@ +namespace AniSprinkles.Services; + +/// +/// Decides when the in-memory diagnostics ring is written to disk and when that file may be thrown +/// away again (#112). +/// +/// Separate from the platform callbacks that drive it — the global exception handlers and the +/// activity's pause and resume — because the interesting part is not the callback, it is the +/// ownership rule below, and that rule is wrong in a way nothing else would notice. +/// +/// +public sealed class DiagnosticsSessionFlusher +{ + private readonly DiagnosticsLogBuffer _buffer; + private readonly DiagnosticsSessionLog _sessionLog; + private readonly object _lock = new(); + private bool _flushedByThisProcess; + + public DiagnosticsSessionFlusher(DiagnosticsLogBuffer buffer, DiagnosticsSessionLog sessionLog) + { + _buffer = buffer; + _sessionLog = sessionLog; + } + + /// + /// Writes the current ring out. Returns whether anything was persisted — false when the ring was + /// empty, or when the write failed. + /// + public bool Flush() + { + lock (_lock) + { + if (!_sessionLog.Save(_buffer.Snapshot())) + { + return false; + } + + _flushedByThisProcess = true; + return true; + } + } + + /// + /// Drops the file, but only if this process is the one that wrote it. Called on resume. + /// + /// The ownership test is the whole point. The file exists to outlive a process that died holding + /// the ring — so if we are still here to resume, it was not needed, and keeping it would put + /// every one of those lines into the next report twice, because the live ring still has them. + /// But a file left by a previous process is exactly the thing worth sending, and clearing + /// it on this process's first resume would delete the crash before the user could report it. + /// + /// + public bool ClearIfOwnedByThisProcess() + { + lock (_lock) + { + if (!_flushedByThisProcess) + { + return false; + } + + _sessionLog.Clear(); + _flushedByThisProcess = false; + return true; + } + } +} diff --git a/src/AniSprinkles.Core/Services/DiagnosticsSessionLog.cs b/src/AniSprinkles.Core/Services/DiagnosticsSessionLog.cs new file mode 100644 index 00000000..8b7993f5 --- /dev/null +++ b/src/AniSprinkles.Core/Services/DiagnosticsSessionLog.cs @@ -0,0 +1,130 @@ +using Microsoft.Extensions.Logging; + +namespace AniSprinkles.Services; + +/// +/// The one file ever writes: a snapshot of the ring taken when the +/// process is about to lose it (#112). +/// +/// The ring is memory, so on its own it cannot answer "the app died, then I went to report it". +/// Android's three global handlers all keep the process alive — UnhandledExceptionRaiser sets +/// Handled = true and UnobservedTaskException calls SetObserved — so for the +/// failures this app actually produces the ring survives and this file is never needed. It exists for +/// the cases that do take the process with them: a native crash, an OOM kill, a force-close. +/// +/// +/// Exactly one file, overwritten each time, holding at most one session. Never appended to, so it +/// cannot grow — the ring's own bounds are the size limit. +/// +/// +/// Deliberately not cleared on sign-out, unlike AppSettings. A crash spanning a +/// sign-out and sign-in is exactly the kind of thing worth reporting, and this app is installed on +/// one person's phone — the case this would protect against, a second account signing in within the +/// retention window and sending the first one's activity, does not arise here. Worth revisiting +/// before any public release, along with the rest of the pre-release logging posture. +/// +/// +public sealed class DiagnosticsSessionLog +{ + /// The header written above the restored lines, so a report reader can see the join. + public const string PreviousSessionHeader = "── previous session ──"; + + private readonly string _filePath; + private readonly ILogger _logger; + private readonly object _lock = new(); + + public DiagnosticsSessionLog(string filePath, ILogger logger) + { + _filePath = filePath; + _logger = logger; + } + + /// + /// Writes over whatever was there. Returns whether it landed. + /// + /// Never throws. Every caller is either a global exception handler or an activity pause — places + /// where an exception escaping would turn a diagnostic convenience into the crash it was meant to + /// explain. + /// + /// + public bool Save(IReadOnlyList lines) + { + if (lines.Count == 0) + { + // Nothing to say. Deliberately leaves any existing file alone rather than truncating it: + // an empty ring on a later pause must not erase the flush from the crash before it. + return false; + } + + try + { + lock (_lock) + { + var directory = Path.GetDirectoryName(_filePath); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + File.WriteAllLines(_filePath, lines); + } + + return true; + } + catch (Exception ex) when (IsFileAccessException(ex)) + { + _logger.LogWarning(ex, "Could not persist the diagnostics session log."); + return false; + } + } + + /// + /// The lines from the last saved session, or empty when there is no file — a first run, or a + /// clean previous shutdown. + /// + public IReadOnlyList Load() + { + try + { + lock (_lock) + { + return File.Exists(_filePath) ? File.ReadAllLines(_filePath) : []; + } + } + catch (Exception ex) when (IsFileAccessException(ex)) + { + _logger.LogWarning(ex, "Could not read the diagnostics session log."); + return []; + } + } + + /// + /// Deletes the file. Called once its contents have been sent, so the same session is not attached + /// to every subsequent report the user files. + /// + public void Clear() + { + try + { + lock (_lock) + { + if (File.Exists(_filePath)) + { + File.Delete(_filePath); + } + } + } + catch (Exception ex) when (IsFileAccessException(ex)) + { + _logger.LogWarning(ex, "Could not clear the diagnostics session log."); + } + } + + private static bool IsFileAccessException(Exception ex) + => ex is IOException + or UnauthorizedAccessException + or DirectoryNotFoundException + or NotSupportedException + or PathTooLongException + or System.Security.SecurityException; +} diff --git a/src/AniSprinkles.Core/Services/ErrorReportService.cs b/src/AniSprinkles.Core/Services/ErrorReportService.cs index 9001622a..b7ab3d42 100644 --- a/src/AniSprinkles.Core/Services/ErrorReportService.cs +++ b/src/AniSprinkles.Core/Services/ErrorReportService.cs @@ -29,6 +29,22 @@ public string Record(Exception ex, string context) var details = SensitiveText.Redact($"{context}{Environment.NewLine}{ex}"); _logger.LogError(ex, "{Context}", context); + + // This call does not create the Sentry event, and its return value is always SentryId.Empty. + // Traced while building #112, and confirmed by the `mechanism: SentryLogger` tag on the + // events themselves: + // + // 1. SentryLoggingOptions.MinimumEventLevel defaults to Error, so the LogError above is + // what the ILogger integration captures. That call gets the real id. + // 2. This one then hits DuplicateEventDetectionEventProcessor — SentryOptions.DeduplicateMode + // defaults to `All ^ InnerException`, which still includes SameExceptionInstance — so the + // processor drops it and SentryClient returns SentryId.Empty. + // 3. Hub.CaptureEvent assigns `scope.LastEventId = id` unguarded, so step 2 also overwrites + // the good id from step 1. SentrySdk.LastEventId is therefore empty too. + // + // It stays because it is the guarantee: if the logging level or a filter ever stops this + // class's LogError reaching Sentry, there is no duplicate to drop and this becomes the only + // path. Just never read its result, and never expect SentrySdk.LastEventId to name it. SentrySdk.CaptureException(ex); return details; diff --git a/src/AniSprinkles.Core/Services/SentryDiagnosticsSink.cs b/src/AniSprinkles.Core/Services/SentryDiagnosticsSink.cs new file mode 100644 index 00000000..c3dd65a6 --- /dev/null +++ b/src/AniSprinkles.Core/Services/SentryDiagnosticsSink.cs @@ -0,0 +1,97 @@ +using System.Text; +using AniSprinkles.Services.Abstractions; +using AniSprinkles.Utilities; +using Microsoft.Extensions.Logging; + +namespace AniSprinkles.Services; + +/// +/// Sends a diagnostic report to Sentry as an event with the log attached (#112). +/// +/// Sentry is the only delivery route. It reaches the maintainer without asking anything of the user, +/// which is what a real bug report needs — and its silence is covered at the UI end instead, by a +/// popup that states what is about to be sent and a confirmation that names it back. +/// +/// +public sealed class SentryDiagnosticsSink : IDiagnosticsSink +{ + /// + /// How long to wait for the envelope to leave. Reports are sent from a screen the user is about + /// to leave — often the very screen that is broken — so returning before the transport has run + /// risks the process going away with the report still queued. Bounded so a dead network cannot + /// hang the confirmation indefinitely. + /// + private static readonly TimeSpan FlushTimeout = TimeSpan.FromSeconds(10); + + private readonly ILogger _logger; + + public SentryDiagnosticsSink(ILogger logger) + { + _logger = logger; + } + + public async Task SendAsync(string report, string? description, CancellationToken cancellationToken = default) + { + if (!SentrySdk.IsEnabled) + { + // No DSN, or the SDK never initialised. Worth saying out loud: the alternative is telling + // the user their report was sent when nothing left the device. + _logger.LogWarning("Diagnostic report not sent: the Sentry SDK is not enabled."); + return false; + } + + try + { + var attachment = Encoding.UTF8.GetBytes(report); + + var eventId = SentrySdk.CaptureMessage( + "Diagnostic report (user-initiated)", + scope => scope.AddAttachment( + attachment, + DiagnosticsReportBuilder.AttachmentFileName, + AttachmentType.Default, + "text/plain"), + SentryLevel.Info); + + if (eventId == SentryId.Empty) + { + _logger.LogWarning("Diagnostic report not sent: Sentry returned an empty event id."); + return false; + } + + if (!string.IsNullOrWhiteSpace(description)) + { + // Sent as feedback linked to the event rather than folded into the message, so it + // shows up in Sentry as a user report. Redacted again here rather than trusting the + // report pass: this is free text the user could have pasted anything into, and it + // takes a different route to Sentry than the attachment does. + SentrySdk.CaptureFeedback(new SentryFeedback( + SensitiveText.Redact(description.Trim()), + contactEmail: null, + name: null, + replayId: null, + url: null, + associatedEventId: eventId)); + } + + await SentrySdk.FlushAsync(FlushTimeout).WaitAsync(cancellationToken).ConfigureAwait(false); + + _logger.LogInformation("Diagnostic report sent ({EventId}, {Bytes} bytes).", eventId, attachment.Length); + return true; + } + catch (OperationCanceledException) + { + // The flush was abandoned, not the capture — the envelope may still go out on its own. + // Reported as a failure anyway: a confirmation the user cannot rely on is worse than none. + _logger.LogWarning("Diagnostic report send was cancelled while flushing."); + return false; + } + catch (Exception ex) + { + // Deliberately broad. 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. + _logger.LogError(ex, "Diagnostic report failed to send."); + return false; + } + } +} diff --git a/src/AniSprinkles/App.xaml.cs b/src/AniSprinkles/App.xaml.cs index a9fa580c..983cc5ab 100644 --- a/src/AniSprinkles/App.xaml.cs +++ b/src/AniSprinkles/App.xaml.cs @@ -13,6 +13,11 @@ public App() AppDomain.CurrentDomain.UnhandledException += (_, e) => { + // Flushed first, before anything that could itself fail. This is the one handler that + // cannot keep the process alive — there is no Handled flag to set — so whatever the ring + // holds reaches disk here or not at all (#112). + DiagnosticsFlush.Flush(); + if (e.ExceptionObject is Exception ex) { ShowCrashAlert(ex); @@ -21,6 +26,7 @@ public App() TaskScheduler.UnobservedTaskException += (_, e) => { + DiagnosticsFlush.Flush(); e.SetObserved(); ShowCrashAlert(e.Exception); }; diff --git a/src/AniSprinkles/MauiProgram.cs b/src/AniSprinkles/MauiProgram.cs index 8eb5ec1f..c12673d9 100644 --- a/src/AniSprinkles/MauiProgram.cs +++ b/src/AniSprinkles/MauiProgram.cs @@ -97,6 +97,34 @@ public static MauiApp CreateMauiApp() builder.Logging.AddFilter("Sentry", LogLevel.Warning); #endif + // The in-memory ring behind Settings' "Report a problem" and the error cards' Report action + // (#112). Registered in every build config and kept at Information deliberately: the file + // logger above drops Information in Release, which filters out every trace worth sending — + // no NAVTRACE, no PageState, no HTTP — and this is the sink that exists to keep them. + // + // Nothing here touches disk. Entries age out after five minutes or fall off the entry cap, + // whichever comes first, so an install that never reports anything pays only the memory. + // DiagnosticsSessionLog is what writes a snapshot down, and only when the process is about + // to be torn away. + const LogLevel diagnosticsMinimumLevel = LogLevel.Information; + var diagnosticsLogBuffer = new DiagnosticsLogBuffer(minimumLevel: diagnosticsMinimumLevel); + builder.Logging.AddProvider(diagnosticsLogBuffer); + builder.Logging.AddFilter(string.Empty, diagnosticsMinimumLevel); + builder.Logging.AddFilter("Microsoft", LogLevel.Warning); + builder.Logging.AddFilter("System", LogLevel.Warning); + builder.Logging.AddFilter("Sentry", LogLevel.Warning); + + // The instance itself, not a factory: the logging pipeline already holds this one, and a + // second would collect nothing while looking like it worked. + builder.Services.AddSingleton(diagnosticsLogBuffer); + builder.Services.AddSingleton(sp => new DiagnosticsSessionLog( + Path.Combine(logDirectory, "previous-session.log"), + sp.GetRequiredService>())); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + // MAUI auto-registers IDispatcher via UseMauiApp, but IPreferences and IAppInfo are only // exposed as the statics Preferences.Default / AppInfo.Current — DI has no default, so // resolving a PageModel that takes either throws InvalidOperationException at startup. diff --git a/src/AniSprinkles/Pages/SettingsPage.xaml b/src/AniSprinkles/Pages/SettingsPage.xaml index 9be826ee..65804986 100644 --- a/src/AniSprinkles/Pages/SettingsPage.xaml +++ b/src/AniSprinkles/Pages/SettingsPage.xaml @@ -55,6 +55,11 @@ + + + diff --git a/src/AniSprinkles/Platforms/Android/MainActivity.cs b/src/AniSprinkles/Platforms/Android/MainActivity.cs index a8a7b73e..8718e697 100644 --- a/src/AniSprinkles/Platforms/Android/MainActivity.cs +++ b/src/AniSprinkles/Platforms/Android/MainActivity.cs @@ -50,6 +50,13 @@ protected override void OnCreate(Bundle? savedInstanceState) Android.Runtime.AndroidEnvironment.UnhandledExceptionRaiser += (sender, args) => { Log.Error(nameof(MainActivity), $"Unhandled Android exception: {args.Exception}"); + + // Handled = true keeps the process — and so the in-memory ring — alive, so this flush is + // belt and braces rather than the only chance. It is here because the app carrying on + // after an unhandled exception is precisely the state a user ends up reporting, and it + // costs one small write on a path that has already gone wrong (#112). + DiagnosticsFlush.Flush(); + args.Handled = true; }; @@ -127,6 +134,12 @@ protected override void OnResume() base.OnResume(); Log.Info(LifecycleTag, $"LIFECYCLE {ActivityIdentity} OnResume"); + // We are still here, so the flush OnPause wrote was not needed — and keeping it would put + // every one of those lines into the next report twice, since the live ring still holds them. + // Only clears a file this process wrote: one left by a process that actually died is the + // thing worth sending, and must survive this. + DiagnosticsFlush.ClearIfOwnedByThisProcess(); + // Re-reads the intent as well as draining. If queuing failed earlier — DI not yet wired, so // ServiceProviderHelper threw — the extras are still on it, and nothing else would ever look // at them again within this activity instance. A no-op on the normal path, where the extras @@ -210,6 +223,13 @@ private static void TryDrainDeepLink() protected override void OnPause() { Log.Info(LifecycleTag, $"LIFECYCLE {ActivityIdentity} OnPause"); + + // The last guaranteed callback before Android may kill the process. Everything after this — + // an OOM kill, a force-close, a native crash — takes the in-memory diagnostics ring with it, + // so this is where it gets written down (#112). Cleared again on resume when the process + // turns out to have survived. + DiagnosticsFlush.Flush(); + base.OnPause(); } diff --git a/src/AniSprinkles/Services/Maui/MauiAppEnvironment.cs b/src/AniSprinkles/Services/Maui/MauiAppEnvironment.cs new file mode 100644 index 00000000..075361bd --- /dev/null +++ b/src/AniSprinkles/Services/Maui/MauiAppEnvironment.cs @@ -0,0 +1,48 @@ +using AniSprinkles.Services.Abstractions; + +namespace AniSprinkles.Services.Maui; + +/// +/// over MAUI Essentials, for the header of a diagnostic report (#112). +/// +/// Lives on this side of the seam because AppInfo and DeviceInfo throw rather than +/// degrade on the plain net10.0 test TFM — reading them from Core would make the whole report +/// flow untestable. Each property is guarded anyway: a report is worth sending with an unknown +/// device model, and is worth nothing if collecting the model threw. +/// +/// +public sealed class MauiAppEnvironment : IAppEnvironment +{ + private const string Unknown = "unknown"; + + public string AppVersion => Safe(() => $"{AppInfo.Current.VersionString} ({AppInfo.Current.BuildString})"); + + public string BuildConfiguration => +#if DEBUG + "Debug"; +#else + "Release"; +#endif + + public string Device => Safe(() => $"{DeviceInfo.Current.Manufacturer} {DeviceInfo.Current.Model}"); + + public string OsVersion => Safe(() => $"{DeviceInfo.Current.Platform} {DeviceInfo.Current.VersionString}"); + + /// + /// Deliberately broad, and deliberately silent. These are header decorations on a report the user + /// is sending because something else already went wrong; one of them throwing must not be the + /// reason the report never arrives, and logging it here would only pad the very log being sent. + /// + private static string Safe(Func read) + { + try + { + var value = read(); + return string.IsNullOrWhiteSpace(value) ? Unknown : value; + } + catch + { + return Unknown; + } + } +} diff --git a/src/AniSprinkles/Services/Maui/MauiDialogService.cs b/src/AniSprinkles/Services/Maui/MauiDialogService.cs index 2882406d..6e889423 100644 --- a/src/AniSprinkles/Services/Maui/MauiDialogService.cs +++ b/src/AniSprinkles/Services/Maui/MauiDialogService.cs @@ -89,6 +89,21 @@ public Task ConfirmAsync( string? iconGlyph = null) => ConfirmPopup.ShowAsync(title, message, confirmText, cancelText, isDestructive, iconGlyph); + public async Task ShowDiagnosticsReportAsync(string summary) + { + var result = await ShowAsync(new DiagnosticsReportPopup(summary), TransparentPopupOptions); + + // Null covers both Cancel and a dismiss by tapping outside — neither may send anything. Only + // a string means Send was pressed, and an empty one still counts: the note is optional. + if (result is not string description) + { + return null; + } + + return new DiagnosticsReportChoice( + string.IsNullOrWhiteSpace(description) ? null : description.Trim()); + } + public async Task PromptAsync( string title, string message, diff --git a/src/AniSprinkles/Utilities/DiagnosticsFlush.cs b/src/AniSprinkles/Utilities/DiagnosticsFlush.cs new file mode 100644 index 00000000..87c95cd6 --- /dev/null +++ b/src/AniSprinkles/Utilities/DiagnosticsFlush.cs @@ -0,0 +1,47 @@ +using AniSprinkles.Services; +using Microsoft.Extensions.DependencyInjection; + +namespace AniSprinkles.Utilities; + +/// +/// The platform shim for (#112) — nothing but a null-tolerant +/// way to reach it from places that have no constructor to inject into. +/// +/// Static and defensively resolved because its callers are the three global exception handlers and +/// the activity's pause and resume: places where DI may not be wired yet, and where an exception +/// escaping would become the crash instead of explaining one. The decision-making lives in Core, +/// where it is testable. +/// +/// +public static class DiagnosticsFlush +{ + /// Writes the ring out. Safe to call from anywhere, including a handler firing during + /// startup before DI exists. + public static void Flush() => Run(flusher => flusher.Flush()); + + /// Drops a flush this process wrote, once it is clear the process survived. + public static void ClearIfOwnedByThisProcess() => Run(flusher => flusher.ClearIfOwnedByThisProcess()); + + private static void Run(Func action) + { + try + { + // Not ServiceProviderHelper.GetServiceProvider: that throws when DI is not yet wired, + // which is a reasonable contract for page creation and the wrong one for a crash handler + // that may fire before the container exists. + var services = Application.Current?.Handler?.MauiContext?.Services + ?? IPlatformApplication.Current?.Services; + + if (services?.GetService() is { } flusher) + { + action(flusher); + } + } + catch + { + // Deliberately silent and deliberately total. Every caller is a crash handler or a + // lifecycle callback; there is nowhere useful for an exception to go from here, and + // logging it would only write into the buffer this just failed to persist. + } + } +} diff --git a/src/AniSprinkles/Views/DiagnosticsReportPopup.xaml b/src/AniSprinkles/Views/DiagnosticsReportPopup.xaml new file mode 100644 index 00000000..4e88e496 --- /dev/null +++ b/src/AniSprinkles/Views/DiagnosticsReportPopup.xaml @@ -0,0 +1,81 @@ + + + + + + + + + + + + + +