Skip to content

feat: add hosted diagnostics uploads - #145

Merged
Quick104 merged 14 commits into
mainfrom
t3code/plan-hosted-diagnostic-uploads
Aug 12, 2026
Merged

Quick104 merged 14 commits into
mainfrom
t3code/plan-hosted-diagnostic-uploads

Conversation

@Quick104

@Quick104 Quick104 commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • add the hosted Silo Diagnostics destination for iOS and tvOS without adding any Silo Server dependency
  • capture offline with conservative local limits, then require exact live collector capabilities and live account ownership before first upload
  • upload a frozen, hosted-only sanitized envelope with pseudonymous installation credentials and idempotent retry/status handling
  • omit account, profile, server, playback-session, hardware-route, and private identifier evidence from hosted bundles while preserving self-hosted behavior
  • retain processing/rejected evidence and persist deletion intents plus READY receipts so Delete and Turn Off remain durable across crashes and restarts
  • update settings and crash prompts with hosted consent, privacy, retention, and destination copy

Validation

  • focused hosted diagnostics API/privacy/erasure tests
  • full diagnostics and storage XCTest matrix
  • tvOS simulator build
  • independent cross-client contract review against the collector

Related changes

No production collector deployment is included in this PR.

Summary by CodeRabbit

  • New Features
    • Choose between hosted Silo Diagnostics and a self-hosted server on iOS and tvOS.
    • Upload, monitor, retry, and delete hosted diagnostic reports with persistent status tracking.
    • Added destination-specific privacy disclosures, consent options, and report messaging.
    • Hosted reports now include enhanced privacy filtering and secure credential handling.
  • Bug Fixes
    • Improved refresh reliability by preventing stale asynchronous results.
    • Consent changes now consistently remove eligible diagnostic data and report deletion failures.
    • Improved recovery from interrupted uploads, invalid reports, and connectivity failures.

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 15 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3201d891-3cfb-4a94-8eb4-9ee0a8b8e6b5

📥 Commits

Reviewing files that changed from the base of the PR and between e8e62c8 and 0df3a97.

📒 Files selected for processing (10)
  • iosApp/Tests/DiagnosticsReviewFixesTests.swift
  • iosApp/Tests/HostedDiagnosticsAPITests.swift
  • iosApp/iosApp/Networking/HostedDiagnosticsAPI.swift
  • iosApp/iosApp/Screens/Settings/DiagnosticsPromptSheet.swift
  • iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsDestination.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsPrompt.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsViewModel.swift
  • iosApp/iosApp/Shared/Diagnostics/PendingReportStore.swift
📝 Walkthrough

Walkthrough

Diagnostics 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.

Changes

Hosted diagnostics destination flow

