Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Features/Panels/LensSheet.swift4// Description: Response Lens — five lenses over an answer (summary, explanation, key points, table, source check),5// each a real streamed model call stored per message, with its steps, sources, cost and model.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import SwiftUI1213/// Runs one lens at a time and keeps the lenses stored for a message. Built only from what the server sends.14@MainActor15@Observable16final class LensRunner {17 private(set) var kinds: [LensKind] = LensKind.builtin18 private(set) var stored: [StoredLens] = []19 private(set) var run: LensRun?20 private(set) var loadError: String?2122 @ObservationIgnored private let api: ChatAPI23 @ObservationIgnored private let messageId: String24 @ObservationIgnored private var task: Task<Void, Never>?2526 init(api: ChatAPI, messageId: String) { self.api = api; self.messageId = messageId }2728 var isRunning: Bool { run?.isRunning == true }2930 func load() async {31 do {32 let r = try await api.lenses(messageId: messageId)33 if !r.kinds.isEmpty { kinds = r.kinds }34 stored = r.stored; loadError = nil35 } catch { loadError = (error as? APIError)?.message ?? String(localized: "Lentilles indisponibles.") }36 }3738 /// Starts a lens: a real model call (and real web searches for `verify`).39 func start(_ lens: String, modelId: String?) {40 stop()41 run = LensRun(lens: lens)42 task = Task { [weak self] in await self?.consume(lens: lens, modelId: modelId) }43 }4445 private func consume(lens: String, modelId: String?) async {46 do {47 switch try await api.openLens(messageId: messageId, lens: lens, modelId: modelId) {48 case .json: break49 case .events(let bytes):50 for try await sse in SSEStream.events(from: bytes) {51 if Task.isCancelled { return }52 run?.apply(LensEvent(sse: sse))53 }54 }55 } catch {56 if Task.isCancelled { return }57 let e = APIError.from(error, offline: false)58 if e.kind != .cancelled, run?.storedId == nil { run?.apply(.error(e.message)) }59 }60 if Task.isCancelled { return }61 run?.apply(.end)62 await load()63 }6465 /// Closes the stream; what was already written stays on screen, marked as stopped.66 func stop() {67 guard task != nil else { return }68 task?.cancel(); task = nil69 if run?.isRunning == true { run?.apply(.error(String(localized: "Lentille arrêtée."))) }70 }7172 func clearRun() { stop(); run = nil }7374 func delete(_ lens: StoredLens) async {75 do { try await api.deleteLens(lens.id); stored.removeAll { $0.id == lens.id }; if run?.storedId == lens.id { run = nil } }76 catch { loadError = (error as? APIError)?.message }77 }78}7980struct LensSheet: View {81 let message: ChatMessage82 @Environment(AppEnvironment.self) private var env83 @Environment(\.dismiss) private var dismiss84 @Environment(\.accessibilityReduceMotion) private var reduceMotion85 @State private var runner: LensRunner?86 @State private var reading: StoredLens?87 @State private var modelId: String?88 @State private var pickingModel = false8990 var body: some View {91 VStack(spacing: 0) {92 SheetHeader(title: String(localized: "Lentilles de réponse"), subtitle: String(localized: "Chaque lentille est un appel réel au modèle, enregistré avec la réponse."), onClose: { dismiss() })93 LumenLine(active: runner?.isRunning == true, cornerRadius: 0).frame(height: 2).animation(Motion.fade, value: runner?.isRunning)94 if let runner {95 ScrollView {96 VStack(alignment: .leading, spacing: 16) {97 kindChips(runner)98 modelRow99 if let run = runner.run { runView(run, runner).transition(.opacity.combined(with: .offset(y: 8))) }100 else if let reading { storedView(reading).transition(.opacity) }101 if let e = runner.loadError { Banner(kind: .warning, text: e) }102 if !runner.stored.isEmpty { storedList(runner) }103 }104 .padding(.horizontal, 16).padding(.top, 8).padding(.bottom, 24)105 .animation(Motion.smooth(reduceMotion), value: runner.run?.lens)106 .animation(Motion.smooth(reduceMotion), value: reading?.id)107 }108 } else { Spacer(); ProgressView(); Spacer() }109 }110 .background(Color.appBackground)111 .task {112 if runner == nil { runner = LensRunner(api: env.api, messageId: message.id) }113 await runner?.load()114 }115 .onDisappear { runner?.stop() }116 .sheet(isPresented: $pickingModel) {117 ModelSheet(purpose: .pick(title: String(localized: "Modèle de la lentille"), current: modelId) { m in modelId = m.id }).presentationDetents([.large])118 }119 }120121 // MARK: lens kinds122123 private func kindChips(_ runner: LensRunner) -> some View {124 ScrollView(.horizontal, showsIndicators: false) {125 HStack(spacing: 8) {126 ForEach(runner.kinds) { k in127 let on = runner.run?.lens == k.id128 Button {129 env.haptics.tap()130 reading = nil131 runner.start(k.id, modelId: modelId)132 } label: { ChipLabel(text: k.label, systemImage: k.symbol, selected: on).frame(minHeight: 44) }133 .buttonStyle(PressScale())134 .disabled(runner.isRunning)135 .accessibilityHint(k.usesWeb ? String(localized: "Appel réel au modèle et recherches web réelles") : String(localized: "Appel réel au modèle"))136 .accessibilityAddTraits(on ? .isSelected : [])137 .accessibilityIdentifier("lens.kind.\(k.id)")138 }139 }140 .padding(.vertical, 1)141 }142 .scrollClipDisabled()143 }144145 private var modelRow: some View {146 Button { pickingModel = true } label: {147 HStack(spacing: 8) {148 Text("Modèle").font(.spCaption).foregroundStyle(Color.muted)149 if let m = env.catalog.model(modelId) { ModelChip(model: m, markSize: 14, font: .spCaption) }150 else { Text("Choisi par le serveur").font(.spCaption).foregroundStyle(Color.textSecondary) }151 Spacer(minLength: 4)152 if modelId != nil {153 Button { modelId = nil } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(Color.muted).frame(width: 36, height: 36).contentShape(.rect) }154 .buttonStyle(.plain).accessibilityLabel(String(localized: "Laisser le serveur choisir le modèle"))155 }156 Image(systemName: "chevron.right").font(.system(size: 10, weight: .bold)).foregroundStyle(Color.muted)157 }158 .padding(.horizontal, 12).frame(minHeight: 44)159 .cardSurface(cornerRadius: Radius.control)160 }161 .buttonStyle(PressScale(scale: 0.98))162 .disabled(runner?.isRunning == true)163 .accessibilityIdentifier("lens.model")164 }165166 // MARK: a run167168 private func title(for lens: String) -> String { (runner?.kinds ?? LensKind.builtin).first { $0.id == lens }?.label ?? lens }169 private func usesWeb(_ lens: String) -> Bool { (runner?.kinds ?? LensKind.builtin).first { $0.id == lens }?.usesWeb ?? false }170171 private func runView(_ run: LensRun, _ runner: LensRunner) -> some View {172 VStack(alignment: .leading, spacing: 12) {173 HStack(spacing: 8) {174 Text(title(for: run.lens)).font(.spHeading).foregroundStyle(Color.textPrimary)175 Spacer(minLength: 4)176 if run.isRunning {177 Button { env.haptics.tap(); runner.stop() } label: { Label("Arrêter", systemImage: "stop.fill").font(.spCaption).foregroundStyle(Color.textPrimary).padding(.horizontal, 12).frame(minHeight: 32).background(Color.surface2, in: .capsule).frame(minHeight: 44) }178 .buttonStyle(PressScale()).accessibilityIdentifier("lens.stop")179 } else {180 Button { runner.clearRun() } label: { Image(systemName: "xmark").font(.system(size: 11, weight: .bold)).foregroundStyle(Color.muted).frame(width: 44, height: 44).contentShape(.rect) }181 .buttonStyle(.plain).accessibilityLabel(String(localized: "Fermer ce résultat"))182 }183 }184 if let m = run.model { ModelChip(logo: identity(m).logo, creatorName: identity(m).creatorName, name: identity(m).name, route: identity(m).route, markSize: 14, font: .spCaption, breathing: run.isRunning) }185 if !run.steps.isEmpty { stepsView(run) }186 if !run.sources.isEmpty { sourcesView(run.sources) }187 if !run.text.isEmpty { MarkdownView(text: run.text).foregroundStyle(Color.textPrimary).accessibilityIdentifier("lens.result") }188 else if run.isRunning { PresenceDots() }189 if let e = run.error { Banner(kind: run.storedId == nil && run.text.isEmpty ? .error : .warning, text: e) }190 if !run.isRunning, run.costUsd != nil || run.latencyMs != nil { metrics(cost: run.costUsd, exact: run.exactCost, latency: run.latencyMs) }191 if run.isRunning { SourceNote(text: usesWeb(run.lens) ? String(localized: "Appel réel au modèle et recherches web réelles, facturés comme une réponse.") : String(localized: "Appel réel au modèle, facturé comme une réponse.")) }192 }193 .padding(14).frame(maxWidth: .infinity, alignment: .leading)194 .cardSurface()195 }196197 private func identity(_ id: String) -> ModelIdentity { ModelIdentity(model: env.catalog.model(id), modelId: id, provider: nil) }198199 private func stepsView(_ run: LensRun) -> some View {200 VStack(alignment: .leading, spacing: 6) {201 ForEach(run.steps) { s in202 let current = run.isRunning && s.id == run.steps.last?.id203 HStack(alignment: .firstTextBaseline, spacing: 8) {204 Image(systemName: current ? "circle.dotted" : "checkmark.circle.fill").font(.system(size: 12, weight: .medium))205 .foregroundStyle(current ? Color.accentColor : Color.success)206 .symbolEffect(.pulse, isActive: current && !reduceMotion)207 Text(s.label).font(.footnote).foregroundStyle(current ? Color.textPrimary : Color.textSecondary)208 }209 .accessibilityElement(children: .combine)210 .accessibilityLabel(current ? String(localized: "En cours : \(s.label)") : String(localized: "Terminé : \(s.label)"))211 }212 }213 .accessibilityIdentifier("lens.steps")214 }215216 private func sourcesView(_ sources: [LensSource]) -> some View {217 VStack(alignment: .leading, spacing: 8) {218 // one card per page (a page may back several claims)219 SourceCards(citations: sources.reduce(into: [Citation]()) { out, s in if !out.contains(where: { $0.url == s.url }) { out.append(s.citation) } })220 let claims = sources.filter { $0.claim?.isEmpty == false }221 if !claims.isEmpty {222 VStack(alignment: .leading, spacing: 5) {223 ForEach(claims) { s in224 HStack(alignment: .firstTextBaseline, spacing: 6) {225 Text(s.citation.domain).font(.caption2.weight(.semibold)).foregroundStyle(Color.accentColor).lineLimit(1).fixedSize()226 Text(s.claim ?? "").font(.caption).foregroundStyle(Color.textSecondary)227 }228 .accessibilityElement(children: .combine)229 }230 }231 }232 }233 }234235 private func metrics(cost: Double?, exact: Bool, latency: Int?) -> some View {236 HStack(spacing: 12) {237 if let cost { FactCell(title: exact ? String(localized: "Coût facturé") : String(localized: "Coût estimé"), value: Format.usd(cost)) }238 if let latency { FactCell(title: String(localized: "Durée"), value: Format.duration(ms: latency)) }239 }240 }241242 // MARK: stored lenses243244 private func storedView(_ lens: StoredLens) -> some View {245 VStack(alignment: .leading, spacing: 12) {246 HStack {247 Text(title(for: lens.lens)).font(.spHeading).foregroundStyle(Color.textPrimary)248 Spacer(minLength: 4)249 Button { reading = nil } label: { Image(systemName: "xmark").font(.system(size: 11, weight: .bold)).foregroundStyle(Color.muted).frame(width: 44, height: 44).contentShape(.rect) }250 .buttonStyle(.plain).accessibilityLabel(String(localized: "Fermer ce résultat"))251 }252 if let m = lens.modelId { let i = identity(m); ModelChip(logo: i.logo, creatorName: i.creatorName, name: i.name, route: i.route, markSize: 14, font: .spCaption) }253 if !lens.sources.isEmpty { sourcesView(lens.sources) }254 MarkdownView(text: lens.content).foregroundStyle(Color.textPrimary).accessibilityIdentifier("lens.result")255 HStack(spacing: 12) {256 if let c = lens.costUsd { FactCell(title: String(localized: "Coût enregistré"), value: Format.usd(c)) }257 if let d = lens.createdAt { FactCell(title: String(localized: "Créée"), value: Format.relative(d)) }258 }259 ShareLink(item: lens.content) { Label("Partager", systemImage: "square.and.arrow.up").font(.spCaption).frame(minHeight: 44) }260 }261 .padding(14).frame(maxWidth: .infinity, alignment: .leading)262 .cardSurface()263 }264265 private func storedList(_ runner: LensRunner) -> some View {266 VStack(alignment: .leading, spacing: 8) {267 Text("Lentilles enregistrées").font(.spMicro).tracking(0.3).textCase(.uppercase).foregroundStyle(Color.muted)268 VStack(spacing: 0) {269 ForEach(Array(runner.stored.reversed().enumerated()), id: \.element.id) { i, lens in270 if i > 0 { Divider().padding(.leading, 44) }271 HStack(spacing: 4) {272 Button { env.haptics.selection(); runner.clearRun(); reading = lens } label: {273 HStack(spacing: 12) {274 Image(systemName: (runner.kinds.first { $0.id == lens.lens }?.symbol) ?? "sparkles").font(.system(size: 14, weight: .medium)).foregroundStyle(Color.accentColor).frame(width: 20)275 VStack(alignment: .leading, spacing: 2) {276 Text(title(for: lens.lens)).font(.subheadline.weight(.medium)).foregroundStyle(Color.textPrimary)277 Text([lens.modelId.map { identity($0).name }, lens.createdAt.map(Format.relative), lens.costUsd.map(Format.usd), lens.status == "complete" ? nil : lens.status].compactMap { $0 }.joined(separator: " · "))278 .font(.caption).foregroundStyle(Color.muted).lineLimit(1)279 }280 Spacer(minLength: 0)281 }282 .frame(minHeight: 52).contentShape(.rect)283 }284 .buttonStyle(.plain)285 .accessibilityIdentifier("lens.stored")286 Button { env.haptics.soften(); if reading?.id == lens.id { reading = nil }; Task { await runner.delete(lens) } } label: {287 Image(systemName: "trash").font(.system(size: 13, weight: .medium)).foregroundStyle(Color.muted).frame(width: 44, height: 44).contentShape(.rect)288 }289 .buttonStyle(PressScale())290 .accessibilityLabel(String(localized: "Supprimer la lentille \(title(for: lens.lens))"))291 }292 .padding(.leading, 12)293 .background(reading?.id == lens.id ? Color.accentSoft : Color.clear)294 }295 }296 .cardSurface()297 }298 }299}300