From 81719b0f5eee2364e60582d942d700cde4e70951 Mon Sep 17 00:00:00 2001 From: Pete Schwamb Date: Mon, 19 Oct 2026 10:06:24 -0500 Subject: [PATCH 1/2] Leave the GitHub issues link to Loop's Report a Problem screen Loop now lists every way to report a problem on one screen, including GitHub issues, so LoopSupport no longer adds its own Submit Bug Report row to Support. Also drops supportMenuItem, which nothing calls. --- LoopSupportKitUI/LoopSupportUI.swift | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/LoopSupportKitUI/LoopSupportUI.swift b/LoopSupportKitUI/LoopSupportUI.swift index e5b6a8f..1351ec7 100644 --- a/LoopSupportKitUI/LoopSupportUI.swift +++ b/LoopSupportKitUI/LoopSupportUI.swift @@ -35,24 +35,12 @@ public final class LoopSupportUI: SupportUI { public func getScenarios(from scenarioURLs: [URL]) -> [LoopScenario] { [] } - public func supportMenuItem(supportInfoProvider: SupportInfoProvider, urlHandler: @escaping (URL) -> Void) -> AnyView? { - return AnyView(Button(LocalizedString("Submit Bug Report", comment: "Navigation link title for Submit Bug Report"), action: { - let url = URL(string: "https://github.com/LoopKit/Loop/issues")! - urlHandler(url) - })) - } - public weak var delegate: SupportUIDelegate? public func initializationComplete(for services: [LoopKit.Service]) { } public func configurationMenuItems() -> [LoopKitUI.CustomMenuItem] { - let view = Button(LocalizedString("Submit Bug Report", comment: "Navigation link title for Submit Bug Report"), action: { - let url = URL(string: "https://github.com/LoopKit/Loop/issues")! - self.delegate?.openURL(url: url) - }) return [ - CustomMenuItem(section: .support, view: AnyView(view)), CustomMenuItem(section: .configuration, view: AnyView(UsageDataPrivacyPreferenceMenuItem())), ] } From 8fa2dce273f9e2edfd3ab7beb665043b253dd513 Mon Sep 17 00:00:00 2001 From: Pete Schwamb Date: Mon, 19 Oct 2026 11:13:36 -0500 Subject: [PATCH 2/2] Provide Report a Problem from LoopSupport The Report a Problem screen, the developer report form and its submitter move here from Loop, so each support plugin decides what its users can report and where it goes. LoopSupport adds one Report a Problem row to Support with all four options: send to the Loop developers, share a diagnostic report, open a GitHub issue, and export critical event logs through the app. The report context is built from the app's bundle and BuildDetails plus the pump and CGM status the delegate provides. --- LoopSupport.xcodeproj/project.pbxproj | 24 ++ .../IssueReport/IssueReportContext.swift | 45 ++++ .../IssueReport/IssueReportSubmitter.swift | 139 ++++++++++ .../IssueReport/ReportProblemView.swift | 153 +++++++++++ .../IssueReport/SendIssueReportView.swift | 249 ++++++++++++++++++ LoopSupportKitUI/LoopSupportUI.swift | 5 + 6 files changed, 615 insertions(+) create mode 100644 LoopSupportKitUI/IssueReport/IssueReportContext.swift create mode 100644 LoopSupportKitUI/IssueReport/IssueReportSubmitter.swift create mode 100644 LoopSupportKitUI/IssueReport/ReportProblemView.swift create mode 100644 LoopSupportKitUI/IssueReport/SendIssueReportView.swift diff --git a/LoopSupport.xcodeproj/project.pbxproj b/LoopSupport.xcodeproj/project.pbxproj index 691c0c0..679fccf 100644 --- a/LoopSupport.xcodeproj/project.pbxproj +++ b/LoopSupport.xcodeproj/project.pbxproj @@ -21,6 +21,10 @@ B66D1F552E6A752300471149 /* Localizable.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = B66D1F542E6A752300471149 /* Localizable.xcstrings */; }; C12ECD05289560B90089EB07 /* LoopSupportKitUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A936A95425BC9A190085119C /* LoopSupportKitUI.framework */; platformFilter = ios; }; C12ECD06289560B90089EB07 /* LoopSupportKitUI.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = A936A95425BC9A190085119C /* LoopSupportKitUI.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + C1A55E022E9F000000B10002 /* IssueReportContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A55E022E9F000000B10001 /* IssueReportContext.swift */; }; + C1A55E022E9F000000B10004 /* IssueReportSubmitter.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A55E022E9F000000B10003 /* IssueReportSubmitter.swift */; }; + C1A55E022E9F000000B10006 /* ReportProblemView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A55E022E9F000000B10005 /* ReportProblemView.swift */; }; + C1A55E022E9F000000B10008 /* SendIssueReportView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A55E022E9F000000B10007 /* SendIssueReportView.swift */; }; C14A7E7C295F2EC100CD87B4 /* UsageDataPrivacyPreferenceView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C14A7E7B295F2EC100CD87B4 /* UsageDataPrivacyPreferenceView.swift */; }; C15349062960AA9000B47074 /* UsageDataPrivacyPreferenceMenuItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = C15349052960AA9000B47074 /* UsageDataPrivacyPreferenceMenuItem.swift */; }; C1BE9741295E3800008BA25D /* LoopKitAnalytics.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1BE9740295E3800008BA25D /* LoopKitAnalytics.swift */; }; @@ -84,6 +88,10 @@ A9CE800A25BCACAE00C04F9B /* LoopSupportPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoopSupportPlugin.swift; sourceTree = ""; }; A9CE801225BCAE4000C04F9B /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; B66D1F542E6A752300471149 /* Localizable.xcstrings */ = {isa = PBXFileReference; lastKnownFileType = text.json.xcstrings; path = Localizable.xcstrings; sourceTree = ""; }; + C1A55E022E9F000000B10001 /* IssueReportContext.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IssueReportContext.swift; sourceTree = ""; }; + C1A55E022E9F000000B10003 /* IssueReportSubmitter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IssueReportSubmitter.swift; sourceTree = ""; }; + C1A55E022E9F000000B10005 /* ReportProblemView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportProblemView.swift; sourceTree = ""; }; + C1A55E022E9F000000B10007 /* SendIssueReportView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SendIssueReportView.swift; sourceTree = ""; }; C14A7E7B295F2EC100CD87B4 /* UsageDataPrivacyPreferenceView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UsageDataPrivacyPreferenceView.swift; sourceTree = ""; }; C15349052960AA9000B47074 /* UsageDataPrivacyPreferenceMenuItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UsageDataPrivacyPreferenceMenuItem.swift; sourceTree = ""; }; C1BE9740295E3800008BA25D /* LoopKitAnalytics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoopKitAnalytics.swift; sourceTree = ""; }; @@ -136,6 +144,7 @@ isa = PBXGroup; children = ( C14A7E7A295F2EA700CD87B4 /* Views */, + C1A55E022E9F000000B10000 /* IssueReport */, A936A95625BC9A190085119C /* LoopSupportKitUI.h */, A936A95725BC9A190085119C /* Info.plist */, B66D1F542E6A752300471149 /* Localizable.xcstrings */, @@ -185,6 +194,17 @@ name = Frameworks; sourceTree = ""; }; + C1A55E022E9F000000B10000 /* IssueReport */ = { + isa = PBXGroup; + children = ( + C1A55E022E9F000000B10001 /* IssueReportContext.swift */, + C1A55E022E9F000000B10003 /* IssueReportSubmitter.swift */, + C1A55E022E9F000000B10005 /* ReportProblemView.swift */, + C1A55E022E9F000000B10007 /* SendIssueReportView.swift */, + ); + path = IssueReport; + sourceTree = ""; + }; C14A7E7A295F2EA700CD87B4 /* Views */ = { isa = PBXGroup; children = ( @@ -349,6 +369,10 @@ A9CE7DA125BC9C0200C04F9B /* OSLog.swift in Sources */, C15349062960AA9000B47074 /* UsageDataPrivacyPreferenceMenuItem.swift in Sources */, C14A7E7C295F2EC100CD87B4 /* UsageDataPrivacyPreferenceView.swift in Sources */, + C1A55E022E9F000000B10002 /* IssueReportContext.swift in Sources */, + C1A55E022E9F000000B10004 /* IssueReportSubmitter.swift in Sources */, + C1A55E022E9F000000B10006 /* ReportProblemView.swift in Sources */, + C1A55E022E9F000000B10008 /* SendIssueReportView.swift in Sources */, A9CE7D8425BC9B3700C04F9B /* LocalizedString.swift in Sources */, A9CE800325BCAC8700C04F9B /* LoopSupportUI.swift in Sources */, C1BE9741295E3800008BA25D /* LoopKitAnalytics.swift in Sources */, diff --git a/LoopSupportKitUI/IssueReport/IssueReportContext.swift b/LoopSupportKitUI/IssueReport/IssueReportContext.swift new file mode 100644 index 0000000..c9f9a19 --- /dev/null +++ b/LoopSupportKitUI/IssueReport/IssueReportContext.swift @@ -0,0 +1,45 @@ +// +// IssueReportContext.swift +// LoopSupportKitUI +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import UIKit +import LoopKit +import LoopKitUI + +enum IssueReportContext { + /// Build, device and pump/CGM details sent with every issue report. + @MainActor + static func current(supportInfo: SupportInfoProvider?) -> [String: IssueReportContextValue] { + let info = Bundle.main.infoDictionary ?? [:] + let buildDetails = Bundle.main.url(forResource: "BuildDetails", withExtension: "plist") + .flatMap { NSDictionary(contentsOf: $0) as? [String: Any] } ?? [:] + + var context: [String: IssueReportContextValue] = [ + "appVersion": .string(info["CFBundleShortVersionString"] as? String ?? ""), + "buildNumber": .string(info["CFBundleVersion"] as? String ?? ""), + "customizations": .strings(buildDetails["com-loopkit-Loop-customizations"] as? [String] ?? []), + "deviceModel": .string(modelIdentifier), + "osVersion": .string(UIDevice.current.systemVersion), + ] + let branch = buildDetails["com-loopkit-LoopWorkspace-git-branch"] as? String ?? buildDetails["com-loopkit-Loop-git-branch"] as? String + context["branch"] = branch.map { .string($0) } + context["workspaceRevision"] = (buildDetails["com-loopkit-LoopWorkspace-git-revision"] as? String).map { .string($0) } + context["loopRevision"] = (buildDetails["com-loopkit-Loop-git-revision"] as? String).map { .string($0) } + context["pumpModel"] = supportInfo?.pumpStatus.map { .string($0.device.model ?? "Unknown") } + context["cgmModel"] = supportInfo?.cgmStatus.map { .string($0.device?.model ?? "Unknown") } + return context + } + + private static var modelIdentifier: String { + #if targetEnvironment(simulator) + return "\(UIDevice.current.model)Simulator" + #else + var info = utsname() + uname(&info) + return withUnsafePointer(to: &info.machine) { $0.withMemoryRebound(to: CChar.self, capacity: 1) { String(validatingUTF8: $0) } } ?? "unknown" + #endif + } +} diff --git a/LoopSupportKitUI/IssueReport/IssueReportSubmitter.swift b/LoopSupportKitUI/IssueReport/IssueReportSubmitter.swift new file mode 100644 index 0000000..13b4f3c --- /dev/null +++ b/LoopSupportKitUI/IssueReport/IssueReportSubmitter.swift @@ -0,0 +1,139 @@ +// +// IssueReportSubmitter.swift +// LoopSupportKitUI +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import Foundation + +struct IssueReport { + struct Contact: Encodable { + var name: String? + var email: String? + var zulip: String? + var github: String? + } + + struct Attachment { + var filename: String + var contentType: String + var data: Data + } + + var title: String? + var description: String + var contact: Contact? + var context: [String: IssueReportContextValue] + var attachments: [Attachment] +} + +enum IssueReportContextValue: Encodable, Equatable { + case string(String) + case strings([String]) + + func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .string(let value): try container.encode(value) + case .strings(let value): try container.encode(value) + } + } +} + +enum IssueReportSubmitterError: LocalizedError { + case server(status: Int, reason: String?) + case invalidResponse + case network(Error) + + var isRetryable: Bool { + switch self { + case .server(let status, _): return status >= 500 + case .invalidResponse, .network: return true + } + } + + var errorDescription: String? { + switch self { + case .server(413, _): + return LocalizedString("The report is too large. Try fewer or smaller screenshots.", comment: "Issue report error when the upload is too large") + case .server(415, _): + return LocalizedString("One of the attachments isn't a supported image type.", comment: "Issue report error when an attachment type is refused") + case .server(429, _): + return LocalizedString("Too many reports have been sent from this network recently. Please try again later.", comment: "Issue report error when rate limited") + case .server(let status, let reason): + return String(format: LocalizedString("The server couldn't accept the report (%1$d %2$@).", comment: "Issue report error with HTTP status (1) and reason (2)"), status, reason ?? "") + case .invalidResponse: + return LocalizedString("The server sent an unexpected response.", comment: "Issue report error for an unreadable response") + case .network(let error): + return error.localizedDescription + } + } +} + +struct IssueReportSubmitter { + static let endpoint = URL(string: "https://ingest.loopkit.org/v1/issues")! + static let apiKey = "7dd7414785560c0dd1ef802ac10c00b4" + + var session: URLSession = .shared + + func submit(_ report: IssueReport) async throws -> String { + let boundary = "Boundary-\(UUID().uuidString)" + var request = URLRequest(url: Self.endpoint) + request.httpMethod = "POST" + request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") + + let body = try Self.body(for: report, boundary: boundary) + let data: Data + let response: URLResponse + do { + (data, response) = try await session.upload(for: request, from: body) + } catch { + throw IssueReportSubmitterError.network(error) + } + guard let response = response as? HTTPURLResponse else { + throw IssueReportSubmitterError.invalidResponse + } + let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] + guard response.statusCode == 200 else { + throw IssueReportSubmitterError.server(status: response.statusCode, reason: json?["error"] as? String) + } + guard let id = json?["id"] as? String else { + throw IssueReportSubmitterError.invalidResponse + } + return id + } + + static func body(for report: IssueReport, boundary: String) throws -> Data { + struct Payload: Encodable { + var title: String? + var description: String + var contact: IssueReport.Contact? + var context: [String: IssueReportContextValue] + } + let payload = try JSONEncoder().encode(Payload(title: report.title, description: report.description, contact: report.contact, context: report.context)) + + var body = Data() + func appendPart(name: String, filename: String? = nil, contentType: String? = nil, data: Data) { + var header = "--\(boundary)\r\nContent-Disposition: form-data; name=\"\(name)\"" + if let filename { + header += "; filename=\"\(filename.replacingOccurrences(of: "\"", with: ""))\"" + } + header += "\r\n" + if let contentType { + header += "Content-Type: \(contentType)\r\n" + } + body.append(Data((header + "\r\n").utf8)) + body.append(data) + body.append(Data("\r\n".utf8)) + } + + appendPart(name: "client", data: Data(apiKey.utf8)) + appendPart(name: "report", contentType: "application/json", data: payload) + for attachment in report.attachments { + appendPart(name: "attachment", filename: attachment.filename, contentType: attachment.contentType, data: attachment.data) + } + body.append(Data("--\(boundary)--\r\n".utf8)) + return body + } +} diff --git a/LoopSupportKitUI/IssueReport/ReportProblemView.swift b/LoopSupportKitUI/IssueReport/ReportProblemView.swift new file mode 100644 index 0000000..dba6e91 --- /dev/null +++ b/LoopSupportKitUI/IssueReport/ReportProblemView.swift @@ -0,0 +1,153 @@ +// +// ReportProblemView.swift +// LoopSupportKitUI +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import SwiftUI +import LoopKitUI + +struct ReportProblemView: View { + let delegate: SupportUIDelegate? + + @State private var isPreparingReport = false + @State private var reportFile: ReportFile? + @State private var writtenReportURL: URL? + + private struct ReportFile: Identifiable { + let url: URL + var id: URL { url } + } + + var body: some View { + List { + Section { + NavigationLink(destination: SendIssueReportView( + context: IssueReportContext.current(supportInfo: delegate), + generateDiagnosticReport: delegate.map { delegate in { await delegate.generateIssueReport() } } + )) { + option( + LocalizedString("Send to the Loop Developers", comment: "Report a problem option: submit an issue report to the developers"), + detail: LocalizedString("Private. Describe the problem and attach screenshots and a diagnostic report. Only the LoopKit development team can see it.", comment: "Report a problem option detail: submit an issue report to the developers") + ) + } + + if delegate != nil { + Button(action: shareDiagnosticReport) { + HStack { + option( + LocalizedString("Share a Diagnostic Report", comment: "Report a problem option: share the diagnostic report yourself"), + detail: LocalizedString("Save the report or send it to someone helping you, for example on Zulip or Facebook. It contains health data such as glucose, insulin, carbs and your therapy settings.", comment: "Report a problem option detail: share the diagnostic report yourself") + ) + if isPreparingReport { + Spacer() + ProgressView() + } + } + } + .disabled(isPreparingReport) + } + + Button(action: { delegate?.openURL(url: URL(string: "https://github.com/LoopKit/Loop/issues")!) }) { + option( + LocalizedString("Open a GitHub Issue", comment: "Report a problem option: open the public GitHub issues page"), + detail: LocalizedString("Public. For bugs you can describe without any personal or health data.", comment: "Report a problem option detail: open the public GitHub issues page") + ) + } + + if let delegate { + NavigationLink(destination: delegate.criticalEventLogExportView()) { + option( + LocalizedString("Export Critical Event Logs", comment: "Report a problem option: export the critical event logs"), + detail: LocalizedString("Detailed logs as files. Only needed when a developer asks for them.", comment: "Report a problem option detail: export the critical event logs") + ) + } + } + } + } + .listStyle(.insetGrouped) + .navigationTitle(LocalizedString("Report a Problem", comment: "Title of the report a problem screen")) + .navigationBarTitleDisplayMode(.inline) + .sheet(item: $reportFile, onDismiss: removeReportFile) { file in + ActivityView(activityItems: [file.url]) + } + } + + private func option(_ title: String, detail: String) -> some View { + VStack(alignment: .leading, spacing: 4) { + Text(title) + .foregroundColor(.primary) + Text(detail) + .font(.footnote) + .foregroundColor(.secondary) + } + .padding(.vertical, 4) + } + + private func shareDiagnosticReport() { + guard let delegate else { + return + } + isPreparingReport = true + Task { @MainActor in + let date = Date() + let report = "Generated: \(date)\n\n" + (await delegate.generateIssueReport()) + let name = "Loop Report \(ISO8601DateFormatter.string(from: date, timeZone: .current, formatOptions: [.withSpaceBetweenDateAndTime, .withInternetDateTime])).md" + let url = FileManager.default.temporaryDirectory.appendingPathComponent(name.replacingOccurrences(of: ":", with: "-")) + do { + try report.write(to: url, atomically: true, encoding: .utf8) + writtenReportURL = url + reportFile = ReportFile(url: url) + } catch { + reportFile = nil + } + isPreparingReport = false + } + } + + private func removeReportFile() { + if let url = writtenReportURL { + try? FileManager.default.removeItem(at: url) + } + writtenReportURL = nil + } +} + +struct ReportProblemMenuItem: View { + let support: LoopSupportUI + + var body: some View { + NavigationLink(destination: ReportProblemView(delegate: support.delegate)) { + Text(LocalizedString("Report a Problem", comment: "The title text for the report a problem menu item")) + } + } +} + +/// Report a Problem shown on its own, outside settings. +struct ReportProblemModal: View { + let delegate: SupportUIDelegate? + + @Environment(\.dismissAction) private var dismiss + + var body: some View { + NavigationView { + ReportProblemView(delegate: delegate) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button(LocalizedString("Done", comment: "Button to close the report a problem screen"), action: dismiss) + } + } + } + } +} + +private struct ActivityView: UIViewControllerRepresentable { + let activityItems: [Any] + + func makeUIViewController(context: Context) -> UIActivityViewController { + UIActivityViewController(activityItems: activityItems, applicationActivities: nil) + } + + func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {} +} diff --git a/LoopSupportKitUI/IssueReport/SendIssueReportView.swift b/LoopSupportKitUI/IssueReport/SendIssueReportView.swift new file mode 100644 index 0000000..9c32a6f --- /dev/null +++ b/LoopSupportKitUI/IssueReport/SendIssueReportView.swift @@ -0,0 +1,249 @@ +// +// SendIssueReportView.swift +// LoopSupportKitUI +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import PhotosUI +import SwiftUI + +struct SendIssueReportView: View { + let context: [String: IssueReportContextValue] + let generateDiagnosticReport: (() async -> String)? + + @Environment(\.dismiss) private var dismiss + + @State private var title = "" + @State private var description = "" + @State private var isAnonymous = true + @State private var contact = IssueReport.Contact() + @State private var includeDiagnosticReport = true + @State private var photoSelection: [PhotosPickerItem] = [] + @State private var screenshots: [Screenshot] = [] + @State private var isSending = false + @State private var sentReportID: String? + @State private var sendError: IssueReportSubmitterError? + @State private var showingError = false + + private static let maxDescriptionLength = 20_000 + private static let maxScreenshots = 8 + private static let maxAttachmentBytes = 10_000_000 + + private struct Screenshot: Identifiable { + let id = UUID() + let image: UIImage + let attachment: IssueReport.Attachment + } + + var body: some View { + Form { + Section(footer: Text(String(format: LocalizedString("%1$d of %2$d characters", comment: "Issue report description length (1: used)(2: limit)"), description.count, Self.maxDescriptionLength))) { + TextField(LocalizedString("Title (optional)", comment: "Placeholder for the issue report title"), text: $title) + ZStack(alignment: .topLeading) { + if description.isEmpty { + Text(LocalizedString("Describe what you saw and what you expected to happen", comment: "Placeholder for the issue report description")) + .foregroundColor(Color(.placeholderText)) + .padding(.top, 8) + .padding(.leading, 4) + } + TextEditor(text: $description) + .frame(minHeight: 160) + } + } + + screenshotsSection + + Section(footer: Text(isAnonymous ? + LocalizedString("The report won't include your name, contact details or anything else that identifies you.", comment: "Footer for an anonymous issue report") : + LocalizedString("Fill in any of these so developers can follow up with you.", comment: "Footer for issue report contact details")) + ) { + Toggle(LocalizedString("Submit Anonymously", comment: "Toggle for submitting an issue report without contact details"), isOn: $isAnonymous) + if !isAnonymous { + TextField(LocalizedString("Name", comment: "Issue report contact name placeholder"), text: binding(\.name)) + .textContentType(.name) + TextField(LocalizedString("Email", comment: "Issue report contact email placeholder"), text: binding(\.email)) + .textContentType(.emailAddress) + .keyboardType(.emailAddress) + .textInputAutocapitalization(.never) + TextField(LocalizedString("Zulip Name", comment: "Issue report contact Zulip placeholder"), text: binding(\.zulip)) + .textInputAutocapitalization(.never) + TextField(LocalizedString("GitHub Username", comment: "Issue report contact GitHub placeholder"), text: binding(\.github)) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + } + } + + if generateDiagnosticReport != nil { + Section(footer: Text(LocalizedString("Attaches Loop's issue report as a text file. It contains health data such as recent glucose, insulin, carbs and your therapy settings.", comment: "Footer for the include diagnostic report toggle"))) { + Toggle(LocalizedString("Include Diagnostic Report", comment: "Toggle for attaching the diagnostic report to an issue report"), isOn: $includeDiagnosticReport) + } + } + + Section(header: Text(LocalizedString("Also Sent", comment: "Header for the build and device details sent with an issue report")), + footer: Text(LocalizedString("Reports go to the LoopKit development team and are visible only to them. Your IP address is used only to limit how often reports can be sent and is never stored.", comment: "Privacy footer for issue reports"))) + { + ForEach(context.keys.sorted(), id: \.self) { key in + HStack { + Text(key) + Spacer() + Text(Self.displayValue(context[key])) + .foregroundColor(.secondary) + .multilineTextAlignment(.trailing) + } + .font(.footnote) + } + } + } + .navigationTitle(LocalizedString("Send to Developers", comment: "Title of the issue report screen")) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + if isSending { + ProgressView() + } else { + Button(LocalizedString("Submit", comment: "Button to submit an issue report to the developers")) { + send() + } + .disabled(!canSend) + } + } + } + .disabled(isSending) + .onChange(of: photoSelection) { _, items in + loadScreenshots(items) + } + .alert(LocalizedString("Report Submitted", comment: "Title of the alert after an issue report was submitted"), isPresented: Binding(get: { sentReportID != nil }, set: { if !$0 { sentReportID = nil } })) { + Button(LocalizedString("Copy ID", comment: "Button to copy the issue report ID")) { + UIPasteboard.general.string = sentReportID + dismiss() + } + Button(LocalizedString("Done", comment: "Button to close the issue report sent alert"), role: .cancel) { + dismiss() + } + } message: { + Text(String(format: LocalizedString("Thank you. Your report ID is %1$@. Mention it if you discuss the problem on Zulip or GitHub.", comment: "Message after an issue report was sent (1: report ID)"), sentReportID ?? "")) + } + .alert(LocalizedString("Unable to Submit Report", comment: "Title of the alert when an issue report fails"), isPresented: $showingError, presenting: sendError) { error in + if error.isRetryable { + Button(LocalizedString("Try Again", comment: "Button to retry sending an issue report")) { + send() + } + } + Button(LocalizedString("OK", comment: "Button to close the issue report error alert"), role: .cancel) {} + } message: { error in + Text(error.localizedDescription) + } + } + + private var screenshotsSection: some View { + Section(footer: Text(String(format: LocalizedString("Up to %1$d screenshots or photos.", comment: "Footer for issue report screenshots (1: limit)"), Self.maxScreenshots))) { + if !screenshots.isEmpty { + ScrollView(.horizontal) { + HStack { + ForEach(screenshots) { screenshot in + Image(uiImage: screenshot.image) + .resizable() + .scaledToFit() + .frame(height: 120) + .clipShape(RoundedRectangle(cornerRadius: 6)) + } + } + } + } + PhotosPicker(selection: $photoSelection, maxSelectionCount: Self.maxScreenshots, matching: .images) { + Text(screenshots.isEmpty ? + LocalizedString("Add Screenshots", comment: "Button to choose screenshots for an issue report") : + LocalizedString("Change Screenshots", comment: "Button to change the screenshots on an issue report")) + } + } + } + + private var trimmedDescription: String { + description.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var canSend: Bool { + !trimmedDescription.isEmpty && description.count <= Self.maxDescriptionLength + } + + private func binding(_ keyPath: WritableKeyPath) -> Binding { + Binding(get: { contact[keyPath: keyPath] ?? "" }, set: { contact[keyPath: keyPath] = $0 }) + } + + private func loadScreenshots(_ items: [PhotosPickerItem]) { + Task { + var loaded: [Screenshot] = [] + for (index, item) in items.enumerated() { + guard let data = try? await item.loadTransferable(type: Data.self), let screenshot = Self.screenshot(from: data, index: index + 1) else { + continue + } + loaded.append(screenshot) + } + screenshots = loaded + } + } + + // The server accepts only PNG and JPEG, so anything else (HEIC from the camera) is converted + private static func screenshot(from data: Data, index: Int) -> Screenshot? { + guard let image = UIImage(data: data) else { + return nil + } + if data.starts(with: [0x89, 0x50, 0x4E, 0x47]), data.count <= maxAttachmentBytes { + return Screenshot(image: image, attachment: .init(filename: "screenshot-\(index).png", contentType: "image/png", data: data)) + } + for quality in [0.8, 0.5, 0.3] { + if let jpeg = image.jpegData(compressionQuality: quality), jpeg.count <= maxAttachmentBytes { + return Screenshot(image: image, attachment: .init(filename: "screenshot-\(index).jpg", contentType: "image/jpeg", data: jpeg)) + } + } + return nil + } + + private static func displayValue(_ value: IssueReportContextValue?) -> String { + switch value { + case .string(let string): return string + case .strings(let strings): return strings.isEmpty ? "–" : strings.joined(separator: ", ") + case nil: return "" + } + } + + private func send() { + isSending = true + Task { + var attachments = screenshots.map(\.attachment) + if includeDiagnosticReport, let generateDiagnosticReport { + let report = await generateDiagnosticReport() + // Stay under the server's per-file limit; decoding repairs a character cut in half + let text = String(decoding: report.utf8.prefix(Self.maxAttachmentBytes - 4), as: UTF8.self) + attachments.append(.init(filename: "diagnostic-report.txt", contentType: "text/plain; charset=utf-8", data: Data(text.utf8))) + } + let report = IssueReport( + title: title.isEmpty ? nil : String(title.prefix(200)), + description: trimmedDescription, + contact: isAnonymous ? nil : Self.trimmed(contact), + context: context, + attachments: attachments + ) + do { + sentReportID = try await IssueReportSubmitter().submit(report) + } catch let error as IssueReportSubmitterError { + sendError = error + showingError = true + } catch { + sendError = .network(error) + showingError = true + } + isSending = false + } + } + + private static func trimmed(_ contact: IssueReport.Contact) -> IssueReport.Contact? { + func clean(_ value: String?) -> String? { + let value = value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return value.isEmpty ? nil : value + } + let result = IssueReport.Contact(name: clean(contact.name), email: clean(contact.email), zulip: clean(contact.zulip), github: clean(contact.github)) + return [result.name, result.email, result.zulip, result.github].allSatisfy({ $0 == nil }) ? nil : result + } +} diff --git a/LoopSupportKitUI/LoopSupportUI.swift b/LoopSupportKitUI/LoopSupportUI.swift index 1351ec7..ce141f2 100644 --- a/LoopSupportKitUI/LoopSupportUI.swift +++ b/LoopSupportKitUI/LoopSupportUI.swift @@ -41,10 +41,15 @@ public final class LoopSupportUI: SupportUI { public func configurationMenuItems() -> [LoopKitUI.CustomMenuItem] { return [ + CustomMenuItem(section: .support, view: AnyView(ReportProblemMenuItem(support: self))), CustomMenuItem(section: .configuration, view: AnyView(UsageDataPrivacyPreferenceMenuItem())), ] } + public func reportProblemView() -> AnyView? { + AnyView(ReportProblemModal(delegate: delegate)) + } + public func loopWillReset() { } public func loopDidReset() { }