Cotton code
132 lines · 5.6 KB · SwiftRaw
// What the app says of itself for the device's reported state (phone// diagnostics, 12 Oct 2026): the core puts it in every exchange body, and the// serving Mac writes it on this device's row (`cotton_devices.reported_state`),// so a session reads a phone's state without the owner. Only what the app// alone knows is said here — the bundle's build and commit, the databases the// sheet lists, the sentence the open card shows; the core adds the schema, the// last answer, what is unsent and a copy in progress (`shell::diagnostics`).import CottonValuesimport Foundationpublic enum Diagnostics {    /// `diagnostics.say` — fire and forget: a state that could not be said is    /// said again with the next change.    public static func say(_ core: (any CottonCalling)?, _ fields: [String: String?]) {        guard let core else { return }        let body = fields.mapValues { $0 ?? "" }        Task { _ = try? await core.callJSON("diagnostics.say", body) }    }    /// `diagnostics.say { usage }` — how the app ran over one MetricKit    /// window, on the device's row with the next state the core tells.    public static func sayUsage(_ core: any CottonCalling, _ usage: DeviceUsage) async {        struct Body: Encodable { let usage: DeviceUsage }        _ = try? await core.callJSON("diagnostics.say", Body(usage: usage))    }    /// This build, as the bundle says it.    public static func sayBuild(_ core: (any CottonCalling)?, facts: BuildFacts = .fromBundle()) {        say(core, ["build": facts.build, "sha": String(facts.commit.prefix(7)), "bundleId": Bundle.main.bundleIdentifier])    }}/// How the app ran over one MetricKit window — the core's `DeviceUsage`/// (fanperf, owner 15 Oct 2026: the animations must never make the app/// heavy, and the owner's own phone proves it). Four figures, nothing else of/// the payload; a figure the payload did not carry is left out.public struct DeviceUsage: Encodable, Sendable, Equatable {    /// When the window ended, RFC 3339.    public let until: String    /// Scroll hitch time over scrolling time, microseconds per second.    public let hitchUsPerS: UInt64?    public let hangs: UInt64?    public let cpuMs: UInt64?    public let peakMemoryBytes: UInt64?    enum CodingKeys: String, CodingKey {        case until        case hitchUsPerS = "hitch_us_per_s"        case hangs        case cpuMs = "cpu_ms"        case peakMemoryBytes = "peak_memory_bytes"    }    /// From MetricKit's own units: the hitch ratio in ms per s, CPU time in    /// seconds, peak memory in bytes. A negative or non-finite figure is left    /// out rather than guessed.    public init(until: Date, hitchMsPerS: Double?, hangs: Int?, cpuSeconds: Double?, peakMemoryBytes: Double?) {        func whole(_ value: Double?, times: Double) -> UInt64? {            guard let value, value.isFinite, value >= 0 else { return nil }            return UInt64((value * times).rounded())        }        self.until = CottonDate.format(until)        self.hitchUsPerS = whole(hitchMsPerS, times: 1000)        self.hangs = hangs.flatMap { $0 >= 0 ? UInt64($0) : nil }        self.cpuMs = whole(cpuSeconds, times: 1000)        self.peakMemoryBytes = whole(peakMemoryBytes, times: 1)    }}/// "Send a report" (phone diagnostics part 3): the core bundles the state, the/// last 500 lines of both logs and the registry files — every line redacted —/// into a document "Phone report · 12 Oct 16:02" in the personal database/// (`shell::report`). It is written on this device's copy, so it goes up with/// the next exchange and works offline.public struct DeviceReport: Sendable, Equatable {    /// The document it was filed as; nil when the write was refused.    public let documentId: String?    /// Why it was not filed, in the core's words.    public let refused: String?    /// The report itself, so a refused one can still be handed over.    public let text: String}/// One headed part of a report that only the app can say (the Debug group).public struct DeviceReportSection: Encodable, Sendable, Equatable {    public let heading: String    public let lines: [String]    public init(heading: String, lines: [String]) {        self.heading = heading        self.lines = lines    }}extension Diagnostics {    /// "Phone report · 12 Oct 16:02" (or "Mac report · …"), in the device's    /// own time zone — the owner reads it where he is.    public static func reportTitle(at date: Date = Date(), timeZone: TimeZone = .current) -> String {        let formatter = DateFormatter()        formatter.locale = Locale(identifier: "en_GB")        formatter.timeZone = timeZone        formatter.dateFormat = "d MMM HH:mm"        #if os(macOS)            let device = "Mac"        #else            let device = "Phone"        #endif        return "\(device) report · \(formatter.string(from: date))"    }    /// `diagnostics.report` — build the report and file it in the personal    /// database. Throws only when the core could not build it at all.    public static func sendReport(        _ core: any CottonCalling, extra: [DeviceReportSection] = []    ) async throws -> DeviceReport {        struct Body: Encodable {            let title: String            let log: [String]            let extra: [DeviceReportSection]        }        let answer = try await core.callJSON(            "diagnostics.report",            Body(title: reportTitle(), log: Log.ring.rendered(), extra: extra)        )        return DeviceReport(            documentId: answer["documentId"]?.string,            refused: answer["refused"]?.string,            text: answer["text"]?.string ?? ""        )    }}