Repository navigation
feat(diagnostics): client diagnostics for iOS and tvOS — capture, consent, and upload - #96
Conversation
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
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe 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. ChangesDiagnostics implementation
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
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
| case .disabled, .storageUnavailable, .quotaExceeded, .tooLarge, .busy, .retryable, .underlying: | ||
| return .keptRetryable |
There was a problem hiding this comment.
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 👍 / 👎.
| do { | ||
| snapshot = try await refreshStatus() | ||
| } catch { | ||
| return nil |
There was a problem hiding this comment.
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 👍 / 👎.
| for report in pendingReports where pendingStore.canAutoUpload( | ||
| fingerprint: report.binding.fingerprint, | ||
| binding: binding | ||
| ) { |
There was a problem hiding this comment.
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 👍 / 👎.
| entries.append(RecentPlaybackSessionEntry( | ||
| sessionID: sessionID, | ||
| recordedAt: DiagnosticsTimestamp.string(from: now) |
There was a problem hiding this comment.
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 👍 / 👎.
| guard requestServerRegistryID == ServerRegistry.shared.activeServerId, | ||
| requestAccessTokenFingerprint == (await Self.currentAccessTokenFingerprint()) else { | ||
| throw DiagnosticsCoordinatorError.identityChanged |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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 winDo not skip server-wide diagnostics cleanup.
When the current-binding purge succeeds, Line 267 passes
false, soServerRegistry.signOutskipspurgeDiagnosticsForServerRegistryID. Reports and consent state for older bindings on this server can remain after sign-out. LetServerRegistryperform 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 winMove the
consentMode = .askside effect out ofmessage(for:).
message(for:)mutatesconsentMode(Line 321) as a side effect of formatting a string, andhandle(_:report:)sets the same value again (Lines 299–301) — sohandledouble-applies it whileuploadAutomaticallyEligibleReports/sendPromptsilently depend on the formatter's hidden mutation to reset consent. This coupling is easy to break during refactors. Consider centralizing thekeptStaleConsent → consentMode = .asktransition in one explicit place and keepingmessage(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 winSend/Always Send/Don't Send action block duplicated across two screens.
DiagnosticsPromptSheet.swiftandDiagnosticsPromptReviewView.swiftreimplement 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 winDuplicated Send/Always Send/Don't Send block; "Don't Send" bypasses the
isWorkingguard.See consolidated comments — nearly identical to
DiagnosticsPromptReviewView.swift, and "Don't Send" isn't gated bymodel.isWorkinglike 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 winDuplicated Send/Always Send/Don't Send block; "Don't Send" bypasses the
isWorkingguard.See consolidated comments for details — this block is near-identical to
DiagnosticsPromptSheet.swift, and the "Don't Send" button here isn't disabled whilemodel.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 winDuplicate
ReportTypetitle / expiry-date logic across the iOS and tvOS pending-report rows.Both files reimplement the same
ReportType → Stringswitch andcapturedAtDate + PendingReportStore.expiryIntervalcalculation, while the sibling tvOS screens (TVDiagnosticsPendingReportScreen.swift,TVDiagnosticsReportSummaryCard.swift) instead reuseDiagnosticsReportSummary.typeTitle/.expiresAt. Extracting this into one shared helper (e.g. onReportType/PendingReport) would keep the mapping consistent if a new report type is ever added.
iosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsSettingsPane.swift#L109-L120: replacetypeTitle(for:)/expiryDate(for:)with the shared helper.iosApp/iosApp/Screens/Settings/DiagnosticsPendingReportRow.swift#L23-L38: replaceexpiryDate/typeTitlewith 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 valueCardinality checks use hard-coded literals instead of deriving from the source collections.
categories.count <= 9and(1...8).contains(entries.count)mirrorDiagnosticsLogCategory.allCases.countandArchive.allowedEntries.countrespectively. 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_atlength isn't validated against the schema'smaxLength: 64.
device.schema.jsoncapscaptured_atat 64 characters, butvalidate()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
makeLogSummaryreaches intoDiagnosticsConsentStore.sharedglobal singleton.Every other dependency (
fileManager) is injected viainit, butdebugLoggingEnabledis pulled from a shared singleton inside a otherwise-pure builder function, makingbuild()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.
logsGzipSizeis computed by gzip-compressinglogsDatapurely to report a byte count inLogSummary, even though the same bytes get compressed again as part oftarDatamoments later (line 61) — doubling deflate work for a summary field. Separately, whenlogsDatais empty,inputBuffer.bindMemory(...).baseAddressisnil, the guard returns early without ever callingdeflate, andgzip()yields an emptyData()instead of a valid (small) gzip stream — harmless here since it only feedslogsGzipSize, but worth noting sincegzip()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 valueSwiftLint
optional_data_string_conversion: prefer the failableString(bytes:encoding:)initializer overString(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: replaceString(decoding: logsData, as: UTF8.self)(line 126) withString(bytes: logsData, encoding: .utf8)and handle thenilcase explicitly when deriving log categories.iosApp/Tests/DiagnosticsContractTests.swift#L94-L104: replaceString(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 winConsider 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
messagestrings 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
📒 Files selected for processing (77)
.gitignoreiosApp/Tests/BreadcrumbJournalTests.swiftiosApp/Tests/ConsentStoreTests.swiftiosApp/Tests/DeviceSnapshotBuilderTests.swiftiosApp/Tests/DiagnosticsBundleBuilderTests.swiftiosApp/Tests/DiagnosticsContractTests.swiftiosApp/Tests/DiagnosticsPromptPolicyTests.swiftiosApp/Tests/Fixtures/DiagnosticsContract/README.mdiosApp/Tests/Fixtures/DiagnosticsContract/attr-registry.jsoniosApp/Tests/Fixtures/DiagnosticsContract/device.schema.jsoniosApp/Tests/Fixtures/DiagnosticsContract/fixtures/invalid/archive-entry-outside-allowlist.jsoniosApp/Tests/Fixtures/DiagnosticsContract/fixtures/invalid/bad-schema-version.jsoniosApp/Tests/Fixtures/DiagnosticsContract/fixtures/invalid/missing-consent.jsoniosApp/Tests/Fixtures/DiagnosticsContract/fixtures/invalid/platform-macos-reserved.jsoniosApp/Tests/Fixtures/DiagnosticsContract/fixtures/invalid/stack-excerpt-over-8kib.jsoniosApp/Tests/Fixtures/DiagnosticsContract/fixtures/invalid/unknown-report-type.jsoniosApp/Tests/Fixtures/DiagnosticsContract/fixtures/valid/android-manual-no-profile.jsoniosApp/Tests/Fixtures/DiagnosticsContract/fixtures/valid/android-manual.jsoniosApp/Tests/Fixtures/DiagnosticsContract/fixtures/valid/android-tv-crash-ueh.jsoniosApp/Tests/Fixtures/DiagnosticsContract/fixtures/valid/device.jsoniosApp/Tests/Fixtures/DiagnosticsContract/fixtures/valid/ios-hang-metrickit.jsoniosApp/Tests/Fixtures/DiagnosticsContract/fixtures/valid/loglines.jsonliosApp/Tests/Fixtures/DiagnosticsContract/fixtures/valid/tvos-abnormal-exit.jsoniosApp/Tests/Fixtures/DiagnosticsContract/logline.schema.jsoniosApp/Tests/Fixtures/DiagnosticsContract/manifest.schema.jsoniosApp/Tests/LogRingTests.swiftiosApp/Tests/MetricKitCaptureTests.swiftiosApp/Tests/PendingReportStoreTests.swiftiosApp/iosApp/ContentView.swiftiosApp/iosApp/Navigation/AppRouter.swiftiosApp/iosApp/Networking/DiagnosticsAPI.swiftiosApp/iosApp/Networking/HTTPClient.swiftiosApp/iosApp/Networking/ServerRegistry.swiftiosApp/iosApp/Screens/Auth/AuthService.swiftiosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swiftiosApp/iosApp/Screens/Player/PlaybackSessionBridge.swiftiosApp/iosApp/Screens/Player/PlayerLog.swiftiosApp/iosApp/Screens/Settings/DiagnosticsPendingReportRow.swiftiosApp/iosApp/Screens/Settings/DiagnosticsPromptPresentationModifier.swiftiosApp/iosApp/Screens/Settings/DiagnosticsPromptReportSummaryView.swiftiosApp/iosApp/Screens/Settings/DiagnosticsPromptReviewView.swiftiosApp/iosApp/Screens/Settings/DiagnosticsPromptSheet.swiftiosApp/iosApp/Screens/Settings/DiagnosticsReportDetailView.swiftiosApp/iosApp/Screens/Settings/DiagnosticsReportSummarySections.swiftiosApp/iosApp/Screens/Settings/DiagnosticsSettingsView.swiftiosApp/iosApp/Screens/Settings/SettingsView.swiftiosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swiftiosApp/iosApp/Shared/Diagnostics/Contract/DeviceSnapshotPayload.swiftiosApp/iosApp/Shared/Diagnostics/Contract/DiagnosticsCrashInfo.swiftiosApp/iosApp/Shared/Diagnostics/Contract/DiagnosticsLogLine.swiftiosApp/iosApp/Shared/Diagnostics/Contract/DiagnosticsManifest.swiftiosApp/iosApp/Shared/Diagnostics/Contract/DiagnosticsValidation.swiftiosApp/iosApp/Shared/Diagnostics/DeviceSnapshotBuilder.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsCapabilityProbe.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsConsentStore.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsFeatureState.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsNotice.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsPrompt.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsPromptPolicy.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsReportSummary.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsViewModel.swiftiosApp/iosApp/Shared/Diagnostics/ExitSentinel.swiftiosApp/iosApp/Shared/Diagnostics/Logging/BreadcrumbJournal.swiftiosApp/iosApp/Shared/Diagnostics/Logging/DiagLog.swiftiosApp/iosApp/Shared/Diagnostics/Logging/LogRing.swiftiosApp/iosApp/Shared/Diagnostics/MetricKitCapture.swiftiosApp/iosApp/Shared/Diagnostics/PendingReportStore.swiftiosApp/iosApp/Shared/Diagnostics/RecentSessionTracker.swiftiosApp/iosApp/iOSApp.swiftiosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsConsentScreen.swiftiosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsPendingReportScreen.swiftiosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsPromptScreen.swiftiosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsReportSummaryCard.swiftiosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsSettingsPane.swiftiosApp/iosApp/tvOS/Screens/Settings/TVSettingsView.swiftiosApp/project.yml
| @@ -0,0 +1,56 @@ | |||
| #if os(iOS) | |||
There was a problem hiding this comment.
🩺 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.
-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
There was a problem hiding this comment.
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 winCancel in-flight requests before purging diagnostics
signOutnever callsHTTPClient.cancelInFlightRequests(), andremovedoes 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
📒 Files selected for processing (4)
iosApp/Tests/DiagnosticsRedactionTests.swiftiosApp/iosApp/ContentView.swiftiosApp/iosApp/Networking/ServerRegistry.swiftiosApp/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
There was a problem hiding this comment.
💡 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 { |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 👍 / 👎.
| - "Diagnostics/DiagnosticsViewModel.swift" | ||
| - "Diagnostics/ExitSentinel.swift" | ||
| - "Diagnostics/MetricKitCapture.swift" | ||
| - "Diagnostics/PendingReportStore.swift" |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 👍 / 👎.
| guard let context = await DiagnosticsCoordinator.shared.captureContext( | ||
| applicationVersionOverride: applicationVersion | ||
| ) else { |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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
|
All review findings addressed in b25015b — the P1 was real and is confirmed fixed:
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 |
There was a problem hiding this comment.
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 winPreserve identical session IDs from different bindings.
Line 45 removes an existing entry by
sessionIDalone. 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 bothsessionIDandbinding.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 winOffline/context failure is conflated with a genuine destination mismatch.
The guard on Lines 229-231 collapses two different failure modes into
.keptDestinationMismatch:
captureContextreturningnil(e.g., offline, or identity mid-change) — a transient condition.report.isUploadable(to:)returningfalse— a real, permanent-for-this-context mismatch.Returning
.keptDestinationMismatchfor the offline case surfaces a misleading message ("Report kept for the server where it was captured.") and, perDiagnosticsViewModel.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 valuePrefer failable
String(bytes:encoding:)overString(decoding:as:).
String(decoding:as:)never fails; malformed bytes are silently replaced rather than surfaced. Since this file writes the snapshot itself (vialogSnapshotArtifact), 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
📒 Files selected for processing (18)
iosApp/Tests/DiagnosticsBundleBuilderTests.swiftiosApp/Tests/DiagnosticsRedactionTests.swiftiosApp/Tests/DiagnosticsReviewFixesTests.swiftiosApp/iosApp/Networking/ServerRegistry.swiftiosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swiftiosApp/iosApp/Screens/Player/PlayerLog.swiftiosApp/iosApp/Screens/Settings/DiagnosticsPromptReviewView.swiftiosApp/iosApp/Screens/Settings/DiagnosticsPromptSheet.swiftiosApp/iosApp/Screens/Settings/DiagnosticsReportDetailView.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsSHA256.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsViewModel.swiftiosApp/iosApp/Shared/Diagnostics/ExitSentinel.swiftiosApp/iosApp/Shared/Diagnostics/Logging/BreadcrumbJournal.swiftiosApp/iosApp/Shared/Diagnostics/MetricKitCapture.swiftiosApp/iosApp/Shared/Diagnostics/PendingReportStore.swiftiosApp/iosApp/Shared/Diagnostics/RecentSessionTracker.swiftiosApp/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
There was a problem hiding this comment.
💡 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() |
There was a problem hiding this comment.
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 👍 / 👎.
| if requirePersistentCapture { | ||
| if record.mode == .never { | ||
| return nil |
There was a problem hiding this comment.
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 👍 / 👎.
| pendingStore.recordAutoUploadAttempt( | ||
| fingerprint: report.binding.fingerprint, | ||
| binding: report.binding.binding | ||
| ) |
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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 👍 / 👎.
| guard let context else { | ||
| return true |
There was a problem hiding this comment.
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 👍 / 👎.
| guard let context = await captureContext(requirePersistentCapture: false), | ||
| report.isUploadable(to: context.binding) else { | ||
| return .keptDestinationMismatch |
There was a problem hiding this comment.
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 👍 / 👎.
| let manifestDraftData = try DiagnosticsJSONCoding.makeEncoder().encode(draft) | ||
| appendEntry("manifest.json", manifestDraftData) |
There was a problem hiding this comment.
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
|
Round-2 findings addressed in 8f266a8 — six fixed, one refuted:
Refuted — embedded iOS suite 680/680 green; SiloTV and iOS builds succeed. 🤖 Generated with Claude Code |
There was a problem hiding this comment.
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 liftMake leftover capture consent- and purge-safe.
The marker is copied before
await, and capture proceeds without rechecking consent. If sign-out callsExitSentinel.shared.purge()during the await, the stale account-bound marker can still reachcaptureAbnormalExit; 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 winFail closed until consent is wired.
captureEnabledGateshould default to{ false };ExitSentinel.shared.appDidLaunch()runs beforeDiagnosticsCoordinatorinstalls 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
📒 Files selected for processing (5)
iosApp/Tests/DiagnosticsReviewFixesTests.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsViewModel.swiftiosApp/iosApp/Shared/Diagnostics/ExitSentinel.swiftiosApp/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
There was a problem hiding this comment.
💡 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".
| let boundContext = marker.binding != nil | ||
| ? context.overridingProfileID(marker.profileID) | ||
| : context |
There was a problem hiding this comment.
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 👍 / 👎.
| Self.breadcrumbConsentContext = BreadcrumbConsentContext( | ||
| binding: binding, | ||
| noticeVersion: noticeVersion | ||
| ) | ||
| Self.breadcrumbContextLock.unlock() |
There was a problem hiding this comment.
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 👍 / 👎.
| manifest.consent = DiagnosticsManifest.Consent( | ||
| mode: manifest.consent.mode, | ||
| noticeVersion: noticeVersion | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
| guard requirePersistentCapture, | ||
| let fallback = lastKnownSnapshotForActiveServer() else { | ||
| return nil |
There was a problem hiding this comment.
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)" |
There was a problem hiding this comment.
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&;,]+"#, |
There was a problem hiding this comment.
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 👍 / 👎.
| return consentStore.persistentCaptureEnabled( | ||
| for: context.binding, | ||
| currentNoticeVersion: context.noticeVersion | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
| if await activeProfileIsChild() == true { | ||
| return nil |
There was a problem hiding this comment.
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
|
Round-3 findings all addressed in 67adedc:
iOS suite 683/683; SiloTV builds. 🤖 Generated with Claude Code |
There was a problem hiding this comment.
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
📒 Files selected for processing (6)
iosApp/Tests/DiagnosticsRedactionTests.swiftiosApp/Tests/DiagnosticsReviewFixesTests.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swiftiosApp/iosApp/Shared/Diagnostics/Logging/DiagLog.swiftiosApp/iosApp/Shared/Diagnostics/MetricKitCapture.swiftiosApp/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
There was a problem hiding this comment.
💡 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".
| guard !(error is DiagnosticsCoordinatorError), | ||
| requirePersistentCapture, | ||
| let fallback = lastKnownSnapshotForActiveServer() else { |
There was a problem hiding this comment.
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 👍 / 👎.
| writeMarker(ExitSentinelMarker( | ||
| runID: DiagLog.captureSessionID, | ||
| startedAt: DiagnosticsTimestamp.string(from: now), | ||
| binding: binding, | ||
| profileID: profileID | ||
| )) |
There was a problem hiding this comment.
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 👍 / 👎.
| let response = try await api.upload( | ||
| manifestData: bundle.manifestData, | ||
| bundleData: bundle.bundleData | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
| return RuntimeIdentity( | ||
| serverRegistryID: serverRegistryID, | ||
| accessTokenFingerprint: DiagnosticsSHA256.hex(data: Data(token.utf8)), | ||
| profileID: AuthService.shared.profileId |
There was a problem hiding this comment.
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 👍 / 👎.
| await ServerRegistry.shared.signOut( | ||
| serverId: activeId, | ||
| purgeDiagnostics: !purgedDiagnostics | ||
| ) |
There was a problem hiding this comment.
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
|
Round-4 findings addressed in a209183:
iOS suite 686/686; SiloTV builds. 🤖 Generated with Claude Code |
There was a problem hiding this comment.
💡 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, |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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 👍 / 👎.
| return consentStore.persistentCaptureEnabled( | ||
| for: context.binding, | ||
| currentNoticeVersion: context.noticeVersion | ||
| ) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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
|
Round-5 review fixes (commit 5ed84ed):
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 |
There was a problem hiding this comment.
💡 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() |
There was a problem hiding this comment.
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 👍 / 👎.
| onNeverSelected: @escaping (DiagnosticsBinding) -> Void = { binding in | ||
| PendingReportStore.shared.purge(binding: binding) | ||
| DiagnosticsCoordinator.purgeBreadcrumbJournal() | ||
| } |
There was a problem hiding this comment.
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 👍 / 👎.
| writeMarker(ExitSentinelMarker( | ||
| runID: DiagLog.captureSessionID, | ||
| startedAt: DiagnosticsTimestamp.string(from: now), | ||
| binding: binding, | ||
| profileID: profileID | ||
| )) |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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 👍 / 👎.
|
The four round-6 review comments landed here after this PR was squash-merged, so the fixes are in a follow-up: #98.
Full iOS suite passes; SiloTV builds. Added leftover-preservation round-trip + breadcrumb-window filter tests. 🤖 Generated with Claude Code |
…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]>
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
DiagLogsafe-logging facade with collection-time redaction and an always-on in-memory ring; curatedcmpLogtee into the ring.DiagnosticsAPI, with vendored contract models and fixture tests.uncompressed_bytesis computed as the full tar stream, matching the contract semantics clarified in the server PR.Consent and UX (disabled by default)
DiagnosticsPromptPolicy).Verification
SiloTestssuite on iPhone 17 Pro simulator: 661 tests, 0 failures, including the diagnostics contract fixture tests, bundle builder, consent store, breadcrumb journal, and prompt policy suites.SiloTVscheme compiles for tvOS simulator.Risks / follow-ups
AI-use disclosure: implemented and verified with Claude Code.
🤖 Generated with Claude Code
https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
Summary by CodeRabbit
New Features
Improvements
Chores