← All repositories

crossmate

A collaborative crossword app for iPhone and iPad

git clone https://code.inqk.net/crossmate.git


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    /// The on-screen list is a quick glance, not the archive — the buffer now
48    /// spans a full day (tens of thousands of entries during a co-solve), and
49    /// rendering it all just buries the tail. The shared file keeps everything.
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    // MARK: - Actions
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    // MARK: - Subviews
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/// The share button, in UIKit deliberately. SwiftUI's `ShareLink` resolves its
242/// item — for a file, render *and* disk write — before it will present the
243/// sheet, which put a count-the-seconds stall between the tap and the menu.
244/// `UIActivityViewController` + a promised `NSItemProvider` has the semantics
245/// the button needs: the sheet presents instantly (the configuration's
246/// metadata provider titles the header without loading the item), and the
247/// promised representation is loaded on a background queue only once the user
248/// picks an activity — the render cost lands inside the chosen activity's own
249/// progress UI, where a wait reads as normal instead of broken.
250///
251/// The button must be the UIKit view itself (a presentation anchor hidden
252/// behind a native toolbar Button never gets installed in the window —
253/// toolbars drop button backgrounds), so it mimics the toolbar's native
254/// styling instead: intrinsic sizing via `sizeThatFits` and the label-colour
255/// tint the surrounding monochrome toolbar items use.
256private struct DiagnosticsShareButton: UIViewRepresentable {
257    /// Runs at tap time on the main actor; must stay cheap (header strings
258    /// plus a copy-on-write take of the entries buffer).
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                    // The open puzzle normally owns first responder so it can
273                    // capture hardware navigation keys. Yield that ownership
274                    // while the activity and its Save to Files filename field
275                    // are presented, then restore it when the activity ends.
276                    HardwareKeyboardInputView.setCaptureSuspended(true)
277                    controller.completionWithItemsHandler = { _, _, _, _ in
278                        Task { @MainActor in
279                            HardwareKeyboardInputView.setCaptureSuspended(false)
280                        }
281                    }
282                    // iPad presents the share sheet as a popover and traps
283                    // without an anchor.
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/// Renders the diagnostics dump only after the user picks an activity in the
316/// share sheet — the promised data representation is not loaded before then.
317/// The dump inputs are snapshotted at tap time, so the file reflects the log
318/// as the user saw it.
319///
320/// The item is a promise rather than a concrete `file:` URL on purpose:
321/// Save to Files treats a raw URL item as "copy this exact file" and pins its
322/// name, whereas a promised representation is a file the destination creates,
323/// so the sheet's rename field works, with `suggestedName` carrying the name.
324///
325/// The promise must be *data*, not a file. The share sheet fails to grant
326/// consumers a sandbox extension for a promised file's URL (Apple DTS,
327/// developer.apple.com/forums/thread/714354), so a promised file
328/// representation makes Save to Files dismiss without saving and share
329/// extensions fail to load the attachment. A data promise crosses to the
330/// consumer directly and the consumer writes its own file, so no sandbox
331/// handoff is involved.
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        // Registered as generic data, not .plainText: messaging apps classify
340        // a plain-text item as message text — Signal loads it as a string and
341        // packages an oversize-text attachment under its own name, ignoring
342        // suggestedName. A generic-data item routes through their file path,
343        // where the materialised file keeps the suggested name. The .txt in
344        // suggestedName still types the file at its destination.
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        // Without metadata the sheet has nothing to title its header with
352        // until the promise is loaded; supply it up front so presenting stays
353        // instant and the header never shows a placeholder name.
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}