SPB Git

Repository Public

ContextInspectorPanel.swift 13.6 KB 243 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Chat/Panels/ContextInspectorPanel.swift3// Description: Context Inspector tab: model and window, estimated next request with its gauge, tokens measured for the last answer, messages, cost, tools, files, last answer's parameters and routing — every figure with its source.4import SwiftUI5import SPChatCore67/// Loads `GET /api/conversations/{id}/context?model=` for the conversation on screen.8@Observable final class ContextInspectorModel {9    private(set) var report: ContextReport?10    private(set) var isLoading = false11    private(set) var error: String?12    private(set) var conversationId: String?13    @ObservationIgnored private var generation = 01415    func load(conversationId id: String?, modelId: String?, api: APIClient) async {16        if id != conversationId { report = nil; error = nil; conversationId = id }17        guard let id else { isLoading = false; return }18        generation += 1; let mine = generation19        isLoading = true20        do {21            let r = try await api.conversationContext(id, model: modelId)22            guard mine == generation else { return }23            report = r; error = nil24        } catch {25            guard mine == generation, APIError.from(error).kind != .cancelled else { return }26            self.error = APIError.from(error).message27        }28        if mine == generation { isLoading = false }29    }30}3132struct ContextInspectorPanel: View {33    let chat: ChatViewModel34    let model: ContextInspectorModel35    @Environment(AppEnvironment.self) private var env3637    /// Reload when the conversation, the selected model, the number of messages or the streaming state changes.38    private struct Trigger: Hashable { var conversation: String?; var model: String?; var messages: Int; var streaming: Bool }39    private var trigger: Trigger { Trigger(conversation: chat.conversationId, model: chat.settings.modelId, messages: chat.messages.count, streaming: chat.isStreaming) }4041    var body: some View {42        Group {43            if chat.conversationId == nil {44                PanelPlaceholder(systemImage: PanelTab.inspector.systemImage, title: "Nouvelle conversation", message: "Le contexte s'affichera après le premier message.")45            } else if let report = model.report {46                ScrollView { content(report).padding(.bottom, DS.S.xl) }47            } else if let error = model.error {48                PanelPlaceholder(systemImage: "exclamationmark.triangle", title: "Contexte indisponible", message: error, actionTitle: "Réessayer") { Task { await reload() } }49            } else {50                Color.clear.frame(maxWidth: .infinity, maxHeight: .infinity)51            }52        }53        .overlay(alignment: .top) { PanelLoadingLine(active: model.isLoading && model.report == nil) }54        .task(id: trigger) { await reload() }55        .accessibilityIdentifier("panel-inspector")56    }5758    private func reload() async { await model.load(conversationId: chat.conversationId, modelId: chat.settings.modelId, api: env.api) }5960    @ViewBuilder private func content(_ r: ContextReport) -> some View {61        VStack(spacing: 0) {62            if r.streaming || chat.isStreaming { streamingRow }63            if let m = r.model { modelSection(m) }64            if let e = r.estimate { estimateSection(e, window: r.model?.contextWindow) }65            if let m = r.measured { measuredSection(m) }66            conversationSection(r)67            toolsSection(r.tools)68            if !r.files.isEmpty { filesSection(r.files) }69            if let last = chat.displayed.last(where: { $0.role == .assistant }) { lastAnswerSection(last) }70            if let d = chat.detail, !d.attachments.isEmpty { attachmentsSection(d.attachments) }71            if let d = chat.detail, !d.artifacts.isEmpty { artifactsSection(d.artifacts) }72        }73    }7475    private var streamingRow: some View {76        VStack(alignment: .leading, spacing: DS.S.s) {77            Text("Génération en cours").font(DS.F.ui).foregroundStyle(DS.C.text)78            Text("Les mesures seront à jour à la fin de la réponse.").font(DS.F.caption).foregroundStyle(DS.C.muted)79        }80        .frame(maxWidth: .infinity, alignment: .leading)81        .padding(.horizontal, DS.S.xl).padding(.vertical, DS.S.l)82        .overlay(alignment: .bottom) { ZStack(alignment: .bottom) { Hairline(); LumenLine(active: true, cornerInset: 0).frame(height: 2) } }83        .accessibilityElement(children: .combine)84    }8586    private func modelSection(_ m: ContextReport.Model) -> some View {87        PanelSection("Modèle du prochain tour") {88            ModelChip(identity: env.catalog.model(m.id).map { ModelIdentity($0) } ?? identity(m), showCatalogNotice: false)89            if m.status == "catalog" { CatalogNotice(compact: false) }90            PanelRow(label: "Fenêtre de contexte", value: m.contextWindow.map { "\(PanelFormat.int($0)) jetons" } ?? "—")91            if let out = m.maxOutputTokens { PanelRow(label: "Sortie maximale", value: "\(PanelFormat.int(out)) jetons") }92        }93    }9495    /// Identity from the report itself when the model is not in the local catalogue.96    private func identity(_ m: ContextReport.Model) -> ModelIdentity {97        var i = ModelIdentity(unknownId: m.id)98        i.name = m.displayName; if let l = m.logo { i.logo = l }; if let c = m.creatorName { i.creatorName = c }; if let r = m.route { i.route = r }99        i.isCatalogOnly = m.status == "catalog"100        return i101    }102103    private func estimateSection(_ e: ContextReport.Estimate, window: Int?) -> some View {104        PanelSection("Prochaine requête", trailing: { EstimateBadge() }) {105            HStack(alignment: .firstTextBaseline, spacing: DS.S.s) {106                Text("≈ " + PanelFormat.int(e.nextRequestTokens)).font(.system(size: 22, weight: .semibold).monospacedDigit()).foregroundStyle(DS.C.text).contentTransition(.numericText())107                Text("jetons").font(DS.F.uiRegular).foregroundStyle(DS.C.text2)108                Spacer(minLength: 0)109                Text(PanelFormat.percent(e.percentOfContext)).font(DS.F.ui.monospacedDigit()).foregroundStyle(DS.C.text2)110            }111            ContextGauge(fraction: e.fraction ?? 0)112                .accessibilityLabel("Estimation : \(PanelFormat.percent(e.percentOfContext)) de la fenêtre de contexte")113            if let window { Text("de la fenêtre de \(Format.tokens(window)) jetons").font(DS.F.caption).foregroundStyle(DS.C.muted) }114            if let n = e.images, n > 0 { PanelRow(label: "Images", value: "\(n) (non comptées)") }115            SourceNote(text: e.source)116        }117    }118119    private func measuredSection(_ m: ContextReport.Measured) -> some View {120        PanelSection("Mesuré · dernière réponse") {121            Grid(alignment: .leading, horizontalSpacing: DS.S.l, verticalSpacing: DS.S.l) {122                GridRow { SourcedFigure(label: "Entrée", value: PanelFormat.int(m.inputTokens)); SourcedFigure(label: "Sortie", value: PanelFormat.int(m.outputTokens)) }123                GridRow { SourcedFigure(label: "Lus du cache", value: PanelFormat.int(m.cachedTokens)); SourcedFigure(label: "Raisonnement", value: PanelFormat.int(m.reasoningTokens)) }124            }125            if let id = m.model { ModelChip(identity: env.catalog.identity(for: id), markSize: 14, font: DS.F.caption) }126            SourceNote(text: [m.source, m.at.map { PanelFormat.dateTime($0) }].compactMap { $0 }.joined(separator: " · "))127        }128    }129130    private func conversationSection(_ r: ContextReport) -> some View {131        PanelSection("Conversation") {132            PanelRow(label: "Messages", value: messagesValue(r.messages))133            PanelRow(label: "Coût", value: Format.usd(r.cost.conversationUsd))134            SourceNote(text: r.cost.source)135            if let c = chat.conversation {136                PanelRow(label: "Créée", value: PanelFormat.dateTime(c.createdAt))137                if let p = env.catalog.project(c.projectId) { PanelRow(label: "Projet", value: p.name) }138            }139        }140    }141142    private func messagesValue(_ m: ContextReport.MessageCounts) -> String {143        guard let u = m.user, let a = m.assistant else { return PanelFormat.int(m.count) }144        return "\(PanelFormat.int(m.count)) · \(u) question\(u > 1 ? "s" : ""), \(a) réponse\(a > 1 ? "s" : "")"145    }146147    private func toolsSection(_ t: ContextReport.Tools) -> some View {148        PanelSection("Outils", trailing: { Text(t.enabled ? "activés" : "désactivés").font(DS.F.caption).foregroundStyle(t.enabled ? DS.C.ok : DS.C.muted).fixedSize() }) {149            if t.list.isEmpty { Text("Aucun outil déclaré.").font(DS.F.caption).foregroundStyle(DS.C.muted) }150            else {151                FlowLayout(spacing: 5) {152                    ForEach(t.list) { tool in153                        Text(tool.name).font(DS.F.mono(10.5)).foregroundStyle(t.enabled ? DS.C.text2 : DS.C.muted)154                            .padding(.horizontal, 6).padding(.vertical, 2.5)155                            .background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.chip, style: .continuous))156                            .help(env.catalog.tool(tool.name)?.description ?? tool.category ?? tool.name)157                    }158                }159                .opacity(t.enabled ? 1 : 0.7)160            }161        }162    }163164    private func filesSection(_ files: [ContextReport.File]) -> some View {165        PanelSection("Fichiers dans le contexte (\(files.count))") {166            ForEach(files) { f in167                FileLine(name: f.filename, detail: [Format.bytes(f.sizeBytes), f.pageCount.map { "\($0) p." }, f.chars.map { "\(PanelFormat.int($0)) car." }, f.tokens.map { "≈ \(Format.tokens($0)) jetons" }].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · "))168            }169        }170    }171172    private func lastAnswerSection(_ last: Message) -> some View {173        PanelSection("Dernière réponse") {174            if let id = last.modelId { ModelChip(identity: env.catalog.identity(for: id), markSize: 14, font: DS.F.caption) }175            if let served = last.routing?.servedBy { PanelRow(label: "Servi par", value: served) }176            if let reason = last.routing?.reason { Text(reason).font(DS.F.caption).foregroundStyle(DS.C.text2).fixedSize(horizontal: false, vertical: true) }177            if let ttft = last.ttftMs { PanelRow(label: "Premier jeton", value: Format.duration(ms: ttft)) }178            if let ms = last.latencyMs { PanelRow(label: "Durée", value: Format.duration(ms: ms)) }179            if last.modelId?.hasPrefix("local:") == true { PanelRow(label: "Coût", value: "local · 0 $") }180            else if let cost = last.costUsd { PanelRow(label: "Coût \(PanelFormat.costBasis(exact: last.isCostExact))", value: Format.usd(cost)) }181            if let ap = last.appliedParameters {182                ForEach(ap.applied.sorted { $0.key < $1.key }, id: \.key) { k, v in PanelRow(label: k, value: v.stringValue ?? v.jsonString()) }183                ForEach(ap.ignored, id: \.param) { i in184                    VStack(alignment: .leading, spacing: 1) {185                        Label("\(i.param) ignoré", systemImage: "exclamationmark.triangle").font(DS.F.caption).foregroundStyle(DS.C.warn)186                        Text(i.reason).font(.system(size: 10.5)).foregroundStyle(DS.C.muted).fixedSize(horizontal: false, vertical: true)187                    }188                    .accessibilityElement(children: .combine)189                }190            }191        }192    }193194    private func attachmentsSection(_ atts: [Attachment]) -> some View {195        PanelSection("Pièces jointes (\(atts.count))") { ForEach(atts) { a in FileLine(name: a.filename, detail: Format.bytes(a.sizeBytes)) } }196    }197198    private func artifactsSection(_ arts: [Artifact]) -> some View {199        PanelSection("Artefacts (\(arts.count))") { ForEach(arts) { a in FileLine(name: a.title, detail: "v\(a.version)", systemImage: ArtifactIcon.name(a.type)) } }200    }201}202203/// « estimation » — said next to every computed (not measured) figure.204struct EstimateBadge: View {205    var body: some View {206        Text("ESTIMATION").font(.system(size: 9, weight: .semibold)).tracking(0.5).foregroundStyle(DS.C.warn)207            .padding(.horizontal, 5).padding(.vertical, 1.5).overlay(Capsule().strokeBorder(DS.C.warn.opacity(0.45), lineWidth: 1)).fixedSize()208            .help("Valeur calculée par le serveur, pas une mesure du fournisseur.").accessibilityLabel("estimation")209    }210}211212/// Share of the context window used by the next request. Iris until 75 %, then warning and danger.213struct ContextGauge: View {214    let fraction: Double215    private var color: Color { fraction >= 0.9 ? DS.C.danger : (fraction >= 0.75 ? DS.C.warn : DS.C.accent) }216    var body: some View {217        GeometryReader { geo in218            ZStack(alignment: .leading) {219                Capsule().fill(DS.C.surface2)220                // a non-zero share stays visible even when it is a fraction of a percent221                Capsule().fill(color).frame(width: fraction > 0 ? max(4, geo.size.width * fraction) : 0)222            }223        }224        .frame(height: 4)225        .motion(DS.Motion.smooth, value: fraction)226    }227}228229struct FileLine: View {230    let name: String231    var detail: String = ""232    var systemImage: String?233    var body: some View {234        HStack(spacing: DS.S.s) {235            Image(systemName: systemImage ?? FileIcon.name(for: name)).font(.system(size: 11)).foregroundStyle(DS.C.muted).frame(width: 16)236            Text(name).font(DS.F.uiRegular).foregroundStyle(DS.C.text).lineLimit(1).truncationMode(.middle)237            Spacer(minLength: DS.S.s)238            if !detail.isEmpty { Text(detail).font(DS.F.caption.monospacedDigit()).foregroundStyle(DS.C.muted).lineLimit(1).fixedSize() }239        }240        .help(name).accessibilityElement(children: .combine)241    }242}243
Files main
Menu

Theme