Crossmate/Views/Settings/DiagnosticsView.swift (15013B)
1import CloudKit
2import LinkPresentation
3import SwiftUI
4import UIKit
5import UniformTypeIdentifiers
6
7private enum TimestampTimeZone {
8 case local
9 case utc
10}
11
12private enum TimestampFormatter {
13 private static let localFormatter: DateFormatter = {
14 let formatter = DateFormatter()
15 formatter.dateStyle = .none
16 formatter.timeStyle = .medium
17 return formatter
18 }()
19
20 private static let utcFormatter: DateFormatter = {
21 let formatter = DateFormatter()
22 formatter.dateStyle = .none
23 formatter.timeStyle = .medium
24 formatter.dateFormat = "h:mm:ss a 'UTC'"
25 formatter.timeZone = TimeZone(secondsFromGMT: 0)
26 return formatter
27 }()
28
29 static func string(from date: Date, in timeZone: TimestampTimeZone) -> String {
30 switch timeZone {
31 case .local:
32 return localFormatter.string(from: date)
33 case .utc:
34 return utcFormatter.string(from: date)
35 }
36 }
37}
38
39struct DiagnosticsView: View {
40 @Environment(\.syncEngine) private var syncEngine
41 @Environment(SyncMonitor.self) private var syncMonitor
42 @Environment(EventLog.self) private var eventLog
43
44 @State private var isSyncing = false
45 @State private var isAuditingStorage = false
46
47
48
49
50 private let visibleEventLimit = 50
51
52 var body: some View {
53 List {
54 Section("Status") {
55 row("Version", versionText)
56 row("Account Status", accountStatusText)
57 row("Engine Running", boolText(syncMonitor.snapshot?.engineRunning))
58 row("Pending Changes", syncMonitor.snapshot.map { String($0.pendingChangesCount) } ?? "Unknown")
59 row("Sharing Health", sharingHealthText)
60 row(
61 "Last Success",
62 syncMonitor.lastSuccessAt.map { TimestampFormatter.string(from: $0, in: .local) } ?? "None"
63 )
64 row("Last Error Phase", syncMonitor.lastErrorPhase ?? "None")
65 row("Last Error Domain", syncMonitor.lastErrorDomain ?? "None")
66 row(
67 "Last Error Code",
68 syncMonitor.lastErrorCode.map(String.init) ?? "None"
69 )
70 row("Last Error Description", syncMonitor.lastErrorDescription ?? "None")
71 }
72
73 Section("Actions") {
74 Button {
75 Task { await runFullSync() }
76 } label: {
77 HStack {
78 Text("Sync Now")
79 if isSyncing {
80 Spacer()
81 ProgressView()
82 }
83 }
84 }
85 .disabled(isSyncing || isAuditingStorage)
86
87 Button("Probe Container") {
88 Task { await probeContainer() }
89 }
90 .disabled(isSyncing || isAuditingStorage)
91
92 Button {
93 Task { await auditCloudStorage() }
94 } label: {
95 HStack {
96 Text("Audit Cloud Storage")
97 if isAuditingStorage {
98 Spacer()
99 ProgressView()
100 }
101 }
102 }
103 .disabled(isSyncing || isAuditingStorage)
104
105 Button("Reset Sync State", role: .destructive) {
106 Task { await resetSyncState() }
107 }
108 .disabled(isSyncing || isAuditingStorage)
109 }
110
111 Section {
112 if eventLog.entries.isEmpty {
113 Text("No events captured yet.")
114 .foregroundStyle(.secondary)
115 } else {
116 ForEach(eventLog.entries.suffix(visibleEventLimit).reversed()) { entry in
117 VStack(alignment: .leading, spacing: 4) {
118 Text(
119 "\(TimestampFormatter.string(from: entry.timestamp, in: .local)) [\(entry.level.uppercased())]"
120 )
121 .font(.caption.monospaced())
122 .foregroundStyle(.secondary)
123
124 Text(entry.message)
125 .font(.caption.monospaced())
126 .textSelection(.enabled)
127 }
128 .padding(.vertical, 2)
129 }
130 }
131 } header: {
132 Text("Recent Events")
133 } footer: {
134 if eventLog.entries.count > visibleEventLimit {
135 Text("Showing the last \(visibleEventLimit) of \(eventLog.entries.count) events. Share Full Log includes the complete history.")
136 }
137 }
138 }
139 .navigationTitle("Diagnostics Log")
140 .navigationBarTitleDisplayMode(.inline)
141 .toolbar {
142 ToolbarItemGroup(placement: .topBarTrailing) {
143 DiagnosticsShareButton(snapshot: { diagnosticDump })
144 }
145 }
146 .task {
147 guard let syncEngine else { return }
148 let snapshot = await syncEngine.diagnosticSnapshot()
149 syncMonitor.updateSnapshot(snapshot)
150 }
151 }
152
153
154
155 private func resetSyncState() async {
156 guard let syncEngine else { return }
157 await syncEngine.resetSyncState()
158 syncMonitor.note("Sync state reset (zone/subscription flags and tokens cleared)")
159 let snapshot = await syncEngine.diagnosticSnapshot()
160 syncMonitor.updateSnapshot(snapshot)
161 }
162
163 private func probeContainer() async {
164 guard let syncEngine else { return }
165 syncMonitor.note("starting container probe")
166 let results = await syncEngine.probeContainer()
167 for (name, result) in results {
168 syncMonitor.note("probe[\(name)]: \(result)")
169 }
170 syncMonitor.note("Container probe complete")
171 }
172
173 private func auditCloudStorage() async {
174 guard !isAuditingStorage, let syncEngine else { return }
175 isAuditingStorage = true
176 defer { isAuditingStorage = false }
177
178 await syncEngine.auditPrivateCloudStorage { message in
179 syncMonitor.note(message)
180 }
181 }
182
183 private func runFullSync() async {
184 guard !isSyncing, let syncEngine else { return }
185 isSyncing = true
186 defer { isSyncing = false }
187
188 await syncMonitor.run("manual fetch") {
189 try await syncEngine.fetchChanges()
190 }
191 await syncMonitor.run("manual private ping fetch") {
192 _ = try await syncEngine.fetchPushPingsDirect(scope: .private)
193 }
194 await syncMonitor.run("manual shared ping fetch") {
195 _ = try await syncEngine.fetchPushPingsDirect(scope: .shared)
196 }
197 await syncMonitor.run("manual push") {
198 try await syncEngine.pushChanges()
199 }
200 let snapshot = await syncEngine.diagnosticSnapshot()
201 syncMonitor.updateSnapshot(snapshot)
202 }
203
204
205
206 @ViewBuilder
207 private func row(_ title: String, _ value: String) -> some View {
208 VStack(alignment: .leading, spacing: 4) {
209 Text(title)
210 .font(.caption)
211 .foregroundStyle(.secondary)
212 Text(value)
213 .font(.body.monospaced())
214 .textSelection(.enabled)
215 }
216 .padding(.vertical, 2)
217 }
218
219 private var accountStatusText: String { DiagnosticsReport.accountStatusText(syncMonitor) }
220
221 private func boolText(_ value: Bool?) -> String { DiagnosticsReport.boolText(value) }
222
223 private var sharingHealthText: String {
224 guard let snapshot = syncMonitor.snapshot else { return "Unknown" }
225 guard snapshot.engineRunning, snapshot.accountStatus == .available else {
226 return "Unavailable"
227 }
228 let count = snapshot.pendingInvitationCount
229 return count == 0
230 ? "Ready"
231 : "\(count) invitation\(count == 1 ? "" : "s") waiting for CloudKit"
232 }
233
234 private var versionText: String { DiagnosticsReport.versionText }
235
236 private var diagnosticDump: DiagnosticsDump {
237 DiagnosticsReport.dump(syncMonitor: syncMonitor, eventLog: eventLog)
238 }
239}
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256private struct DiagnosticsShareButton: UIViewRepresentable {
257
258
259 let snapshot: @MainActor () -> DiagnosticsDump
260
261 func makeUIView(context: Context) -> UIButton {
262 let button = UIButton(type: .system)
263 button.setImage(UIImage(systemName: "square.and.arrow.up"), for: .normal)
264 button.tintColor = .label
265 button.accessibilityLabel = "Share Full Log"
266 button.addAction(
267 UIAction { [snapshot, weak button] _ in
268 MainActor.assumeIsolated {
269 guard let button else { return }
270 let configuration = DiagnosticsShareItem.configuration(for: snapshot())
271 let controller = UIActivityViewController(activityItemsConfiguration: configuration)
272
273
274
275
276 HardwareKeyboardInputView.setCaptureSuspended(true)
277 controller.completionWithItemsHandler = { _, _, _, _ in
278 Task { @MainActor in
279 HardwareKeyboardInputView.setCaptureSuspended(false)
280 }
281 }
282
283
284 if let popover = controller.popoverPresentationController {
285 popover.sourceView = button
286 popover.sourceRect = button.bounds
287 }
288 var presenter = button.window?.rootViewController
289 while let presented = presenter?.presentedViewController {
290 presenter = presented
291 }
292 guard let presenter else {
293 HardwareKeyboardInputView.setCaptureSuspended(false)
294 return
295 }
296 presenter.present(controller, animated: true)
297 }
298 },
299 for: .touchUpInside
300 )
301 return button
302 }
303
304 func updateUIView(_ uiView: UIButton, context: Context) {}
305
306 func sizeThatFits(
307 _ proposal: ProposedViewSize,
308 uiView: UIButton,
309 context: Context
310 ) -> CGSize? {
311 uiView.intrinsicContentSize
312 }
313}
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332private enum DiagnosticsShareItem {
333 private static let fileName = "crossmate-diagnostics.txt"
334
335 @MainActor
336 static func configuration(for dump: DiagnosticsDump) -> UIActivityItemsConfiguration {
337 let provider = NSItemProvider()
338 provider.suggestedName = fileName
339
340
341
342
343
344
345 provider.registerDataRepresentation(for: .data, visibility: .all) { completion in
346 completion(Data(dump.rendered().utf8), nil)
347 return nil
348 }
349
350 let configuration = UIActivityItemsConfiguration(itemProviders: [provider])
351
352
353
354 configuration.metadataProvider = { key in
355 switch key {
356 case .title:
357 return fileName
358 case .linkPresentationMetadata:
359 let metadata = LPLinkMetadata()
360 metadata.title = fileName
361 return metadata
362 default:
363 return nil
364 }
365 }
366 return configuration
367 }
368}