Repository navigation
feat: add hosted diagnostics uploads - #145
Conversation
|
Warning Review limit reachedYou’ve reached a temporary PR review limit under our Fair Usage Limits Policy. Next review available in: 15 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (10)
📝 WalkthroughWalkthroughDiagnostics now supports hosted and self-hosted destinations across capture, consent, storage, upload, deletion, refresh, privacy filtering, and iOS/tvOS settings. Hosted reports use protected credentials, sanitized envelopes, durable lifecycle records, and destination-scoped asynchronous state. ChangesHosted diagnostics destination flow
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant SettingsView
participant DiagnosticsViewModel
participant DiagnosticsCoordinator
participant PendingReportStore
participant HostedDiagnosticsAPI
SettingsView->>DiagnosticsViewModel: select hosted destination
DiagnosticsViewModel->>DiagnosticsCoordinator: refresh hosted status
DiagnosticsCoordinator->>HostedDiagnosticsAPI: fetch capabilities and account status
DiagnosticsCoordinator->>PendingReportStore: load destination-scoped reports
DiagnosticsViewModel->>DiagnosticsCoordinator: create or upload report
DiagnosticsCoordinator->>HostedDiagnosticsAPI: register, create, and upload report
HostedDiagnosticsAPI-->>DiagnosticsCoordinator: processing or ready state
DiagnosticsCoordinator->>PendingReportStore: persist hosted state
DiagnosticsViewModel-->>SettingsView: display destination-specific status
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 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: 305bc4261e
ℹ️ 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".
|
Bugbot is not enabled for your account, so this pull request was not reviewed. Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ecc8667511
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e8e62c8238
ℹ️ 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".
There was a problem hiding this comment.
Actionable comments posted: 12
🧹 Nitpick comments (14)
iosApp/iosApp/Networking/HostedDiagnosticsAPI.swift (4)
531-543: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winMake
expiresAtoptional or remove it.
HostedCreateReportResponse.expiresAtis declared non-optional and is never read. Decoding therefore fails if the collector omitsexpires_at, and the create step fails for a field this client ignores. That couples the upload path to an unused part of the contract.Declare it as
String?, or remove the property.♻️ Proposed change
private struct HostedCreateReportResponse: Decodable { let reportID: String let shortID: String let uploadToken: String - let expiresAt: String + let expiresAt: String?🤖 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/HostedDiagnosticsAPI.swift` around lines 531 - 543, Update HostedCreateReportResponse.expiresAt to be optional, or remove the unused property and its CodingKeys entry, so decoding succeeds when expires_at is omitted while preserving the existing create-report response handling.
165-179: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winClamp the collector-advertised
maxBundleBytesto the local conservative bound.
capabilities()pinscollectorId, requires schema 1, and pinsretentionDaysto the local conservative value. It accepts any positivemaxBundleBytesandmaxManifestBytes.
DiagnosticsCoordinator.uploadHostedusescontext.maxBundleBytesas the only size gate before the bundle leaves the device. A collector response that advertises a very large limit therefore raises the volume of evidence this client will upload, with no local ceiling. The other privacy-relevant fields already fail closed against local constants, so this field is the outlier.Bound the accepted values by
conservativeCaptureStatus.🛡️ Proposed fix
guard response.collectorId == HostedDiagnosticsCapabilities.pinnedCollectorID, response.acceptedSchemaVersions.contains(1), response.maxBundleBytes > 0, + response.maxBundleBytes <= HostedDiagnosticsCapabilities.conservativeCaptureStatus.maxBundleBytes ?? .max, response.maxManifestBytes > 0, + response.maxManifestBytes <= HostedDiagnosticsCapabilities.conservativeCaptureStatus.maxManifestBytes ?? .max, response.retentionDays == HostedDiagnosticsCapabilities.conservativeCaptureStatus.retentionDays, response.consentNoticeVersion > 0 else { throw HostedDiagnosticsAPIError.collectorIdentityMismatch }Adjust the optional handling to match the actual optionality of those fields on
DiagnosticsStatusResponse.🤖 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/HostedDiagnosticsAPI.swift` around lines 165 - 179, Update the validation in HostedDiagnosticsAPI.capabilities() so the collector-advertised maxBundleBytes cannot exceed HostedDiagnosticsCapabilities.conservativeCaptureStatus.maxBundleBytes, while still requiring it to be positive. Preserve the existing collector identity, schema, retention, and maxManifestBytes checks, and handle the field according to its optionality in DiagnosticsStatusResponse.
401-476: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsolidate the three
performvariants.
perform,performAccepted, andperformNoContentrepeat the same 25-line shape. Only the accepted status-code check and the decode step differ. One private helper that returns the validated(Data, HTTPURLResponse)pair removes about 50 duplicated lines and keeps the error mapping in one place.♻️ Proposed refactor
+ private func performValidated( + _ request: URLRequest, + isAcceptable: (Int) -> Bool + ) async throws -> Data { + do { + let (data, response) = try await session.data(for: request) + guard let httpResponse = response as? HTTPURLResponse else { + throw HostedDiagnosticsAPIError.invalidResponse + } + guard isAcceptable(httpResponse.statusCode) else { + let envelope = try? DiagnosticsJSONCoding.makeDecoder().decode( + HostedErrorEnvelope.self, + from: data + ) + throw HostedDiagnosticsAPIError.http( + statusCode: httpResponse.statusCode, + code: envelope?.error + ) + } + return data + } catch let error as HostedDiagnosticsAPIError { + throw error + } catch { + throw HostedDiagnosticsAPIError.underlying(String(describing: error)) + } + } + private func perform<Response: Decodable>( _ request: URLRequest, as type: Response.Type ) async throws -> Response { - do { - let (data, response) = try await session.data(for: request) - guard let httpResponse = response as? HTTPURLResponse else { - throw HostedDiagnosticsAPIError.invalidResponse - } - guard (200...299).contains(httpResponse.statusCode) else { - let envelope = try? DiagnosticsJSONCoding.makeDecoder().decode( - HostedErrorEnvelope.self, - from: data - ) - throw HostedDiagnosticsAPIError.http( - statusCode: httpResponse.statusCode, - code: envelope?.error - ) - } - return try DiagnosticsJSONCoding.makeDecoder().decode(type, from: data) - } catch let error as HostedDiagnosticsAPIError { - throw error - } catch { - throw HostedDiagnosticsAPIError.underlying(String(describing: error)) - } + let data = try await performValidated(request) { (200...299).contains($0) } + do { + return try DiagnosticsJSONCoding.makeDecoder().decode(type, from: data) + } catch { + throw HostedDiagnosticsAPIError.underlying(String(describing: error)) + } }Then express
performAcceptedasisAcceptable: { $0 == 202 }andperformNoContentasisAcceptable: { $0 == 204 }with the result discarded.🤖 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/HostedDiagnosticsAPI.swift` around lines 401 - 476, Consolidate the duplicated request validation and error mapping from perform, performAccepted, and performNoContent into one private helper that returns the validated Data and HTTPURLResponse. Parameterize the helper with an isAcceptable status-code closure, then have perform decode its response, performAccepted use { $0 == 202 }, and performNoContent use { $0 == 204 } while discarding the returned data.
286-286: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the manual
Content-Lengthassignment.URLSessionmanages this reserved header from thehttpBodydata, so the assignment is redundant and may be ignored or overwritten.🤖 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/HostedDiagnosticsAPI.swift` at line 286, Remove the manual Content-Length header assignment from the upload request setup. Let URLSession derive the header from the request’s httpBody while preserving the rest of the upload configuration.iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift (2)
259-298: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCount sanitization-dropped log lines in the manifest.
sanitizeHostedLogJSONLdrops a line when decoding fails, when validation fails, or when re-encoding fails. The count of dropped lines is discarded.
makeLogSummarythen reportsdroppedLines: droppedLogLines, which is the capture-time count only, andlines:counts the surviving lines. The manifest therefore understates how much evidence the hosted path removed, and a systematic sanitization failure is invisible to both the collector and the user.Return the omitted count and add it to
droppedLines.🤖 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 259 - 298, The sanitizeHostedLogJSONL flow should return both the sanitized Data and the number of input lines omitted due to decode, validation, or encode failures. Update its caller, including makeLogSummary, to add this sanitization count to the existing capture-time droppedLogLines value while retaining lines as the surviving-line count.
9-11: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winRetaining
archiveEntriesstores hosted evidence twice on disk.
PendingReportStore.saveHostedEnvelopewritesmanifest.json,bundle.tar.gz, and every element ofarchiveEntriesinto anentries/directory. The uncompressed entries are the same evidence thatbundle.tar.gzalready holds, and the original pending-report directory still holds the rawlogs.jsonl,device.json, andcrash/*files. A hosted report therefore occupies roughly three copies of its evidence until the upload completes.With a bundle bound at 10 MiB compressed, the uncompressed
entries/copy can be substantially larger than the archive itself.
reframeHostedonly needs the entry list, and the entries are recoverable frombundleDataby reading the tar. Consider persistingbundle.tar.gzalone and extracting entries on the reframe path, which is rare.🤖 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 9 - 11, The hosted pending-report persistence flow should stop storing the redundant archiveEntries payload alongside bundle.tar.gz. Update PendingReportStore.saveHostedEnvelope and the hosted reframeHosted path to persist only the compressed bundle and recover the entry list by extracting bundleData from the tar when reframing, while preserving the existing reframing behavior.iosApp/iosApp/Shared/Diagnostics/DiagnosticsConsentStore.swift (1)
126-147: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDocument the ownership contract of
purgeImmediately.The default
truekeeps existing callers unchanged, so the change is backward compatible. However, a caller that passesfalsetakes over responsibility for erasing local evidence after a.neverselection. If that caller fails or returns early, pending reports, breadcrumbs, and the log ring survive a user-visible "Never" choice.Add a doc comment that states this contract so a future caller does not disable the purge without staging its own deletion.
📝 Proposed doc comment
+ /// Persists `mode` for `binding`. + /// + /// If `purgeImmediately` is `false`, this method does not run the + /// `.never` cleanup callback. The caller must then erase local evidence + /// itself (for example by staging a durable hosted deletion intent). func setMode( _ mode: DiagnosticsConsentChoice, for binding: DiagnosticsBinding, noticeVersion: Int, now: Date = Date(), purgeImmediately: Bool = true ) {🤖 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/DiagnosticsConsentStore.swift` around lines 126 - 147, Add a documentation comment immediately before DiagnosticsConsentStore.setMode describing purgeImmediately: it defaults to true and triggers local evidence deletion for .never selections; callers passing false assume responsibility for purging pending reports, breadcrumbs, and the log ring, including handling early returns or failures.iosApp/Tests/DiagnosticsViewModelTests.swift (1)
21-53: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winBound the background work that
loadstarts, and isolate the shared consent store.Two test-hygiene gaps in this case:
load(profile:)callscoordinator.scheduleHostedDeletionMaintenance(), which starts an unstructuredTask. The test returns and the teardown block deletesrootwhile that task may still touchpendingStore. The task also reaches static coordinator state through its purge paths. This is a cross-test flakiness source.- Unlike
testOutOfOrderDestinationRefreshCannotPublishStaleState, this case injects noconsentStore, so the view model and the coordinator fall back toDiagnosticsConsentStore.sharedand process-wideSharedDefaults.shared. The assertions still hold today only becausecanManageDiagnostics(profile: nil)is false andloadreturns before any consent read. That is an implicit dependency on unrelated behavior.Also add the
installBreadcrumbConsentContextForTests(nil)reset that the sibling test uses.🧪 Proposed changes
let pendingStore = PendingReportStore(rootDirectory: root) + let consentStore = DiagnosticsConsentStore( + defaults: defaults, + onNeverSelected: { _ in } + ) let coordinator = DiagnosticsCoordinator( + consentStore: consentStore, destinationStore: destinationStore, pendingStore: pendingStore ) let model = DiagnosticsViewModel( coordinator: coordinator, + consentStore: consentStore, pendingStore: pendingStore, destinationStore: destinationStore ) + defer { DiagnosticsCoordinator.installBreadcrumbConsentContextForTests(nil) }For the maintenance task, expose a test-visible completion hook on
DiagnosticsCoordinator(the coordinator already storeshostedDeletionMaintenanceTask) and await it before the test returns.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@iosApp/Tests/DiagnosticsViewModelTests.swift` around lines 21 - 53, Update testLoadSynchronizesDestinationChangedByAnotherViewModel to inject an isolated consent store instead of relying on DiagnosticsConsentStore.shared and SharedDefaults.shared, and reset the breadcrumb consent context with installBreadcrumbConsentContextForTests(nil) as the sibling test does. Use the test-visible completion hook for DiagnosticsCoordinator.hostedDeletionMaintenanceTask and await it before teardown, ensuring the unstructured maintenance task has finished before the temporary root is removed.iosApp/iosApp/Shared/Diagnostics/PendingReportStore.swift (4)
1076-1082: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReplace the empty
ifblock with a comment on the guard it explains.Lines 1077-1082 contain an
ifstatement whose body holds only comments. The control flow does nothing. The behavior it describes is implemented by the guard at lines 1096-1099.♻️ Proposed cleanup
let hostedErasureStateIsReadable = (try? loadHostedErasureLedgersLocked()) != nil - if !hostedErasureStateIsReadable { - // Without trustworthy erasure state an unreadable directory could - // be the only surviving copy of a report already marked READY or - // deleting. Preserve every hosted directory; self-hosted expiry - // remains independent of this collector-local state. - } + // Without trustworthy erasure state an unreadable directory could be the + // only surviving copy of a report already marked READY or deleting. + // Preserve every hosted directory below; self-hosted expiry remains + // independent of this collector-local state.🤖 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/PendingReportStore.swift` around lines 1076 - 1082, Remove the empty if !hostedErasureStateIsReadable block and move its explanatory comment directly above the guard that preserves hosted directories (the guard around lines 1096-1099). Keep the existing hosted erasure readability computation and guard behavior unchanged.
576-597: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the redundant hosted destination check.
Line 576 already returns unless
binding.destinationChoice == .hosted. The condition at line 589 is therefore always true, so the nested block adds no behavior and hides that fact from the reader.♻️ Proposed simplification
- if binding.destinationChoice == .hosted { - for (reportID, receipt) in erasureState.readyReceipts - where receipt.binding == binding { - intents[reportID] = DiagnosticsTimestamp.string(from: now) - } - for reportID in additionalRemoteReportIDs { - intents[reportID.uuidString.lowercased()] = DiagnosticsTimestamp.string(from: now) - } - } + for (reportID, receipt) in erasureState.readyReceipts where receipt.binding == binding { + intents[reportID] = DiagnosticsTimestamp.string(from: now) + } + for reportID in additionalRemoteReportIDs { + intents[reportID.uuidString.lowercased()] = DiagnosticsTimestamp.string(from: now) + }🤖 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/PendingReportStore.swift` around lines 576 - 597, Remove the redundant `if binding.destinationChoice == .hosted` wrapper in the erasure-intent update flow, since the earlier guard already enforces hosted destinations. Keep the `readyReceipts` and `additionalRemoteReportIDs` loops executing directly after the report-intent loop.
320-334: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winMove startup reconciliation out of
init.
initperforms synchronous disk work: it reads both ledger files, can rewritehosted-ready-receipts.json, and can create the root andpendingdirectories throughensureDirectory.PendingReportStore.sharedis constructed lazily on first access, which can be the main thread during launch or during a settings screen presentation. Construction then blocks on file I/O and creates directories even when no diagnostics evidence exists.Prefer an explicit
reconcileHostedReadyReceipts()entry point that the coordinator calls from its existing asynchronous maintenance path, for example alongsidescheduleHostedDeletionMaintenance().♻️ Proposed shape
init( rootDirectory: URL? = nil, fileManager: FileManager = .default, hostedDeletionRemover: ((URL) throws -> Void)? = nil ) { self.fileManager = fileManager self.hostedDeletionRemover = hostedDeletionRemover ?? { url in try fileManager.removeItem(at: url) } self.rootDirectory = rootDirectory ?? DiagnosticsStorageRoot.baseDirectory(fileManager: fileManager) .appendingPathComponent("Diagnostics", isDirectory: true) - lock.lock() - try? reconcileHostedReadyReceiptsLocked(now: Date()) - lock.unlock() } + + /// Finishes an interrupted READY removal. Call this off the launch path. + func reconcileHostedReadyReceipts(now: Date = Date()) { + lock.lock() + defer { lock.unlock() } + try? reconcileHostedReadyReceiptsLocked(now: now) + }🤖 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/PendingReportStore.swift` around lines 320 - 334, Move the synchronous reconcileHostedReadyReceiptsLocked call out of PendingReportStore.init so initialization only assigns dependencies and paths without disk I/O or directory creation. Add an explicit reconcileHostedReadyReceipts() entry point that acquires the lock and performs reconciliation, then invoke it from the coordinator’s existing asynchronous maintenance flow alongside scheduleHostedDeletionMaintenance().
107-115: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse
isAwaitingHostedStatusfor hosted-status polling.Replace the polling predicates in
pendingReports(for:)andperformUpload(report:)withreport.state.isAwaitingHostedStatus. Keep thehostedRemoteShortID == nilchecks in the upload-fence path.🤖 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/PendingReportStore.swift` around lines 107 - 115, Update pendingReports(for:) and performUpload(report:) to use report.state.isAwaitingHostedStatus for hosted-status polling decisions. Preserve the existing hostedRemoteShortID == nil checks in the upload-fence path.iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift (2)
512-528: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low valueRecompute the deletion-intent set for the final filter.
deletingis captured at line 506, before the polling loop suspends.pollHostedStatusawaits network calls, so a concurrentdelete(report:)orturnOffAndDelete(binding:)can stage a new intent during that interval. The secondlistReportscall at line 525 then filters against the stale set and can present a report that is already staged for remote deletion and whose local removal failed.Re-read the intents after the loop.
♻️ Proposed change
+ let deletingAfterPolling: Set<UUID> + if binding.destinationChoice == .hosted { + guard let refreshed = try? pendingStore.hostedDeletionIntents() else { return [] } + deletingAfterPolling = Set(refreshed) + } else { + deletingAfterPolling = [] + } return pendingStore.listReports(for: binding, now: Date()).filter { - !deleting.contains($0.id) + !deletingAfterPolling.contains($0.id) }🤖 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 512 - 528, Recompute the deletion-intent set after the asynchronous polling loop and use that refreshed set for the final listReports filter. Keep the initial deleting snapshot for the pre-loop reports selection, but ensure reports staged by concurrent delete(report:) or turnOffAndDelete(binding:) during pollHostedStatus are excluded from the returned results.
1740-1746: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueClear
cachedHostedCredentialIdentitywith the other cached status state.
clearContext(for:)resetscachedStatus,cachedStatusDestination,cachedStatusServerRegistryID, andcachedStatusAccessTokenFingerprint, but leavescachedHostedCredentialIdentityset. That value belongs to the same status response.No current reader is affected, because
captureContextreads it only immediately after a successful hosted refresh anduploadHostedrevalidates against the liveTokenStore. Clear it anyway so the cached-status fields stay consistent as a group.♻️ Proposed change
if cachedStatus?.binding == binding { cachedStatus = nil cachedStatusDestination = nil cachedStatusServerRegistryID = nil cachedStatusAccessTokenFingerprint = nil + cachedHostedCredentialIdentity = nil }🤖 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 1740 - 1746, Update clearContext(for:) to also set cachedHostedCredentialIdentity to nil when cachedStatus matches the binding, keeping it synchronized with the other cached status fields.
🤖 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/HostedDiagnosticsAPI.swift`:
- Around line 201-214: Set the metadata request timeout to 10 seconds, matching
capabilities() and deleteReport. Apply this override to the request in
reportStatus, the in-upload status refresh, and registerInstallation, while
leaving the bundle PUT timeout unchanged.
In `@iosApp/iosApp/Screens/Settings/DiagnosticsPromptSheet.swift`:
- Around line 33-50: Reset showAlwaysConfirmation when model.allowsAlwaysSend
becomes false, using a change-observation mechanism on the surrounding
DiagnosticsPromptSheet view rather than relying on the conditional button’s
removal. Preserve the existing confirmation dialog and sendPrompt(always:)
behavior, and ensure the stale presentation state is cleared before the Always
option can reappear.
In `@iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift`:
- Around line 565-571: Restrict the whole-assignment sanitization in
sanitizeHostedTextualIdentifiers and its
sanitizeHostedPrivateIdentifierAssignments/sanitizeHostedNetworkIdentityAssignments
flow to non-JSON entries only. Preserve the structural JSON sanitizers for
manifest.json, device.json, logs.jsonl, crash/summary.json,
crash/metrickit.json, and breadcrumbs.jsonl, ensuring no JSON key or structural
character is removed.
- Around line 495-499: Update sanitizeHostedMessage to apply
redactHostedAbsolutePaths to each field value, alongside the existing
sanitizeHostedContainerText and sanitizeHostedBarePrivateIdentifiers calls.
Preserve the current scalar-field and JSON-value sanitization flow, and adjust
affected privacy-test expectations if double redaction through
sanitizeHostedCrashText changes outputs.
- Around line 573-597: Remove the force unwrap when converting match.range in
templateHostedURLPaths to a String range; use guarded optional binding and
continue to the next match when conversion fails. Preserve the existing
replacement behavior for valid ranges while ensuring malformed grapheme-boundary
matches are skipped without trapping.
In `@iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift`:
- Around line 1060-1063: The remote READY result must remain authoritative
despite local bookkeeping failures. In DiagnosticsCoordinator.swift at lines
1060-1063 within uploadHosted, change the recordHostedReadyAndDelete(report)
call to ignore local errors so .uploaded(response) is returned after confirmed
creation; apply the same change in the .ready branch of pollHostedStatus at
lines 1117-1118 after confirmed status.
- Around line 1847-1858: Update the HostedDiagnosticsAPIError classification
branch in DiagnosticsCoordinator so the .http statusCode case treats HTTP 429 as
transient alongside the existing 500...599 range. Keep all other status-code and
hosted error classifications unchanged, matching hostedHTTPFailureDisposition.
- Around line 649-652: Resolve the SwiftLint optional_data_string_conversion
warning in the snapshot parsing flow by either using a failable String
initializer and falling back to the ring snapshot when decoding fails, or
retaining String(decoding:as:) with a line-level SwiftLint exemption that
documents why lossy decoding is acceptable. Keep the existing line splitting and
mapping behavior for successfully decoded snapshot data.
In `@iosApp/iosApp/Shared/Diagnostics/DiagnosticsDestination.swift`:
- Around line 56-58: Update DiagnosticsBinding creation and destination
selection around destinationChoice so self-hosted bindings cannot accept
serverInstanceID values beginning with Self.hostedPrefix. Validate and reject
the reserved hosted: prefix when constructing the self-hosted binding, while
preserving hosted classification for genuine hosted bindings; alternatively,
store the binding destination explicitly and have
DiagnosticsCoordinator.refreshStatus use it instead of inferring from
serverInstanceID.
In `@iosApp/iosApp/Shared/Diagnostics/DiagnosticsPrompt.swift`:
- Around line 15-17: Update the recipient text in the reports
destination-selection expression to use the product name “Silo Diagnostics”
consistently, replacing the lowercase “diagnostics” wording while preserving the
existing hosted/server administrator branching.
In `@iosApp/iosApp/Shared/Diagnostics/DiagnosticsViewModel.swift`:
- Around line 209-226: The destination-change invalidation in
DiagnosticsViewModel.setDestination must reset consentMode to .ask alongside
statusSnapshot, pendingReports, and sentHistory, matching
synchronizeSelectedDestination. In
iosApp/iosApp/Shared/Diagnostics/DiagnosticsViewModel.swift lines 209-226, add
this reset; iosApp/iosApp/Screens/Settings/DiagnosticsSettingsView.swift lines
62-78 requires no direct change. Confirm the settings row displays “Ask” while
the destination-scoped refresh is loading, including the tvOS modeTitle path.
In `@iosApp/iosApp/Shared/Diagnostics/PendingReportStore.swift`:
- Around line 1100-1105: Update the hosted branch in cleanupExpiredLocked to
catch and suppress failures from stageHostedDeletionAndDeleteLocked, matching
enforceCapLocked’s existing handling so one expired hosted report cannot abort
save(_:) or prevent unrelated captures from being persisted. Preserve durable
retry behavior through prepareHostedDeletionRetries.
---
Nitpick comments:
In `@iosApp/iosApp/Networking/HostedDiagnosticsAPI.swift`:
- Around line 531-543: Update HostedCreateReportResponse.expiresAt to be
optional, or remove the unused property and its CodingKeys entry, so decoding
succeeds when expires_at is omitted while preserving the existing create-report
response handling.
- Around line 165-179: Update the validation in
HostedDiagnosticsAPI.capabilities() so the collector-advertised maxBundleBytes
cannot exceed
HostedDiagnosticsCapabilities.conservativeCaptureStatus.maxBundleBytes, while
still requiring it to be positive. Preserve the existing collector identity,
schema, retention, and maxManifestBytes checks, and handle the field according
to its optionality in DiagnosticsStatusResponse.
- Around line 401-476: Consolidate the duplicated request validation and error
mapping from perform, performAccepted, and performNoContent into one private
helper that returns the validated Data and HTTPURLResponse. Parameterize the
helper with an isAcceptable status-code closure, then have perform decode its
response, performAccepted use { $0 == 202 }, and performNoContent use { $0 ==
204 } while discarding the returned data.
- Line 286: Remove the manual Content-Length header assignment from the upload
request setup. Let URLSession derive the header from the request’s httpBody
while preserving the rest of the upload configuration.
In `@iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift`:
- Around line 259-298: The sanitizeHostedLogJSONL flow should return both the
sanitized Data and the number of input lines omitted due to decode, validation,
or encode failures. Update its caller, including makeLogSummary, to add this
sanitization count to the existing capture-time droppedLogLines value while
retaining lines as the surviving-line count.
- Around line 9-11: The hosted pending-report persistence flow should stop
storing the redundant archiveEntries payload alongside bundle.tar.gz. Update
PendingReportStore.saveHostedEnvelope and the hosted reframeHosted path to
persist only the compressed bundle and recover the entry list by extracting
bundleData from the tar when reframing, while preserving the existing reframing
behavior.
In `@iosApp/iosApp/Shared/Diagnostics/DiagnosticsConsentStore.swift`:
- Around line 126-147: Add a documentation comment immediately before
DiagnosticsConsentStore.setMode describing purgeImmediately: it defaults to true
and triggers local evidence deletion for .never selections; callers passing
false assume responsibility for purging pending reports, breadcrumbs, and the
log ring, including handling early returns or failures.
In `@iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift`:
- Around line 512-528: Recompute the deletion-intent set after the asynchronous
polling loop and use that refreshed set for the final listReports filter. Keep
the initial deleting snapshot for the pre-loop reports selection, but ensure
reports staged by concurrent delete(report:) or turnOffAndDelete(binding:)
during pollHostedStatus are excluded from the returned results.
- Around line 1740-1746: Update clearContext(for:) to also set
cachedHostedCredentialIdentity to nil when cachedStatus matches the binding,
keeping it synchronized with the other cached status fields.
In `@iosApp/iosApp/Shared/Diagnostics/PendingReportStore.swift`:
- Around line 1076-1082: Remove the empty if !hostedErasureStateIsReadable block
and move its explanatory comment directly above the guard that preserves hosted
directories (the guard around lines 1096-1099). Keep the existing hosted erasure
readability computation and guard behavior unchanged.
- Around line 576-597: Remove the redundant `if binding.destinationChoice ==
.hosted` wrapper in the erasure-intent update flow, since the earlier guard
already enforces hosted destinations. Keep the `readyReceipts` and
`additionalRemoteReportIDs` loops executing directly after the report-intent
loop.
- Around line 320-334: Move the synchronous reconcileHostedReadyReceiptsLocked
call out of PendingReportStore.init so initialization only assigns dependencies
and paths without disk I/O or directory creation. Add an explicit
reconcileHostedReadyReceipts() entry point that acquires the lock and performs
reconciliation, then invoke it from the coordinator’s existing asynchronous
maintenance flow alongside scheduleHostedDeletionMaintenance().
- Around line 107-115: Update pendingReports(for:) and performUpload(report:) to
use report.state.isAwaitingHostedStatus for hosted-status polling decisions.
Preserve the existing hostedRemoteShortID == nil checks in the upload-fence
path.
In `@iosApp/Tests/DiagnosticsViewModelTests.swift`:
- Around line 21-53: Update
testLoadSynchronizesDestinationChangedByAnotherViewModel to inject an isolated
consent store instead of relying on DiagnosticsConsentStore.shared and
SharedDefaults.shared, and reset the breadcrumb consent context with
installBreadcrumbConsentContextForTests(nil) as the sibling test does. Use the
test-visible completion hook for
DiagnosticsCoordinator.hostedDeletionMaintenanceTask and await it before
teardown, ensuring the unstructured maintenance task has finished before the
temporary root is removed.
🪄 Autofix
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: 215c617d-dd55-46a9-8871-914cf7dc3eb5
📒 Files selected for processing (19)
iosApp/Tests/ConsentStoreTests.swiftiosApp/Tests/DiagnosticsViewModelTests.swiftiosApp/Tests/HostedDiagnosticsAPITests.swiftiosApp/iosApp/Networking/DiagnosticsAPI.swiftiosApp/iosApp/Networking/HostedDiagnosticsAPI.swiftiosApp/iosApp/Networking/ServerRegistry.swiftiosApp/iosApp/Screens/Settings/DiagnosticsPromptSheet.swiftiosApp/iosApp/Screens/Settings/DiagnosticsSettingsView.swiftiosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsConsentStore.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsDestination.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsPrompt.swiftiosApp/iosApp/Shared/Diagnostics/DiagnosticsViewModel.swiftiosApp/iosApp/Shared/Diagnostics/PendingReportStore.swiftiosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsConsentScreen.swiftiosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsDestinationScreen.swiftiosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsPromptScreen.swiftiosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsSettingsPane.swift
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0df3a97232
ℹ️ 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 mode != .always || allowsAlwaysSend else { return } | ||
| let operationGeneration = generation |
There was a problem hiding this comment.
Recheck the destination before auto-uploading in Always mode
This guard validates allowsAlwaysSend only before reloadLocalState suspends. On iOS, if the user confirms Always for the self-hosted destination and switches the still-enabled destination picker to Hosted while that reload is awaiting report polling, the destination refresh can populate pendingReports with hosted reports; after the stale reload returns, the subsequent Always branch iterates that new list and uploads those reports automatically, despite hosted diagnostics explicitly disallowing automatic sends. Recheck the captured generation/binding before starting the auto-upload.
Useful? React with 👍 / 👎.
Summary
Silo Diagnosticsdestination for iOS and tvOS without adding any Silo Server dependencyValidation
Related changes
No production collector deployment is included in this PR.
Summary by CodeRabbit