Skip to content

fix(diagnostics): harden profile gating and crash evidence isolation - #98

Merged
Quick104 merged 14 commits into
mainfrom
feat/client-diagnostics-apple
Jul 22, 2026
Merged

Quick104 merged 14 commits into
mainfrom
feat/client-diagnostics-apple

Conversation

@Quick104

@Quick104 Quick104 commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #96 (already squash-merged). Addresses the four round-6 review comments posted after the merge.

  • AuthService profile invalidation on every profile write — moved DiagnosticsCoordinator.activeProfileDidChange() out of the selectProfile call site and into the profileId setter, plus the ServerRegistry.switchTo/remove server-restore paths. Every active-profile change now fails the breadcrumb/session/exit-sentinel gate closed until the new profile is confirmed non-child, instead of only the select path.
  • Purge the tvOS exit marker when reports are turned off — the consent store's Never transition now calls ExitSentinel.shared.purge() on tvOS, so an armed marker can't survive to later surface as an abnormal-exit report after collection was turned off.
  • Preserve leftover markers until capture succeeds — the exit sentinel now keeps an unclean previous run's marker in a distinct leftover slot before arming the current run, so crash evidence survives a failed captureLeftoverIfNeeded() and a subsequent background/terminate. Decode stays backward-compatible; slot bookkeeping extracted to ExitSentinelMarkerStore and unit-tested.
  • Filter MetricKit breadcrumbs to the reporting window — attached breadcrumbs are now scoped to the payload's periodStart/periodEnd (with a margin) so relaunch/post-incident and older-segment lines don't ride along with a crash/hang report.

Tests: full iOS suite (Silo, iPhone 17 Pro) passes; SiloTV (Apple TV 4K 3rd gen) builds. Added a leftover-preservation round-trip test and a breadcrumb-window filter test.

🤖 Generated with Claude Code

https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh

Summary by CodeRabbit

  • New Features

    • Added diagnostics report creation and upload, including compressed logs, device details, crash evidence, and manifest metadata.
    • Added multipart diagnostics networking with status checks, authentication refresh, and clearer upload error handling.
    • Added navigation breadcrumbs to improve troubleshooting context.
    • Added abnormal-exit evidence capture on supported platforms.
  • Bug Fixes

    • Improved privacy and consent enforcement, including profile and child-account eligibility checks.
    • Prevented unrelated logs, sessions, and crash evidence from being included in reports.
    • Improved cleanup when signing out, switching profiles, or disabling diagnostics.
    • Corrected pending-report retention and duplicate handling.

Quick104 and others added 10 commits July 20, 2026 13:25
Implements the Apple slice of the client-diagnostics spec (silo-server
docs/design/2026-07-19-client-diagnostics.md): vendored contract models
with fixture tests, DiagLog safe-logging facade with collection-time
redaction and an always-on memory ring, breadcrumb journal, tar.gz bundle
builder + multipart upload via DiagnosticsAPI, MetricKit crash/hang capture
(iOS), abnormal-exit sentinel (tvOS) with consent gating, server+account-
bound consent and pending-report stores with sign-out purge, device
snapshot with hashed route identifiers, Diagnostics settings + consent
prompts on both platforms, and a curated cmpLog tee into the ring.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XppCCycoaskCsW7ja1fZct
…gs UX (iOS + tvOS)

Adds the user-facing layer over the diagnostics slice: the crash/hang
pending-report prompt flow with a review sheet before anything uploads,
per-fingerprint suppression and child-profile gating via
DiagnosticsPromptPolicy, an automatic upload path for always-on consent,
report summary and detail screens, Diagnostics settings panes on both
platforms, and pending-report notifications posted from MetricKit
capture so an active session can surface the prompt.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
-debugServer/-debugUsername/-debugPassword sign in through the real
checkServer -> login -> selectProfile flow and land on Home, so
simulator-driven end-to-end runs (paired with -debugPlayFirst) need no
UI input. DEBUG builds only.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
…s in logs

A captured report leaked the server domain three ways: HTTPClient error
lines with full URLs, wss:// URLs inside NSError descriptions (the URL
regex only matched http/https), and the potential for bare hostnames
outside URL syntax. Now:

- URL normalization hashes the host to a stable [host:<sha256-12>]
  token (ws/wss included), keeping lines correlatable without exposing
  the domain; loopback hosts stay literal for playback debugging.
- Every remembered server hostname from ServerRegistry is registered
  with the redactor and replaced even when it appears as bare text —
  known-string matching avoids the false positives a generic domain
  regex would hit (bundle ids, file names).
- Email addresses are redacted, and username/login/email key-values
  join the token key-value redaction (= and : separators).

Verified on a live report: zero domain occurrences in the bundle,
hashed tokens in place, loopback URLs intact.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
- Move DiagnosticsSHA256 into its own file so the SiloTVTopShelf target
  (which compiles the logging/redaction slice) links DiagLog.hostToken
- Refresh the stored manifest consent notice_version at upload time so a
  report captured under an older notice isn't rejected as stale_consent forever
- Classify too_large uploads as a permanent local failure (new report state)
  instead of retrying the same oversized bundle indefinitely
- Preserve crash capture when the status refresh is offline by falling back to
  the last-known-good status/binding (in-memory, then persisted per server)
- Gate persistent capture for child profiles, mirroring the prompt policy
- Filter breadcrumbs.jsonl to the crashed run's lines for abnormal-exit reports
- Snapshot logs at capture time and prefer the frozen snapshot when building an
  old crash/hang/abnormal-exit bundle (manual reports still use the live ring)
- Distinguish a token rotation from a real identity change by comparing the
  server id + account id rather than raw access-token fingerprints
- Skip reports marked needsServerUpdate/tooLarge in auto-upload and prompting
- Scope recorded playback session IDs to the active binding so another
  server/account's sessions can't leak into a report bound elsewhere
