Skip to content

feat(diagnostics): client diagnostics for iOS and tvOS — capture, consent, and upload - #96

Merged
Quick104 merged 9 commits into
mainfrom
feat/client-diagnostics-apple
Jul 21, 2026
Merged

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

Conversation

@Quick104

@Quick104 Quick104 commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When the app crashes, hangs, or misbehaves in the field there is no way to get logs or crash evidence back to the user's server. This implements the Apple slice of the client diagnostics capability (spec: Silo-Server/silo-server#430; server side: Silo-Server/silo-server#445).

What this adds

Capture and packaging

  • DiagLog safe-logging facade with collection-time redaction and an always-on in-memory ring; curated cmpLog tee into the ring.
  • Breadcrumb journal for pre-crash context; device snapshot with hashed route identifiers.
  • MetricKit crash/hang capture (iOS) and an abnormal-exit sentinel (tvOS).
  • tar.gz bundle builder + multipart upload via DiagnosticsAPI, with vendored contract models and fixture tests. uncompressed_bytes is computed as the full tar stream, matching the contract semantics clarified in the server PR.

Consent and UX (disabled by default)

  • Server+account-bound consent store with sign-out purge; nothing is collected beyond the memory ring, and nothing leaves the device, without explicit opt-in.
  • Pending-report prompt flow: after a detected crash/hang the user is asked whether to send the report, with a review sheet showing exactly what would be uploaded before anything is sent.
  • Per-fingerprint suppression, child-profile gating, and an always-on consent mode for automatic upload (DiagnosticsPromptPolicy).
  • Diagnostics settings panes and report summary/detail screens on both iOS and tvOS.

Verification

Risks / follow-ups

  • No on-device (physical hardware) validation of the MetricKit payload path yet; MetricKit delivery windows make that impractical in a simulator run.
  • Android client (silo-android) is not started; it is the remaining platform for this capability.
  • UI screenshots can be added on request.

AI-use disclosure: implemented and verified with Claude Code.

🤖 Generated with Claude Code

https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh

Summary by CodeRabbit

  • New Features

    • Added an iOS/tvOS Diagnostics area in Settings with consent controls (Ask/Always/Never), debug logging, pending report management, and sent history.
    • Added iOS/tvOS screens to review and send diagnostics (send once/always, decline) and manage pending reports; tvOS includes “Send Diagnostics Now,” plus tvOS-specific consent/pending/prompt screens.
    • Enhanced diagnostics capture with breadcrumb tracking across app launch, navigation/screen changes, playback, focus/lifecycle, and tvOS abnormal-exit.
  • Improvements

    • Improved diagnostics uploads via multipart support, stricter manifest/log contract validation, stronger upload error handling, and more reliable sensitive-data redaction.
  • Chores

    • Updated iOS local build-state ignores for iOS Swift artifacts.

Quick104 and others added 2 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
@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR adds an iOS/tvOS diagnostics system with validated contracts, redacted logging, persistent breadcrumbs and pending reports, MetricKit and abnormal-exit capture, multipart uploads, consent management, lifecycle integration, and platform-specific settings and prompts.

Changes

Diagnostics implementation