Layer / File(s) Summary
Destination and consent contracts
iosApp/iosApp/Shared/Diagnostics/DiagnosticsDestination.swift, iosApp/iosApp/Networking/ServerRegistry.swift, iosApp/iosApp/Shared/Diagnostics/DiagnosticsConsentStore.swift
The app persists hosted or self-hosted destination selection. Active server reads use a lock-protected snapshot. Consent changes support deferred purging.
Hosted API and sanitized bundles
iosApp/iosApp/Networking/HostedDiagnosticsAPI.swift, iosApp/iosApp/Networking/DiagnosticsAPI.swift, iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift
The hosted API manages credentials, capability checks, report upload, polling, deletion, response validation, and redirect blocking. Hosted bundles sanitize logs, manifests, device data, crash data, MetricKit data, paths, and identifiers.
Hosted report persistence and deletion
iosApp/iosApp/Shared/Diagnostics/PendingReportStore.swift
Hosted reports persist envelope generations, processing states, consent refresh requirements, READY receipts, rejection codes, and deletion intents. Recovery, validation, quarantine, expiry, capacity eviction, and remote deletion retry paths are added.
Destination-aware coordinator orchestration
iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift
The coordinator separates hosted and self-hosted flows, guards refreshes and uploads with destination epochs and identity checks, freezes capture evidence, tracks upload handoff, and drains hosted deletion intents.
View model, prompts, and settings UI
iosApp/iosApp/Shared/Diagnostics/DiagnosticsViewModel.swift, iosApp/iosApp/Shared/Diagnostics/DiagnosticsPrompt.swift, iosApp/iosApp/Screens/Settings/*, iosApp/iosApp/tvOS/Screens/Settings/*, iosApp/Tests/*
The view model and settings screens support destination selection, destination-specific privacy and consent messaging, hosted upload states, asynchronous deletion, and stale-refresh protection. Tests cover destination synchronization, refresh races, context cleanup, and deferred purging.

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
Loading

Possibly related PRs

  • Silo-Server/silo-apple#96: Extends the same diagnostics coordinator, storage, networking, bundle, consent, and settings components.
  • Silo-Server/silo-apple#98: Shares diagnostics redaction and capture-gating changes in DiagnosticsBundleBuilder and DiagnosticsCoordinator.
  • Silo-Server/silo-apple#99: Shares coordinator, evidence-isolation, and diagnostics bundle privacy handling changes.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.31% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding hosted diagnostics uploads.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch t3code/plan-hosted-diagnostic-uploads

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

@Quick104
Quick104 marked this pull request as ready for review August 12, 2026 12:38

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

@cursor

cursor Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

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.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 12

🧹 Nitpick comments (14)
iosApp/iosApp/Networking/HostedDiagnosticsAPI.swift (4)

531-543: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Make expiresAt optional or remove it.

HostedCreateReportResponse.expiresAt is declared non-optional and is never read. Decoding therefore fails if the collector omits expires_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 win

Clamp the collector-advertised maxBundleBytes to the local conservative bound.

capabilities() pins collectorId, requires schema 1, and pins retentionDays to the local conservative value. It accepts any positive maxBundleBytes and maxManifestBytes.

DiagnosticsCoordinator.uploadHosted uses context.maxBundleBytes as 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 win

Consolidate the three perform variants.

perform, performAccepted, and performNoContent repeat 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 performAccepted as isAcceptable: { $0 == 202 } and performNoContent as isAcceptable: { $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 value

Remove the manual Content-Length assignment. URLSession manages this reserved header from the httpBody data, 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 win

Count sanitization-dropped log lines in the manifest.

sanitizeHostedLogJSONL drops a line when decoding fails, when validation fails, or when re-encoding fails. The count of dropped lines is discarded.

makeLogSummary then reports droppedLines: droppedLogLines, which is the capture-time count only, and lines: 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 win

Retaining archiveEntries stores hosted evidence twice on disk.

PendingReportStore.saveHostedEnvelope writes manifest.json, bundle.tar.gz, and every element of archiveEntries into an entries/ directory. The uncompressed entries are the same evidence that bundle.tar.gz already holds, and the original pending-report directory still holds the raw logs.jsonl, device.json, and crash/* 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.

reframeHosted only needs the entry list, and the entries are recoverable from bundleData by reading the tar. Consider persisting bundle.tar.gz alone 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 win

Document the ownership contract of purgeImmediately.

The default true keeps existing callers unchanged, so the change is backward compatible. However, a caller that passes false takes over responsibility for erasing local evidence after a .never selection. 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 win

Bound the background work that load starts, and isolate the shared consent store.

Two test-hygiene gaps in this case:

  1. load(profile:) calls coordinator.scheduleHostedDeletionMaintenance(), which starts an unstructured Task. The test returns and the teardown block deletes root while that task may still touch pendingStore. The task also reaches static coordinator state through its purge paths. This is a cross-test flakiness source.
  2. Unlike testOutOfOrderDestinationRefreshCannotPublishStaleState, this case injects no consentStore, so the view model and the coordinator fall back to DiagnosticsConsentStore.shared and process-wide SharedDefaults.shared. The assertions still hold today only because canManageDiagnostics(profile: nil) is false and load returns 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 stores hostedDeletionMaintenanceTask) 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 value

Replace the empty if block with a comment on the guard it explains.

Lines 1077-1082 contain an if statement 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 value

Remove 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 win

Move startup reconciliation out of init.

init performs synchronous disk work: it reads both ledger files, can rewrite hosted-ready-receipts.json, and can create the root and pending directories through ensureDirectory. PendingReportStore.shared is 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 alongside scheduleHostedDeletionMaintenance().

♻️ 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 value

Use isAwaitingHostedStatus for hosted-status polling.

Replace the polling predicates in pendingReports(for:) and performUpload(report:) with report.state.isAwaitingHostedStatus. Keep the hostedRemoteShortID == nil checks 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 value

Recompute the deletion-intent set for the final filter.

deleting is captured at line 506, before the polling loop suspends. pollHostedStatus awaits network calls, so a concurrent delete(report:) or turnOffAndDelete(binding:) can stage a new intent during that interval. The second listReports call 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 value

Clear cachedHostedCredentialIdentity with the other cached status state.

clearContext(for:) resets cachedStatus, cachedStatusDestination, cachedStatusServerRegistryID, and cachedStatusAccessTokenFingerprint, but leaves cachedHostedCredentialIdentity set. That value belongs to the same status response.

No current reader is affected, because captureContext reads it only immediately after a successful hosted refresh and uploadHosted revalidates against the live TokenStore. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 5dce823 and e8e62c8.

📒 Files selected for processing (19)
  • iosApp/Tests/ConsentStoreTests.swift
  • iosApp/Tests/DiagnosticsViewModelTests.swift
  • iosApp/Tests/HostedDiagnosticsAPITests.swift
  • iosApp/iosApp/Networking/DiagnosticsAPI.swift
  • iosApp/iosApp/Networking/HostedDiagnosticsAPI.swift
  • iosApp/iosApp/Networking/ServerRegistry.swift
  • iosApp/iosApp/Screens/Settings/DiagnosticsPromptSheet.swift
  • iosApp/iosApp/Screens/Settings/DiagnosticsSettingsView.swift
  • iosApp/iosApp/Shared/Diagnostics/Bundle/DiagnosticsBundleBuilder.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsConsentStore.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsDestination.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsPrompt.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsViewModel.swift
  • iosApp/iosApp/Shared/Diagnostics/PendingReportStore.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsConsentScreen.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsDestinationScreen.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsPromptScreen.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVDiagnosticsSettingsPane.swift

@Quick104
Quick104 merged commit 5ebee24 into main Aug 12, 2026
1 check passed
@Quick104
Quick104 deleted the t3code/plan-hosted-diagnostic-uploads branch August 12, 2026 19:58

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +176 to +177
guard mode != .always || allowsAlwaysSend else { return }
let operationGeneration = generation

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant