Cotton code
477 lines · 20.0 KB · SwiftRaw
// Cotton Meetings' one door into the core. Every rule is the core's// (meetings-core, `apps/meetings/CORE.md`): the tables, the status a meeting// walks, where its audio is written, recovery after a kill, the windows a// long recording is heard in, merging them, naming a speaker, the files a// transcript is shared as. This file only names the methods and reads their// answers into what the screens draw.//// While a method answers `not_yet` (its shape without its body) or// `unknown_method` (absent from this build's core), the recording still// happens and the card still tells the truth: the row is written as a plain// record (`recording`, then `waiting`) under the take's own id and the audio// stays on the phone, as meetings-android does; reads fall back to// `records.list`; sharing words the transcript here.#if os(iOS)import CottonKitimport CottonValuesimport Foundationenum MeetingsMethod {    static let recordStart = "meetings.record.start"    static let recordTick = "meetings.record.tick"    static let recordStop = "meetings.record.stop"    static let recordRecover = "meetings.record.recover"    static let transcribed = "meetings.transcribed"    static let transcribe = "meetings.transcribe"    static let next = "meetings.next"    static let windows = "meetings.windows"    static let merge = "meetings.merge"    static let read = "meetings.read"    static let nameSpeaker = "meetings.speaker.name"    static let export = "meetings.export"    static let summarise = "meetings.summarise"    static let actionTodo = "meetings.action.todo"}enum MeetingsTable {    static let meeting = "meetings_meeting"    static let speaker = "meetings_speaker"    static let line = "meetings_line"}/// True for an answer that means "this core has no body for that yet".func meetingsNotHere(_ error: Error) -> Bool {    guard let error = error as? CottonCallError else { return false }    return error.code == "unknown_method" || error.code == "not_yet"}/// A meeting's status as the screen tells it.enum MeetingStatus: Equatable, Sendable {    case recording    case waiting    case transcribing(by: String?)    case ready    case failed(String?)    init(raw: String?, why: String?, by: String?) {        switch raw ?? "" {        case "recording": self = .recording        case "transcribing": self = .transcribing(by: by)        case "ready": self = .ready        case "failed": self = .failed(why)        default: self = .waiting        }    }}/// One meeting, as the list and the transcript page draw it.struct MeetingRow: Identifiable, Equatable, Sendable {    let id: String    let title: String?    let kind: MeetingKind    let startedAt: Date?    let durationMs: Int?    let status: MeetingStatus    let summary: String?    /// `<where>:<engine>`, e.g. `mac:sherpa:whisper-large-v3`.    let transcribedBy: String?    let languages: [String]    let marks: [Int]    /// The audio's media key, where the row names one.    let audioKey: String?    /// Whether this phone holds the audio (`on_phone`, the device's answer).    let onPhone: Bool    init(id: String, data: [String: RecordValue]) {        self.id = id        title = data["title"]?.text        kind = MeetingKind(rawValue: data["kind"]?.text ?? "") ?? .meeting        startedAt = (data["started_at"]?.text).flatMap { CottonDate.parse($0) }        durationMs = data["duration_ms"]?.number.map { Int($0) }        transcribedBy = data["transcribed_by"]?.text        let why = data["status_why"]?.text        status = MeetingStatus(raw: data["status"]?.text, why: why, by: transcribedBy)        summary = data["summary"]?.text        languages = (data["languages"]?.text ?? "").split(separator: ",")            .map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }        if case .list(let items) = data["marks"] ?? .null {            marks = items.compactMap { $0.number.map { Int($0) } }        } else {            marks = []        }        audioKey = Self.key(data["audio"])        onPhone = data["on_phone"]?.text == "kept"    }    /// Where it was transcribed: the part of `transcribed_by` before the engine.    var transcribedWhere: String? { transcribedBy?.split(separator: ":").first.map(String.init) }    /// A file column's key: a bare key, or `{key|ref|path}`.    private static func key(_ value: RecordValue?) -> String? {        switch value ?? .null {        case .text(let key): return key.isEmpty ? nil : key        case .object(let fields): return fields["key"]?.text ?? fields["ref"]?.text ?? fields["path"]?.text        default: return nil        }    }}/// One speaker of a meeting.struct MeetingSpeaker: Identifiable, Equatable, Sendable {    let id: String    let label: String    let name: String?}/// One thing a meeting said is to be done, as the core hands it (lane/// meetings-summaries): who and the day only where the meeting said them, and/// its one act, Add to todos, or the words saying it was added.struct MeetingAction: Identifiable, Equatable, Sendable {    let id: String    let words: String    let who: String?    /// `YYYY-MM-DD`.    let due: String?    let dueSaid: String?    let added: Bool    /// The act's label while it is not added.    let act: String?    /// The words saying it was added.    let said: String?    init(_ flat: [String: RecordValue]) {        id = flat["id"]?.text ?? ""        words = flat["words"]?.text ?? ""        who = flat["who"]?.text        due = flat["due"]?.text        dueSaid = flat["due_said"]?.text        added = flat["added"] == .bool(true)        if case .object(let act) = flat["act"] ?? .null { self.act = act["label"]?.text } else { act = nil }        said = flat["said"]?.text    }}/// A meeting's summary as the page draws it: the points, why there is none/// yet, and its actions.struct MeetingNotes: Equatable, Sendable {    var summary: String?    var note: String?    var actions: [MeetingAction] = []}/// One line of a transcript.struct MeetingLine: Identifiable, Equatable, Sendable {    let id: String    let speaker: String    let startMs: Int    let endMs: Int    let text: String}/// The transcript, as every transcription step hands it to the core.struct MeetingTranscript: Codable, Equatable, Sendable {    struct Speaker: Codable, Equatable, Sendable { let label: String }    struct Line: Codable, Equatable, Sendable {        /// Nil from the phone (one microphone, one voice it cannot tell apart): the core's merge keeps such lines as        /// one voice across windows (CONTRACT.md "Recordings"); a speaker only where the voices were told apart.        let speaker: String?        let start_ms: Int        let end_ms: Int        let text: String        let language: String?    }    let by: String    let languages: [String]    let speakers: [Speaker]    let lines: [Line]}/// One window of a long recording, as the core cuts it.struct MeetingWindow: Codable, Equatable, Sendable {    let index: Int    let start_ms: Int    let end_ms: Int}struct MeetingsCore: Sendable {    let core: any CottonCalling    private struct Listed: Decodable { let records: [CoreRecords.WireRecord] }    // MARK: - Recording    struct Started: Decodable, Sendable {        let meeting: String        let audio_path: String    }    /// The meeting's row stands at `recording` from the first second; the    /// core says which file to write. Nil while the core has no body for it.    /// `id` is this take's id, so a start sent twice is one recording.    func recordStart(kind: MeetingKind, id: String, startedAt: Date) async throws -> Started? {        do {            return try await core.call(                MeetingsMethod.recordStart,                ["kind": RecordValue.text(kind.rawValue), "id": .text(id), "started_at": .text(CottonDate.format(startedAt))],                as: Started.self)        } catch where meetingsNotHere(error) {            return nil        }    }    /// Every ~10 s while recording, so a crash still knows the length.    func recordTick(meeting: String, durationMs: Int) async {        _ = try? await core.callJSON(            MeetingsMethod.recordTick, ["meeting": RecordValue.text(meeting), "duration_ms": .number(Double(durationMs))])    }    /// What `record.stop` and a named `record.recover` send.    struct Finish: Encodable, Sendable {        let id: String        let path: String        let format: String        let duration_ms: Int        let marks: [Int]        let ended_at: String    }    /// The take is over: the core takes the bytes at `path` (in `format`) into    /// the store and the meeting waits.    func recordStop(_ finish: Finish) async throws {        _ = try await core.callJSON(MeetingsMethod.recordStop, finish)    }    /// One take the app holds and the core has not finished (a killed    /// process's, or one whose start never reached the core): the core makes    /// it a meeting as Stop would.    func recordRecover(_ finish: Finish) async throws {        _ = try await core.callJSON(MeetingsMethod.recordRecover, finish)    }    /// Once at launch: every `recording` row whose audio is here is finished    /// as Stop would; answers the meetings recovered, or nil where the core    /// has no body yet.    func recordRecover() async -> [String]? {        struct Recovered: Decodable {            struct One: Decodable { let meeting: String }            let recovered: [One]        }        do {            return try await core.call(MeetingsMethod.recordRecover, EmptyRequest(), as: Recovered.self)                .recovered.map(\.meeting)        } catch {            if !meetingsNotHere(error) { Log.warn("meetings: record.recover refused: \(error)") }            return nil        }    }    // MARK: - Transcribing    /// The next recording this phone should transcribe; nil when there is    /// none (or the core cannot say yet). `peek` claims nothing; `except`    /// passes over recordings the object refused; `id` takes that one only.    func next(charging: Bool, battery: Int? = nil, peek: Bool = false, except: [String] = [], id: String? = nil) async -> (meeting: String, audio: URL)? {        struct Next: Decodable { let meeting: String?; let audio_path: String? }        var request: [String: RecordValue] = ["on": .text("phone"), "charging": .bool(charging)]        // The core decides what a phone off power takes (CONTRACT.md "Recordings": a short one at 30% or more).        if let battery { request["battery"] = .number(Double(battery)) }        if peek { request["peek"] = .bool(true) }        if !except.isEmpty { request["except"] = .list(except.map(RecordValue.text)) }        if let id { request["id"] = .text(id) }        guard let answer = try? await core.call(MeetingsMethod.next, request, as: Next.self),              let meeting = answer.meeting, let path = answer.audio_path        else { return nil }        return (meeting, URL(fileURLWithPath: path))    }    /// What the object said to this phone's claim.    enum Claim: Equatable { case claimed, heldByAnother, alone }    /// Claim a recording through the object (`meeting_claim { id, by: phone }`),    /// so the phone and the Mac never both take one: `heldByAnother` on its    /// 409 (`not_waiting`, `not_yours`), `alone` where this phone is not    /// signed in or reaches no object (it is then the only transcriber it    /// can know of).    func claim(_ meeting: String) async -> Claim {        do {            _ = try await core.callJSON(                CottonMethod.objectAct,                ["act": RecordValue.text("meeting_claim"), "args": .object(["id": .text(meeting), "by": .text("phone")])])            return .claimed        } catch let error as CottonCallError where error.code == "not_waiting" || error.code == "not_yours" {            return .heldByAnother        } catch {            if (error as? CottonCallError)?.code != "sign_in_first" {                Log.warn("meetings: the object did not answer this phone's claim on \(meeting): \(error)")            }            return .alone        }    }    /// Give up a recording claimed through the object (`meeting_failed`).    func giveUp(_ meeting: String, why: String) async {        _ = try? await core.callJSON(            CottonMethod.objectAct,            ["act": RecordValue.text("meeting_failed"), "args": .object(["id": .text(meeting), "why": .text(why)])])    }    /// The windows the core cuts a recording of this length into.    func windows(durationMs: Int) async -> [MeetingWindow]? {        struct Windows: Decodable { let windows: [MeetingWindow] }        return try? await core.call(            MeetingsMethod.windows, ["duration_ms": RecordValue.number(Double(durationMs))], as: Windows.self        ).windows    }    struct HeardWindow: Encodable, Sendable {        let index: Int        let start_ms: Int        let end_ms: Int        let language: String?        let lines: [MeetingTranscript.Line]    }    /// The windows' lines made one transcript: the core de-duplicates the    /// overlaps and numbers the speakers.    func merge(_ windows: [HeardWindow]) async throws -> MeetingTranscript {        struct Merged: Decodable { let transcript: MeetingTranscript }        struct Request: Encodable, Sendable { let windows: [HeardWindow] }        return try await core.call(MeetingsMethod.merge, Request(windows: windows), as: Merged.self).transcript    }    /// Hand the core a finished transcript.    func transcribed(meeting: String, _ transcript: MeetingTranscript) async throws {        struct Request: Encodable, Sendable { let meeting: String; let transcript: MeetingTranscript }        _ = try await core.callJSON(MeetingsMethod.transcribed, Request(meeting: meeting, transcript: transcript))    }    /// The step that claimed it could not finish: the meeting is `failed`    /// with `why` (a word of the set's `why.*`), and Try again asks anew.    func transcriptionFailed(_ meeting: String, why: String) async throws {        _ = try await core.callJSON(MeetingsMethod.transcribed, ["id": RecordValue.text(meeting), "failed": .text(why)])    }    /// Ask for the meeting to be transcribed again.    func transcribeAgain(_ meeting: String) async throws {        _ = try await core.callJSON(MeetingsMethod.transcribe, ["id": RecordValue.text(meeting)])    }    // MARK: - Reading, naming, sharing    func meetings() async throws -> [MeetingRow] {        let rows = try await list(MeetingsTable.meeting, where: [:], limit: 200)        return rows.map { MeetingRow(id: $0.id, data: $0.data) }            .sorted { ($0.startedAt ?? .distantPast) > ($1.startedAt ?? .distantPast) }    }    /// The meeting whole: its row, its speakers, its lines, its summary and actions.    func read(_ id: String) async throws -> (MeetingRow, [MeetingSpeaker], [MeetingLine], MeetingNotes) {        // The core's rows come flat: `{id, …fields}`.        struct Read: Decodable {            let meeting: [String: RecordValue]            let speakers: [[String: RecordValue]]            let lines: [[String: RecordValue]]            let actions: [[String: RecordValue]]?            let summary_note: String?        }        func wire(_ flat: [String: RecordValue]) -> (id: String, data: [String: RecordValue]) {            var data = flat            return (data.removeValue(forKey: "id")?.text ?? "", data)        }        do {            let read = try await core.call(MeetingsMethod.read, ["id": RecordValue.text(id)], as: Read.self)            let row = wire(read.meeting)            let notes = MeetingNotes(                summary: read.meeting["summary"]?.text, note: read.summary_note,                actions: (read.actions ?? []).map(MeetingAction.init))            return (MeetingRow(id: row.id, data: row.data),                    read.speakers.map { Self.speaker(wire($0)) },                    read.lines.map { Self.line(wire($0)) }.sorted { $0.startMs < $1.startMs },                    notes)        } catch where meetingsNotHere(error) {            let row = try await core.call(                CottonMethod.recordsGet, ["table": RecordValue.text(MeetingsTable.meeting), "id": .text(id)],                as: CoreRecords.WireRecord.self)            let speakers = (try? await list(MeetingsTable.speaker, where: ["meeting": .text(id)], limit: 50)) ?? []            let lines = (try? await list(MeetingsTable.line, where: ["meeting": .text(id)], limit: 5000)) ?? []            return (MeetingRow(id: row.id, data: row.data), speakers.map { Self.speaker(($0.id, $0.data)) },                    lines.map { Self.line(($0.id, $0.data)) }.sorted { $0.startMs < $1.startMs },                    MeetingNotes(summary: row.data["summary"]?.text))        }    }    private static func speaker(_ row: (id: String, data: [String: RecordValue])) -> MeetingSpeaker {        MeetingSpeaker(id: row.id, label: row.data["label"]?.text ?? row.id, name: row.data["name"]?.text)    }    private static func line(_ row: (id: String, data: [String: RecordValue])) -> MeetingLine {        MeetingLine(            id: row.id,            speaker: row.data["speaker"]?.text ?? "",            startMs: Int(row.data["start_ms"]?.number ?? 0),            endMs: Int(row.data["end_ms"]?.number ?? 0),            text: row.data["text"]?.text ?? "")    }    /// Add to todos: the core makes the todo from the action and links it.    func addToTodos(_ action: MeetingAction) async throws {        _ = try await core.callJSON(MeetingsMethod.actionTodo, ["id": RecordValue.text(action.id)])    }    /// Ask the Mac for the summary again.    func summariseAgain(_ meeting: String) async throws {        _ = try await core.callJSON(MeetingsMethod.summarise, ["id": RecordValue.text(meeting)])    }    /// Name a speaker in place, for this meeting only.    func name(speaker: MeetingSpeaker, as name: String) async throws {        do {            _ = try await core.callJSON(                MeetingsMethod.nameSpeaker, ["speaker": RecordValue.text(speaker.id), "name": .text(name)])        } catch where meetingsNotHere(error) {            _ = try await core.callJSON("records.update", [                "table": RecordValue.text(MeetingsTable.speaker), "id": .text(speaker.id),                "patch": .object(["name": .text(name)]),            ])        }    }    /// The open bundle a meeting is shared as: the audio, `transcript.txt`,    /// `transcript.srt`, `transcript.json`. Nil while the core cannot make it.    func export(_ id: String) async -> [(name: String, url: URL, type: String)]? {        struct Exported: Decodable {            struct File: Decodable { let name: String; let path: String; let type: String }            let files: [File]        }        guard let answer = try? await core.call(MeetingsMethod.export, ["id": RecordValue.text(id)], as: Exported.self)        else { return nil }        return answer.files.map { ($0.name, URL(fileURLWithPath: $0.path), $0.type) }    }    /// A path on this phone to the meeting's audio, fetched first when it is    /// not here; nil when there is none to have.    func audio(of row: MeetingRow) async -> URL? {        guard let key = row.audioKey else { return nil }        struct Read: Encodable, Sendable { let args: [String: String] }        if let here = try? await core.callJSON(CottonMethod.readMediaPath, Read(args: ["key": key])),           let path = here.text("path"), FileManager.default.fileExists(atPath: path)        {            return URL(fileURLWithPath: path)        }        guard let fetched = try? await core.callJSON(CottonMethod.mediaEnsure, Read(args: ["key": key])),              let path = fetched.text("path")        else { return nil }        return URL(fileURLWithPath: path)    }    private func list(_ table: String, where filter: [String: RecordValue], limit: Int) async throws        -> [CoreRecords.WireRecord]    {        var request: [String: RecordValue] = ["table": .text(table), "limit": .number(Double(limit)), "page": .number(0)]        if !filter.isEmpty { request["where"] = .object(filter) }        return try await core.call(CottonMethod.recordsList, request, as: Listed.self).records    }}#endif