SPB Git

Repository Public

LensPanel.swift 22.0 KB 405 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Chat/Panels/LensPanel.swift3// Description: Response Lens tab: run a lens (summary, explanation, key points, table, source verification) on an answer with a real streamed model call, show steps, sources, cost and latency, reopen and delete the stored lenses.4import SwiftUI5import SPChatCore67/// Lenses of one answer: kinds offered by the server, stored lenses, and the run in progress.8@Observable final class LensModel {9    private(set) var messageId: String?10    private(set) var kinds: [LensKind] = []11    private(set) var lenses: [StoredLens] = []12    /// The run in progress, or the last one when it failed (so that its error stays readable).13    private(set) var run: LensAccumulator?14    private(set) var isLoading = false15    private(set) var loadError: String?16    private(set) var isCancelling = false17    /// Stored lens on screen.18    var selectedId: String?19    /// Model asked for the next run; nil = the server's default.20    var modelId: String?21    /// How long a cancelled run may take to confirm before the connection is dropped.22    @ObservationIgnored var cancelGrace: Duration = .seconds(4)23    @ObservationIgnored private var task: Task<Void, Never>?24    @ObservationIgnored private var generation = 02526    var isRunning: Bool { run?.isRunning == true }27    var selected: StoredLens? { lenses.first { $0.id == selectedId } }28    func label(for lens: String) -> String { kinds.first { $0.id == lens }?.label ?? lens }2930    func load(messageId id: String?, api: APIClient) async {31        if id != messageId {32            // another answer: the local stream is dropped (the server finishes and stores its run on its own)33            task?.cancel(); task = nil; run = nil; isCancelling = false34            lenses = []; selectedId = nil; loadError = nil; messageId = id35        }36        guard let id else { isLoading = false; return }37        generation += 1; let mine = generation38        isLoading = true39        do {40            let list = try await api.lenses(messageId: id)41            guard mine == generation else { return }42            apply(list); loadError = nil43        } catch {44            guard mine == generation, APIError.from(error).kind != .cancelled else { return }45            loadError = APIError.from(error).message46        }47        if mine == generation { isLoading = false }48    }4950    private func apply(_ list: LensList) {51        if !list.kinds.isEmpty { kinds = list.kinds }52        lenses = list.lenses53        if selected == nil { selectedId = lenses.first?.id }54    }5556    /// Starts a real lens run (`POST /api/lens`, SSE).57    func start(_ lens: String, api: APIClient) {58        guard let messageId, !isRunning else { return }59        run = LensAccumulator(lens: lens, modelId: modelId); isCancelling = false60        let model = modelId61        task = Task { [weak self] in62            do {63                switch try await api.openLens(messageId: messageId, lens: lens, modelId: model) {64                case .json(_, let j): self?.interrupt(j["error"]?.stringValue ?? "Réponse inattendue du serveur.")65                case .events(_, let bytes):66                    var parser = SSEParser()67                    for try await chunk in bytes {68                        guard let self, self.messageId == messageId else { return }69                        let events = parser.feed(chunk).map(LensEvent.init)70                        if !events.isEmpty, await self.absorb(events, api: api) { return }71                    }72                    self?.interrupt("La connexion s'est fermée avant la fin de la lens.")73                }74            } catch {75                let e = APIError.from(error)76                self?.interrupt(e.kind == .cancelled ? nil : e.message)77            }78        }79    }8081    /// Applies a batch of events (one observable update per network chunk). Returns true when the run is over.82    private func absorb(_ events: [LensEvent], api: APIClient) async -> Bool {83        guard var acc = run else { return true }84        for e in events { acc.apply(e) }85        run = acc86        guard acc.isFinished else { return false }87        await finish(acc, api: api)88        return true89    }9091    private func finish(_ acc: LensAccumulator, api: APIClient) async {92        let cancelled = isCancelling93        isCancelling = false; task = nil94        guard !acc.failed, let stored = acc.result else { return } // the failed run stays on screen with its error95        if cancelled, stored.isEmpty {96            // a run stopped before its first word is stored empty by the server: it is removed97            if !stored.id.isEmpty { try? await api.deleteLens(stored.id) }98            run = nil99            return100        }101        lenses.removeAll { $0.id == stored.id }102        lenses.insert(stored, at: 0); selectedId = stored.id; run = nil103        // the server's list is the truth (a new lens may replace the previous one of the same kind)104        if let messageId, let list = try? await api.lenses(messageId: messageId), self.messageId == messageId {105            let exact = stored.exactCost106            apply(list)107            if let i = lenses.firstIndex(where: { $0.id == stored.id }) { lenses[i].exactCost = lenses[i].exactCost ?? exact; if lenses[i].latencyMs == nil { lenses[i].latencyMs = stored.latencyMs } }108            if lenses.contains(where: { $0.id == stored.id }) { selectedId = stored.id }109        }110    }111112    private func interrupt(_ message: String?) {113        task = nil114        guard var acc = run, acc.isRunning else { return }115        if isCancelling || message == nil { run = nil; isCancelling = false; return }116        acc.interrupt(message ?? ""); run = acc117    }118119    /// Stops the run: the server cancels the model call (`POST /api/chat/cancel {runId}`), then the stream ends by itself.120    func cancel(api: APIClient) {121        guard isRunning, !isCancelling else { return }122        isCancelling = true123        guard let runId = run?.runId else { task?.cancel(); task = nil; run = nil; isCancelling = false; return }124        let grace = cancelGrace125        Task { [weak self] in126            try? await api.cancelGeneration(runId: runId, messageId: nil)127            try? await Task.sleep(for: grace)128            guard let self, self.isCancelling, self.run?.runId == runId else { return }129            self.task?.cancel(); self.task = nil; self.run = nil; self.isCancelling = false130        }131    }132133    /// Closes the error of a failed run.134    func dismissRun() { if !isRunning { run = nil } }135136    func delete(_ id: String, api: APIClient) async throws {137        try await api.deleteLens(id)138        lenses.removeAll { $0.id == id }139        if selectedId == id { selectedId = lenses.first?.id }140    }141}142143struct LensPanel: View {144    let chat: ChatViewModel145    @Bindable var window: WindowModel146    let model: LensModel147    @Environment(AppEnvironment.self) private var env148    @State private var pendingDelete: StoredLens?149150    /// The answer the lens works on: the one asked for from the transcript, else the last answer of the thread.151    private var target: Message? {152        let answers = chat.messages.filter { $0.role == .assistant && !$0.isOptimistic }153        if let id = window.lensMessageId, let m = answers.first(where: { $0.id == id }) ?? chat.detail?.messages.first(where: { $0.id == id && $0.role == .assistant }) { return m }154        return answers.last155    }156    private var isLastAnswer: Bool { target?.id == chat.messages.last(where: { $0.role == .assistant })?.id }157158    var body: some View {159        Group {160            if let target {161                ScrollView {162                    VStack(spacing: 0) {163                        targetSection(target)164                        chooserSection165                        if let run = model.run { runSection(run) }166                        else if let lens = model.selected { resultSection(lens) }167                        if !model.lenses.isEmpty { storedSection }168                    }169                    .padding(.bottom, DS.S.xl)170                }171            } else {172                PanelPlaceholder(systemImage: PanelTab.lens.systemImage, title: "Aucune réponse à examiner", message: "Une lens résume, explique ou vérifie une réponse du modèle.")173            }174        }175        .overlay(alignment: .top) { PanelLoadingLine(active: model.isLoading && model.kinds.isEmpty) }176        .task(id: target?.id) { await model.load(messageId: target?.id, api: env.api) }177        .confirmationDialog("Supprimer cette lens ?", isPresented: Binding(get: { pendingDelete != nil }, set: { if !$0 { pendingDelete = nil } }), presenting: pendingDelete) { lens in178            Button("Supprimer", role: .destructive) { Task { do { try await model.delete(lens.id, api: env.api) } catch { env.toasts.error(error) } } }179            Button("Annuler", role: .cancel) {}180        } message: { lens in Text("« \(model.label(for: lens.lens)) » sera retirée du serveur. Cette action est définitive.") }181        .accessibilityIdentifier("panel-lens")182    }183184    // MARK: Target answer185186    private func targetSection(_ m: Message) -> some View {187        PanelSection("Réponse examinée", trailing: {188            if !isLastAnswer { Button("Dernière réponse") { window.lensMessageId = nil }.buttonStyle(.plain).font(DS.F.caption).foregroundStyle(DS.C.accent).fixedSize().disabled(model.isRunning) }189        }) {190            Button { if chat.messages.contains(where: { $0.id == m.id }) { chat.scrollTarget = m.id } } label: {191                VStack(alignment: .leading, spacing: DS.S.xs) {192                    if let id = m.modelId { ModelChip(identity: env.catalog.identity(for: id), markSize: 14, font: DS.F.caption) }193                    Text(flat(m.visibleText)).font(DS.F.caption).foregroundStyle(DS.C.text2).lineLimit(2).multilineTextAlignment(.leading).frame(maxWidth: .infinity, alignment: .leading)194                }195                .contentShape(Rectangle())196            }197            .buttonStyle(.plain).help("Afficher cette réponse dans la conversation")198        }199    }200201    private func flat(_ s: String) -> String { PanelFormat.plain(s) }202203    // MARK: Lens chooser204205    private var chooserSection: some View {206        PanelSection("Lens") {207            if model.kinds.isEmpty {208                if let e = model.loadError {209                    Text(e).font(DS.F.caption).foregroundStyle(DS.C.danger).fixedSize(horizontal: false, vertical: true)210                    Button("Réessayer") { Task { await model.load(messageId: target?.id, api: env.api) } }.buttonStyle(ChipStyle())211                } else { Text("Chargement des lens…").font(DS.F.caption).foregroundStyle(DS.C.muted) }212            } else {213                FlowLayout(spacing: 6) {214                    ForEach(model.kinds) { kind in215                        Button { model.start(kind.id, api: env.api) } label: {216                            HStack(spacing: 4) {217                                if kind.usesWeb { Image(systemName: "globe").font(.system(size: 10)).accessibilityHidden(true) }218                                Text(kind.label)219                            }220                        }221                        .buttonStyle(ChipStyle(selected: model.run?.lens == kind.id && model.isRunning))222                        .disabled(model.isRunning)223                        .help(kind.usesWeb ? "\(kind.label) — lance de vraies recherches web (appel facturé)" : "\(kind.label) — appel réel au modèle (facturé)")224                        .accessibilityLabel(kind.usesWeb ? "\(kind.label), avec recherche web" : kind.label)225                        .accessibilityIdentifier("lens-kind-\(kind.id)")226                    }227                }228                modelMenu229            }230        }231    }232233    private var modelMenu: some View {234        HStack(spacing: DS.S.s) {235            Text("Modèle").font(DS.F.caption).foregroundStyle(DS.C.muted)236            Menu {237                Button { model.modelId = nil } label: { if model.modelId == nil { Label("Par défaut du serveur", systemImage: "checkmark") } else { Text("Par défaut du serveur") } }238                Divider()239                ForEach(env.catalog.menuModels) { m in240                    let title = m.displayName + (m.isOpenRouter ? " · OpenRouter" : "")241                    Button { model.modelId = m.id } label: { if model.modelId == m.id { Label(title, systemImage: "checkmark") } else { Text(title) } }242                }243            } label: {244                HStack(spacing: 4) {245                    if let id = model.modelId { ModelChip(identity: env.catalog.identity(for: id), markSize: 13, font: DS.F.caption) }246                    else { Text("Par défaut du serveur").font(DS.F.caption).foregroundStyle(DS.C.text2) }247                    Image(systemName: "chevron.up.chevron.down").font(.system(size: 8, weight: .semibold)).foregroundStyle(DS.C.muted)248                }249                .contentShape(Rectangle())250            }251            .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize()252            .disabled(model.isRunning).help("Modèle utilisé pour la prochaine lens").accessibilityLabel("Modèle de la lens")253            Spacer(minLength: 0)254        }255    }256257    // MARK: Run in progress (or failed)258259    private func runSection(_ run: LensAccumulator) -> some View {260        VStack(alignment: .leading, spacing: DS.S.m) {261            HStack(alignment: .top, spacing: DS.S.s) {262                VStack(alignment: .leading, spacing: DS.S.xs) {263                    Text(model.label(for: run.lens)).font(DS.F.heading).foregroundStyle(DS.C.text).lineLimit(2)264                    if let id = run.modelId { ModelChip(identity: env.catalog.identity(for: id), markSize: 13, font: DS.F.caption, breathing: run.isRunning) }265                }266                Spacer(minLength: 0)267                if run.isRunning { Button(model.isCancelling ? "Arrêt…" : "Arrêter") { model.cancel(api: env.api) }.buttonStyle(ChipStyle()).disabled(model.isCancelling).accessibilityIdentifier("lens-cancel") }268                else { IconButton(systemImage: "xmark", label: "Fermer") { model.dismissRun() } }269            }270            if !run.steps.isEmpty { LensSteps(steps: run.steps) }271            if !run.displaySources.isEmpty { LensSources(sources: run.displaySources) }272            if !run.displayText.isEmpty { MarkdownView(text: run.displayText).textSelection(.enabled) }273            else if run.isRunning, run.steps.isEmpty { Text(run.started ? "Le modèle rédige…" : "Envoi de la demande…").font(DS.F.caption).foregroundStyle(DS.C.muted) }274            if let e = run.error {275                Label(e, systemImage: "exclamationmark.triangle").font(DS.F.caption).foregroundStyle(DS.C.danger).fixedSize(horizontal: false, vertical: true)276                    .accessibilityIdentifier("lens-error")277            }278        }279        .environment(\.transcriptFontSize, 13)280        .padding(.horizontal, DS.S.xl).padding(.vertical, DS.S.l).frame(maxWidth: .infinity, alignment: .leading)281        .overlay(alignment: .top) { LumenLine(active: run.isRunning, cornerInset: 0).frame(height: 2).offset(y: -1) }282        .overlay(alignment: .bottom) { Hairline() }283    }284285    // MARK: Stored lens on screen286287    private func resultSection(_ lens: StoredLens) -> some View {288        VStack(alignment: .leading, spacing: DS.S.m) {289            HStack(alignment: .top, spacing: DS.S.s) {290                VStack(alignment: .leading, spacing: DS.S.xs) {291                    Text(model.label(for: lens.lens)).font(DS.F.heading).foregroundStyle(DS.C.text).lineLimit(2)292                    if let id = lens.modelId { ModelChip(identity: env.catalog.identity(for: id), markSize: 13, font: DS.F.caption) }293                }294                Spacer(minLength: 0)295                IconButton(systemImage: "doc.on.doc", label: "Copier le résultat") { Pasteboard.copy(lens.content); env.toasts.show("Lens copiée") }.foregroundStyle(DS.C.muted)296            }297            if !lens.sources.isEmpty { LensSources(sources: lens.sources) }298            if lens.isEmpty { Text("Cette lens est vide.").font(DS.F.caption).foregroundStyle(DS.C.muted) }299            else { MarkdownView(text: lens.content).textSelection(.enabled) }300            if let e = lens.error, !e.isEmpty { Label(e, systemImage: "exclamationmark.triangle").font(DS.F.caption).foregroundStyle(DS.C.danger) }301            Text(figures(lens)).font(.system(size: 10.5).monospacedDigit()).foregroundStyle(DS.C.muted).fixedSize(horizontal: false, vertical: true)302        }303        .environment(\.transcriptFontSize, 13)304        .padding(.horizontal, DS.S.xl).padding(.vertical, DS.S.l).frame(maxWidth: .infinity, alignment: .leading)305        .overlay(alignment: .bottom) { Hairline() }306        .accessibilityIdentifier("lens-result")307    }308309    /// « 0.0001 $ estimé · 815 ms · 19 nov., 09 h 40 »310    private func figures(_ lens: StoredLens) -> String {311        var parts: [String] = []312        if lens.modelId?.hasPrefix("local:") == true { parts.append("local · 0 $") }313        else if let c = lens.costUsd { parts.append("\(Format.usd(c, digits: 5)) \(PanelFormat.costBasis(exact: lens.isCostExact))") }314        if let l = lens.latencyMs { parts.append(Format.duration(ms: l)) }315        if let u = lens.usage, u.input > 0 || u.output > 0 { parts.append("\(Format.tokens(u.input)) → \(Format.tokens(u.output)) jetons") }316        if let d = lens.createdAt { parts.append(PanelFormat.dateTime(d)) }317        return parts.joined(separator: " · ")318    }319320    // MARK: Stored lenses of this answer321322    private var storedSection: some View {323        PanelSection("Enregistrées pour cette réponse (\(model.lenses.count))") {324            VStack(spacing: 2) {325                ForEach(model.lenses) { lens in326                    let selected = lens.id == model.selectedId && model.run == nil327                    HStack(spacing: DS.S.s) {328                        Button { model.dismissRun(); if !model.isRunning { model.selectedId = lens.id } } label: {329                            HStack(spacing: DS.S.s) {330                                VStack(alignment: .leading, spacing: 1) {331                                    Text(model.label(for: lens.lens)).font(DS.F.ui).foregroundStyle(selected ? DS.C.accent : DS.C.text).lineLimit(1)332                                    Text([env.catalog.displayName(forModel: lens.modelId), lens.createdAt.map { Format.relative($0) }, lens.costUsd.map { Format.usd($0, digits: 5) }].compactMap { $0 }.joined(separator: " · "))333                                        .font(.system(size: 10.5).monospacedDigit()).foregroundStyle(DS.C.muted).lineLimit(1)334                                }335                                Spacer(minLength: 0)336                            }337                            .contentShape(Rectangle())338                        }339                        .buttonStyle(.plain).disabled(model.isRunning)340                        .accessibilityLabel("Rouvrir la lens \(model.label(for: lens.lens))").accessibilityAddTraits(selected ? .isSelected : [])341                        IconButton(systemImage: "trash", label: "Supprimer la lens \(model.label(for: lens.lens))") { pendingDelete = lens }.foregroundStyle(DS.C.muted)342                    }343                    .padding(.horizontal, DS.S.m).padding(.vertical, 5)344                    .background(selected ? DS.C.accentSoft : .clear, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))345                }346            }347            .padding(.horizontal, -DS.S.m)348        }349    }350}351352/// Stages of a running lens: a state dot per step, the one in progress pulses (static under Reduce Motion).353private struct LensSteps: View {354    let steps: [LensAccumulator.Step]355    var body: some View {356        VStack(alignment: .leading, spacing: 5) {357            ForEach(steps) { step in358                HStack(spacing: DS.S.m) {359                    StateDot(state: step.state)360                    Text(step.label).font(DS.F.caption).foregroundStyle(step.state == .running ? DS.C.text : DS.C.text2).lineLimit(2)361                }362                .accessibilityElement(children: .combine)363                .accessibilityLabel("\(step.label), \(step.state == .running ? "en cours" : (step.state == .done ? "terminé" : "interrompu"))")364            }365        }366    }367}368369private struct StateDot: View {370    let state: LensAccumulator.Step.State371    @Environment(\.accessibilityReduceMotion) private var reduceMotion372    @State private var dim = false373    private var color: Color { switch state { case .running: DS.C.accent; case .done: DS.C.ok; case .failed: DS.C.danger } }374    var body: some View {375        Circle().fill(color).frame(width: 6, height: 6).opacity(state == .running && dim ? 0.35 : 1)376            .onChange(of: state, initial: true) { _, s in377                if s == .running, !reduceMotion { withAnimation(.easeInOut(duration: 0.8).repeatForever(autoreverses: true)) { dim = true } } else { withAnimation(DS.Motion.fade) { dim = false } }378            }379            .accessibilityHidden(true)380    }381}382383/// Sources checked by `verify`: domain, title, and the claim each one was checked against.384private struct LensSources: View {385    let sources: [LensSource]386    @Environment(\.openURL) private var openURL387    var body: some View {388        VStack(spacing: DS.S.s) {389            ForEach(sources) { s in390                Button { if let u = URL(string: s.url), u.scheme == "https" || u.scheme == "http" { openURL(u) } } label: {391                    VStack(alignment: .leading, spacing: 2) {392                        Text(s.domain).font(DS.F.micro).tracking(0.3).foregroundStyle(DS.C.muted).lineLimit(1)393                        Text(s.title ?? s.url).font(DS.F.caption).foregroundStyle(DS.C.text).lineLimit(2).multilineTextAlignment(.leading)394                        if let claim = s.claim, !claim.isEmpty { Text("« \(claim) »").font(.system(size: 10.5)).foregroundStyle(DS.C.text2).lineLimit(3).multilineTextAlignment(.leading) }395                    }396                    .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, DS.S.m).padding(.vertical, 7)397                    .surface(radius: DS.R.control)398                    .contentShape(Rectangle())399                }400                .buttonStyle(.plain).help(s.url).accessibilityLabel("Source \(s.domain) : \(s.title ?? s.url)")401            }402        }403    }404}405
Files main
Menu

Theme