- Truncate MetricKit stack_excerpt by UTF-8 bytes, not characters
- Drop the redundant named-keys frame traversal that duplicated stack frames
- Note the MetricKit delivery-time binding limitation at the capture site
- Hold BreadcrumbJournal's lock across readAll() so reads can't race rotation
- Disable decline/delete buttons while the view model isWorking (iOS + tvOS)
- Register the legacy host for redaction during ServerRegistry migration
- Serialize ExitSentinel.captureEnabled writes with its lock via setCaptureEnabled
- Coalesce overlapping foreground refreshes in DiagnosticsViewModel
- Gate verbose 1 Hz [CMP-DIAG] player traces behind the Debug Logging toggle
- Tests: use failable String(bytes:encoding:) and XCTUnwrap in redaction tests;
  add focused tests for consent refresh, permanent-failure state, session
  scoping, and byte-safe stack truncation

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
- Clear cached/persisted status and breadcrumb consent context when purging
  a signed-out binding, so a later capture can't recreate default-Ask consent
  and resume diagnostics for the old account (#1)
- Gate persistent capture on server availability, not just consent != Never,
  so a disabled/storage-unavailable server never stores crash reports (#2)
- Persist the binding (and profile) in abnormal-exit markers and attribute the
  report to it; drop markers whose account no longer matches, keeping legacy
  markers' best-effort behavior (#3)
- Default breadcrumb capture to disabled until stored consent loads, bootstrapping
  from the last-known status so a Never account's fresh launch writes nothing (#4)
- Treat a status-refresh failure during upload as retryable instead of a
  destination mismatch (wrong message + 24h retry suppression) (#5)
- Suppress declined prompts for the report's lifetime via a per-report flag;
  declined reports stay manually sendable but never re-prompt or auto-upload (#6)

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
- DiagnosticsCoordinator: drop abnormal-exit markers captured under a
  child profile by re-checking the marker's own profile at capture, not
  just the profile active now (an unknown status keeps the marker for a
  later retry).
- DiagnosticsCoordinator: rotate the breadcrumb journal when the active
  server/account binding changes mid-run so a new binding can't bundle
  the previous one's breadcrumbs; the first establish of a launch still
  keeps the prior run's trail for abnormal-exit capture.
- DiagnosticsCoordinator: restrict the last-known-status offline fallback
  to genuine network/status failures; identityChanged (signed out / no
  token) and missing-account no longer capture against a stale binding.
- DiagnosticsCoordinator: gate breadcrumb capture on server availability
  so disabled/storage_unavailable status no longer arms capture,
  consistent with the persistent-capture gate.
- DiagnosticsCoordinator: fail closed when the active profile's child
  status can't be resolved during persistent capture (getProfiles()
  failed offline) instead of proceeding.
- PendingReportStore: refresh consent.mode as well as notice_version from
  the current consent record at upload so a demoted Always->Ask report
  can't still claim mode=always (manual reports stay manual).
- MetricKitCapture: cap crash.summary to 8192 UTF-8 bytes after prefixing
  the first frame, reusing the byte-safe truncation.
- DiagLog: redact HTTPClient's camelCase/wrapper header forms harvested
  from OSLog (profileId=, auth(...), profileToken(...), accessToken /
  refreshToken key-values).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
- Restrict the offline capture fallback to genuinely transient failures:
  only network/offline errors and 5xx server errors fall back to the
  last-known snapshot; auth/permission (401/403), missing endpoint (404),
  other 4xx, malformed responses, and identity-level errors now fail closed
  so a capture is never queued against a signed-out or unavailable binding.
- Back-fill the tvOS exit-sentinel marker binding the moment diagnostics
  first resolves it (coordinator refresh completion), not only on a later
  foreground, so a first-run crash before any status refresh is still
  attributed to the right account instead of a legacy/unbound marker.
- Re-verify the active destination immediately before posting a diagnostics
  bundle; the bundle build (OSLog harvest + gzip) can outlast an account
  switch, and a same-server switch keeps server_instance_id, so keep the
  report retryable rather than upload it to the newly active account.
- Drop the access-token fingerprint from the view model's RuntimeIdentity so
  a transparent token refresh during load() is no longer misread as an
  identity change and reset(); the stable identity is server registry id plus
  profile id, with sign-out still detected via token presence and generation.
- Always run the registry-wide diagnostics purge on sign-out (it clears
  reports/consent under older server_instance_ids for the same URL); the
  current-binding purge only skips its own duplicate work, never the
  registry-wide purge.
- Gate uploads on the captured profile: the server rejects an upload whose
  X-Profile-Id header (the currently active profile) disagrees with the
  manifest's report.profile_id (HTTP 400 profile_mismatch). Hold a report
  captured under another profile as retryable — before the bundle build and
  again right before the POST — so it uploads next time the capturing profile
  is active, mirroring the server's resolveProfileID trim-and-compare rule.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
- DiagnosticsCoordinator: verify a *stable* destination identity (server
  registry id + selected profile, plus a token-presence sign-out check)
  before posting a bundle, not the access-token value. A transparent token
  refresh during buildBundle no longer trips the pre-POST check and defers
  the Always-path auto-upload for 24h; a genuine same-server account switch
  still fails closed (it clears the token and lands on a different profile).
- DiagLog/LogRing: clear the process-wide log ring when the active
  diagnostics binding changes, mirroring the breadcrumb-journal purge at the
  same trigger, so a new binding's manual report or crash snapshot can't
  include the previous binding's CMP/playback log lines. Adds LogRing.clear().
- DiagnosticsCoordinator: re-evaluate the breadcrumb gate on profile change
  (and status refresh) so an adult->child profile switch disarms breadcrumb
  and exit-sentinel capture, consistent with the persistent-capture child
  gate; fails closed immediately on switch until the async child check lands.
- PlaybackSessionBridge: gate RecentSessionTracker recording on the same
  capture-enabled signal (isDiagnosticsCaptureEnabled) as breadcrumbs, so
  session IDs aren't accumulated while collection is off (Never / disabled /
  storage-unavailable) and later surfaced in a report after re-enable.
- DiagLog.replaceKnownHosts: rewrite as a single forward pass that never
  rescans replaced output, fixing an infinite loop when a registered host is
  a substring of its replacement token (e.g. "host" vs "[host:...]"). Adds a
  pathological-host regression test plus a LogRing.clear() test.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
- AuthService: move diagnostics profile invalidation into the profileId
  setter (and the ServerRegistry switchTo/remove profile-restore paths) so
  every active-profile change fails the breadcrumb/session/exit-sentinel gate
  closed, not just the selectProfile path.
- DiagnosticsConsentStore: purge the tvOS ExitSentinel marker when Crash
  Reports is set to Never, so an armed marker can't later surface as an
  abnormal-exit report after collection was turned off.
- ExitSentinel: preserve an unclean previous run's marker in a distinct
  leftover slot before arming the current run, so a crash marker survives a
  failed captureLeftoverIfNeeded and a subsequent background/terminate;
  decode stays backward-compatible. Extracted ExitSentinelMarkerStore for
  the (now unit-tested) slot bookkeeping.
- MetricKitCapture: filter attached breadcrumbs to the payload's reporting
  window (with margin) so post-incident/relaunch and older-segment lines
  don't ride along with a crash/hang report.
- Tests: leftover-preservation round-trip and breadcrumb-window filtering.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refines iOS/tvOS diagnostics capture with fail-closed profile eligibility, persistent exit-sentinel evidence, run-scoped MetricKit filtering, scrubbed bundle generation, multipart uploads, lifecycle breadcrumbs, scoped cleanup, and expanded regression tests.

Changes

Diagnostics eligibility and evidence scoping

Layer / File(s) Summary
Profile eligibility and scoped evidence
iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift, iosApp/Tests/DiagnosticsReviewFixesTests.swift
Profile eligibility is persisted by binding and profile, asynchronous results are generation-guarded, persistent captures fail closed when eligibility is unknown, and abnormal-exit breadcrumbs and logs are filtered by run ID and timestamp.
Exit-sentinel lifecycle and evidence preservation
iosApp/iosApp/Shared/Diagnostics/ExitSentinel.swift, iosApp/Tests/DiagnosticsReviewFixesTests.swift
Exit markers use separate current and leftover slots, preserve prior-run evidence, scope clearing by run ID, support rebinding, and retry leftover capture.

Bundle and reporting pipeline

Layer / File(s) Summary
Bundle construction and diagnostics transport
iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift, iosApp/iosApp/Networking/HTTPClient.swift, iosApp/iosApp/Networking/DiagnosticsAPI.swift, iosApp/Tests/DiagnosticsBundleBuilderTests.swift, iosApp/Tests/DiagnosticsReviewFixesTests.swift
Diagnostics artifacts are scrubbed, tarred, gzipped, and validated before multipart upload; multipart retries, response decoding, error mapping, deterministic filenames, and non-UTF8 redaction behavior are covered.
MetricKit and pending-report retention
iosApp/iosApp/Shared/Diagnostics/MetricKitCapture.swift, iosApp/iosApp/Shared/Diagnostics/PendingReportStore.swift, iosApp/Tests/DiagnosticsReviewFixesTests.swift, iosApp/Tests/PendingReportStoreTests.swift
MetricKit reports contain isolated crash evidence and empty log/session sentinels, while fingerprints are marked seen only after retained reports load successfully.

Application lifecycle integration

Layer / File(s) Summary
Application lifecycle and playback integration
iosApp/iosApp/Screens/Auth/AuthService.swift, iosApp/iosApp/Networking/ServerRegistry.swift, iosApp/iosApp/Navigation/AppRouter.swift, iosApp/iosApp/ContentView.swift, iosApp/iosApp/Screens/Player/PlayerLog.swift, iosApp/iosApp/Shared/Diagnostics/DiagnosticsConsentStore.swift, iosApp/iosApp/Shared/Diagnostics/RecentSessionTracker.swift, iosApp/project.yml, iosApp/Tests/DiagnosticsReviewFixesTests.swift
Profile, server, authentication, navigation, consent, and playback transitions now gate or purge diagnostics state, record navigation breadcrumbs, filter CMP logs, register sensitive hosts, and scope recent-session cleanup.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

  • Silo-Server/silo-apple#96: Introduces the diagnostics infrastructure that this PR refines across capture, eligibility, storage, upload, and lifecycle paths.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.56% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main diagnostics changes around profile gating and crash evidence isolation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/client-diagnostics-apple

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7ac520a970

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

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

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
iosApp/iosApp/Screens/Settings/DiagnosticsPromptReviewView.swift (1)

16-41: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated Send / Always Send / Don't Send action block across two views. Both files independently implement the identical set of actions and confirmation dialog, which is why the confirmation wording already drifted between them (singular vs. plural, fixed separately). Extracting a shared view/component would prevent future divergence.

  • iosApp/iosApp/Screens/Settings/DiagnosticsPromptReviewView.swift#L16-L41: extract this action Section (Send/Always Send confirmation/Don't Send) into a shared DiagnosticsPromptActionsSection view parameterized by model.
  • iosApp/iosApp/Screens/Settings/DiagnosticsPromptSheet.swift#L17-L46: replace this duplicated block with the same shared DiagnosticsPromptActionsSection view.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@iosApp/iosApp/Screens/Settings/DiagnosticsPromptReviewView.swift` around
lines 16 - 41, Extract the duplicated Send/Always Send confirmation/Don't Send
Section from DiagnosticsPromptReviewView.swift lines 16-41 into a shared
DiagnosticsPromptActionsSection parameterized by model, preserving the existing
actions, disabled states, and confirmation wording. Replace the equivalent block
in DiagnosticsPromptSheet.swift lines 17-46 with this shared view so both
screens use one implementation.
iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift (1)

125-127: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Minor: String(decoding:as:) flagged by SwiftLint, inconsistent with scrubExactTokenMatches's failable pattern in the same file.

Low-value nitpick — String(decoding:as:) is non-optional and widely accepted for non-critical text (here only used for computing log category summaries), so this is optional.

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

In `@iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift`
around lines 125 - 127, In the diagnostics log parsing flow near
scrubExactTokenMatches, replace the SwiftLint-flagged non-failable
String(decoding:as:) conversion with the file’s existing failable decoding
pattern. Preserve the current line splitting behavior and ensure decoding
failure does not disrupt bundle construction.

Source: Linters/SAST tools

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

Inline comments:
In `@iosApp/iosApp/Navigation/AppRouter.swift`:
- Around line 289-297: Update expiredSession so the breadcrumb target matches
the destination selected by authState: use "login" when
ServerRegistry.shared.hasActiveServer is true and the user needs login, and use
the server-setup target when it is false and authState becomes needsServerSetup.
Keep the existing path reset and state transitions unchanged.

In `@iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift`:
- Around line 86-101: Update scrubExactTokenMatches to fail closed when the
input cannot be decoded as UTF-8 instead of returning the original data.
Propagate an error or replace/drop the offending bundle entry through the
caller’s existing diagnostics-building flow, ensuring malformed content is never
uploaded unredacted while preserving current behavior for valid UTF-8 data.

In `@iosApp/project.yml`:
- Around line 202-217: Update the SiloTVTopShelf source exclusions in
project.yml to exclude the entire recursive Diagnostics tree with a single
Diagnostics/** pattern. Ensure this covers nested paths such as Contract,
Logging, and DiagnosticsSHA256 while preserving unrelated Shared helpers
required by the target.

---

Nitpick comments:
In `@iosApp/iosApp/Screens/Settings/DiagnosticsPromptReviewView.swift`:
- Around line 16-41: Extract the duplicated Send/Always Send confirmation/Don't
Send Section from DiagnosticsPromptReviewView.swift lines 16-41 into a shared
DiagnosticsPromptActionsSection parameterized by model, preserving the existing
actions, disabled states, and confirmation wording. Replace the equivalent block
in DiagnosticsPromptSheet.swift lines 17-46 with this shared view so both
screens use one implementation.

In `@iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift`:
- Around line 125-127: In the diagnostics log parsing flow near
scrubExactTokenMatches, replace the SwiftLint-flagged non-failable
String(decoding:as:) conversion with the file’s existing failable decoding
pattern. Preserve the current line splitting behavior and ensure decoding
failure does not disrupt bundle construction.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 185da3e7-7593-4a32-b1fc-2dd3d245961d

📥 Commits

Reviewing files that changed from the base of the PR and between 4905b8f and 7ac520a.

📒 Files selected for processing (80)
  • .gitignore
  • iosApp/Tests/BreadcrumbJournalTests.swift
  • iosApp/Tests/ConsentStoreTests.swift
  • iosApp/Tests/DeviceSnapshotBuilderTests.swift
  • iosApp/Tests/DiagnosticsBundleBuilderTests.swift
  • iosApp/Tests/DiagnosticsContractTests.swift
  • iosApp/Tests/DiagnosticsPromptPolicyTests.swift
  • iosApp/Tests/DiagnosticsRedactionTests.swift
  • iosApp/Tests/DiagnosticsReviewFixesTests.swift
  • iosApp/Tests/Fixtures/DiagnosticsContract/README.md
  • iosApp/Tests/Fixtures/DiagnosticsContract/attr-registry.json
  • iosApp/Tests/Fixtures/DiagnosticsContract/device.schema.json
  • iosApp/Tests/Fixtures/DiagnosticsContract/fixtures/invalid/archive-entry-outside-allowlist.json
  • iosApp/Tests/Fixtures/DiagnosticsContract/fixtures/invalid/bad-schema-version.json
  • iosApp/Tests/Fixtures/DiagnosticsContract/fixtures/invalid/missing-consent.json
  • iosApp/Tests/Fixtures/DiagnosticsContract/fixtures/invalid/platform-macos-reserved.json
  • iosApp/Tests/Fixtures/DiagnosticsContract/fixtures/invalid/stack-excerpt-over-8kib.json
  • iosApp/Tests/Fixtures/DiagnosticsContract/fixtures/invalid/unknown-report-type.json
  • iosApp/Tests/Fixtures/DiagnosticsContract/fixtures/valid/android-manual-no-profile.json
  • iosApp/Tests/Fixtures/DiagnosticsContract/fixtures/valid/android-manual.json
  • iosApp/Tests/Fixtures/DiagnosticsContract/fixtures/valid/android-tv-crash-ueh.json
  • iosApp/Tests/Fixtures/DiagnosticsContract/fixtures/valid/device.json
  • iosApp/Tests/Fixtures/DiagnosticsContract/fixtures/valid/ios-hang-metrickit.json
  • iosApp/Tests/Fixtures/DiagnosticsContract/fixtures/valid/loglines.jsonl
  • iosApp/Tests/Fixtures/DiagnosticsContract/fixtures/valid/tvos-abnormal-exit.json
  • iosApp/Tests/Fixtures/DiagnosticsContract/logline.schema.json
  • iosApp/Tests/Fixtures/DiagnosticsContract/manifest.schema.json
  • iosApp/Tests/LogRingTests.swift
  • iosApp/Tests/MetricKitCaptureTests.swift
  • iosApp/Tests/PendingReportStoreTests.swift
  • iosApp/iosApp/ContentView.swift
  • iosApp/iosApp/Navigation/AppRouter.swift
  • iosApp/iosApp/Networking/DiagnosticsAPI.swift
  • iosApp/iosApp/Networking/HTTPClient.swift
  • iosApp/iosApp/Networking/ServerRegistry.swift
  • iosApp/iosApp/Screens/Auth/AuthService.swift
  • iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift
  • iosApp/iosApp/Screens/Player/PlaybackSessionBridge.swift
  • iosApp/iosApp/Screens/Player/PlayerLog.swift
  • iosApp/iosApp/Screens/Settings/DiagnosticsPendingReportRow.swift
  • iosApp/iosApp/Screens/Settings/DiagnosticsPromptPresentationModifier.swift
  • iosApp/iosApp/Screens/Settings/DiagnosticsPromptReportSummaryView.swift
  • iosApp/iosApp/Screens/Settings/DiagnosticsPromptReviewView.swift
  • iosApp/iosApp/Screens/Settings/DiagnosticsPromptSheet.swift
  • iosApp/iosApp/Screens/Settings/DiagnosticsReportDetailView.swift
  • iosApp/iosApp/Screens/Settings/DiagnosticsReportSummarySections.swift
  • iosApp/iosApp/Screens/Settings/DiagnosticsSettingsView.swift
  • iosApp/iosApp/Screens/Settings/SettingsView.swift
  • iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift
  • iosApp/iosApp/Shared/Diagnostics/Contract/DeviceSnapshotPayload.swift
  • iosApp/iosApp/Shared/Diagnostics/Contract/DiagnosticsCrashInfo.swift
  • iosApp/iosApp/Shared/Diagnostics/Contract/DiagnosticsLogLine.swift
  • iosApp/iosApp/Shared/Diagnostics/Contract/DiagnosticsManifest.swift
  • iosApp/iosApp/Shared/Diagnostics/Contract/DiagnosticsValidation.swift
  • iosApp/iosApp/Shared/Diagnostics/DeviceSnapshotBuilder.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsCapabilityProbe.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsConsentStore.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsFeatureState.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsNotice.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsPrompt.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsPromptPolicy.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsReportSummary.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsSHA256.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsViewModel.swift
  • iosApp/iosApp/Shared/Diagnostics/ExitSentinel.swift
  • iosApp/iosApp/Shared/Diagnostics/Logging/BreadcrumbJournal.swift
  • iosApp/iosApp/Shared/Diagnostics/Logging/DiagLog.swift
  • iosApp/iosApp/Shared/Diagnostics/Logging/LogRing.swift
  • iosApp/iosApp/Shared/Diagnostics/MetricKitCapture.swift
  • iosApp/iosApp/Shared/Diagnostics/PendingReportStore.swift
  • iosApp/iosApp/Shared/Diagnostics/RecentSessionTracker.swift
  • iosApp/iosApp/iOSApp.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsConsentScreen.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsPendingReportScreen.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsPromptScreen.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsReportSummaryCard.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsSettingsPane.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVSettingsView.swift
  • iosApp/project.yml

Comment thread iosApp/project.yml Resolved
@Quick104 Quick104 changed the title fix(diagnostics): round-6 review findings (follow-up to #96) fix(diagnostics): harden profile gating and crash evidence isolation Jul 21, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
iosApp/iosApp/Networking/ServerRegistry.swift (1)

229-235: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Close diagnostics eligibility before active-profile teardown.

Persisted purges do not invalidate in-memory profile eligibility. Sign-out never invokes the lifecycle gate, and removal leaves the old gate active until after several awaits; diagnostics can remain eligible for the stale profile during those transitions.

  • iosApp/iosApp/Networking/ServerRegistry.swift#L229-L235: for an active server, call activeProfileWillChange() before purging and activeProfileDidChange() after clearing the profile mirrors.
  • iosApp/iosApp/Networking/ServerRegistry.swift#L251-L256: call activeProfileWillChange() before the purge/cancellation awaits; retain the existing post-fallback activeProfileDidChange().
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@iosApp/iosApp/Networking/ServerRegistry.swift` around lines 229 - 235, Update
ServerRegistry.signOut at iosApp/iosApp/Networking/ServerRegistry.swift:229-235
to call activeProfileWillChange() before diagnostic purges when signing out the
active server, then call activeProfileDidChange() after clearing the profile
mirrors. Also update the removal flow at
iosApp/iosApp/Networking/ServerRegistry.swift:251-256 to call
activeProfileWillChange() before purge and cancellation awaits while retaining
the existing post-fallback activeProfileDidChange() call.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@iosApp/iosApp/Networking/ServerRegistry.swift`:
- Around line 229-235: Update ServerRegistry.signOut at
iosApp/iosApp/Networking/ServerRegistry.swift:229-235 to call
activeProfileWillChange() before diagnostic purges when signing out the active
server, then call activeProfileDidChange() after clearing the profile mirrors.
Also update the removal flow at
iosApp/iosApp/Networking/ServerRegistry.swift:251-256 to call
activeProfileWillChange() before purge and cancellation awaits while retaining
the existing post-fallback activeProfileDidChange() call.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a3e91942-6263-4a9a-a2a7-89aeb135e923

📥 Commits

Reviewing files that changed from the base of the PR and between 7ac520a and 8c331e3.

📒 Files selected for processing (11)
  • iosApp/Tests/DiagnosticsBundleBuilderTests.swift
  • iosApp/Tests/DiagnosticsReviewFixesTests.swift
  • iosApp/iosApp/Navigation/AppRouter.swift
  • iosApp/iosApp/Networking/DiagnosticsAPI.swift
  • iosApp/iosApp/Networking/HTTPClient.swift
  • iosApp/iosApp/Networking/ServerRegistry.swift
  • iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift
  • iosApp/iosApp/Shared/Diagnostics/ExitSentinel.swift
  • iosApp/iosApp/Shared/Diagnostics/MetricKitCapture.swift
  • iosApp/project.yml
🚧 Files skipped from review as they are similar to previous changes (6)
  • iosApp/iosApp/Networking/HTTPClient.swift
  • iosApp/iosApp/Navigation/AppRouter.swift
  • iosApp/iosApp/Shared/Diagnostics/ExitSentinel.swift
  • iosApp/iosApp/Networking/DiagnosticsAPI.swift
  • iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8c331e377b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

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

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread iosApp/iosApp/ContentView.swift Resolved
Quick104 added 2 commits July 22, 2026 08:20
…cs-apple

# Conflicts:
#	iosApp/Tests/DiagnosticsBundleBuilderTests.swift
#	iosApp/Tests/DiagnosticsReviewFixesTests.swift
#	iosApp/iosApp/Networking/DiagnosticsAPI.swift
#	iosApp/iosApp/Networking/HTTPClient.swift
#	iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift
#	iosApp/iosApp/Shared/Diagnostics/DiagnosticsConsentStore.swift
#	iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift
#	iosApp/iosApp/Shared/Diagnostics/ExitSentinel.swift
#	iosApp/iosApp/Shared/Diagnostics/MetricKitCapture.swift
#	iosApp/project.yml
@Quick104
Quick104 merged commit 4f4b1d7 into main Jul 22, 2026
1 check was pending
@Quick104
Quick104 deleted the feat/client-diagnostics-apple branch July 22, 2026 12:34

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
iosApp/Tests/PendingReportStoreTests.swift (1)

36-40: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert the specific eviction error.

XCTAssertThrowsError accepts any error, so this test could pass if the delayed save fails before cap enforcement. Match the DiagnosticsStoreError.unreadableReport case to make the regression assertion specific.

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

In `@iosApp/Tests/PendingReportStoreTests.swift` around lines 36 - 40, Update the
save assertion in the pending report store test to verify that the thrown error
is specifically DiagnosticsStoreError.unreadableReport, rather than accepting
any error. Keep the existing delayed-save setup and cap-enforcement scenario
unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@iosApp/Tests/PendingReportStoreTests.swift`:
- Around line 36-40: Update the save assertion in the pending report store test
to verify that the thrown error is specifically
DiagnosticsStoreError.unreadableReport, rather than accepting any error. Keep
the existing delayed-save setup and cap-enforcement scenario unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f036a6e3-8a78-4d2f-aab5-4368c6caab6e

📥 Commits

Reviewing files that changed from the base of the PR and between 8c331e3 and 59e217a.

📒 Files selected for processing (10)
  • iosApp/Tests/DiagnosticsReviewFixesTests.swift
  • iosApp/Tests/PendingReportStoreTests.swift
  • iosApp/iosApp/ContentView.swift
  • iosApp/iosApp/Networking/ServerRegistry.swift
  • iosApp/iosApp/Screens/Player/PlayerLog.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsConsentStore.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift
  • iosApp/iosApp/Shared/Diagnostics/MetricKitCapture.swift
  • iosApp/iosApp/Shared/Diagnostics/PendingReportStore.swift
  • iosApp/iosApp/Shared/Diagnostics/RecentSessionTracker.swift
🚧 Files skipped from review as they are similar to previous changes (7)
  • iosApp/iosApp/Shared/Diagnostics/PendingReportStore.swift
  • iosApp/iosApp/Screens/Player/PlayerLog.swift
  • iosApp/iosApp/Shared/Diagnostics/RecentSessionTracker.swift
  • iosApp/Tests/DiagnosticsReviewFixesTests.swift
  • iosApp/iosApp/Networking/ServerRegistry.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsConsentStore.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 59e217aaf3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

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

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

let ringSnapshot = DiagLog.ring.snapshot()
let lines = ringSnapshot.lines + harvestOSLogLines(since: since)
let candidateLines = ringSnapshot.lines + harvestOSLogLines(since: start)
let lines = Self.logLines(candidateLines, forRunID: runID, since: start)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve an empty abnormal-exit log snapshot

When this run-id filter leaves no failed-run entries after a tvOS relaunch, logSnapshotArtifact returns nil and the abnormal-exit capture saves no logs.jsonl. buildBundle treats a missing snapshot as a manual report and harvests the live ring/OSLog at upload time, so the report can include later relaunch/navigation/playback logs instead of freezing the intentional absence of attributable failed-run logs; save an empty logs.jsonl artifact for this case.

Useful? React with 👍 / 👎.

#if os(iOS) || os(tvOS)
// URL, active id, and credential slot now agree; it is safe to resolve
// the restored profile against the newly selected server.
DiagnosticsCoordinator.activeProfileDidChange()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Wait for the new binding before reopening capture

After switching from one saved server to another, this immediately starts the async profile check while DiagnosticsCoordinator.currentDiagnosticsBinding can still be the previous server's breadcrumbConsentContext until the foreground diagnostics refresh completes. If the restored profile on the new server is adult and that lookup returns first, activeProfileBreadcrumbEligible can reopen under the old binding, so early breadcrumbs/CMP logs/session IDs from the new server get recorded against the previous account; keep the gate closed until the new diagnostics status/binding has been published or clear the old context before this recheck.

Useful? React with 👍 / 👎.

// replaced only through `setCaptureEnabled` so the closure storage is
// never accessed concurrently.
private var captureEnabledGate: () -> Bool = { true }
private var captureEnabledGate: () -> Bool = { false }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Arm the sentinel from cached state before refresh

With this default closed, a tvOS cold launch does not arm the current-run marker until a successful diagnostics refresh later installs the gate and the profile lookup resolves. For an already-consented adult profile that launches offline, or crashes during slow startup before those awaits finish, no current marker is ever written, so the next relaunch has no abnormal-exit report to preserve; seed the gate from the last-known binding/profile eligibility or otherwise arm once cached adult eligibility is available before the first live refresh.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant