// `/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.importCottonKitimportCottonValuesimportSwiftUIpublicenumActivityTables {/// The one record of `activity`: this database, as this device reads it.publicstaticlet 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.staticlet table = "activity"staticlet title = "Activity"/// The value a run's state is written with to take it out of the queue.staticlet 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.staticlet runsLimit = 200staticlet auditLimit = 100/// The three sources, made afresh for each store.staticvar sources: [any SettingsTableSource] { [ActivityFactsSource(), AssistantRunSource(), AssistantCallSource()] }/// The records verbs for the three tables, over the core the app holds,/// drawing the database's catalogue.staticfunc 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.staticfunc heldLine(_ held: String?) -> String {switch held {case"replica": returnShellLines.line("activity", "tables.a_copy_on_this")case"served": returnShellLines.line("activity", "tables.the_file_this_mac")default: returnShellLines.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.staticfunc stoppedLabel(_ reason: String?) -> String? {switch reason {casenil, "", "answered"?: returnnilcase"turn_ceiling"?: returnShellLines.line("activity", "tables.stopped_at_its_turn")case"time_ceiling"?: returnShellLines.line("activity", "tables.stopped_at_its_time")case"no_key"?: returnShellLines.line("activity", "tables.stopped_no_key_stored")case"model_refused"?: returnShellLines.line("activity", "tables.the_model_refused")caselet 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.staticfunc costLabel(_ cost: Double?) -> String? {guardlet cost, cost > 0else { returnnil }returnString(format: cost < 0.01 ? "$%.4f" : "$%.2f", cost) }/// What a run stopped on and spent, or nil when neither says anything.staticfunc 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`.staticfunc 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.staticfunc 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.staticfunc 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.staticfunc read(_ core: any CottonCalling) asyncthrows -> JSONValue {tryawait 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.structActivityRequest: Encodable, Sendable {var args: ArgsstructArgs: 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.structActivityFactsSource: SettingsTableSource {let table = ActivityTables.tablefunc records(_ core: any CottonCalling) asyncthrows -> [TableRecord] { [ActivityTables.factsRecord(tryawaitActivityTables.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.structAssistantRunSource: SettingsTableSource {let table = "assistant_run"func records(_ core: any CottonCalling) asyncthrows -> [TableRecord] {tryawaitActivityTables.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) asyncthrows -> SettingsWrite {try refuseUnwritable(patch, writable: ["state"])guard patch["state"]?.text == ActivityTables.cancelled, !record.id.isEmpty else {throwSettingsRecordsError.refusedValue(table: table, column: "state") } _ = tryawait core.call(CottonMethod.write,WriteRequest(tool: "cancel_run", args: .object(["id": .string(record.id)])),as: WriteAnswer.self )returnSettingsWrite(before: record, after: nil, undo: nil) }}/// `assistant_call`: what the connected assistants did here, newest first.structAssistantCallSource: SettingsTableSource {let table = "assistant_call"func records(_ core: any CottonCalling) asyncthrows -> [TableRecord] {tryawaitActivityTables.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.structActivityRoute: View { @Environment(\.cottonCore) privatevar core @Environment(\.cottonSync) privatevar sync @Environment(\.tableDefinitions) privatevar definitions @State privatevar records: SettingsRecords? @State privatevar revision = 0var body: someView {Group {iflet records, let definition = definitions[ActivityTables.table] {RecordOpening(definition: definition, opens: .record(ActivityTables.thisID, nil)) .environment(\.records, records) .environment(\.recordsRevision, revision) .refreshable { revision += 1 } } elseif 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) { _, _ inguardlet sync, sync.invalidated.contains(.activity) else { return } revision += 1 } }}