Cotton code
252 lines · 11.9 KB · SwiftRaw
// `/activity` as tables: what this database is (`activity`, one record), the// assistant's runs (`assistant_run`) and every call a connected assistant made// here (`assistant_call`) — drawn by the deck and list surfaces from their// definitions (`activity`, `assistant_run`, `assistant_call`, as the object serves them),// nothing drawn here.//// BAND-AID until the record verbs answer these three tables from the engine// (asked of the core: `list_records`/`get_record` for each, `update_record(assistant_run,// {state: cancelled})` = `cancel_run`). Until then each table is answered// from `read.activity` — the one read the old screen made — by a// `SettingsTableSource` over `SettingsRecords`, the actor that already answers// tables from the app's own reads, so its paging, change records and refusals// are the ones every Settings table has.//// **Four strings are the SERVER's and pass through untouched**: a run's// `task`, `receipt` and `error`, and a call's `args_summary`. The words made// here are the old screen's own and nothing else: which file this is ("A copy// on this device"), what a run stopped on and spent ("Stopped at its turn// limit · $0.0042 spent").//// **A failed run is offered no Retry, on purpose**: its sentence names what// stopped it (no key stored, a refusal, a limit), asking again unchanged fails// the same way, and no owner-scope re-queue exists — the only one is// ADMIN-signed. Cancel is the one write: it takes a QUEUED run out of the// queue, and the row goes (there is no cancelled state to stamp).//// **A ceiling is not a failure**: a done run that stopped at its turn or time// limit says so on its spent line and gets no error invented for it.import CottonKitimport CottonValuesimport SwiftUIpublic enum ActivityTables {    /// The one record of `activity`: this database, as this device reads it.    public static let thisID = "this"    /// The page's table, and the title its one record carries. Constants    /// rather than literals at their use, because a literal subscript or    /// `.text("…")` reads as an answer's key to the read-key sweep.    static let table = "activity"    static let title = "Activity"    /// The value a run's state is written with to take it out of the queue.    static let cancelled = "cancelled"    /// The most `read.activity` hands up in one answer — asked for, rather    /// than its defaults (50 and 20), so the lists are as long as it allows.    static let runsLimit = 200    static let auditLimit = 100    /// The three sources, made afresh for each store.    static var sources: [any SettingsTableSource] {        [ActivityFactsSource(), AssistantRunSource(), AssistantCallSource()]    }    /// The records verbs for the three tables, over the core the app holds,    /// drawing the database's catalogue.    static func records(core: any CottonCalling) -> SettingsRecords {        SettingsRecords(core: core, definitions: nil, sources: sources)    }    // ── The old screen's own words ──────────────────────────────────────────    /// WHICH FILE this is, never where it is on a disk: the crate answers a    /// word (`shell::file::FileHeld`) and the sentence is written here.    static func heldLine(_ held: String?) -> String {        switch held {        case "replica": return ShellLines.line("activity", "tables.a_copy_on_this")        case "served": return ShellLines.line("activity", "tables.the_file_this_mac")        default: return ShellLines.line("activity", "tables.not_known_yet")        }    }    /// The label for a stopping word, or nil when there is nothing to say:    /// `answered` says nothing under a run that already says Done, and a word    /// the server adds tomorrow is drawn AS ITSELF.    static func stoppedLabel(_ reason: String?) -> String? {        switch reason {        case nil, "", "answered"?: return nil        case "turn_ceiling"?: return ShellLines.line("activity", "tables.stopped_at_its_turn")        case "time_ceiling"?: return ShellLines.line("activity", "tables.stopped_at_its_time")        case "no_key"?: return ShellLines.line("activity", "tables.stopped_no_key_stored")        case "model_refused"?: return ShellLines.line("activity", "tables.the_model_refused")        case let other?: return other        }    }    /// A metered cost as money: two decimals once there is a cent, four    /// below — "$0.00" beside a key the owner pays with reads as free. Null    /// or zero says nothing (nobody costed it, which is not free). Dollars,    /// as `cost_usd` is.    static func costLabel(_ cost: Double?) -> String? {        guard let cost, cost > 0 else { return nil }        return String(format: cost < 0.01 ? "$%.4f" : "$%.2f", cost)    }    /// What a run stopped on and spent, or nil when neither says anything.    static func spentLine(stoppedReason: String?, costUsd: Double?) -> String? {        let parts = [stoppedLabel(stoppedReason), costLabel(costUsd).map { "\($0) spent" }].compactMap { $0 }        return parts.isEmpty ? nil : parts.joined(separator: " \u{00B7} ")    }    // ── Rows ────────────────────────────────────────────────────────────────    /// The `activity` record off `read.activity`'s `replica`.    static func factsRecord(_ replica: JSONValue?) -> TableRecord {        settingsRecord(thisID, [            "title": .text(title),            "workspace_id": .maybe(replica?.text("workspaceId")),            "device_id": .maybe(replica?.text("deviceId")),            "held": .text(heldLine(replica?.text("held"))),            "pending": .number(Double(max(0, replica?.number("pending") ?? 0))),        ])    }    /// One run, its keys as `crates/cotton-ffi/src/phone/activity.rs` writes    /// them. The error is a FAILED run's only — a queued row may carry the    /// no-key sentence while it waits, and the old screen said it only once    /// the run had failed.    static func runRecord(_ run: JSONValue) -> TableRecord {        let state = run.text("state")        return settingsRecord(run.text("id") ?? "", [            "task": .maybe(run.text("task")),            "state": .maybe(state),            "class": .maybe(run.text("class")),            "receipt": .maybe(run.text("receipt")),            "error": state == "failed" ? .maybe(run.text("error")) : nil,            "spent": .maybe(spentLine(stoppedReason: run.text("stoppedReason"), costUsd: run.decimal("costUsd"))),            "turns": .number(Double(run.number("turns") ?? 0)),            "stopped_reason": .maybe(run.text("stoppedReason")),            "cost_usd": .maybe(run.decimal("costUsd")),            "result_note_id": .maybe(run.text("resultNoteId")),            "queued_at": .maybe(run.text("queuedAt")),            "started_at": .maybe(run.text("startedAt")),            "finished_at": .maybe(run.text("finishedAt")),        ])    }    /// One audit line. `ok` absent reads as SUCCEEDED: the crate writes a    /// real boolean on every row, and a key gone missing must not accuse a    /// connection. A connection that is gone leaves `token_name` blank; the    /// line stays.    static func callRecord(_ entry: JSONValue) -> TableRecord {        settingsRecord(entry.text("id") ?? "", [            "tool": .maybe(entry.text("tool")),            "token_name": .maybe(entry.text("tokenName")),            "outcome": .text(entry["ok"]?.bool == false ? "refused" : "ok"),            "args_summary": .maybe(entry.text("argsSummary")),            "created_at": .maybe(entry.text("createdAt")),        ])    }    /// `read.activity`'s answer, asking for as much as it hands up.    static func read(_ core: any CottonCalling) async throws -> JSONValue {        try await core.callJSON(CottonMethod.readActivity, ActivityRequest(limit: runsLimit, auditLimit: auditLimit))    }}/// `read.activity`'s request: both optional, each REFUSED outside its range/// (runs 1…200, audit 1…100) rather than clamped.struct ActivityRequest: Encodable, Sendable {    var args: Args    struct Args: Encodable, Sendable {        var limit: Int?        var auditLimit: Int?    }    init(limit: Int? = nil, auditLimit: Int? = nil) {        args = Args(limit: limit, auditLimit: auditLimit)    }}/// `activity`: one record, what this database is.struct ActivityFactsSource: SettingsTableSource {    let table = ActivityTables.table    func records(_ core: any CottonCalling) async throws -> [TableRecord] {        [ActivityTables.factsRecord(try await ActivityTables.read(core)["replica"])]    }}/// `assistant_run`: the runs, newest first as the read orders them/// (`COALESCE(finished_at, started_at, queued_at)`). Cancel is the one write.struct AssistantRunSource: SettingsTableSource {    let table = "assistant_run"    func records(_ core: any CottonCalling) async throws -> [TableRecord] {        try await ActivityTables.read(core).list("runs").map(ActivityTables.runRecord)    }    /// `{state: cancelled}` is `cancel_run`, and nothing else is written. The    /// row GOES, so the change has no after and no undo; a refusal (a run that    /// is no longer queued) reaches the slip in the crate's own sentence.    func update(_ record: TableRecord, patch: [String: RecordValue], core: any CottonCalling) async throws -> SettingsWrite {        try refuseUnwritable(patch, writable: ["state"])        guard patch["state"]?.text == ActivityTables.cancelled, !record.id.isEmpty else {            throw SettingsRecordsError.refusedValue(table: table, column: "state")        }        _ = try await core.call(            CottonMethod.write,            WriteRequest(tool: "cancel_run", args: .object(["id": .string(record.id)])),            as: WriteAnswer.self        )        return SettingsWrite(before: record, after: nil, undo: nil)    }}/// `assistant_call`: what the connected assistants did here, newest first.struct AssistantCallSource: SettingsTableSource {    let table = "assistant_call"    func records(_ core: any CottonCalling) async throws -> [TableRecord] {        try await ActivityTables.read(core).list("audit").map(ActivityTables.callRecord)    }}/// `/activity`: the `activity` record on its card (`RecordOpening`) — its/// title and "This database" — over the three tables' verbs, built from the/// core once it is here. A pull, or a `data` event naming/// `.activity` (`cotton_assistant_runs`, `cotton_mcp_audit`), reads it all/// again in place.struct ActivityRoute: View {    @Environment(\.cottonCore) private var core    @Environment(\.cottonSync) private var sync    @Environment(\.tableDefinitions) private var definitions    @State private var records: SettingsRecords?    @State private var revision = 0    var body: some View {        Group {            if let records, let definition = definitions[ActivityTables.table] {                RecordOpening(definition: definition, opens: .record(ActivityTables.thisID, nil))                    .environment(\.records, records)                    .environment(\.recordsRevision, revision)                    .refreshable { revision += 1 }            } else if records != nil {                PaperScreen {                    QuietState(title: ShellLines.line("activity", "tables.activity_could_not_be"), message: ShellLines.line("activity", "tables.this_build_has_no"))                }            } else {                PaperScreen { EmptyView() }  // no loader: the rows are local and land next frame            }        }        .task(id: core != nil) {            guard records == nil, let core else { return }            records = ActivityTables.records(core: core)        }        .onChange(of: sync?.revision ?? 0) { _, _ in            guard let sync, sync.invalidated.contains(.activity) else { return }            revision += 1        }    }}