SPB Git

Repository Public

ResearchInsight.swift 27.7 KB 485 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Research/ResearchInsight.swift3// Description: What an answer says about itself: the model the router chose and why, tokens and cost (never guessed), provenance of the tools that really ran, the execution trace of a generation, and the approvals the research agent asks for.4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89private typealias P = VQTokens.Palette10private typealias T = VQTokens.Typography1112/// Numbers of this feature are written the English-Canadian way (the app's interface language).13enum RFmt {14    static func tokens(_ n: Int) -> String { VQFormat.tokens(n, locale: .enCA) }15    /// A cost the server stated. Small amounts keep their cents of a cent.16    static func usd(_ v: Double) -> String { v == 0 ? "$0.00" : v < 0.01 ? String(format: "$%.4f", v) : String(format: "$%.2f", v) }17    static func ms(_ v: Double?) -> String {18        guard let v else { return "—" }19        return v < 1000 ? "\(Int(v.rounded())) ms" : v < 60_000 ? String(format: "%.1f s", v / 1000) : "\(Int(v / 60_000)) min \(Int((v.truncatingRemainder(dividingBy: 60_000)) / 1000)) s"20    }21    /// What a usage object states about cost, in words: a total, or "not priced" with the part that is known.22    static func cost(_ c: VQUsageCounters) -> String {23        if let v = c.costUsd { return usd(v) }24        if let k = c.knownCostUsd, k > 0 { return "not priced · known \(usd(k))" }25        return "not priced"26    }27}2829/// `Auto → model` with the router's sentence; the candidates it scored on demand.30struct RouteLine: View {31    let app: AppEnvironment32    let requested: String?33    let route: VQRouteDecision?34    let waiting: Bool35    @State private var showCandidates = false3637    var body: some View {38        if let route {39            HStack(alignment: .firstTextBaseline, spacing: 6) {40                Text("Auto").font(T.overline.f).tracking(0.9).foregroundStyle(P.accentText)41                Image(systemName: "arrow.right").font(.system(size: 9, weight: .semibold)).foregroundStyle(P.text3)42                VQProviderLogo(provider: route.provider, size: 12)43                Text(app.studies.modelLabel(route.model)).font(T.bodySm.f.weight(.semibold)).foregroundStyle(P.text1)44                Text(route.reason).font(T.caption.f).foregroundStyle(P.text2).lineLimit(2).help(route.reason)45                if !route.candidates.isEmpty {46                    Button("Candidates") { showCandidates = true }.buttonStyle(.link).font(T.caption.f)47                        .accessibilityIdentifier("route.candidates")48                        .popover(isPresented: $showCandidates, arrowEdge: .bottom) { candidates(route).vqTheme(app.vqTheme) }49                }50            }51            .accessibilityElement(children: .contain).accessibilityIdentifier("route.line")52        } else if requested == "auto", waiting {53            HStack(spacing: 6) {54                Text("Auto").font(T.overline.f).tracking(0.9).foregroundStyle(P.accentText)55                Text("the server is choosing a model…").font(T.caption.f).foregroundStyle(P.text3)56            }57        }58    }5960    private func candidates(_ r: VQRouteDecision) -> some View {61        VStack(alignment: .leading, spacing: 10) {62            VStack(alignment: .leading, spacing: 2) {63                Text("Router decision").font(T.heading.f)64                Text("Strategy: \(r.strategy). Scores are the router's own; nothing was run to compute them.").font(T.caption.f).foregroundStyle(P.text2)65            }66            VStack(alignment: .leading, spacing: 0) {67                ForEach(Array(r.candidates.enumerated()), id: \.offset) { i, c in68                    HStack(alignment: .firstTextBaseline, spacing: 10) {69                        Text(c.score.map { String(format: "%.3f", $0) } ?? "—").font(T.numSm.f).foregroundStyle(c.model == r.model ? P.accentText : P.text2).frame(width: 44, alignment: .trailing)70                        VStack(alignment: .leading, spacing: 1) {71                            Text(app.studies.modelLabel(c.model)).font(T.bodySm.f.weight(c.model == r.model ? .semibold : .regular))72                            Text(c.why).font(T.caption.f).foregroundStyle(P.text2).fixedSize(horizontal: false, vertical: true)73                        }74                        Spacer(minLength: 0)75                    }76                    .padding(.vertical, 6)77                    if i < r.candidates.count - 1 { Rectangle().fill(P.line).frame(height: 1) }78                }79            }80        }81        .padding(14).frame(width: 440)82    }83}8485/// Tokens and cost of an answer, as the `done` event or the stored message stated them. A click shows each model.86struct UsageLine: View {87    let app: AppEnvironment88    let usage: VQUsage?89    let model: String?90    @State private var open = false9192    var body: some View {93        if let usage {94            Button { open = true } label: {95                HStack(spacing: 6) {96                    if let model, let p = app.studies.provider(of: model) { VQProviderLogo(provider: p, size: 11) }97                    if let model { Text(app.studies.modelLabel(model)).foregroundStyle(P.text2) }98                    Text("\(RFmt.tokens(usage.inputTokens)) in · \(RFmt.tokens(usage.outputTokens)) out").foregroundStyle(P.text3)99                    Text(RFmt.cost(usage.counters)).foregroundStyle(usage.costUsd == nil ? P.warn : P.text2)100                }101                .font(T.numSm.f).contentShape(Rectangle())102            }103            .buttonStyle(.plain).help("Tokens and cost reported by the server for this answer. Click for each model.")104            .accessibilityIdentifier("usage.line")105            .popover(isPresented: $open, arrowEdge: .bottom) { breakdown(usage).vqTheme(app.vqTheme) }106        } else if let model {107            HStack(spacing: 6) {108                if let p = app.studies.provider(of: model) { VQProviderLogo(provider: p, size: 11) }109                Text(app.studies.modelLabel(model)).font(T.numSm.f).foregroundStyle(P.text3)110            }111        }112    }113114    private func breakdown(_ u: VQUsage) -> some View {115        VStack(alignment: .leading, spacing: 10) {116            Text("Usage of this answer").font(T.heading.f)117            Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 5) {118                GridRow {119                    ForEach(["Model", "Role", "Calls", "Input", "Output", "Cost"], id: \.self) { Text($0).font(T.overline.f).tracking(0.9).foregroundStyle(P.text3) }120                }121                Rectangle().fill(P.line).frame(height: 1).gridCellColumns(6)122                ForEach(Array(u.byModel.enumerated()), id: \.offset) { _, m in123                    GridRow {124                        HStack(spacing: 5) { VQProviderLogo(provider: m.provider, size: 11); Text(app.studies.modelLabel(m.model)).font(T.bodySm.f) }125                        Text(m.role?.rawValue ?? "—").font(T.caption.f).foregroundStyle(P.text2)126                        Text(m.counters.calls.map(String.init) ?? "—").font(T.numSm.f).gridColumnAlignment(.trailing)127                        Text(RFmt.tokens(m.counters.inputTokens)).font(T.numSm.f).gridColumnAlignment(.trailing)128                        Text(RFmt.tokens(m.counters.outputTokens)).font(T.numSm.f).gridColumnAlignment(.trailing)129                        Text(m.counters.costUsd.map(RFmt.usd) ?? "not priced").font(T.numSm.f).foregroundStyle(m.counters.costUsd == nil ? P.warn : P.text1).gridColumnAlignment(.trailing)130                    }131                }132                Rectangle().fill(P.line).frame(height: 1).gridCellColumns(6)133                GridRow {134                    Text("Total").font(T.bodySm.f.weight(.semibold)); Text(""); Text("")135                    Text(RFmt.tokens(u.inputTokens)).font(T.numSm.f.weight(.medium))136                    Text(RFmt.tokens(u.outputTokens)).font(T.numSm.f.weight(.medium))137                    Text(u.costUsd.map(RFmt.usd) ?? "not priced").font(T.numSm.f.weight(.medium)).foregroundStyle(u.costUsd == nil ? P.warn : P.text1)138                }139            }140            if u.costUsd == nil {141                Text("At least one call has no known price, so no total is given. \(u.counters.knownCostUsd.map { "Calls that have a price add up to \(RFmt.usd($0))." } ?? "")")142                    .font(T.caption.f).foregroundStyle(P.text2).fixedSize(horizontal: false, vertical: true)143            } else {144                Text("Computed by the server from its price table at the time of each call.").font(T.caption.f).foregroundStyle(P.text3)145            }146        }147        .padding(14).frame(minWidth: 460)148    }149}150151/// Where the data of an answer came from: one line per tool that really ran, for a set of symbols.152struct ProvenanceButton: View {153    let app: AppEnvironment154    let sources: [VQProvenanceSource]155    @State private var open = false156157    var body: some View {158        if !sources.isEmpty {159            Button { open = true } label: {160                Label("Provenance · \(sources.count)", systemImage: "checkmark.seal").font(T.caption.f).foregroundStyle(P.text2)161            }162            .buttonStyle(.plain).help("The tools and providers this answer's data came from")163            .accessibilityIdentifier("provenance.button")164            .popover(isPresented: $open, arrowEdge: .bottom) { list.vqTheme(app.vqTheme) }165        }166    }167168    private var list: some View {169        VStack(alignment: .leading, spacing: 10) {170            VStack(alignment: .leading, spacing: 2) {171                Text("Provenance").font(T.heading.f)172                Text("Built by the server from the tool calls that actually ran (lead and sub-analysts).").font(T.caption.f).foregroundStyle(P.text2)173            }174            ScrollView {175                VStack(alignment: .leading, spacing: 0) {176                    ForEach(Array(sources.enumerated()), id: \.offset) { i, s in177                        HStack(alignment: .firstTextBaseline, spacing: 10) {178                            Image(systemName: s.ok ? "checkmark.circle" : "xmark.circle").font(.system(size: 11)).foregroundStyle(s.ok ? app.settings.upColor : P.critical)179                                .accessibilityLabel(s.ok ? "at least one call succeeded" : "no call succeeded")180                            VStack(alignment: .leading, spacing: 2) {181                                Text(s.tool).font(.system(size: 12, weight: .medium, design: .monospaced)).foregroundStyle(P.text1)182                                if !s.symbols.isEmpty { Text(s.symbols.joined(separator: " · ")).font(T.numSm.f).foregroundStyle(P.text2).lineLimit(2) }183                            }184                            Spacer(minLength: 8)185                            VStack(alignment: .trailing, spacing: 2) {186                                Text(s.provider.rawValue).font(T.overline.f).tracking(0.9).foregroundStyle(P.text2)187                                Text("\(s.calls) call\(s.calls == 1 ? "" : "s") · \(s.retrievedAt.map { Fmt.dateTime($0) } ?? "time not stated")").font(T.numSm.f).foregroundStyle(P.text3)188                            }189                        }190                        .padding(.vertical, 7)191                        if i < sources.count - 1 { Rectangle().fill(P.line).frame(height: 1) }192                    }193                }194            }195            .frame(maxHeight: 340)196        }197        .padding(14).frame(width: 460)198    }199}200201/// The execution trace of a generation (`GET /api/v2/generations/:id/trace`): only what really ran.202struct TraceSheet: View {203    let app: AppEnvironment204    /// A generation id, or nil with a conversation id for its latest generation.205    let generationId: String?206    let sessionId: String?207    @Environment(\.dismiss) private var dismiss208    @State private var trace: VQGenerationTrace?209    @State private var failure: String?210    @State private var cachedAt: Date?211212    var body: some View {213        VStack(alignment: .leading, spacing: 0) {214            HStack(alignment: .firstTextBaseline) {215                VStack(alignment: .leading, spacing: 2) {216                    Text("Execution trace").font(T.title.f)217                    Text(trace.map { "Generation \($0.generationId)" } ?? "Reading the trace…").font(T.numSm.f).foregroundStyle(P.text3).textSelection(.enabled)218                }219                Spacer()220                if let cachedAt { Label("Cached \(Fmt.relative(cachedAt))", systemImage: "internaldrive").font(T.caption.f).foregroundStyle(P.warn) }221                Button("Done") { dismiss() }.keyboardShortcut(.defaultAction).accessibilityIdentifier("trace.done")222            }223            .padding(.horizontal, 20).padding(.vertical, 14)224            Rectangle().fill(P.line).frame(height: 1)225            if let t = trace { ScrollView { content(t).padding(20) } }226            else if let failure { VQEmptyState(systemImage: "exclamationmark.triangle", title: "No trace for this answer", message: failure).frame(maxWidth: .infinity, maxHeight: .infinity) }227            else { VStack(alignment: .leading, spacing: 16) { VQSkeletonText(lines: 3); VQSkeletonRows(rows: 8, columns: 5) }.padding(20).frame(maxHeight: .infinity, alignment: .top) }228        }229        .frame(width: 760, height: 640)230        .background(P.ink0)231        .task { await load() }232    }233234    private func load() async {235        #if DEBUG236        if let f = app.studies.fixture { trace = VQGenerationTrace(json: f.trace); return }237        #endif238        do {239            let vq = app.vq, gid = generationId, sid = sessionId240            let r = try await app.research.cachedJSON("trace-\(gid ?? "latest")-\(sid ?? "")") {241                try await vq.client.json(.get("/api/v2/generations/\(VQRequest.segment(gid ?? "latest"))/trace", gid == nil ? VQQueryItem.optional("sessionId", sid) : []))242            }243            trace = VQGenerationTrace(json: r.value); cachedAt = r.fromCache ? r.fetchedAt : nil244        } catch let e as VQError where e.kind == .notFound { failure = "The server keeps no trace of this generation (answers produced before backend 6 have none)." }245        catch { failure = error.localizedDescription }246    }247248    private func tile(_ label: String, _ value: String, tone: Color = P.text1) -> some View {249        VStack(alignment: .leading, spacing: 3) {250            Text(label).font(T.overline.f).tracking(0.9).foregroundStyle(P.text3)251            Text(value).font(T.numMd.f).foregroundStyle(tone).lineLimit(1).minimumScaleFactor(0.7)252        }253        .frame(maxWidth: .infinity, alignment: .leading)254    }255256    @ViewBuilder private func content(_ t: VQGenerationTrace) -> some View {257        let failed = t.toolCalls.filter { !$0.ok }.count258        let duration: Double? = t.startedAt.flatMap { s in t.finishedAt.map { $0.timeIntervalSince(s) * 1000 } }259        VStack(alignment: .leading, spacing: 22) {260            HStack(alignment: .top, spacing: 16) {261                tile("Status", t.status.rawValue.capitalized, tone: t.status == .error ? P.critical : P.text1)262                tile("Mode", t.mode.flatMap { ResearchMode(rawValue: $0)?.title } ?? t.mode ?? "—")263                tile("Model", app.studies.modelLabel(t.model))264                tile("Duration", RFmt.ms(duration))265                tile("Tool calls", failed > 0 ? "\(t.toolCalls.count) · \(failed) failed" : "\(t.toolCalls.count)", tone: failed > 0 ? P.warn : P.text1)266                tile("Cost", t.usage.map { RFmt.cost($0.counters) } ?? "not stated")267            }268            if let req = t.requestedModel, req != t.model {269                Text("Requested: \(app.studies.modelLabel(req)) — the server ran \(app.studies.modelLabel(t.model)).").font(T.caption.f).foregroundStyle(P.text2)270            }271            if let s = t.startedAt { Text("Started \(Fmt.dateTime(s))\(t.finishedAt.map { " · finished \(Fmt.dateTime($0))" } ?? " · still running")").font(T.caption.f).foregroundStyle(P.text3) }272273            if !t.plan.isEmpty {274                section("Plan") {275                    VStack(alignment: .leading, spacing: 5) {276                        ForEach(Array(t.plan.enumerated()), id: \.offset) { _, step in277                            Label { Text(step.title).font(T.bodySm.f) } icon: {278                                Image(systemName: step.status == "done" ? "checkmark.circle.fill" : step.status == "in_progress" ? "circle.dotted.circle" : "circle")279                                    .foregroundStyle(step.status == "done" ? app.settings.upColor : step.status == "in_progress" ? P.accentText : P.text3)280                            }281                        }282                    }283                }284            }285            if !t.agents.isEmpty {286                section("Agents") {287                    Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 6) {288                        GridRow { ForEach(["Agent", "Role", "Status", "Tools", "Duration"], id: \.self) { Text($0).font(T.overline.f).tracking(0.9).foregroundStyle(P.text3) } }289                        ForEach(t.agents) { a in290                            GridRow {291                                Text(a.name).font(T.bodySm.f)292                                Text((a.role ?? a.kind ?? "—").replacingOccurrences(of: "_", with: " ")).font(T.caption.f).foregroundStyle(P.text2)293                                Text(a.status.rawValue).font(T.caption.f).foregroundStyle(a.status == .failed ? P.critical : P.text2)294                                Text(a.toolCount.map(String.init) ?? "—").font(T.numSm.f)295                                Text(RFmt.ms(a.durationMs)).font(T.numSm.f)296                            }297                        }298                    }299                }300            }301            if !t.budget.isEmpty {302                section("Budget") {303                    VStack(alignment: .leading, spacing: 4) {304                        ForEach(Array(t.budget.enumerated()), id: \.offset) { _, b in BudgetNote(event: b) }305                    }306                }307            }308            if let u = t.usage, !u.byModel.isEmpty {309                section("Usage") {310                    VStack(alignment: .leading, spacing: 4) {311                        ForEach(Array(u.byModel.enumerated()), id: \.offset) { _, m in312                            HStack(spacing: 8) {313                                VQProviderLogo(provider: m.provider, size: 11)314                                Text(app.studies.modelLabel(m.model)).font(T.bodySm.f)315                                Text(m.role?.rawValue ?? "").font(T.caption.f).foregroundStyle(P.text3)316                                Spacer()317                                Text("\(m.counters.calls.map { "\($0) calls · " } ?? "")\(RFmt.tokens(m.counters.inputTokens)) in · \(RFmt.tokens(m.counters.outputTokens)) out · \(m.counters.costUsd.map(RFmt.usd) ?? "not priced")").font(T.numSm.f).foregroundStyle(P.text2)318                            }319                        }320                    }321                }322            }323            section("Tool calls · \(t.toolCalls.count)") {324                if t.toolCalls.isEmpty { Text("No tool call was recorded for this generation.").font(T.bodySm.f).foregroundStyle(P.text3) }325                else {326                    let slowest = max(1, t.toolCalls.compactMap(\.ms).max() ?? 1)327                    VStack(alignment: .leading, spacing: 0) {328                        ForEach(Array(t.toolCalls.enumerated()), id: \.offset) { i, c in329                            HStack(alignment: .firstTextBaseline, spacing: 10) {330                                Text(offset(c.at, from: t.startedAt)).font(T.numSm.f).foregroundStyle(P.text3).frame(width: 58, alignment: .trailing)331                                Image(systemName: c.ok ? "checkmark" : "xmark").font(.system(size: 9, weight: .bold)).foregroundStyle(c.ok ? app.settings.upColor : P.critical).frame(width: 12)332                                    .accessibilityLabel(c.ok ? "succeeded" : "failed")333                                VStack(alignment: .leading, spacing: 2) {334                                    HStack(spacing: 6) {335                                        Text(c.tool).font(.system(size: 12, design: .monospaced)).foregroundStyle(P.text1)336                                        if let a = c.agent, a != "lead" { Text(a).font(T.caption.f).foregroundStyle(P.text3) }337                                    }338                                    if let e = c.error, !e.isEmpty { Text(e).font(T.caption.f).foregroundStyle(P.critical).lineLimit(3) }339                                }340                                Spacer(minLength: 8)341                                // the bar is the share of the slowest call: a reading aid, not a measurement of its own342                                Capsule().fill(P.ink4).frame(width: 90, height: 3).overlay(alignment: .leading) { Capsule().fill(c.ok ? P.text3 : P.critical).frame(width: max(2, 90 * (c.ms ?? 0) / slowest), height: 3) }343                                Text(RFmt.ms(c.ms)).font(T.numSm.f).foregroundStyle(P.text2).frame(width: 64, alignment: .trailing)344                            }345                            .padding(.vertical, 5)346                            if i < t.toolCalls.count - 1 { Rectangle().fill(P.line.opacity(0.6)).frame(height: 1) }347                        }348                    }349                }350            }351        }352    }353354    private func offset(_ at: Date?, from start: Date?) -> String {355        guard let at, let start else { return "—" }356        let s = max(0, at.timeIntervalSince(start))357        return String(format: "+%d:%02d", Int(s) / 60, Int(s) % 60)358    }359360    private func section<C: View>(_ title: String, @ViewBuilder _ content: () -> C) -> some View {361        VStack(alignment: .leading, spacing: 10) {362            VStack(alignment: .leading, spacing: 6) {363                Text(title).font(T.overline.f).tracking(0.9).foregroundStyle(P.text3)364                Rectangle().fill(P.line).frame(height: 1)365            }366            content()367        }368    }369}370371/// A budget of the generation was reached: the agent was told to conclude.372struct BudgetNote: View {373    let event: VQBudgetEvent374    var body: some View {375        let cost = event.kind == .cost376        let spent = event.spent.map { cost ? RFmt.usd($0) : "\(Int($0.rounded())) min" } ?? "—"377        let limit = event.limit.map { cost ? RFmt.usd($0) : "\(Int($0.rounded())) min" } ?? "—"378        Label("\(cost ? "Cost" : "Time") budget reached: \(spent) of \(limit). The agent was asked to conclude.", systemImage: "gauge.with.dots.needle.100percent")379            .font(T.caption.f).foregroundStyle(P.warn)380    }381}382383// MARK: - Approvals (CONTRACT §9.7)384385/// The agent waits for an answer: the shared kit's approval card in the conversation, above the composer (what, why,386/// the time left, the two answers), with the full sheet one click away.387struct ApprovalBanner: View {388    let app: AppEnvironment389    var body: some View {390        let pending = app.research.pendingApprovals391        if !pending.isEmpty {392            VStack(alignment: .trailing, spacing: 6) {393                ForEach(pending) { a in394                    ResearchApprovalCard(a, onApprove: { Task { await app.research.answer(a, .approve) } }, onRefuse: { Task { await app.research.answer(a, .deny) } })395                    Button("Details…") { app.research.presentedApproval = a }.buttonStyle(.link).font(T.caption.f).accessibilityIdentifier("approval.review")396                }397            }398            .padding(.horizontal, 20).padding(.vertical, 8)399            .background(P.ink0)400            .overlay(alignment: .top) { Rectangle().fill(P.line).frame(height: 1) }401        }402    }403}404405/// The request in full: what, why, the detail, what saying yes authorises, how long is left — and the two answers.406struct ApprovalSheet: View {407    let app: AppEnvironment408    let approval: VQResearchApproval409    @Environment(\.dismiss) private var dismiss410    @State private var busy = false411412    private var symbol: String {413        switch approval.action.known { case .openNetwork?: "network"; case .sendData?: "arrow.up.forward.app"; case .raiseBudget?: "gauge.with.dots.needle.100percent"; default: "hand.raised" }414    }415416    var body: some View {417        VStack(alignment: .leading, spacing: 0) {418            HStack(alignment: .top, spacing: 14) {419                Image(systemName: symbol).font(.system(size: 22, weight: .medium)).foregroundStyle(P.accentText).frame(width: 40, height: 40)420                    .background(P.accent.opacity(0.12), in: RoundedRectangle(cornerRadius: 10, style: .continuous))421                VStack(alignment: .leading, spacing: 4) {422                    Text("AUTHORISATION REQUESTED").font(T.overline.f).tracking(0.9).foregroundStyle(P.text3)423                    Text(approval.title(.en)).font(T.title.f).foregroundStyle(P.text1).fixedSize(horizontal: false, vertical: true)424                }425            }426            .padding(.bottom, 16)427428            block("Why the agent asks") { Text(approval.reason ?? "The agent gave no reason.").font(T.bodySm.f).foregroundStyle(approval.reason == nil ? P.text3 : P.text1).textSelection(.enabled) }429            let details = approval.details(.en, locale: .enCA)430            if !details.isEmpty {431                block("Detail") {432                    VStack(alignment: .leading, spacing: 4) {433                        ForEach(Array(details.enumerated()), id: \.offset) { _, d in434                            HStack(alignment: .firstTextBaseline) {435                                Text(d.label).font(T.caption.f).foregroundStyle(P.text2).frame(width: 150, alignment: .leading)436                                Text(d.value).font(T.numSm.f).foregroundStyle(P.text1).textSelection(.enabled)437                            }438                        }439                    }440                }441            }442            block("What approving authorises") { Text(approval.scope(.en)).font(T.bodySm.f).foregroundStyle(P.text1) }443444            TimelineView(.periodic(from: .now, by: 1)) { ctx in445                let c = approval.countdown(now: ctx.date)446                VStack(alignment: .leading, spacing: 6) {447                    HStack {448                        Text(c.expired ? "This request has expired: it counts as refused." : "Without an answer the request is refused in").font(T.caption.f).foregroundStyle(c.expired ? P.critical : P.text2)449                        if !c.expired { Text(c.label).font(T.numSm.f.weight(.medium)).foregroundStyle(c.urgent ? P.critical : P.text1) }450                        Spacer()451                    }452                    GeometryReader { g in453                        Capsule().fill(P.ink4).overlay(alignment: .leading) { Capsule().fill(c.urgent || c.expired ? P.critical : P.accent).frame(width: g.size.width * (1 - c.elapsedShare)) }454                    }455                    .frame(height: 3).accessibilityHidden(true)456                }457                .padding(.top, 4).padding(.bottom, 18)458                HStack {459                    Text("Your answer is recorded in the audit trail.").font(T.caption.f).foregroundStyle(P.text3)460                    Spacer()461                    Button("Later") { app.research.presentedApproval = nil; dismiss() }.help("Leaves the request pending; it stays in the conversation.")462                        .accessibilityIdentifier("approval.later")463                    Button("Deny", role: .destructive) { answer(.deny) }.disabled(busy || c.expired).accessibilityIdentifier("approval.deny")464                    Button("Approve") { answer(.approve) }.buttonStyle(.borderedProminent).tint(P.accent).disabled(busy || c.expired).accessibilityIdentifier("approval.approve")465                }466            }467        }468        .padding(22).frame(width: 520)469        .background(P.ink1)470    }471472    private func answer(_ d: VQResearchApproval.Decision) {473        busy = true474        Task { await app.research.answer(approval, d); busy = false; dismiss() }475    }476477    private func block<C: View>(_ title: String, @ViewBuilder _ content: () -> C) -> some View {478        VStack(alignment: .leading, spacing: 5) {479            Text(title).font(T.overline.f).tracking(0.9).foregroundStyle(P.text3)480            content().frame(maxWidth: .infinity, alignment: .leading)481        }482        .padding(.bottom, 14)483    }484}485
Files main
Menu

Theme