Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Features/Panels/ContextSheet.swift4// Description: Context Inspector — what the next request of a conversation will carry: an estimate (labelled as one),5// the figures measured on the last answer, messages, files, tools and cost, each with its source.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import SwiftUI1213struct ContextSheet: View {14 let session: ChatSession15 @Environment(AppEnvironment.self) private var env16 @Environment(\.dismiss) private var dismiss17 @Environment(\.accessibilityReduceMotion) private var reduceMotion18 @State private var report: ContextReport?19 @State private var error: String?20 @State private var shown = 0.02122 var body: some View {23 VStack(spacing: 0) {24 SheetHeader(title: String(localized: "Inspecteur de contexte"), subtitle: String(localized: "Ce que portera la prochaine requête de cette conversation."), onClose: { dismiss() })25 ScrollView {26 VStack(alignment: .leading, spacing: 14) {27 if let r = report {28 gauge(r)29 if r.measuredSource != nil || r.measuredInput != nil { measured(r) }30 composition(r)31 if !r.files.isEmpty { files(r) }32 tools(r)33 cost(r)34 } else if let error {35 ContentUnavailableView { Label("Contexte indisponible", systemImage: "wifi.slash") } description: { Text(error) } actions: { Button("Réessayer") { Task { await load() } } }36 } else { HStack { Spacer(); ProgressView().padding(.top, 60); Spacer() } }37 }38 .padding(.horizontal, 16).padding(.top, 8).padding(.bottom, 24)39 }40 }41 .background(Color.appBackground)42 .task { await load() }43 .refreshable { await load() }44 }4546 private func load() async {47 guard let id = session.conversationId else { error = String(localized: "La conversation n’a pas encore de message."); return }48 do {49 let r = try await env.api.context(conversation: id, model: env.sendOptions.modelId)50 report = r; error = nil51 withAnimation(Motion.smooth(reduceMotion)) { shown = min(max((r.percentOfContext ?? 0) / 100, 0), 1) }52 } catch let e { if report == nil { error = (e as? APIError)?.message ?? String(localized: "Chargement impossible.") } }53 }5455 private func block<Content: View>(_ title: String, source: String?, @ViewBuilder content: () -> Content) -> some View {56 VStack(alignment: .leading, spacing: 12) {57 Text(title).font(.spHeading).foregroundStyle(Color.textPrimary)58 content()59 if let source, !source.isEmpty { SourceNote(text: source) }60 }61 .padding(14).frame(maxWidth: .infinity, alignment: .leading)62 .cardSurface()63 }6465 // MARK: estimate6667 private func gauge(_ r: ContextReport) -> some View {68 let pct = r.percentOfContext ?? 069 let tint: Color = pct >= 90 ? .danger : pct >= 70 ? .warning : .accentColor70 return VStack(alignment: .leading, spacing: 12) {71 HStack(spacing: 8) {72 if let m = env.catalog.model(r.modelId) { ModelChip(model: m, markSize: 16, font: .spUI) }73 else if let name = r.modelName { Text(name).font(.spUI).foregroundStyle(Color.textPrimary) }74 Spacer(minLength: 4)75 Text("estimation").font(.spMicro).tracking(0.4).textCase(.uppercase).foregroundStyle(Color.warning)76 .padding(.horizontal, 7).padding(.vertical, 3).background(Color.warning.opacity(0.12), in: .capsule)77 }78 HStack(alignment: .lastTextBaseline, spacing: 6) {79 Text(pct < 1 && pct > 0 ? String(format: "%.1f %%", pct) : String(format: "%.0f %%", pct)).font(.system(.largeTitle, design: .default, weight: .semibold).monospacedDigit()).foregroundStyle(Color.textPrimary).contentTransition(.numericText())80 Text("de la fenêtre de contexte").font(.subheadline).foregroundStyle(Color.textSecondary)81 }82 GeometryReader { geo in83 ZStack(alignment: .leading) {84 Capsule().fill(Color.surface2)85 Capsule().fill(tint).frame(width: max(geo.size.width * shown, shown > 0 ? 6 : 0))86 }87 }88 .frame(height: 8)89 HStack(spacing: 12) {90 FactCell(title: String(localized: "Prochaine requête"), value: r.nextRequestTokens.map { "≈ \(Format.tokens($0))" } ?? "—", note: String(localized: "jetons, estimés"))91 FactCell(title: String(localized: "Fenêtre"), value: r.contextWindow.map { Format.tokens($0) } ?? "—", note: String(localized: "jetons"))92 }93 if let s = r.estimateSource { SourceNote(text: s) }94 if r.streaming { Label("Une réponse est en cours : les chiffres bougeront à la fin.", systemImage: "dot.radiowaves.left.and.right").font(.caption).foregroundStyle(Color.muted) }95 }96 .padding(14).frame(maxWidth: .infinity, alignment: .leading)97 .cardSurface()98 .accessibilityElement(children: .contain)99 .accessibilityIdentifier("context.gauge")100 }101102 // MARK: measured, composition, files, tools, cost103104 private func measured(_ r: ContextReport) -> some View {105 block(String(localized: "Mesuré sur la dernière réponse"), source: r.measuredSource) {106 LazyVGrid(columns: [GridItem(.adaptive(minimum: 104), spacing: 12, alignment: .topLeading)], alignment: .leading, spacing: 14) {107 if let v = r.measuredInput { FactCell(title: String(localized: "Entrée"), value: Format.tokens(v), note: String(localized: "jetons")) }108 if let v = r.measuredOutput { FactCell(title: String(localized: "Sortie"), value: Format.tokens(v), note: String(localized: "jetons")) }109 if let v = r.measuredCached, v > 0 { FactCell(title: String(localized: "En cache"), value: Format.tokens(v), note: String(localized: "jetons")) }110 if let v = r.measuredReasoning, v > 0 { FactCell(title: String(localized: "Raisonnement"), value: Format.tokens(v), note: String(localized: "jetons")) }111 if let d = r.measuredAt { FactCell(title: String(localized: "Mesuré"), value: Format.relative(d)) }112 }113 }114 }115116 private func composition(_ r: ContextReport) -> some View {117 block(String(localized: "Messages"), source: String(localized: "Fil actif de la conversation, compté par le serveur")) {118 HStack(spacing: 12) {119 FactCell(title: String(localized: "Total"), value: r.messageCount.formatted())120 FactCell(title: String(localized: "Toi"), value: r.userCount.formatted())121 FactCell(title: String(localized: "Assistant"), value: r.assistantCount.formatted())122 }123 }124 }125126 private func files(_ r: ContextReport) -> some View {127 block(String(localized: "Fichiers"), source: String(localized: "Fichiers joints à la conversation, tels que le serveur les décrit")) {128 VStack(alignment: .leading, spacing: 8) {129 ForEach(r.files) { f in130 HStack(spacing: 10) {131 Image(systemName: "doc").font(.subheadline).foregroundStyle(Color.accentColor).frame(width: 20)132 VStack(alignment: .leading, spacing: 1) {133 Text(f.name).font(.subheadline).foregroundStyle(Color.textPrimary).lineLimit(1)134 if let d = f.detail { Text(d).font(.caption).foregroundStyle(Color.muted).lineLimit(1) }135 }136 }137 .accessibilityElement(children: .combine)138 }139 }140 }141 }142143 private func tools(_ r: ContextReport) -> some View {144 block(String(localized: "Outils"), source: String(localized: "Réglage de la conversation sur le serveur ; le sélecteur d’outils du compositeur peut restreindre chaque message")) {145 Label(r.toolsEnabled ? String(localized: "Activés pour cette conversation") : String(localized: "Désactivés pour cette conversation"), systemImage: r.toolsEnabled ? "checkmark.circle.fill" : "minus.circle")146 .font(.subheadline).foregroundStyle(r.toolsEnabled ? Color.success : Color.muted)147 if r.toolsEnabled, !r.tools.isEmpty {148 let known = Dictionary(env.settings.tools.map { ($0.name, $0) }, uniquingKeysWith: { a, _ in a })149 LazyVGrid(columns: [GridItem(.adaptive(minimum: 130), spacing: 8, alignment: .leading)], alignment: .leading, spacing: 8) {150 ForEach(r.tools, id: \.self) { name in151 let t = known[name] ?? ServerTool(name: name)152 Label(t.label, systemImage: t.symbol).font(.spCaption).foregroundStyle(Color.textSecondary).lineLimit(1)153 .padding(.horizontal, 9).padding(.vertical, 6).frame(maxWidth: .infinity, alignment: .leading).background(Color.surface2, in: .rect(cornerRadius: Radius.control, style: .continuous))154 }155 }156 }157 }158 }159160 private func cost(_ r: ContextReport) -> some View {161 block(String(localized: "Coût de la conversation"), source: r.costSource) {162 Text(Format.usd(r.conversationUsd)).font(.system(.title2, design: .default, weight: .semibold).monospacedDigit()).foregroundStyle(Color.textPrimary)163 }164 }165}166