Layer / File(s) Summary
Contracts and validation
iosApp/iosApp/Shared/Diagnostics/Contract/*, iosApp/Tests/Fixtures/DiagnosticsContract/*, iosApp/Tests/DiagnosticsContractTests.swift
Adds Codable diagnostics contracts, validation rules, JSON schemas, valid/invalid fixtures, and fixture-based tests.
Logging and capture
iosApp/iosApp/Shared/Diagnostics/Logging/*, MetricKitCapture.swift, PendingReportStore.swift
Adds redacted logs, ring buffering, rotating breadcrumbs, MetricKit parsing, deduplication, and filesystem-backed pending reports.
Bundle and upload flow
DiagnosticsBundleBuilder.swift, DiagnosticsCoordinator.swift, Networking/DiagnosticsAPI.swift, Networking/HTTPClient.swift
Builds validated tar/gzip bundles, scrubs tokens, fetches availability, uploads multipart data, maps errors, and manages report lifecycle.
Consent and lifecycle integration
DiagnosticsConsentStore.swift, DiagnosticsViewModel.swift, ContentView.swift, ExitSentinel.swift
Persists consent and history, handles foreground and authentication changes, triggers uploads, and captures tvOS abnormal exits.
Settings and prompts
Screens/Settings/*, tvOS/Screens/Settings/*, SettingsView.swift, TVSettingsView.swift
Adds iOS and tvOS diagnostics settings, consent flows, pending-report review, upload actions, and sent-history displays.
Playback instrumentation
Navigation/AppRouter.swift, Screens/Player/*, iOSApp.swift
Records navigation, playback-session, audio-route, lifecycle, and curated player-pipeline breadcrumbs.
Build support
.gitignore, iosApp/project.yml
Ignores local iOS build directories and excludes diagnostics sources from the tvOS Top Shelf target.

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

Possibly related PRs

Sequence Diagram(s)

sequenceDiagram
  participant App
  participant DiagnosticsViewModel
  participant DiagnosticsCoordinator
  participant PendingReportStore
  participant DiagnosticsAPI
  App->>DiagnosticsViewModel: handleForeground()
  DiagnosticsViewModel->>DiagnosticsCoordinator: refresh status and list reports
  DiagnosticsCoordinator->>PendingReportStore: load eligible reports
  DiagnosticsViewModel->>DiagnosticsCoordinator: upload pending report
  DiagnosticsCoordinator->>DiagnosticsAPI: upload manifest and bundle
  DiagnosticsAPI-->>DiagnosticsCoordinator: upload result
  DiagnosticsCoordinator->>PendingReportStore: delete or retain report
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.36% 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 work for iOS/tvOS, including capture, consent, and upload.
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 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: 0284b77e79

ℹ️ 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".

}

do {
let bundle = try await buildBundle(for: report)

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 Refresh report consent before uploading pending bundles

When the server's consent notice advances after a report was captured, this still rebuilds the upload from the pending report's stored manifest, so consent.notice_version remains stale. The server will return stale_consent, and even after the user re-consents the same pending manifest is uploaded again because the report on disk is never updated, leaving those older reports impossible to send until they expire or are deleted.

Useful? React with 👍 / 👎.

Comment on lines +372 to +373
case .disabled, .storageUnavailable, .quotaExceeded, .tooLarge, .busy, .retryable, .underlying:
return .keptRetryable

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 Do not retry permanently oversized diagnostics bundles

If the upload endpoint returns too_large for a bundle that exceeds the server's limit, this classifies it as retryable. For reports whose fixed artifacts or generated archive stay over the limit, automatic upload will keep rebuilding and retrying the same invalid payload while telling the user it will retry, instead of trimming or discarding/marking the report as a permanent local failure.

Useful? React with 👍 / 👎.

Comment on lines +182 to +185
do {
snapshot = try await refreshStatus()
} catch {
return nil

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 crash reports when status refresh is offline

When MetricKit or the tvOS exit sentinel tries to capture a report while the server is temporarily unreachable, this catch returns nil before anything is saved. Both capture paths guard on captureContext, so the diagnostic is dropped instead of queued for later upload even if this device already has cached status and consent for the active server.

Useful? React with 👍 / 👎.

Comment on lines +281 to +284
for report in pendingReports where pendingStore.canAutoUpload(
fingerprint: report.binding.fingerprint,
binding: binding
) {

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 Skip reports that already need a server update

After an unsupported_schema response, handleUploadError marks report.state.needsServerUpdate, but this auto-upload loop only checks the throttle. With Always Send enabled, the same incompatible report is retried every day until expiry, and Ask mode can prompt it again from the same unfiltered pending list, even though the user was told the server needs an update.

Useful? React with 👍 / 👎.

Comment on lines +35 to +37
entries.append(RecentPlaybackSessionEntry(
sessionID: sessionID,
recordedAt: DiagnosticsTimestamp.string(from: now)

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 Scope recent playback sessions to the report binding

This tracker records only the session ID in one global recent-session list, so after watching on server/account A and then switching to server/account B, recentSessionIDs() can be written into B's diagnostics manifest. Those IDs are server-scoped playback state, which makes cross-binding reports misleading and leaks another server/account's session identifiers.

Useful? React with 👍 / 👎.

Comment on lines +67 to +69
guard requestServerRegistryID == ServerRegistry.shared.activeServerId,
requestAccessTokenFingerprint == (await Self.currentAccessTokenFingerprint()) else {
throw DiagnosticsCoordinatorError.identityChanged

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 Do not treat token refresh as an identity change

When the access token has expired, HTTPClient can successfully refresh it during either getDiagnosticsStatus() or currentUser(), but this guard then compares the old and new token fingerprints and throws identityChanged. That makes the first diagnostics refresh after an otherwise normal token refresh look offline, and capture paths that swallow captureContext failures can drop the MetricKit/exit-sentinel report instead of saving it.

Useful? React with 👍 / 👎.

@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: 9

Caution

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

⚠️ Outside diff range comments (1)
iosApp/iosApp/Screens/Auth/AuthService.swift (1)

251-268: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Do not skip server-wide diagnostics cleanup.

When the current-binding purge succeeds, Line 267 passes false, so ServerRegistry.signOut skips purgeDiagnosticsForServerRegistryID. Reports and consent state for older bindings on this server can remain after sign-out. Let ServerRegistry perform its full purge, or always run the registry-ID purge separately.

🤖 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/Auth/AuthService.swift` around lines 251 - 268, The
sign-out flow in AuthService currently disables ServerRegistry’s server-wide
diagnostics purge when the current-binding purge succeeds. Update the
ServerRegistry.shared.signOut call to always request purgeDiagnostics, ensuring
purgeDiagnosticsForServerRegistryID runs for all bindings while preserving the
existing current-binding purge behavior.
🧹 Nitpick comments (12)
iosApp/iosApp/Shared/Diagnostics/DiagnosticsViewModel.swift (1)

296-328: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Move the consentMode = .ask side effect out of message(for:).

message(for:) mutates consentMode (Line 321) as a side effect of formatting a string, and handle(_:report:) sets the same value again (Lines 299–301) — so handle double-applies it while uploadAutomaticallyEligibleReports/sendPrompt silently depend on the formatter's hidden mutation to reset consent. This coupling is easy to break during refactors. Consider centralizing the keptStaleConsent → consentMode = .ask transition in one explicit place and keeping message(for:) pure.

🤖 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/DiagnosticsViewModel.swift` around lines 296
- 328, The message(for:) formatter should be pure and must no longer mutate
consentMode. Centralize the keptStaleConsent transition in the explicit
decision-handling flow, such as handle(_:report:), while preserving the reset
behavior for every caller that processes that decision, including
uploadAutomaticallyEligibleReports and sendPrompt; remove the duplicate
assignment so the transition occurs exactly once.
iosApp/iosApp/Shared/Diagnostics/ExitSentinel.swift (1)

51-55: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

readMarker() is invoked twice while holding the lock.

Both branches re-read the marker from disk. Cache it once to avoid the second file read.

♻️ Optional simplification
-        if let marker = readMarker(), marker.runID != DiagLog.captureSessionID {
-            leftoverMarker = marker
-        } else if readMarker()?.runID == DiagLog.captureSessionID {
-            return
-        }
+        let existing = readMarker()
+        if let existing, existing.runID != DiagLog.captureSessionID {
+            leftoverMarker = existing
+        } else if existing?.runID == DiagLog.captureSessionID {
+            return
+        }
🤖 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/ExitSentinel.swift` around lines 51 - 55,
Update the marker handling logic around readMarker() to invoke it once, store
the result in a local value, and use that cached marker for both the runID
comparison and leftoverMarker assignment while preserving the existing return
behavior.
iosApp/iosApp/Screens/Settings/DiagnosticsPromptSheet.swift (2)

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

Send/Always Send/Don't Send action block duplicated across two screens. DiagnosticsPromptSheet.swift and DiagnosticsPromptReviewView.swift reimplement the same three buttons, confirmation dialog, and copy almost verbatim; future changes (e.g., new consent copy, new action) risk updating only one site.

  • iosApp/iosApp/Screens/Settings/DiagnosticsPromptSheet.swift#L22-44: extract the Send/Always Send/Don't Send block (including the confirmation dialog) into a shared view/section taking the reports list and model, reuse it here.
  • iosApp/iosApp/Screens/Settings/DiagnosticsPromptReviewView.swift#L17-39: reuse the same extracted component instead of the duplicated block.
🤖 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/DiagnosticsPromptSheet.swift` at line 1,
Extract the duplicated Send/Always Send/Don't Send buttons, confirmation dialog,
and related copy from DiagnosticsPromptSheet and DiagnosticsPromptReviewView
into one shared SwiftUI view or section that accepts the reports list and model.
Replace both existing action blocks with this shared component, preserving their
current behavior and presentation.

22-44: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated Send/Always Send/Don't Send block; "Don't Send" bypasses the isWorking guard.

See consolidated comments — nearly identical to DiagnosticsPromptReviewView.swift, and "Don't Send" isn't gated by model.isWorking like the Send actions above it.

🤖 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/DiagnosticsPromptSheet.swift` around lines 22
- 44, Consolidate the duplicated Send, Always Send, and Don't Send actions
shared with DiagnosticsPromptReviewView.swift into the existing reusable
implementation, preserving the confirmation dialog behavior. Ensure the Don't
Send action is also disabled while model.isWorking, matching the guards on the
Send actions.
iosApp/iosApp/Screens/Settings/DiagnosticsPromptReviewView.swift (1)

17-39: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated Send/Always Send/Don't Send block; "Don't Send" bypasses the isWorking guard.

See consolidated comments for details — this block is near-identical to DiagnosticsPromptSheet.swift, and the "Don't Send" button here isn't disabled while model.isWorking, unlike the Send actions above it.

🤖 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 17 - 39, Consolidate the Send, Always Send, and Don't Send actions in
DiagnosticsPromptReviewView with the shared implementation used by
DiagnosticsPromptSheet.swift, preserving the confirmation behavior. Ensure the
Don't Send action also respects model.isWorking by disabling it during active
work, matching the other actions.
iosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsSettingsPane.swift (1)

109-120: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate ReportType title / expiry-date logic across the iOS and tvOS pending-report rows.

Both files reimplement the same ReportType → String switch and capturedAtDate + PendingReportStore.expiryInterval calculation, while the sibling tvOS screens (TVDiagnosticsPendingReportScreen.swift, TVDiagnosticsReportSummaryCard.swift) instead reuse DiagnosticsReportSummary.typeTitle/.expiresAt. Extracting this into one shared helper (e.g. on ReportType/PendingReport) would keep the mapping consistent if a new report type is ever added.

  • iosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsSettingsPane.swift#L109-L120: replace typeTitle(for:)/expiryDate(for:) with the shared helper.
  • iosApp/iosApp/Screens/Settings/DiagnosticsPendingReportRow.swift#L23-L38: replace expiryDate/typeTitle with the same shared helper.
🤖 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/tvOS/Screens/Settings/TVDiagnosticsSettingsPane.swift` around
lines 109 - 120, Extract the duplicated ReportType title mapping and
PendingReport expiry calculation into one shared helper, reusing the existing
DiagnosticsReportSummary.typeTitle/expiresAt pattern or an equivalent shared
symbol. Update TVDiagnosticsSettingsPane.swift lines 109-120 and
DiagnosticsPendingReportRow.swift lines 23-38 to remove their local
typeTitle/expiryDate implementations and call the shared helper instead.
iosApp/iosApp/Shared/Diagnostics/Contract/DiagnosticsManifest.swift (1)

203-206: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Cardinality checks use hard-coded literals instead of deriving from the source collections.

categories.count <= 9 and (1...8).contains(entries.count) mirror DiagnosticsLogCategory.allCases.count and Archive.allowedEntries.count respectively. If a category or allowlist entry is ever added/removed, these literals silently drift from the real cardinality.

♻️ Proposed fix
-            guard categories.count <= 9, Set(categories).count == categories.count else {
+            guard categories.count <= DiagnosticsLogCategory.allCases.count,
+                  Set(categories).count == categories.count else {
-            guard (1...8).contains(entries.count),
+            guard (1...Self.allowedEntries.count).contains(entries.count),

Also applies to: 234-238

🤖 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/Contract/DiagnosticsManifest.swift` around
lines 203 - 206, Replace the hard-coded cardinality bounds in the diagnostics
validation rules with counts derived from the authoritative collections: use
DiagnosticsLogCategory.allCases.count for categories and
Archive.allowedEntries.count for entries. Update both the categories check near
the shown guard and the corresponding entries validation, while preserving the
existing uniqueness and allowed-range behavior.
iosApp/iosApp/Shared/Diagnostics/Contract/DeviceSnapshotPayload.swift (1)

23-45: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

captured_at length isn't validated against the schema's maxLength: 64.

device.schema.json caps captured_at at 64 characters, but validate() only checks non-emptiness. Since this is machine-generated ISO-8601 text, risk is low, but adding the bound keeps the client gate faithful to the vendored contract.

🤖 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/Contract/DeviceSnapshotPayload.swift` around
lines 23 - 45, The validate() method in DeviceSnapshotPayload must enforce the
schema’s 64-character maximum for capturedAt in addition to non-emptiness.
Update the capturedAt guard to reject values exceeding 64 characters while
preserving the existing invalidField("device.captured_at") error.
iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift (3)

120-143: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

makeLogSummary reaches into DiagnosticsConsentStore.shared global singleton.

Every other dependency (fileManager) is injected via init, but debugLoggingEnabled is pulled from a shared singleton inside a otherwise-pure builder function, making build() harder to unit test deterministically and coupling this layer to consent-store lifecycle/timing.

♻️ Proposed fix: inject the flag
     func build(
         report: PendingReport,
         logLines: [String],
         droppedLogLines: Int,
-        redactionTokens: [String] = []
+        redactionTokens: [String] = [],
+        debugLoggingEnabled: Bool = DiagnosticsConsentStore.shared.debugLoggingEnabled
     ) throws -> DiagnosticsBundleBuildResult {
...
-        draft.logSummary = makeLogSummary(
+        draft.logSummary = makeLogSummary(
             logsData: logsData,
             logsGzipSize: logsGzipSize,
-            droppedLines: droppedLogLines
+            droppedLines: droppedLogLines,
+            debugLoggingEnabled: debugLoggingEnabled
         )
🤖 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 120 - 143, Update DiagnosticsBundleBuilder initialization and
makeLogSummary to receive the debug-logging flag as an injected dependency,
alongside the existing fileManager dependency. Replace the direct
DiagnosticsConsentStore.shared.debugLoggingEnabled access with that stored
value, and ensure build() passes the injected flag through consistently.

24-29: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

gzip(logsData) is computed twice, and returns non-gzip empty output for empty input.

logsGzipSize is computed by gzip-compressing logsData purely to report a byte count in LogSummary, even though the same bytes get compressed again as part of tarData moments later (line 61) — doubling deflate work for a summary field. Separately, when logsData is empty, inputBuffer.bindMemory(...).baseAddress is nil, the guard returns early without ever calling deflate, and gzip() yields an empty Data() instead of a valid (small) gzip stream — harmless here since it only feeds logsGzipSize, but worth noting since gzip() is a general-purpose helper.

Also applies to: 220-227

🤖 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 24 - 29, Update DiagnosticsBundleBuilder’s gzip usage to avoid
compressing logsData solely for logsGzipSize when the same data is compressed
again during tarData construction; reuse the existing compressed result or
derive the summary size from that single compression. Also update the gzip
helper to produce a valid gzip stream for empty input by handling the nil input
buffer without skipping required stream finalization.

120-143: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

SwiftLint optional_data_string_conversion: prefer the failable String(bytes:encoding:) initializer over String(decoding:as:). Both sites use the non-failable UTF-8 decode, which silently substitutes invalid byte sequences instead of surfacing a decode failure.

  • iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift#L120-L143: replace String(decoding: logsData, as: UTF8.self) (line 126) with String(bytes: logsData, encoding: .utf8) and handle the nil case explicitly when deriving log categories.
  • iosApp/Tests/DiagnosticsContractTests.swift#L94-L104: replace String(decoding: data, as: UTF8.self) (line 96) with the failable initializer so a malformed fixture fails the test loudly instead of decoding with replacement characters.
🤖 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 120 - 143, The UTF-8 conversions at both affected sites must use
failable decoding and handle invalid data explicitly. In
iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift lines
120-143, update makeLogSummary to use String(bytes:encoding:) and define the
intended nil behavior when deriving categories. In
iosApp/Tests/DiagnosticsContractTests.swift lines 94-104, use the failable
initializer and make malformed fixture decoding fail the test explicitly.

Source: Linters/SAST tools

iosApp/iosApp/Shared/Diagnostics/Logging/DiagLog.swift (1)

181-223: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Consider broadening redaction beyond URLs/auth/tokens.

Current patterns cover URLs, Authorization/Cookie headers, Bearer tokens, JWTs, and key=value secrets, but nothing targets other common PII (e.g. email addresses) that could land in free-text message strings from call sites outside this file. Not a confirmed leak here, but worth hardening given the redaction is the sole safety net for arbitrary log text.

🤖 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/Logging/DiagLog.swift` around lines 181 -
223, Extend DiagnosticsRedactor with a dedicated regex and sanitization step for
common PII such as email addresses, replacing matches with a consistent redacted
marker. Apply this within sanitize(_:,maxLength:) alongside the existing URL,
credential, and token redaction while preserving the current ordering and length
limit.
🤖 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/ContentView.swift`:
- Around line 93-98: Update DiagnosticsViewModel.handleForeground() to track
whether a foreground refresh is already in flight, guarding before its first
suspension so concurrent auth-state, server/profile, notification, and
scene-phase triggers coalesce into one execution. Set the guard before awaiting
work and clear it on every completion path, while preserving the existing prompt
and refresh behavior.

In `@iosApp/iosApp/Screens/Settings/DiagnosticsPromptSheet.swift`:
- Line 1: Add .disabled(model.isWorking) to the decline/delete action buttons in
DiagnosticsPromptSheet, DiagnosticsPromptReviewView, and
DiagnosticsReportDetailView, matching the existing Send button busy-guard and
preventing concurrent operations on shared diagnostics state.

In `@iosApp/iosApp/Screens/Settings/DiagnosticsReportDetailView.swift`:
- Around line 28-34: Update the “Delete Report” Button in the diagnostics detail
view to be disabled while model.isWorking, matching the existing “Send Report”
guard. Preserve the current delete action and dismissal behavior once the model
is no longer working.

In `@iosApp/iosApp/Shared/Diagnostics/ExitSentinel.swift`:
- Line 25: Update the captureEnabled assignment in
DiagnosticsCoordinator.updateBreadcrumbConsentContext to synchronize access
using ExitSentinel’s existing lock, matching the protected read in
appDidEnterForeground. Ensure all closure storage reads and writes are
serialized, or replace the storage with an equivalent atomic mechanism.

In `@iosApp/iosApp/Shared/Diagnostics/Logging/BreadcrumbJournal.swift`:
- Around line 90-95: Guard the entire readAll() operation with the same lock
used by appendRenderedLine and purgeLocked, including orderedSegmentURLs() and
readCompleteLines calls, so segment discovery and file reads cannot overlap
append or rotation. Preserve the existing decoder and flattened result behavior
while ensuring the lock is released after all reads complete.

In `@iosApp/iosApp/Shared/Diagnostics/Logging/DiagLog.swift`:
- Around line 202-223: Update secretKeyValueRegex and replaceSecretKeyValues to
support both “=” and “:” delimiters, preserving optional whitespace around the
delimiter. Ensure replacement parsing handles either delimiter so
colon-delimited values receive the same redaction as equals-delimited secrets.

In `@iosApp/iosApp/Shared/Diagnostics/MetricKitCapture.swift`:
- Around line 167-172: Update the stack excerpt truncation in the surrounding
function to limit the returned string to 8192 UTF-8 bytes rather than 8192
characters. Preserve valid UTF-8 boundaries while truncating so the result
always satisfies DiagnosticsCrashInfo.validate().
- Around line 190-197: Remove the redundant named-keys recursion loop from the
frame collection logic, keeping the dictionary.values traversal in collectFrames
as the sole recursive pass over child values. Preserve the existing frame
collection and 12-frame cap behavior.

In `@iosApp/Tests/DiagnosticsBundleBuilderTests.swift`:
- Line 12: Update the rendered string conversion in the relevant test to use
Swift’s failable String(bytes:encoding:) initializer with UTF-8 instead of
String(decoding:as:), preserving the existing scrubbed-data conversion and
handling the optional result appropriately.

---

Outside diff comments:
In `@iosApp/iosApp/Screens/Auth/AuthService.swift`:
- Around line 251-268: The sign-out flow in AuthService currently disables
ServerRegistry’s server-wide diagnostics purge when the current-binding purge
succeeds. Update the ServerRegistry.shared.signOut call to always request
purgeDiagnostics, ensuring purgeDiagnosticsForServerRegistryID runs for all
bindings while preserving the existing current-binding purge behavior.

---

Nitpick comments:
In `@iosApp/iosApp/Screens/Settings/DiagnosticsPromptReviewView.swift`:
- Around line 17-39: Consolidate the Send, Always Send, and Don't Send actions
in DiagnosticsPromptReviewView with the shared implementation used by
DiagnosticsPromptSheet.swift, preserving the confirmation behavior. Ensure the
Don't Send action also respects model.isWorking by disabling it during active
work, matching the other actions.

In `@iosApp/iosApp/Screens/Settings/DiagnosticsPromptSheet.swift`:
- Line 1: Extract the duplicated Send/Always Send/Don't Send buttons,
confirmation dialog, and related copy from DiagnosticsPromptSheet and
DiagnosticsPromptReviewView into one shared SwiftUI view or section that accepts
the reports list and model. Replace both existing action blocks with this shared
component, preserving their current behavior and presentation.
- Around line 22-44: Consolidate the duplicated Send, Always Send, and Don't
Send actions shared with DiagnosticsPromptReviewView.swift into the existing
reusable implementation, preserving the confirmation dialog behavior. Ensure the
Don't Send action is also disabled while model.isWorking, matching the guards on
the Send actions.

In `@iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift`:
- Around line 120-143: Update DiagnosticsBundleBuilder initialization and
makeLogSummary to receive the debug-logging flag as an injected dependency,
alongside the existing fileManager dependency. Replace the direct
DiagnosticsConsentStore.shared.debugLoggingEnabled access with that stored
value, and ensure build() passes the injected flag through consistently.
- Around line 24-29: Update DiagnosticsBundleBuilder’s gzip usage to avoid
compressing logsData solely for logsGzipSize when the same data is compressed
again during tarData construction; reuse the existing compressed result or
derive the summary size from that single compression. Also update the gzip
helper to produce a valid gzip stream for empty input by handling the nil input
buffer without skipping required stream finalization.
- Around line 120-143: The UTF-8 conversions at both affected sites must use
failable decoding and handle invalid data explicitly. In
iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift lines
120-143, update makeLogSummary to use String(bytes:encoding:) and define the
intended nil behavior when deriving categories. In
iosApp/Tests/DiagnosticsContractTests.swift lines 94-104, use the failable
initializer and make malformed fixture decoding fail the test explicitly.

In `@iosApp/iosApp/Shared/Diagnostics/Contract/DeviceSnapshotPayload.swift`:
- Around line 23-45: The validate() method in DeviceSnapshotPayload must enforce
the schema’s 64-character maximum for capturedAt in addition to non-emptiness.
Update the capturedAt guard to reject values exceeding 64 characters while
preserving the existing invalidField("device.captured_at") error.

In `@iosApp/iosApp/Shared/Diagnostics/Contract/DiagnosticsManifest.swift`:
- Around line 203-206: Replace the hard-coded cardinality bounds in the
diagnostics validation rules with counts derived from the authoritative
collections: use DiagnosticsLogCategory.allCases.count for categories and
Archive.allowedEntries.count for entries. Update both the categories check near
the shown guard and the corresponding entries validation, while preserving the
existing uniqueness and allowed-range behavior.

In `@iosApp/iosApp/Shared/Diagnostics/DiagnosticsViewModel.swift`:
- Around line 296-328: The message(for:) formatter should be pure and must no
longer mutate consentMode. Centralize the keptStaleConsent transition in the
explicit decision-handling flow, such as handle(_:report:), while preserving the
reset behavior for every caller that processes that decision, including
uploadAutomaticallyEligibleReports and sendPrompt; remove the duplicate
assignment so the transition occurs exactly once.

In `@iosApp/iosApp/Shared/Diagnostics/ExitSentinel.swift`:
- Around line 51-55: Update the marker handling logic around readMarker() to
invoke it once, store the result in a local value, and use that cached marker
for both the runID comparison and leftoverMarker assignment while preserving the
existing return behavior.

In `@iosApp/iosApp/Shared/Diagnostics/Logging/DiagLog.swift`:
- Around line 181-223: Extend DiagnosticsRedactor with a dedicated regex and
sanitization step for common PII such as email addresses, replacing matches with
a consistent redacted marker. Apply this within sanitize(_:,maxLength:)
alongside the existing URL, credential, and token redaction while preserving the
current ordering and length limit.

In `@iosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsSettingsPane.swift`:
- Around line 109-120: Extract the duplicated ReportType title mapping and
PendingReport expiry calculation into one shared helper, reusing the existing
DiagnosticsReportSummary.typeTitle/expiresAt pattern or an equivalent shared
symbol. Update TVDiagnosticsSettingsPane.swift lines 109-120 and
DiagnosticsPendingReportRow.swift lines 23-38 to remove their local
typeTitle/expiryDate implementations and call the shared helper instead.
🪄 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: 02b24b4b-bf57-411d-b7d4-c99ec36d37f3

📥 Commits

Reviewing files that changed from the base of the PR and between 7d9e7b4 and 0284b77.

📒 Files selected for processing (77)
  • .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/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/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/iosApp/ContentView.swift Resolved
@@ -0,0 +1,56 @@
#if os(iOS)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Decline/delete actions bypass the shared model.isWorking busy-guard used by the adjacent Send actions. In each file the Send-style buttons are .disabled(model.isWorking), but the decline/delete counterpart isn't, so it can run concurrently with an in-flight upload against the same shared PendingReportStore/DiagnosticsViewModel state.

  • iosApp/iosApp/Screens/Settings/DiagnosticsPromptSheet.swift#L44-44: add .disabled(model.isWorking) to the "Don't Send" button.
  • iosApp/iosApp/Screens/Settings/DiagnosticsPromptReviewView.swift#L39-39: add .disabled(model.isWorking) to the "Don't Send" button.
  • iosApp/iosApp/Screens/Settings/DiagnosticsReportDetailView.swift#L28-34: add .disabled(model.isWorking) to the "Delete Report" button.
🤖 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/DiagnosticsPromptSheet.swift` at line 1, Add
.disabled(model.isWorking) to the decline/delete action buttons in
DiagnosticsPromptSheet, DiagnosticsPromptReviewView, and
DiagnosticsReportDetailView, matching the existing Send button busy-guard and
preventing concurrent operations on shared diagnostics state.

Quick104 and others added 2 commits July 21, 2026 09:04
-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

@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: 2

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)

209-217: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Cancel in-flight requests before purging diagnostics signOut never calls HTTPClient.cancelInFlightRequests(), and remove does it only after the purge. A late callback can recreate pending reports after cleanup; cancel first, then purge in both paths.

🤖 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 209 - 217, Update
signOut and remove to call HTTPClient.cancelInFlightRequests() before any
diagnostics purge, ensuring in-flight callbacks cannot recreate reports after
cleanup. Preserve the existing purge behavior and apply the cancellation
ordering consistently in both paths.
🤖 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/Networking/ServerRegistry.swift`:
- Line 305: Update the migration flow in ServerRegistry’s
migrateLegacyIfNeeded() to register the legacy-created entry with
registerDiagnosticsSensitiveHosts([entry]) before migration completes, or ensure
all entries are registered after migration. Preserve the existing load()
registration behavior for persisted registry entries.

In `@iosApp/Tests/DiagnosticsRedactionTests.swift`:
- Around line 7-8: Update the test helper rendered to unwrap the optional result
from DiagLog.renderedLine instead of coalescing nil to an empty string. Make
rendered and its callers throwing as needed, or explicitly fail the test when
rendering returns nil, so redaction assertions always operate on a successfully
rendered line.

---

Outside diff comments:
In `@iosApp/iosApp/Networking/ServerRegistry.swift`:
- Around line 209-217: Update signOut and remove to call
HTTPClient.cancelInFlightRequests() before any diagnostics purge, ensuring
in-flight callbacks cannot recreate reports after cleanup. Preserve the existing
purge behavior and apply the cancellation ordering consistently in both paths.
🪄 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: e0817662-1913-4184-ae05-db5e00467d6a

📥 Commits

Reviewing files that changed from the base of the PR and between 0284b77 and 48aa543.

📒 Files selected for processing (4)
  • iosApp/Tests/DiagnosticsRedactionTests.swift
  • iosApp/iosApp/ContentView.swift
  • iosApp/iosApp/Networking/ServerRegistry.swift
  • iosApp/iosApp/Shared/Diagnostics/Logging/DiagLog.swift
🚧 Files skipped from review as they are similar to previous changes (2)
  • iosApp/iosApp/Shared/Diagnostics/Logging/DiagLog.swift
  • iosApp/iosApp/ContentView.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: 48aa543cad

ℹ️ 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".

for: snapshot.binding,
currentNoticeVersion: snapshot.status.consentNoticeVersion
)
if requirePersistentCapture, record.mode == .never {

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 Gate diagnostics capture for child profiles

When the active profile is a child, MetricKit and the tvOS exit sentinel call captureContext() directly; this gate only rejects Never consent and never checks DiagnosticsConsentStore.canManageDiagnostics for the active profile. That means a crash while a child profile is selected is still saved as an account-bound pending report, and a later adult profile on the same account can be prompted to upload logs from the child session, defeating the child-profile gating added for diagnostics.

Useful? React with 👍 / 👎.

let rendered = message()
print(rendered)
#if os(iOS) || os(tvOS)
DiagLog.i(.playback, "CMP", rendered)

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 Honor the debug logging toggle before recording CMP traces

With Debug Logging off, cmpLog still appends every CMP trace into the diagnostics ring unconditionally; I checked the new debugLoggingEnabled uses and they only store the toggle and stamp log_summary.debug_logging. As a result, manual and crash reports still include verbose playback/HLS diagnostics such as the 1Hz [CMP-DIAG] lines despite the user-facing setting indicating only basic logs should be collected.

Useful? React with 👍 / 👎.

Comment thread iosApp/project.yml
- "Diagnostics/DiagnosticsViewModel.swift"
- "Diagnostics/ExitSentinel.swift"
- "Diagnostics/MetricKitCapture.swift"
- "Diagnostics/PendingReportStore.swift"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep DiagnosticsSHA256 available to Top Shelf

The Top Shelf target still compiles iosApp/Shared, which includes Diagnostics/Logging/DiagLog.swift, but this exclude removes the only file that defines DiagnosticsSHA256 (verified with git grep -n "DiagnosticsSHA256"). Because DiagLog.hostToken calls DiagnosticsSHA256.shortHex, the SiloTVTopShelf extension will fail to build once this target is regenerated from project.yml.

Useful? React with 👍 / 👎.

captureSessionID: marker.runID
)
var artifacts: [PendingReportArtifact] = []
let breadcrumbs = Self.renderBreadcrumbs(breadcrumbLines)

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 Filter abnormal-exit breadcrumbs to the crashed run

For a tvOS abnormal-exit report, this writes every persisted breadcrumb segment into breadcrumbs.jsonl even though the code already isolated crashedRunBreadcrumbLines for the marker run. After relaunch, the journal can include the new run's startup/navigation breadcrumbs or older retained segments, so the uploaded crash evidence can be polluted with post-restart or unrelated context instead of just the run that failed.

Useful? React with 👍 / 👎.

Comment on lines +47 to +49
guard let context = await DiagnosticsCoordinator.shared.captureContext(
applicationVersionOverride: applicationVersion
) else {

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 Bind MetricKit reports to the crash-time account

MetricKit delivers crash/hang diagnostics later, but this captures them using the server/account that happens to be active at delivery time. If a user crashes on server/account A and switches or signs into B before MetricKit calls didReceive, the pending report is bound to B and can upload A's crash context to the wrong destination instead of preserving the crash-time binding.

Useful? React with 👍 / 👎.

let redactionTokens = await Self.currentTokenRedactionValues()
return try bundleBuilder.build(
report: report,
logLines: ringSnapshot.lines + osLogLines,

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 Do not package live logs into old pending reports

For any pending crash/hang/abnormal-exit report, bundle building uses the current in-memory ring and current-process OSLog lines at review/upload time rather than logs captured with that report. When a report is sent hours or days later, or after the user has used another server/profile, the uploaded logs.jsonl can contain unrelated post-incident activity instead of the failure context.

Useful? React with 👍 / 👎.

- 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
@Quick104

Copy link
Copy Markdown
Contributor Author

All review findings addressed in b25015b — the P1 was real and is confirmed fixed:

  • P1 Top Shelf build break: DiagnosticsSHA256 moved to its own file compiled by every consumer target (baseline build of SiloTVTopShelf failed exactly as Codex predicted; now green).
  • Stale consent: uploads rewrite only consent.notice_version from the current consent record; captured evidence stays frozen.
  • too_large: now a permanent state (backward-compatible decode) with a user-facing message instead of retrying forever; permanent-failure reports (needsServerUpdate/tooLarge) are excluded from auto-upload and the Ask prompt.
  • Offline capture: crash/exit capture falls back to the last-known-good status snapshot (in-memory, then per-server persisted store) instead of dropping the report; only drops with no known binding.
  • Child profiles: persistent capture is gated when the active profile is positively a child.
  • Capture-time evidence: crash/hang/abnormal-exit reports snapshot the log ring + OSLog into a logs.jsonl artifact at capture; bundle build prefers the snapshot (manual reports keep the live ring). Abnormal-exit breadcrumbs are filtered to the crashed run.
  • Identity vs token rotation: refresh compares server id + user id, not token fingerprints — a routine token refresh no longer throws identityChanged.
  • Session binding: recent playback sessions are stamped with their DiagnosticsBinding and filtered per report binding — no more cross-server leakage.
  • Debug Logging toggle: verbose [CMP-DIAG] traces only enter the diagnostics ring when the toggle is on; errors/lifecycle lines always kept.
  • Also: byte-safe stack_excerpt truncation, deduped MetricKit frame traversal, locked BreadcrumbJournal.readAll(), busy-guards on decline/delete buttons, legacy-migration host registration for redaction, ExitSentinel lock-guarded capture flag, in-flight guard in handleForeground(), and the test-hygiene items (XCTUnwrap, failable String init).

Skipped with a documented limitation: binding MetricKit reports to the crash-time account (delivery-time binding) — a proper fix needs a persisted binding timeline; noted in a comment at the capture site. The colon-delimited secret redaction was already fixed in 48aa543.

Full iOS suite, SiloTV, and SiloTVTopShelf all build/test green.

🤖 Generated with Claude Code

@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 (2)
iosApp/iosApp/Shared/Diagnostics/RecentSessionTracker.swift (1)

34-55: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Preserve identical session IDs from different bindings.

Line 45 removes an existing entry by sessionID alone. Because IDs are server-scoped, recording the same ID under another server/account silently removes the first report's session evidence.

  • iosApp/iosApp/Shared/Diagnostics/RecentSessionTracker.swift#L34-L55: deduplicate on both sessionID and binding.
  • iosApp/Tests/DiagnosticsReviewFixesTests.swift#L50-L62: add a regression case that records the same ID for both bindings and verifies each report retains it.
Proposed fix
-        entries.removeAll { $0.sessionID == sessionID }
+        entries.removeAll { $0.sessionID == sessionID && $0.binding == binding }
🤖 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/RecentSessionTracker.swift` around lines 34
- 55, Update RecentSessionTracker.record to deduplicate entries using both
sessionID and binding, preserving identical IDs associated with different
bindings. In iosApp/iosApp/Shared/Diagnostics/RecentSessionTracker.swift lines
34-55, change the removal predicate accordingly; in
iosApp/Tests/DiagnosticsReviewFixesTests.swift lines 50-62, add a regression
test recording the same ID for two bindings and verifying both reports retain
it.
iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift (1)

228-258: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Offline/context failure is conflated with a genuine destination mismatch.

The guard on Lines 229-231 collapses two different failure modes into .keptDestinationMismatch:

  • captureContext returning nil (e.g., offline, or identity mid-change) — a transient condition.
  • report.isUploadable(to:) returning false — a real, permanent-for-this-context mismatch.

Returning .keptDestinationMismatch for the offline case surfaces a misleading message ("Report kept for the server where it was captured.") and, per DiagnosticsViewModel.uploadAutomaticallyEligibleReports, unconditionally consumes the 24h auto-upload throttle window regardless of decision — so a merely-offline attempt silently defers the real retry by a full day.

🐛 Proposed fix: separate the two failure modes
-        guard let context = await captureContext(requirePersistentCapture: false),
-              report.isUploadable(to: context.binding) else {
-            return .keptDestinationMismatch
-        }
+        guard let context = await captureContext(requirePersistentCapture: false) else {
+            return .keptRetryable
+        }
+        guard report.isUploadable(to: context.binding) else {
+            return .keptDestinationMismatch
+        }
🤖 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/DiagnosticsCoordinator.swift` around lines
228 - 258, Separate the guard in upload(report:) into distinct handling for
captureContext failure and report.isUploadable(to:) failure. Return the existing
retryable/retained decision for a nil context so offline or transient identity
changes do not appear as destination mismatches or consume the auto-upload
throttle; return .keptDestinationMismatch only when a valid context exists but
the report is not uploadable to that context.
🧹 Nitpick comments (1)
iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift (1)

159-169: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Prefer failable String(bytes:encoding:) over String(decoding:as:).

String(decoding:as:) never fails; malformed bytes are silently replaced rather than surfaced. Since this file writes the snapshot itself (via logSnapshotArtifact), the input should always be valid UTF‑8, so this is low-risk, but a failable initializer is safer against unexpected on-disk corruption.

🤖 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/DiagnosticsCoordinator.swift` around lines
159 - 169, Update the snapshot parsing in DiagnosticsCoordinator to use the
failable String(bytes:encoding:) initializer instead of String(decoding:as:),
and handle a nil result by falling through the existing failure path. Preserve
the current line splitting and bundleBuilder.build flow for valid UTF-8 snapshot
data.

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.

Outside diff comments:
In `@iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift`:
- Around line 228-258: Separate the guard in upload(report:) into distinct
handling for captureContext failure and report.isUploadable(to:) failure. Return
the existing retryable/retained decision for a nil context so offline or
transient identity changes do not appear as destination mismatches or consume
the auto-upload throttle; return .keptDestinationMismatch only when a valid
context exists but the report is not uploadable to that context.

In `@iosApp/iosApp/Shared/Diagnostics/RecentSessionTracker.swift`:
- Around line 34-55: Update RecentSessionTracker.record to deduplicate entries
using both sessionID and binding, preserving identical IDs associated with
different bindings. In
iosApp/iosApp/Shared/Diagnostics/RecentSessionTracker.swift lines 34-55, change
the removal predicate accordingly; in
iosApp/Tests/DiagnosticsReviewFixesTests.swift lines 50-62, add a regression
test recording the same ID for two bindings and verifying both reports retain
it.

---

Nitpick comments:
In `@iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift`:
- Around line 159-169: Update the snapshot parsing in DiagnosticsCoordinator to
use the failable String(bytes:encoding:) initializer instead of
String(decoding:as:), and handle a nil result by falling through the existing
failure path. Preserve the current line splitting and bundleBuilder.build flow
for valid UTF-8 snapshot data.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c4f3215a-2fa4-4f1b-b632-f9f8cc346904

📥 Commits

Reviewing files that changed from the base of the PR and between 48aa543 and b25015b.

📒 Files selected for processing (18)
  • iosApp/Tests/DiagnosticsBundleBuilderTests.swift
  • iosApp/Tests/DiagnosticsRedactionTests.swift
  • iosApp/Tests/DiagnosticsReviewFixesTests.swift
  • iosApp/iosApp/Networking/ServerRegistry.swift
  • iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift
  • iosApp/iosApp/Screens/Player/PlayerLog.swift
  • iosApp/iosApp/Screens/Settings/DiagnosticsPromptReviewView.swift
  • iosApp/iosApp/Screens/Settings/DiagnosticsPromptSheet.swift
  • iosApp/iosApp/Screens/Settings/DiagnosticsReportDetailView.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.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/MetricKitCapture.swift
  • iosApp/iosApp/Shared/Diagnostics/PendingReportStore.swift
  • iosApp/iosApp/Shared/Diagnostics/RecentSessionTracker.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsPendingReportScreen.swift
🚧 Files skipped from review as they are similar to previous changes (13)
  • iosApp/iosApp/Screens/Settings/DiagnosticsPromptSheet.swift
  • iosApp/iosApp/Screens/Player/PlayerLog.swift
  • iosApp/iosApp/Shared/Diagnostics/PendingReportStore.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsPendingReportScreen.swift
  • iosApp/iosApp/Screens/Settings/DiagnosticsReportDetailView.swift
  • iosApp/iosApp/Shared/Diagnostics/MetricKitCapture.swift
  • iosApp/iosApp/Networking/ServerRegistry.swift
  • iosApp/Tests/DiagnosticsBundleBuilderTests.swift
  • iosApp/iosApp/Screens/Settings/DiagnosticsPromptReviewView.swift
  • iosApp/iosApp/Shared/Diagnostics/ExitSentinel.swift
  • iosApp/iosApp/Shared/Diagnostics/Logging/BreadcrumbJournal.swift
  • iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsViewModel.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: b25015b161

ℹ️ 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".

if let binding {
purgeDiagnostics(for: binding)
}
Self.purgeBreadcrumbJournal()

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 Clear stale diagnostics context on sign-out

After an active-server sign-out, this purge removes pending files/consent but leaves cachedStatus/LastKnownStatusStore and breadcrumbConsentContext pointing at the signed-out binding. Because the consent record was removed, later breadcrumb checks or persistent captures recreate the missing consent as default Ask and can start saving diagnostics for the old account again; clear the in-memory and persisted binding context when purging the current binding.

Useful? React with 👍 / 👎.

Comment on lines +284 to +286
if requirePersistentCapture {
if record.mode == .never {
return nil

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 Gate persistent capture on server availability

When /diagnostics/status returns disabled, this still returns a persistent capture context as long as the local consent is not Never. MetricKit and the tvOS exit sentinel can therefore store crash reports while the server-side diagnostics feature is disabled, and those reports become prompt/auto-upload candidates if the server is later re-enabled; persistent capture should be skipped unless the status is available.

Useful? React with 👍 / 👎.

Comment on lines +192 to +195
pendingStore.recordAutoUploadAttempt(
fingerprint: report.binding.fingerprint,
binding: report.binding.binding
)

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 Suppress declined prompts for the report lifetime

When the user taps Don't Send in Ask mode, this records the decline through the same auto-upload throttle used for retries. That throttle expires after 24 hours while pending reports live for seven days, so the same crash/hang can be presented again on a later foreground even though the user already declined that specific report; use a separate suppression state or delete the declined prompt reports.

Useful? React with 👍 / 👎.


#if os(tvOS)
func captureAbnormalExit(marker: ExitSentinelMarker) async -> Bool {
guard let context = await captureContext() else {

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 Bind abnormal-exit markers to the crashed account

When a leftover tvOS marker is captured, this calls captureContext() and binds the report to whatever server/account is active at capture time; the marker itself only stores the run ID and start time. If the previous run died under server/account A but the next launch requires login or lets the user switch to B before captureLeftoverIfNeeded() runs, B receives A's abnormal-exit breadcrumbs/logs, so persist the binding with the marker and skip mismatches.

Useful? React with 👍 / 👎.

Comment on lines +612 to +613
guard let context else {
return true

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 Keep breadcrumbs disabled until consent is known

When no diagnostics context has been loaded yet, this default enables disk breadcrumb capture. On a fresh launch for an account that previously selected Never, early lifecycle/navigation breadcrumbs are written before the first status refresh can reload that consent, and if the refresh stays offline they continue to persist despite the user's Never setting; default to disabled or load the stored consent before writing breadcrumbs.

Useful? React with 👍 / 👎.

Comment on lines +229 to +231
guard let context = await captureContext(requirePersistentCapture: false),
report.isUploadable(to: context.binding) else {
return .keptDestinationMismatch

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 Treat status-refresh failures during upload as retryable

If the report list was loaded while the server was available but this extra captureContext refresh fails during the actual upload, the guard returns keptDestinationMismatch even though the destination was never checked. In the Always Send path the attempt is already throttled before calling upload, so one transient status failure can suppress retries for 24 hours and show the wrong destination-mismatch message; return a retryable/offline result instead when context refresh fails.

Useful? React with 👍 / 👎.

Comment on lines +42 to +43
let manifestDraftData = try DiagnosticsJSONCoding.makeEncoder().encode(draft)
appendEntry("manifest.json", manifestDraftData)

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 Put the finalized manifest inside the uploaded archive

This adds manifest.json to the tar before the archive metadata is computed, so the file inside the bundle is only a DiagnosticsManifestDraft and lacks the required archive section that the sidecar manifest has. Any server-side archive validation or later inspection of the uploaded bundle's own manifest.json will see an invalid manifest even though the multipart manifest validates; rebuild or replace this entry after finalizing the archive fields.

Useful? React with 👍 / 👎.

- 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
@Quick104

Copy link
Copy Markdown
Contributor Author

Round-2 findings addressed in 8f266a8 — six fixed, one refuted:

  • Sign-out: purging a binding now also clears the in-memory status cache, the persisted last-known-status snapshot, and the breadcrumb consent context for that binding — a signed-out account's consent can no longer resurrect as default-Ask.
  • Capture gating: persistent capture requires the (last-known) server status to be available; a server with diagnostics disabled no longer accumulates pending crash reports. Offline capture still works off the last-known-available snapshot.
  • Abnormal-exit binding: the exit-sentinel marker now records the binding (and profile) at run start, back-filled after first refresh; capture binds the report to the crashed account, and a marker that mismatches the active account is consumed and dropped rather than leaking evidence across accounts. Marker decode stays backward-compatible.
  • Breadcrumbs: default is now off until consent context is known, bootstrapped from the persisted last-known status — a Never account's fresh launch honors Never before any network refresh.
  • Upload errors: a failed status refresh during upload returns a retryable result instead of keptDestinationMismatch (which was suppressing retries for 24h with the wrong message); genuine mismatches still report as such.
  • Declined prompts: promptDeclined is now a persisted per-report state (decode-compatible) — declined reports never re-prompt and are excluded from Always-mode auto-upload for their lifetime, while remaining manually sendable from Settings. (Deliberate semantic: an explicit per-report decline outranks a later mode change; flag if you'd rather Always override it.)

Refuted — embedded manifest.json (BundleBuilder): not a bug. finalized(archive:) copies every draft field and adds only archive, so the embedded entry equals the part-1 manifest minus archive field-for-field — which is exactly what the spec defines (design doc, hashing note) and exactly what the server's embedded-manifest comparison validates against. Changing it would break ingestion.

iOS suite 680/680 green; SiloTV and iOS builds succeed.

🤖 Generated with Claude Code

@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 (2)
iosApp/iosApp/Shared/Diagnostics/ExitSentinel.swift (2)

132-138: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Make leftover capture consent- and purge-safe.

The marker is copied before await, and capture proceeds without rechecking consent. If sign-out calls ExitSentinel.shared.purge() during the await, the stale account-bound marker can still reach captureAbnormalExit; completion also clears whichever leftover is currently stored. Serialize or cancel in-flight capture, revalidate consent, and clear only when the stored marker still matches the captured marker.

🤖 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/ExitSentinel.swift` around lines 132 - 138,
Update captureLeftoverIfNeeded to prevent stale account-bound markers from being
captured or cleared after purge: serialize or cancel in-flight capture,
revalidate consent after awaiting captureAbnormalExit, and clear the marker only
if the currently stored marker still equals the captured marker. Preserve the
existing no-marker early return and successful-capture behavior.

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

Fail closed until consent is wired. captureEnabledGate should default to { false }; ExitSentinel.shared.appDidLaunch() runs before DiagnosticsCoordinator installs the consent gate on tvOS, so the current { true } default can arm or clear the marker before consent state exists.

🤖 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/ExitSentinel.swift` at line 45, Change the
default closure for captureEnabledGate in ExitSentinel from enabled to disabled
by default, so appDidLaunch cannot arm or clear the marker before
DiagnosticsCoordinator installs the consent gate. Preserve the configured gate
behavior once consent wiring is initialized.
🤖 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/Shared/Diagnostics/ExitSentinel.swift`:
- Around line 132-138: Update captureLeftoverIfNeeded to prevent stale
account-bound markers from being captured or cleared after purge: serialize or
cancel in-flight capture, revalidate consent after awaiting captureAbnormalExit,
and clear the marker only if the currently stored marker still equals the
captured marker. Preserve the existing no-marker early return and
successful-capture behavior.
- Line 45: Change the default closure for captureEnabledGate in ExitSentinel
from enabled to disabled by default, so appDidLaunch cannot arm or clear the
marker before DiagnosticsCoordinator installs the consent gate. Preserve the
configured gate behavior once consent wiring is initialized.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 24c57b9b-07ee-4fc7-8987-3ccaf381c9f4

📥 Commits

Reviewing files that changed from the base of the PR and between b25015b and 8f266a8.

📒 Files selected for processing (5)
  • iosApp/Tests/DiagnosticsReviewFixesTests.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsViewModel.swift
  • iosApp/iosApp/Shared/Diagnostics/ExitSentinel.swift
  • iosApp/iosApp/Shared/Diagnostics/PendingReportStore.swift
🚧 Files skipped from review as they are similar to previous changes (3)
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift
  • iosApp/iosApp/Shared/Diagnostics/PendingReportStore.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsViewModel.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: 8f266a8ea2

ℹ️ 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 on lines +378 to +380
let boundContext = marker.binding != nil
? context.overridingProfileID(marker.profileID)
: context

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 Drop child-profile abnormal-exit markers

If the tvOS marker was written while a child profile was active but captureLeftoverIfNeeded() runs after an adult profile is selected, captureContext() approves the current adult profile and this then re-attaches marker.profileID to the saved report. Because the sentinel gate is account-consent based rather than profile-aware, that path can still persist and later prompt/upload an abnormal-exit report from the child session; check the marker's profile before overriding or discard markers captured under child profiles.

Useful? React with 👍 / 👎.

Comment on lines +629 to +633
Self.breadcrumbConsentContext = BreadcrumbConsentContext(
binding: binding,
noticeVersion: noticeVersion
)
Self.breadcrumbContextLock.unlock()

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 Clear old breadcrumbs when bindings change

When a user switches from server/account A to B in the same app run, this replaces the active consent context but leaves the existing breadcrumb journal intact. MetricKit later uploads breadcrumbsData(), and the tvOS abnormal-exit path filters only by run ID, so B's crash report can include A's navigation/playback breadcrumbs, including session_id entries recorded before the switch; clear the journal when the binding changes or stamp/filter breadcrumbs by binding.

Useful? React with 👍 / 👎.

Comment on lines +423 to +426
manifest.consent = DiagnosticsManifest.Consent(
mode: manifest.consent.mode,
noticeVersion: noticeVersion
)

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 Refresh consent mode with the notice

When an old pending report was captured under Always and the server advances the notice, record(...) demotes the stored consent to Ask, but this rewrite preserves the manifest's old mode while only bumping notice_version. If the user then approves the Ask prompt, the uploaded manifest still claims consent.mode = always for the new notice even though the current consent is prompt-only; update the mode from the current consent/upload action along with the notice.

Useful? React with 👍 / 👎.

Comment on lines +281 to +283
guard requirePersistentCapture,
let fallback = lastKnownSnapshotForActiveServer() else {
return nil

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 Only fallback when refresh is offline

When refreshStatus() throws identityChanged because there is no current access token, such as after refresh-token expiry has routed the app back to login, this still falls back to the last-known snapshot for persistent captures. MetricKit can deliver while the app is unauthenticated, so this can recreate default Ask consent and queue a report bound to the old account instead of skipping until an authenticated identity is available; only network/status failures should use the offline fallback.

Useful? React with 👍 / 👎.

guard let firstFrame = stackExcerpt?.split(separator: "\n").first else {
return prefix
}
return "\(prefix): \(firstFrame)"

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 Cap MetricKit summaries after prefixing

When the first MetricKit frame is close to the 8 KiB contract limit, stackExcerpt is trimmed but summary prefixes that same frame without another byte cap. The diagnostics schema caps crash.summary at 8192 bytes, while local validation only checks that it is non-empty, so those pending MetricKit reports build locally and then fail upload as invalid until they expire.

Useful? React with 👍 / 👎.

options: []
)
private static let secretKeyValueRegex = try! NSRegularExpression(
pattern: #"(?i)\b(access_token|profile_token|refresh_token|token|jwt|signature|sig|api_key|apikey|key|username|user_name|login|email|user)\s*[:=]\s*[^\s&;,]+"#,

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 Redact camelCase profile and token headers

Diagnostics now harvests current-process OSLog lines, including HTTPClient's public debug header string (profileId=..., auth(…suffix), profileToken(…suffix)). This redaction pattern only handles snake_case token keys and misses those camelCase/wrapper forms, so uploaded logs.jsonl can expose the active profile ID and token suffixes whenever debug HTTP logs are present; add these header forms to the collection redactor or stop harvesting them.

Useful? React with 👍 / 👎.

Comment on lines +703 to +706
return consentStore.persistentCaptureEnabled(
for: context.binding,
currentNoticeVersion: context.noticeVersion
)

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 Disable breadcrumbs when status is unavailable

When /diagnostics/status returns disabled or storage_unavailable, the coordinator still installs a breadcrumb context and this gate checks only local consent. For any Ask/Always account, the app keeps writing disk breadcrumbs and arming the tvOS sentinel while the server-side feature is unavailable, and those retained breadcrumbs can later be bundled if diagnostics is re-enabled; include the availability status in this gate or clear the journal on unavailable status.

Useful? React with 👍 / 👎.

Comment on lines +311 to +312
if await activeProfileIsChild() == true {
return nil

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 Fail closed when child status is unknown

If the active profile is a child but getProfiles() fails during persistent capture (for example while offline and falling back to last-known status), activeProfileIsChild() returns nil and this equality check allows the report to be saved. The prompt/upload gate later looks at the current profile rather than the report's captured profile, so a child-session crash can still be uploaded by an adult profile; skip persistent capture unless the active profile is known to be non-child.

Useful? React with 👍 / 👎.

- 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
@Quick104

Copy link
Copy Markdown
Contributor Author

Round-3 findings all addressed in 67adedc:

  • Child markers: abnormal-exit capture re-checks the marker's profile and drops child-run markers even after switching to an adult profile; legacy markers keep prior behavior, undeterminable status retries rather than leaking.
  • Binding switch: the breadcrumb journal is purged when the active binding changes mid-run (first-establish and same-binding refreshes don't purge, so crash-trail capture is preserved).
  • Fallback scope: the last-known-status fallback now only applies to network/transient failures — identityChanged/missing-account errors skip capture instead of binding to a stale account.
  • Breadcrumb availability: breadcrumb capture is gated on server status available, consistent with persistent capture.
  • Fail closed: unknown child status (profiles fetch failed) skips persistent capture; "no profile selected" correctly stays capturable.
  • Consent mode: pending-report uploads refresh consent mode along with notice version — a demoted Always→Ask report no longer uploads claiming always.
  • Summary cap: MetricKit summaries are byte-capped after frame prefixing (shared UTF-8-safe helper).
  • Redaction: camelCase token keys (accessToken/refreshToken/profileToken/profileId) and the auth(…)/profileToken(…) wrapper forms from HTTPClient debug lines are now redacted, with tests using the actual format strings.

iOS suite 683/683; SiloTV builds.

🤖 Generated with Claude Code

@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: 1

🤖 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/Shared/Diagnostics/DiagnosticsCoordinator.swift`:
- Around line 420-429: The marker handling around profileIsChild must remove or
expire markers whose profile cannot be resolved permanently, rather than
retaining them after a nil result. Update the nil branch in the
marker-processing flow to apply the existing age/TTL or cleanup mechanism, while
preserving the current true and false behaviors.
🪄 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: 1ad36b76-0f1b-41e1-8ef6-689f36b23a39

📥 Commits

Reviewing files that changed from the base of the PR and between 8f266a8 and 67adedc.

📒 Files selected for processing (6)
  • iosApp/Tests/DiagnosticsRedactionTests.swift
  • iosApp/Tests/DiagnosticsReviewFixesTests.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift
  • iosApp/iosApp/Shared/Diagnostics/Logging/DiagLog.swift
  • iosApp/iosApp/Shared/Diagnostics/MetricKitCapture.swift
  • iosApp/iosApp/Shared/Diagnostics/PendingReportStore.swift
🚧 Files skipped from review as they are similar to previous changes (5)
  • iosApp/Tests/DiagnosticsRedactionTests.swift
  • iosApp/iosApp/Shared/Diagnostics/Logging/DiagLog.swift
  • iosApp/iosApp/Shared/Diagnostics/MetricKitCapture.swift
  • iosApp/Tests/DiagnosticsReviewFixesTests.swift
  • iosApp/iosApp/Shared/Diagnostics/PendingReportStore.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: 67adedc5e4

ℹ️ 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 on lines +310 to +312
guard !(error is DiagnosticsCoordinatorError),
requirePersistentCapture,
let fallback = lastKnownSnapshotForActiveServer() else {

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 Restrict capture fallback to transient status failures

Fresh evidence in the current code is that this guard only excludes DiagnosticsCoordinatorError; status/auth failures from refreshStatus() are HTTPErrors, so a refresh-token-expired 401 (or a 404/403 from the diagnostics status endpoint) still falls back to lastKnownSnapshotForActiveServer(). In those cases the app may already be signed out or the endpoint may be unavailable, but MetricKit/tvOS capture can still queue a report against the old binding; only network/transient server failures should use the last-known snapshot, with auth/status failures failing closed.

Useful? React with 👍 / 👎.

Comment on lines +104 to +109
writeMarker(ExitSentinelMarker(
runID: DiagLog.captureSessionID,
startedAt: DiagnosticsTimestamp.string(from: now),
binding: binding,
profileID: profileID
))

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 Rewrite the exit marker after diagnostics binding loads

When tvOS starts with no last-known diagnostics snapshot (for example first login after install or after a purge), SiloApp.init arms the sentinel before any status refresh, so this write stores binding: nil; updateBreadcrumbConsentContext later learns the binding but never updates the current marker unless another foreground event happens. If the app then crashes in that same foreground, the marker is treated as legacy on relaunch and can be bound to whichever account is active at capture time, so binding support still misses this common first-run path.

Useful? React with 👍 / 👎.

Comment on lines +280 to +283
let response = try await api.upload(
manifestData: bundle.manifestData,
bundleData: bundle.bundleData
)

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 Re-check the destination before posting bundles

If the active server/account changes after captureContext passes but before this upload call (bundle building can harvest OSLog and gzip data first), HTTPClient resolves the current TokenStore at request time and can send this old report to the newly active destination. The server may reject a different server instance, but for a same-server account switch the manifest only carries server_instance_id, so the new account can receive the previous account's diagnostics; re-check the active identity immediately before posting or bind the request to the captured server/token.

Useful? React with 👍 / 👎.

Comment on lines +361 to +364
return RuntimeIdentity(
serverRegistryID: serverRegistryID,
accessTokenFingerprint: DiagnosticsSHA256.hex(data: Data(token.utf8)),
profileID: AuthService.shared.profileId

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 Do not reset diagnostics after token refresh

Fresh evidence after the coordinator fix is that the foreground workflow still includes the access-token fingerprint in RuntimeIdentity. When load(profile:) hits an expired access token, HTTPClient can refresh it successfully during the status/user calls, but the comparison at the end of handleForeground() then sees a different fingerprint and calls reset(), skipping the prompt or Always-mode auto-upload until another foreground/server/profile event happens.

Useful? React with 👍 / 👎.

Comment on lines +265 to +268
await ServerRegistry.shared.signOut(
serverId: activeId,
purgeDiagnostics: !purgedDiagnostics
)

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 Run the registry-wide diagnostics purge on sign-out

When the current binding purge succeeds, this passes purgeDiagnostics: false, so ServerRegistry.signOut skips purgeDiagnosticsForServerRegistryID entirely. If this registry URL has diagnostics stored under another recorded server_instance_id (for example after a server restore/reinstall at the same URL), sign-out only removes the current binding and leaves the older pending files/consent/history on disk; still run the registry-wide purge and make the current-binding purge only avoid duplicate current work.

Useful? React with 👍 / 👎.

- 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
@Quick104

Copy link
Copy Markdown
Contributor Author

Round-4 findings addressed in a209183:

  • Fallback classification: the last-known-status fallback now applies only to genuinely transient failures (network/5xx); auth failures and other definitive server answers skip capture.
  • Exit marker binding: the tvOS marker is rewritten as soon as the diagnostics binding first loads, not just on later foregrounds — first-launch-after-install runs are no longer unbound.
  • Pre-upload destination check: the active binding is re-verified immediately before the POST (bundle building takes time; a mid-build server switch now aborts cleanly).
  • RuntimeIdentity: token fingerprint removed from the identity tuple (server + user + profile) — a token refresh no longer resets diagnostics state.
  • Sign-out purge: the registry-wide purge always runs exactly once.
  • Cross-repo: pending uploads are now held (retryable) when the stored manifest's profile differs from the active profile, matching the server's new profile_mismatch rejection instead of failing against it.

iOS suite 686/686; SiloTV builds.

🤖 Generated with Claude Code

@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: a2091830af

ℹ️ 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 bundle = try await buildBundle(for: report)
guard destinationTokenFingerprint != nil,
ServerRegistry.shared.activeServerId == destinationServerRegistryID,
await Self.currentAccessTokenFingerprint() == destinationTokenFingerprint,

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 Use stable identity before posting diagnostics

If another request refreshes an expired access token while buildBundle is running, this fingerprint comparison fails even though the active server/account/profile did not change. In the Always Send path the auto-upload attempt is already throttled before upload(report:) is called, so a normal token refresh can turn a sendable report into keptRetryable and delay the next automatic attempt for 24 hours; re-check a stable destination identity instead of the raw access-token value.

Useful? React with 👍 / 👎.

typealias Category = DiagnosticsLogCategory

static let captureSessionID = UUID().uuidString.lowercased()
static let ring = LogRing()

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 Scope the diagnostics log ring by binding

This ring is process-wide and is read wholesale by both manual report building and crash-time log snapshots, but nothing clears or stamps it when the active server/account/profile changes. If a user plays content on server/account A, switches to B in the same app run, and then sends a manual report or crashes under B, B's diagnostics bundle can include A's CMP/playback log lines; clear the ring on binding changes or store enough binding metadata to filter it.

Useful? React with 👍 / 👎.

Comment on lines +885 to +888
return consentStore.persistentCaptureEnabled(
for: context.binding,
currentNoticeVersion: context.noticeVersion
)

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 Keep breadcrumb capture disabled for child profiles

When the active profile changes from an adult to a child, this gate can keep using the last adult account context and only checks server availability plus account consent, not whether the current profile may manage diagnostics. In that child-profile session, navigation/playback breadcrumbs and the tvOS sentinel can still be persisted and later bundled when an adult profile sends a report; include the active-profile eligibility in this gate or clear the context on child profile switches.

Useful? React with 👍 / 👎.

sessionId = session.sessionId
currentSession = session
#if os(iOS) || os(tvOS)
RecentSessionTracker.shared.record(sessionID: session.sessionId)

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 Gate recent session persistence on diagnostics capture

This records every adopted playback session under the current diagnostics binding even when breadcrumbs/persistent capture are disabled by Crash Reports = Never or by a disabled/storage-unavailable diagnostics status. Those session IDs are then pulled into a later manifest for the same binding after diagnostics is re-enabled or a manual report is sent, so playback identifiers from a period where diagnostics collection was off can still be uploaded; skip recording unless the same consent/availability gate allows capture.

Useful? React with 👍 / 👎.

for host in hosts {
guard result.range(of: host, options: .caseInsensitive) != nil else { continue }
let token = hostToken(host)
while let range = result.range(of: host, options: .caseInsensitive) {

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 Avoid re-matching redacted host tokens

When a remembered server host is a substring of the replacement token, this loop never makes progress because each replacement reintroduces the same host text. A local server configured as http://host is enough: URL redaction produces http://[host:…], and the next iteration keeps replacing the host inside that token forever, hanging diagnostics log rendering on the main/player path; perform replacements from the original ranges or use a token that cannot contain the matched host.

Useful? React with 👍 / 👎.

- 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
@Quick104

Copy link
Copy Markdown
Contributor Author

Round-5 review fixes (commit 5ed84ed):

  • DiagnosticsCoordinator ~313 (Use stable identity before posting): FIXED — pre-POST check now compares a stable identity (server registry id + selected profile) plus a token-presence sign-out check, not the access-token value, so a transparent token refresh during buildBundle no longer flips a sendable Always report to keptRetryable.
  • DiagLog ~17 (Scope log ring by binding): FIXED — the process-wide ring is cleared when the active binding changes, at the same trigger as the breadcrumb-journal purge (added LogRing.clear()); first-establish of a launch still keeps the prior run's lines.
  • DiagnosticsCoordinator ~888 (Keep breadcrumb capture disabled for child profiles): FIXED — breadcrumb/exit-sentinel gate re-evaluates the active-profile child status on profile change and status refresh (fails closed immediately on switch), consistent with the persistent-capture child gate.
  • PlaybackSessionBridge ~183 (Gate recent session persistence on diagnostics capture): FIXED — RecentSessionTracker recording is now gated on the same capture-enabled signal (isDiagnosticsCaptureEnabled) as breadcrumbs, so session IDs aren't recorded while collection is off.
  • DiagLog ~263 replaceKnownHosts (Avoid re-matching redacted host tokens): FIXED (real bug) — rewritten as a single forward pass that never rescans replaced output, ending the infinite loop when a host is a substring of its token (e.g. "host" vs "[host:…]"); added a pathological-host regression test.

Verified: full iOS suite (688 tests, 0 failures, iPhone 17 Pro) and SiloTV build (Apple TV 4K 3rd gen, CODE_SIGNING_ALLOWED=NO) both pass.

🤖 Generated with Claude Code

@Quick104
Quick104 merged commit 4905b8f into main Jul 21, 2026
1 check passed
@Quick104
Quick104 deleted the feat/client-diagnostics-apple branch July 21, 2026 18:16

@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: 5ed84edcf5

ℹ️ 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".

// eligibility now that the active profile changed so an adult→child
// switch disarms breadcrumb/session capture even though the
// server/account binding is unchanged.
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 Move diagnostics profile invalidation into the profile setter

Fresh evidence in this version is that the new diagnostics invalidation only runs from selectProfile, but existing flows still change the active profile without calling this method (for example clearing AuthService.shared.profileId when entering profile selection, and ServerRegistry.switchTo restoring a saved profile directly). When those paths move from an adult context to no profile or a saved child profile, the synchronous breadcrumb/sentinel gate can keep the previous adult eligibility until a later successful refresh, so early navigation/playback breadcrumbs or the tvOS marker can be captured under an ineligible profile; put the invalidation on every profile-id write instead of only this select path.

Useful? React with 👍 / 👎.

Comment on lines +68 to +71
onNeverSelected: @escaping (DiagnosticsBinding) -> Void = { binding in
PendingReportStore.shared.purge(binding: binding)
DiagnosticsCoordinator.purgeBreadcrumbJournal()
}

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 Purge the tvOS exit marker when reports are turned off

When a tvOS user changes Crash Reports to Never, this callback deletes pending reports and breadcrumbs but leaves the currently armed ExitSentinel marker on disk until a normal background/terminate path runs. If the app crashes in that same foreground, the marker is retained as a leftover; after relaunch it is skipped while consent is Never, but it can still be captured later if the user switches back to Ask/Always, producing an abnormal-exit report for a run that occurred after collection was turned off. Purge the sentinel marker here as well.

Useful? React with 👍 / 👎.

Comment on lines +104 to +109
writeMarker(ExitSentinelMarker(
runID: DiagLog.captureSessionID,
startedAt: DiagnosticsTimestamp.string(from: now),
binding: binding,
profileID: profileID
))

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 leftover markers until capture succeeds

When tvOS relaunches after an unclean exit, this writes the current run's marker immediately after reading the previous run's marker into memory. If captureLeftoverIfNeeded() then returns false because status/profile lookup is temporarily unavailable, a normal background/terminate of the relaunch removes the new marker and the previous crash marker is no longer on disk, so the report cannot be retried on the next launch; keep the old marker persisted until it is either saved or explicitly discarded.

Useful? React with 👍 / 👎.

) else {
return
}
let breadcrumbs = DiagnosticsCoordinator.shared.breadcrumbsData()

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 Filter MetricKit breadcrumbs to the reporting window

MetricKit diagnostics are delivered after the incident, often on the next launch, but this snapshots every persisted breadcrumb line at delivery time. The journal can already contain relaunch startup/navigation breadcrumbs or older retained segments, so an iOS crash/hang report can upload post-incident or unrelated context; filter the journal by the MetricKit payload's periodStart/periodEnd (or otherwise freeze only incident-window breadcrumbs) before saving the artifact.

Useful? React with 👍 / 👎.

@Quick104

Copy link
Copy Markdown
Contributor Author

The four round-6 review comments landed here after this PR was squash-merged, so the fixes are in a follow-up: #98.

  • AuthService: profile invalidation moved into the profileId setter (+ ServerRegistry.switchTo/remove) so every active-profile change fails the breadcrumb/session/exit-sentinel gate closed, not just selectProfile.
  • DiagnosticsConsentStore: Never transition purges the tvOS ExitSentinel marker so an armed marker can't later surface as an abnormal-exit report.
  • ExitSentinel: preserve an unclean run's marker in a distinct leftover slot before arming the current run (survives failed capture + background/terminate); decode stays backward-compatible.
  • MetricKitCapture: breadcrumbs filtered to the payload's reporting window (with margin) so post-incident/relaunch lines don't ride along.

Full iOS suite passes; SiloTV builds. Added leftover-preservation round-trip + breadcrumb-window filter tests.

🤖 Generated with Claude Code

Quick104 added a commit that referenced this pull request Jul 22, 2026
…98)

* feat(diagnostics): Apple client diagnostics slice (iOS + tvOS)

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

* feat(diagnostics): consent prompts, pending-report review, and settings 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

* feat(debug): auto-login launch arguments for simulator E2E runs

-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

* fix(diagnostics): redact server hosts, emails, and identity key-values 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

* fix(diagnostics): address PR #96 review findings

- 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

* fix(diagnostics): address round-2 review findings on PR #96

- 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

* fix(diagnostics): address round-3 review findings on PR #96

- 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

* fix(diagnostics): address round-4 review findings on PR #96

- 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

* fix(diagnostics): address round-5 review findings on PR #96

- 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

* fix(diagnostics): address round-6 review findings on PR #96

- 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

* fix(diagnostics): address PR review feedback

* fix(diagnostics): address automated review follow-ups

* fix(diagnostics): close evidence isolation gaps

---------

Co-authored-by: Claude Fable 5 <[email protected]>
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