hex/ios/HEXMobile/Feedback/FeedbackSender.swift
Ryan Vogel b99f938bf6
iOS: Send feedback form (Bellhop), email decides anonymous (#2575)
* iOS: Send feedback form that posts to Bellhop

Adds a Send feedback form to the Hex app (never the keyboard) that sends one
report to Bellhop, Anomaly's feedback inbox, following blhp.app/docs/feedback's
"Building a feedback form" checklist:

- Entry points: a Send feedback row on Home's Privacy policy / Support /
  Acknowledgements card, and one at the end of Settings › Experiments. Both
  are absent in a build without a report key.
- The form: Problem / Idea / Question / Other, an optional subject, the
  message, pictures (Hex's own key window drawn just before the form opens,
  removable with one tap; more from the permission-free photo picker, up to
  5), an optional email, Send anonymously (hides the email and drops email
  and install id), and what is sent in plain words. Limits are checked
  before sending (message 20,000, subject 200, 5 pictures, 10 MiB each,
  20 MiB in all); every picture is re-encoded as JPEG at 80% with its
  longest side at most 2048 px (HEIC included).
- Sending: multipart/form-data with a payload JSON part and screenshot
  parts, an Idempotency-Key made at the tap and reused for every retry,
  visible upload progress, network failures and 5xx retried 4 times with
  1/2/4 s backoff, 409 request_pending and 429 retried after Retry-After,
  other 4xx never retried. 401 and 403 feedback_disabled are logged as a
  fault and shown as "unavailable"; 413, 415, 429 and offline get kind
  words. A thank-you says, when the answer has email "pending", that a
  reply comes by email and the address needs confirming once.
- Payload: message, subject, category, app, device (model identifier,
  BCP 47 locale), metadata (screen, dictation_language, speech_model),
  email and a random install id kept in Hex's UserDefaults. No user, no
  logs, nothing Hex keeps on the phone.
- Report key: BELLHOP_REPORT_KEY in HEXMobile/Feedback.xcconfig (empty in
  git), set by a gitignored Feedback.local.xcconfig or by ci_post_clone.sh
  from Xcode Cloud's BELLHOP_REPORT_KEY secret, read at run time from
  Info.plist's BellhopReportKey. No key lives in Swift.
- Debug-only launch arguments (--feedback-log-request, --feedback-key,
  --feedback-endpoint, --feedback-drop-first-response,
  --feedback-broken-image) for simulator proof of each path.
- Simplified Chinese for every new string; docs in
  ios/docs/settings-and-home.md.

Verified on the Studio's iPhone 17 Pro simulator (iOS 27.2) through the
form itself: a send with picture and email got 201 #3, email "pending";
an anonymous send got 201 #4, email "none", with no email or install_id in
the payload; a dropped first answer was retried with the same key and got
the same #5; a wrong key got one 401 and "unavailable"; a refused
connection was tried 4 times (0, +1, +3, +7 s) with one key, then said
offline; a half-cut picture got one 415. The keyboard appex has no
Bellhop key or address. code-shape.py --check passes. No unit test: no
existing HEXMobileTests file covers the app's networking.

* Privacy: say what Send feedback sends, when and to whom

The app's Privacy page and the website's privacy policy (site/src/iphone.ts)
said Hex collects no data. With Send feedback that's no longer exact, so:

- Settings › Privacy gets a Feedback note (only in builds with a report
  key): nothing is sent until Send; then the message, pictures kept, email
  if given and details about Hex and the iPhone go to Anomaly's feedback
  inbox; dictations, typing and what Hex learned never do.
- The policy's summary, card line (CARD_VERSION 2) and description now say
  Hex sends only the feedback you choose to send; a new "Feedback you send"
  section lists every field, when (only on Send), to whom (Anomaly's
  feedback inbox, Bellhop), what anonymous drops, and what is never
  included; "no servers your words could be sent to" and the children line
  are reworded to stay true. The header comment that checks claims against
  ios/ names the new request.

Verified: site bun test passes (20/20) and renderPrivacy renders the new
section; the Privacy page's string has its Simplified Chinese.

* iOS feedback: the email decides anonymous, no Send anonymously switch

Ryan: one thing instead of two. The optional email now decides:

- An email given: not anonymous; the email and the install id are sent,
  as before.
- No email: "anonymous": true, no email and no install id (none is made
  for an anonymous send), no user, nothing identifying in metadata.
- A typed email that isn't an address stops Send; once they leave the
  field the form says "That isn't an email address. Fix it, or clear it
  to send without one." It is never sent broken or as anonymous by
  accident.

Removed: the Send anonymously switch and its strings. Added one line under
the email field, "With an email, the team can reply. Without one, your
feedback is anonymous.", and the what-is-sent paragraph follows the field
(the install id is named only with an email). The website policy's
feedback section now covers Hex on iPhone and on Android together, for the
Android form being built alongside. Simplified Chinese for the new strings;
docs updated.

Verified on the Studio's iPhone 17 Pro simulator through the form: with
ryan@anoma.ly and Hex's window picture, 201 #6, email "pending", payload
with email and install_id; with no email, 201 #7, email "none", payload
"anonymous": true and no email, install_id or user. No existing
HEXMobileTests file covers the feedback payload, so no test case changed.

* iOS feedback: ship the report key in Feedback.xcconfig

The key only came from a gitignored local file or an Xcode Cloud secret that
doesn't exist, so a TestFlight build would have had no Send feedback row.
Bellhop report keys are publishable and safe to ship inside an app, and
Android keeps its key in android/gradle.properties, so:

- HEXMobile/Feedback.xcconfig now sets BELLHOP_REPORT_KEY. The optional
  include of Feedback.local.xcconfig stays after it, so a local file or
  ci_post_clone.sh (from an Xcode Cloud BELLHOP_REPORT_KEY secret, if one
  is ever set) overrides it, for a rotation. Still no key in Swift; it
  reaches the app as Info.plist's BellhopReportKey.
- ci_post_clone.sh and the docs say so; rotation: new key, revoke the old
  in Bellhop › Settings › Report keys, change the xcconfig, ship a build.
- FeedbackSender logs "feedback sent as #<number>" (notice, public), so a
  Release build's send can be traced to its issue.

Verified from a clean tree of this commit (git archive, no local override)
on the Studio: a Release simulator build's Info.plist carries the key, the
app shows Send feedback on Home and a send through the form got 201.
2026-11-23 16:00:03 -05:00

140 lines
6.5 KiB
Swift

import Foundation
import Observation
import os
/// Sends one feedback request, with its upload's progress, retrying as `FeedbackRetry` says
/// with the same body and Idempotency-Key, so a retry can never make a second issue.
@MainActor
@Observable
final class FeedbackSender {
/// 0…1 while the body uploads.
private(set) var progress: Double = 0
private(set) var attempt = 0
private let log = Logger(subsystem: "anomaly.hex.mobile", category: "feedback")
func send(_ request: FeedbackRequest, key: String) async -> FeedbackOutcome {
let key = Self.override("--feedback-key") ?? key
let endpoint = Self.override("--feedback-endpoint").flatMap(URL.init(string:)) ?? Feedback.endpoint
Self.record(request)
attempt = 0
while true {
attempt += 1
progress = 0
var status: Int?
var code: String?
var retryAfter: String?
do {
let delegate = FeedbackUploadProgress { [weak self] fraction in
Task { @MainActor in self?.progress = fraction }
}
let (data, response) = try await URLSession.shared.upload(for: request.urlRequest(key: key, endpoint: endpoint), from: request.body, delegate: delegate)
let http = response as? HTTPURLResponse
Self.recordAnswer(status: http?.statusCode ?? 0, body: data, attempt: attempt)
if Self.dropsResponse(attempt: attempt) { throw URLError(.networkConnectionLost) }
status = http?.statusCode
retryAfter = http?.value(forHTTPHeaderField: "Retry-After")
let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
if status == 201, let number = json?["number"] as? Int {
progress = 1
let email = json?["email"] as? String
log.notice("feedback sent as #\(number, privacy: .public)")
return .sent(number: number, emailPending: email == "pending")
}
code = (json?["error"] as? [String: Any])?["code"] as? String
log.error("feedback answered \(status ?? 0, privacy: .public) \(code ?? "", privacy: .public)")
} catch {
log.error("feedback attempt \(self.attempt, privacy: .public) failed: \(error.localizedDescription, privacy: .public)")
Self.recordError(error, attempt: attempt)
}
if let wait = FeedbackRetry.delay(afterStatus: status, code: code, retryAfter: retryAfter, attempt: attempt) {
try? await Task.sleep(for: .seconds(wait))
continue
}
guard let status else { return .failed(.offline) }
let failure = FeedbackRetry.failure(status: status, code: code)
if failure == .unavailable {
// The report key's setup (revoked, or feedback not allowed): the team's to fix.
log.fault("feedback is unavailable: \(status, privacy: .public) \(code ?? "", privacy: .public)")
}
return .failed(failure)
}
}
// MARK: - Simulator proof (debug builds only)
/// `--feedback-key`, `--feedback-endpoint`: a wrong key, an unreachable address.
private static func override(_ name: String) -> String? {
#if DEBUG
let args = ProcessInfo.processInfo.arguments
guard let i = args.firstIndex(of: name), i + 1 < args.count else { return nil }
return args[i + 1]
#else
return nil
#endif
}
/// `--feedback-drop-first-response`: the first answer is lost as a dropped connection is.
private static func dropsResponse(attempt: Int) -> Bool {
#if DEBUG
return attempt == 1 && ProcessInfo.processInfo.arguments.contains("--feedback-drop-first-response")
#else
return false
#endif
}
/// `--feedback-log-request`: what was sent, without the key, in Documents/feedback-requests.
private static func record(_ request: FeedbackRequest) {
#if DEBUG
guard ProcessInfo.processInfo.arguments.contains("--feedback-log-request") else { return }
let headers = request.urlRequest(key: "<report key>").allHTTPHeaderFields ?? [:]
let summary: [String: Any] = [
"headers": headers,
"payload": (try? JSONSerialization.jsonObject(with: request.payload)) ?? [:],
"bodyBytes": request.body.count,
"screenshots": request.pictures,
]
write(summary, suffix: "request")
#endif
}
private static func recordAnswer(status: Int, body: Data, attempt: Int) {
#if DEBUG
guard ProcessInfo.processInfo.arguments.contains("--feedback-log-request") else { return }
let answer = (try? JSONSerialization.jsonObject(with: body)) ?? String(decoding: body, as: UTF8.self)
write(["attempt": attempt, "status": status, "body": answer, "dropped": dropsResponse(attempt: attempt)], suffix: "answer")
#endif
}
private static func recordError(_ error: Error, attempt: Int) {
#if DEBUG
guard ProcessInfo.processInfo.arguments.contains("--feedback-log-request") else { return }
write(["attempt": attempt, "error": String(describing: error)], suffix: "error")
#endif
}
#if DEBUG
private static func write(_ object: [String: Any], suffix: String) {
let folder = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("feedback-requests")
try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
let name = "\(Int(Date().timeIntervalSince1970 * 1000))-\(suffix).json"
if let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys]) {
try? data.write(to: folder.appendingPathComponent(name))
}
}
#endif
}
/// The upload's progress, from URLSession's task delegate.
nonisolated final class FeedbackUploadProgress: NSObject, URLSessionTaskDelegate, Sendable {
private let report: @Sendable (Double) -> Void
init(report: @escaping @Sendable (Double) -> Void) {
self.report = report
}
func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64,
totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
guard totalBytesExpectedToSend > 0 else { return }
report(Double(totalBytesSent) / Double(totalBytesExpectedToSend))
}
}