SPB Git

Repository Public

MessageView.swift 37.5 KB 637 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Components/MessageView.swift3// Description: One message of the transcript (Visual System V2): user bubble, bubble-less assistant answer with model header line, tool-call lines, source cards, action bar, details and Smart Follow-Ups.4import SwiftUI5import SPChatCore67/// Actions a message row can trigger. Passed as one value so that rows stay cheap to compare.8struct MessageActions {9    var regenerate: (Message, String?) -> Void = { _, _ in }10    var edit: (Message, String) -> Void = { _, _ in }11    var showVersion: (Message) -> Void = { _ in }12    var fork: (Message) -> Void = { _ in }13    var decideTools: (Message, [String], [String]) -> Void = { _, _, _ in }14    var speak: (Message) -> Void = { _ in }15    var openArtifact: (String) -> Void = { _ in }16    var openAttachment: (String, String) -> Void = { _, _ in }17    /// Opens the Response Lens panel on this answer.18    var lens: (Message) -> Void = { _ in }19    /// Sends a Smart Follow-Up as the next message.20    var followUp: (String) -> Void = { _ in }21    /// « Régénérer avec un autre modèle… » — opens the full model picker for this answer.22    var regenerateWithPicker: (Message) -> Void = { _ in }23}2425struct MessageRow: View, Equatable {26    let message: Message27    /// Versions of this turn (same parent and role), oldest first; one element when there is no alternative.28    let versions: [Message]29    let isBusy: Bool30    let showReasoning: Bool31    let highlighted: Bool32    /// Last message of the thread: its Smart Follow-Ups are offered.33    var isLast = false34    let actions: MessageActions3536    nonisolated static func == (a: MessageRow, b: MessageRow) -> Bool {37        a.message == b.message && a.isBusy == b.isBusy && a.showReasoning == b.showReasoning && a.highlighted == b.highlighted && a.isLast == b.isLast && a.versions.map(\.id) == b.versions.map(\.id)38    }3940    var body: some View {41        Group {42            if message.role == .user { UserMessageView(message: message, versions: versions, isBusy: isBusy, actions: actions) }43            else { AssistantMessageView(message: message, versions: versions, isBusy: isBusy, showReasoning: showReasoning, isLast: isLast, actions: actions) }44        }45        .padding(.vertical, 2)46        .background(highlighted ? DS.C.accentSoft : .clear, in: RoundedRectangle(cornerRadius: DS.R.card, style: .continuous))47        .accessibilityElement(children: .contain)48        .accessibilityIdentifier(message.role == .user ? "message-user" : "message-assistant")49    }50}5152// MARK: - User5354struct UserMessageView: View {55    let message: Message56    let versions: [Message]57    let isBusy: Bool58    let actions: MessageActions59    @Environment(\.transcriptFontSize) private var size60    @State private var editing = false61    @State private var editText = ""62    @State private var hovering = false63    @FocusState private var editorFocused: Bool6465    var body: some View {66        VStack(alignment: .trailing, spacing: 4) {67            let files = message.parts.filter { $0.textValue == nil }68            if !files.isEmpty { AttachmentStrip(parts: files, actions: actions) }69            if editing {70                VStack(alignment: .trailing, spacing: 8) {71                    TextEditor(text: $editText).font(.system(size: size)).scrollContentBackground(.hidden).frame(minHeight: 60, maxHeight: 260).focused($editorFocused)72                        .accessibilityLabel("Modifier le message")73                    HStack {74                        Button("Annuler") { editing = false }.keyboardShortcut(.cancelAction)75                        Button("Envoyer") { editing = false; actions.edit(message, editText) }.keyboardShortcut(.return, modifiers: .command).buttonStyle(.borderedProminent)76                            .disabled(editText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)77                    }78                    .controlSize(.small)79                }80                .padding(10).background(DS.C.userBubble, in: RoundedRectangle(cornerRadius: DS.R.bubble, style: .continuous))81                .overlay(RoundedRectangle(cornerRadius: DS.R.bubble, style: .continuous).strokeBorder(DS.C.accent.opacity(0.55), lineWidth: 1))82            } else if !message.visibleText.isEmpty {83                BubbleWidth {84                    Text(message.visibleText).font(.system(size: size)).lineSpacing(size * 0.28).textSelection(.enabled).foregroundStyle(DS.C.text)85                        .padding(.horizontal, 14).padding(.vertical, 9)86                        .background(DS.C.userBubble, in: RoundedRectangle(cornerRadius: DS.R.bubble, style: .continuous))87                }88                .frame(maxWidth: .infinity, alignment: .trailing)89            }90            HStack(spacing: 6) {91                VersionSwitcher(message: message, versions: versions, disabled: isBusy, actions: actions)92                if !message.isOptimistic {93                    IconButton(systemImage: "doc.on.doc", label: "Copier le message") { Pasteboard.copy(message.visibleText) }94                    IconButton(systemImage: "pencil", label: "Modifier et renvoyer") { editText = message.visibleText; editing = true; editorFocused = true }.disabled(isBusy)95                }96            }97            .font(.caption).foregroundStyle(DS.C.muted).opacity(hovering || versions.count > 1 || editing ? 1 : 0)98            .animation(DS.Motion.fade, value: hovering)99        }100        .frame(maxWidth: .infinity, alignment: .trailing)101        .onHover { hovering = $0 }102        .contextMenu {103            Button("Copier") { Pasteboard.copy(message.visibleText) }104            Button("Modifier et renvoyer") { editText = message.visibleText; editing = true }.disabled(isBusy || message.isOptimistic)105        }106    }107}108109/// Lays the user bubble out at its natural width, capped at 80 % of the reading column.110private struct BubbleWidth: Layout {111    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {112        guard let v = subviews.first else { return .zero }113        let cap = (proposal.width ?? 600) * 0.8114        return v.sizeThatFits(ProposedViewSize(width: cap, height: proposal.height))115    }116    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {117        subviews.first?.place(at: bounds.origin, proposal: ProposedViewSize(width: bounds.width, height: bounds.height))118    }119}120121// MARK: - Assistant122123struct AssistantMessageView: View {124    let message: Message125    let versions: [Message]126    let isBusy: Bool127    let showReasoning: Bool128    var isLast = false129    let actions: MessageActions130    @Environment(AppEnvironment.self) private var env131    @Environment(\.transcriptFontSize) private var size132    @State private var hovering = false133    @State private var showDetails = false134135    private var isStreaming: Bool { message.status == .streaming }136    private var identity: ModelIdentity { env.catalog.identity(for: message.modelId) }137138    var body: some View {139        VStack(alignment: .leading, spacing: 10) {140            header141            ForEach(Array(segments.enumerated()), id: \.offset) { _, segment in142                switch segment {143                case .part(let part): partView(part)144                case .tools(let calls, let reasoning): ToolCallGroup(calls: calls, reasoning: showReasoning ? reasoning : [], message: message, isBusy: isBusy, actions: actions)145                }146            }147            let sources = message.citations148            if !sources.isEmpty { SourceCards(citations: sources) }149            if isStreaming && message.parts.isEmpty { Text("…").font(.system(size: size)).foregroundStyle(DS.C.muted).accessibilityLabel("Le modèle réfléchit") }150            statusView151            footer152            if isLast, !isBusy, !isStreaming, let f = message.followups, !f.isEmpty, env.catalog.followUpsEnabled { FollowUpChips(suggestions: f, action: actions.followUp) }153        }154        .frame(maxWidth: .infinity, alignment: .leading)155        .onHover { hovering = $0 }156        .contextMenu {157            Button("Copier la réponse") { MessageCopy.copy(message, fontSize: size) }158            Button("Copier en Markdown") { Pasteboard.copy(message.visibleText) }159            Divider()160            Button("Régénérer") { actions.regenerate(message, nil) }.disabled(isBusy)161            Button("Régénérer avec un autre modèle…") { actions.regenerateWithPicker(message) }.disabled(isBusy)162            Button("Response Lens") { actions.lens(message) }.disabled(isStreaming || message.isOptimistic)163            Button("Lire à voix haute") { actions.speak(message) }.disabled(message.visibleText.isEmpty)164            Button("Créer une branche à partir d'ici") { actions.fork(message) }.disabled(isBusy)165        }166    }167168    /// Header line: `[ModelMark] name · route · served by · time`. The mark breathes while the model generates.169    private var header: some View {170        HStack(spacing: 7) {171            ModelChip(identity: identity, markSize: 16, font: .system(size: 12.5, weight: .semibold), breathing: isStreaming)172            if let mode = message.routing?.mode, mode != "manual" {173                Text(RoutingMode(rawValue: mode)?.label.lowercased() ?? mode).font(DS.F.caption).foregroundStyle(DS.C.muted).help(message.routing?.reason ?? "Modèle choisi par le routeur")174            }175            if let served = message.routing?.servedBy, !served.isEmpty, served != message.modelId {176                // the route badge already says OpenRouter: only the upstream provider is added177                Text("· servi par " + (served.hasPrefix("OpenRouter · ") ? String(served.dropFirst(13)) : served)).font(DS.F.caption).foregroundStyle(DS.C.muted).lineLimit(1).help("Fournisseur qui a servi la requête : \(served)")178            }179            if !isStreaming { Text("· " + message.createdAt.formatted(date: .omitted, time: .shortened)).font(DS.F.caption).foregroundStyle(DS.C.muted) }180            Spacer(minLength: 0)181        }182    }183184    private enum Segment { case part(MessagePart), tools([ToolCall], reasoning: [String]) }185    /// Parts in order; citations are gathered into one row of source cards under the text, and a run of three or more186    /// tool calls (with the reasoning steps between them) is folded into one summary line — an agentic search can chain187    /// a dozen calls.188    private var segments: [Segment] {189        var out: [Segment] = []; var run: [MessagePart] = []190        func flush() {191            let calls = run.compactMap { p -> ToolCall? in if case .toolCall(let c) = p { return c }; return nil }192            if calls.count >= 3 { out.append(.tools(calls, reasoning: run.compactMap { p in if case .reasoning(let t, _) = p, !t.isEmpty { return t }; return nil })) }193            else { out += run.map { .part($0) } }194            run = []195        }196        for p in message.parts {197            switch p {198            case .citation: continue199            case .toolCall: run.append(p)200            case .reasoning where !run.isEmpty: run.append(p)201            default: flush(); out.append(.part(p))202            }203        }204        flush()205        return out206    }207208    @ViewBuilder private func partView(_ part: MessagePart) -> some View {209        switch part {210        case .text(let t): if !t.isEmpty { MarkdownView(text: t) }211        case .reasoning(let t, _): if showReasoning, !t.isEmpty { ReasoningView(text: t, streaming: isStreaming && message.visibleText.isEmpty) }212        case .toolCall(let call): ToolCallView(call: call, message: message, isBusy: isBusy, actions: actions)213        case .image, .file, .generatedImage: AttachmentStrip(parts: [part], actions: actions)214        case .artifact(let id, let title, let type, let language):215            Button { actions.openArtifact(id) } label: {216                HStack(spacing: 10) {217                    Image(systemName: ArtifactIcon.name(type)).font(.system(size: 16)).foregroundStyle(DS.C.accent).frame(width: 26)218                    VStack(alignment: .leading, spacing: 1) { Text(title).font(DS.F.ui).foregroundStyle(DS.C.text).lineLimit(1); Text("Artefact · \(language ?? type)").font(DS.F.caption).foregroundStyle(DS.C.muted) }219                    Spacer(); Image(systemName: "chevron.right").font(.caption).foregroundStyle(DS.C.muted)220                }221                .padding(.horizontal, 12).padding(.vertical, 9).frame(maxWidth: 420).contentShape(Rectangle())222            }223            .buttonStyle(.plain).surface().accessibilityLabel("Ouvrir l'artefact \(title)")224        case .citation, .unknown: EmptyView()225        }226    }227228    @ViewBuilder private var statusView: some View {229        switch message.status {230        case .cancelled: StatusPill(text: "Arrêtée", color: DS.C.muted, systemImage: "stop.circle")231        case .incomplete:232            HStack(spacing: 8) {233                StatusPill(text: "Incomplète", color: DS.C.warn, systemImage: "exclamationmark.triangle")234                if let e = message.error { Text(e).font(.caption).foregroundStyle(DS.C.text2).lineLimit(2) }235                Button("Reprendre") { actions.regenerate(message, nil) }.controlSize(.small).disabled(isBusy)236            }237        case .error:238            HStack(spacing: 8) {239                StatusPill(text: "Échec", color: DS.C.danger, systemImage: "xmark.octagon")240                Text(message.error ?? "Le fournisseur a renvoyé une erreur.").font(.caption).foregroundStyle(DS.C.text2).lineLimit(3).textSelection(.enabled)241                Button("Réessayer") { actions.regenerate(message, nil) }.controlSize(.small).disabled(isBusy)242            }243        default: EmptyView()244        }245    }246247    /// Action bar: copy · regenerate (▾ other model) · branch · lens · speak · details. Quiet until hovered.248    @ViewBuilder private var footer: some View {249        if !isStreaming {250            HStack(spacing: 4) {251                VersionSwitcher(message: message, versions: versions, disabled: isBusy, actions: actions)252                IconButton(systemImage: "doc.on.doc", label: "Copier la réponse") { MessageCopy.copy(message, fontSize: size); env.toasts.show("Réponse copiée") }253                Menu {254                    Button("Régénérer") { actions.regenerate(message, nil) }255                    Divider()256                    Section("Avec un autre modèle") {257                        ForEach(env.catalog.menuModels.prefix(14)) { m in258                            Button { actions.regenerate(message, m.id) } label: { Text(m.menuTitle) }259                        }260                        Button("Choisir dans le catalogue…") { actions.regenerateWithPicker(message) }261                    }262                } label: { Image(systemName: "arrow.clockwise").frame(width: 22, height: 22) } primaryAction: { actions.regenerate(message, nil) }263                    .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize().disabled(isBusy).help("Régénérer (clic long : avec un autre modèle)").accessibilityLabel("Régénérer")264                    .accessibilityIdentifier("regenerate")265                IconButton(systemImage: "arrow.triangle.branch", label: "Créer une branche à partir d'ici") { actions.fork(message) }.disabled(isBusy)266                IconButton(systemImage: "camera.aperture", label: "Response Lens : résumer, expliquer, vérifier…") { actions.lens(message) }.disabled(message.isOptimistic).accessibilityIdentifier("lens-button")267                IconButton(systemImage: "speaker.wave.2", label: "Lire à voix haute") { actions.speak(message) }.disabled(message.visibleText.isEmpty)268                Spacer(minLength: 8)269                if let ignored = message.appliedParameters?.ignored, !ignored.isEmpty {270                    Label("\(ignored.count) non appliqué\(ignored.count > 1 ? "s" : "")", systemImage: "exclamationmark.circle").font(DS.F.caption).foregroundStyle(DS.C.warn)271                        .help("Paramètres non appliqués : " + ignored.map { "\($0.param) (\($0.reason))" }.joined(separator: " ; "))272                        .accessibilityLabel("Paramètres non appliqués : " + ignored.map { "\($0.param), \($0.reason)" }.joined(separator: " ; "))273                }274                detailsButton275            }276            .font(.caption).foregroundStyle(DS.C.muted)277            .opacity(hovering || versions.count > 1 || showDetails ? 1 : 0.5)278            .animation(DS.Motion.fade, value: hovering)279        }280    }281282    /// Details: tokens, cost (« facturé » when the provider reported the billed amount, « estimé » otherwise), latency.283    @ViewBuilder private var detailsButton: some View {284        if message.usage != nil || message.costUsd != nil || message.latencyMs != nil || identity.isLocal {285            Button { showDetails.toggle() } label: {286                HStack(spacing: 8) {287                    if let u = message.usage { Text("\(Format.tokens(u.input)) → \(Format.tokens(u.output))") }288                    if let cost = message.costLabel(route: identity.route) { Text(cost) }289                    if let l = message.latencyMs { Text(Format.duration(ms: l)) }290                }291                .font(.system(size: 10.5).monospacedDigit()).foregroundStyle(DS.C.muted).contentShape(Rectangle())292            }293            .buttonStyle(.plain).help("Détails de la réponse").accessibilityLabel("Détails : jetons, coût, durée")294            .popover(isPresented: $showDetails, arrowEdge: .bottom) { MessageDetails(message: message, identity: identity).padding(14).frame(width: 300) }295        }296    }297}298299/// Popover behind the metrics of an answer.300struct MessageDetails: View {301    let message: Message302    let identity: ModelIdentity303    var body: some View {304        VStack(alignment: .leading, spacing: 10) {305            ModelChip(identity: identity, markSize: 18, showCatalogNotice: true)306            if let r = message.routing?.reason, !r.isEmpty { Text(r).font(DS.F.caption).foregroundStyle(DS.C.text2).fixedSize(horizontal: false, vertical: true) }307            Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 5) {308                if let s = message.routing?.servedBy { row("Servi par", s) }309                if let u = message.usage {310                    row("Entrée", "\(u.input.formatted()) jetons" + ((u.cached ?? 0) > 0 ? " (dont \(u.cached!.formatted()) en cache)" : ""))311                    row("Sortie", "\(u.output.formatted()) jetons" + ((u.reasoning ?? 0) > 0 ? " (dont \(u.reasoning!.formatted()) de raisonnement)" : ""))312                }313                if identity.isLocal { row("Coût", "0 $ (local)") } else if let c = message.costUsd { row(message.isCostExact ? "Coût facturé" : "Coût estimé", Format.usd(c, digits: 6)) }314                if let t = message.ttftMs { row("Premier jeton", Format.duration(ms: t)) }315                if let l = message.latencyMs { row("Durée", Format.duration(ms: l)) }316                if let s = message.stopReason { row("Fin", s) }317            }318            Text(identity.isLocal ? "Inférence locale MacLustr AI : aucune facturation à la requête." : message.isCostExact ? "Coût facturé : montant rapporté par le fournisseur pour cette requête." : "Coût estimé : jetons × prix du catalogue.").font(.system(size: 10.5)).foregroundStyle(DS.C.muted).fixedSize(horizontal: false, vertical: true)319            if let ap = message.appliedParameters, !ap.ignored.isEmpty {320                Rectangle().fill(DS.C.border).frame(height: 1)321                ForEach(ap.ignored, id: \.param) { i in322                    VStack(alignment: .leading, spacing: 1) { Text("\(i.param) non appliqué").font(DS.F.caption).foregroundStyle(DS.C.warn); Text(i.reason).font(.system(size: 10.5)).foregroundStyle(DS.C.text2).fixedSize(horizontal: false, vertical: true) }323                }324            }325        }326    }327    private func row(_ k: String, _ v: String) -> some View {328        GridRow { Text(k).font(DS.F.caption).foregroundStyle(DS.C.muted); Text(v).font(.system(size: 11.5).monospacedDigit()).foregroundStyle(DS.C.text).textSelection(.enabled) }329    }330}331332// MARK: - Sources and follow-ups333334/// Sources returned by `web_search` (`citation` parts): a horizontal row of compact, numbered cards — domain in335/// caption, title on two lines. Favicon-less by design: nothing is fetched to draw a card.336struct SourceCards: View {337    let citations: [Citation]338    var body: some View {339        VStack(alignment: .leading, spacing: 6) {340            Label("\(citations.count) source\(citations.count > 1 ? "s" : "")", systemImage: "globe").font(DS.F.caption).foregroundStyle(DS.C.muted)341            ScrollView(.horizontal) {342                HStack(spacing: 8) {343                    ForEach(Array(citations.enumerated()), id: \.element.id) { i, c in SourceCard(index: i + 1, citation: c) }344                }345                .padding(.vertical, 1).padding(.horizontal, 1)346            }347            .scrollIndicators(.never).scrollBounceBehavior(.basedOnSize, axes: .horizontal)348        }349        .accessibilityElement(children: .contain).accessibilityIdentifier("source-cards")350    }351}352353struct SourceCard: View {354    let index: Int355    let citation: Citation356    @Environment(\.openURL) private var openURL357    @State private var hovering = false358    var body: some View {359        Button { if let url = LinkPolicy.safeURL(citation.url) { openURL(url) } } label: {360            VStack(alignment: .leading, spacing: 4) {361                HStack(spacing: 5) {362                    Text("\(index)").font(.system(size: 9.5, weight: .bold).monospacedDigit()).foregroundStyle(DS.C.accent)363                        .frame(minWidth: 15, minHeight: 15).background(DS.C.accentSoft, in: RoundedRectangle(cornerRadius: 4, style: .continuous))364                    Text(citation.domain).font(DS.F.caption).foregroundStyle(DS.C.muted).lineLimit(1)365                }366                Text(citation.title?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty ?? citation.domain).font(.system(size: 12, weight: .medium)).foregroundStyle(DS.C.text)367                    .lineLimit(2, reservesSpace: true).multilineTextAlignment(.leading)368            }369            .padding(.horizontal, 10).padding(.vertical, 8).frame(width: 190, alignment: .leading).contentShape(Rectangle())370        }371        .buttonStyle(.plain)372        .background(hovering ? DS.C.surface2 : DS.C.surface, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))373        .overlay(RoundedRectangle(cornerRadius: DS.R.control, style: .continuous).strokeBorder(hovering ? DS.C.borderStrong : DS.C.border, lineWidth: 1))374        .onHover { hovering = $0 }375        .help([citation.url, citation.snippet.map { String($0.prefix(280)) }].compactMap { $0 }.joined(separator: "\n\n"))376        .contextMenu { Button("Ouvrir dans le navigateur") { if let url = LinkPolicy.safeURL(citation.url) { openURL(url) } }; Button("Copier le lien") { Pasteboard.copy(citation.url) } }377        .accessibilityLabel("Source \(index) : \(citation.title ?? citation.domain), \(citation.domain)").accessibilityIdentifier("source-card")378    }379}380381private extension String { var nonEmpty: String? { isEmpty ? nil : self } }382383/// Smart Follow-Ups proposed by the server after an answer: one click sends the suggestion.384struct FollowUpChips: View {385    let suggestions: [String]386    let action: (String) -> Void387    var body: some View {388        VStack(alignment: .leading, spacing: 6) {389            ForEach(suggestions.prefix(3), id: \.self) { s in390                Button { action(s) } label: {391                    HStack(spacing: 7) {392                        Image(systemName: "arrow.turn.down.right").font(.system(size: 10, weight: .semibold)).foregroundStyle(DS.C.accent)393                        Text(s).font(.system(size: 12.5)).foregroundStyle(DS.C.text2).lineLimit(2).multilineTextAlignment(.leading)394                    }395                    .padding(.horizontal, 11).padding(.vertical, 7).contentShape(Rectangle())396                }397                .buttonStyle(.plain)398                .background(DS.C.surface, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))399                .overlay(RoundedRectangle(cornerRadius: DS.R.control, style: .continuous).strokeBorder(DS.C.border, lineWidth: 1))400                .help("Envoyer cette suite").accessibilityIdentifier("followup")401            }402        }403        .padding(.top, 2).accessibilityElement(children: .contain).accessibilityLabel("Suites proposées")404    }405}406407struct VersionSwitcher: View {408    let message: Message409    let versions: [Message]410    let disabled: Bool411    let actions: MessageActions412    var body: some View {413        if versions.count > 1, let i = versions.firstIndex(where: { $0.id == message.id }) {414            HStack(spacing: 2) {415                IconButton(systemImage: "chevron.left", label: "Version précédente") { actions.showVersion(versions[i - 1]) }.disabled(disabled || i == 0)416                Text("\(i + 1)/\(versions.count)").font(.caption.monospacedDigit()).accessibilityLabel("Version \(i + 1) sur \(versions.count)")417                IconButton(systemImage: "chevron.right", label: "Version suivante") { actions.showVersion(versions[i + 1]) }.disabled(disabled || i == versions.count - 1)418            }419        }420    }421}422423/// Quiet « waiting » mark used before the first token (Streaming Presence is carried by the Lumen line and the424/// breathing model mark — no spinner, no bouncing dots).425struct TypingIndicator: View {426    var body: some View { Text("…").font(.system(size: 14, weight: .semibold)).foregroundStyle(DS.C.muted).padding(.vertical, 2).accessibilityLabel("Le modèle réfléchit") }427}428429struct ReasoningView: View {430    let text: String431    let streaming: Bool432    @State private var expanded = false433    @Environment(\.transcriptFontSize) private var size434    var body: some View {435        VStack(alignment: .leading, spacing: 6) {436            Button { withAnimation(DS.Motion.snappy) { expanded.toggle() } } label: {437                HStack(spacing: 6) {438                    Image(systemName: "brain").font(.system(size: 11))439                    Text(streaming ? "Raisonnement en cours" : "Raisonnement").font(DS.F.caption)440                    Image(systemName: "chevron.right").font(.system(size: 8, weight: .bold)).rotationEffect(.degrees(expanded ? 90 : 0))441                }442                .foregroundStyle(DS.C.muted).contentShape(Rectangle())443            }444            .buttonStyle(.plain).accessibilityLabel(expanded ? "Masquer le raisonnement" : "Afficher le raisonnement")445            if expanded {446                Text(text).font(.system(size: size * 0.92)).foregroundStyle(DS.C.text2).textSelection(.enabled).lineSpacing(3)447                    .frame(maxWidth: .infinity, alignment: .leading).padding(.leading, 10)448                    .overlay(alignment: .leading) { Rectangle().fill(DS.C.border).frame(width: 2) }449            }450        }451    }452}453454/// A run of consecutive tool calls folded into one line: « 9 outils · web_search ×5 · fetch_page ×4 », with the call in455/// progress shown underneath; expandable to the full list.456struct ToolCallGroup: View {457    let calls: [ToolCall]458    var reasoning: [String] = []459    let message: Message460    let isBusy: Bool461    let actions: MessageActions462    @State private var expanded = false463464    private var summary: String {465        var counts: [(String, Int)] = []466        for c in calls { if let i = counts.firstIndex(where: { $0.0 == c.name }) { counts[i].1 += 1 } else { counts.append((c.name, 1)) } }467        return counts.map { $0.1 > 1 ? "\($0.0) ×\($0.1)" : $0.0 }.joined(separator: " · ")468    }469    private var needsAttention: [ToolCall] { calls.filter { $0.status == .running || $0.status == .pendingApproval } }470    private var failed: Int { calls.filter { $0.status == .error }.count }471472    var body: some View {473        VStack(alignment: .leading, spacing: 6) {474            Button { withAnimation(DS.Motion.snappy) { expanded.toggle() } } label: {475                HStack(spacing: 7) {476                    Circle().fill(needsAttention.isEmpty ? (failed > 0 ? DS.C.warn : DS.C.ok) : DS.C.accent).frame(width: 6, height: 6)477                    Image(systemName: "wrench.and.screwdriver").font(.system(size: 11)).foregroundStyle(DS.C.text2).frame(width: 14)478                    Text("\(calls.count) outils").font(.system(size: 12, weight: .medium)).foregroundStyle(DS.C.text2)479                    Text("· " + summary).font(DS.F.mono(11)).foregroundStyle(DS.C.muted).lineLimit(1)480                    Spacer(minLength: 4)481                    if failed > 0 { Text("\(failed) en erreur").font(DS.F.caption).foregroundStyle(DS.C.danger) }482                    let total = calls.compactMap(\.durationMs).reduce(0, +)483                    if total > 0 { Text(Format.duration(ms: total)).font(.system(size: 10.5).monospacedDigit()).foregroundStyle(DS.C.muted) }484                    Image(systemName: "chevron.right").font(.system(size: 8, weight: .bold)).foregroundStyle(DS.C.muted).rotationEffect(.degrees(expanded ? 90 : 0))485                }486                .padding(.horizontal, 10).padding(.vertical, 7).contentShape(Rectangle())487            }488            .buttonStyle(.plain)489            .overlay(RoundedRectangle(cornerRadius: DS.R.control, style: .continuous).strokeBorder(DS.C.border, lineWidth: 1))490            .accessibilityLabel("\(calls.count) appels d'outils : \(summary)").accessibilityHint(expanded ? "Replier" : "Déplier")491            ForEach(expanded ? calls : needsAttention, id: \.id) { c in ToolCallView(call: c, message: message, isBusy: isBusy, actions: actions) }492            if expanded, !reasoning.isEmpty { ReasoningView(text: reasoning.joined(separator: "\n\n"), streaming: false) }493        }494    }495}496497/// One line per tool call — « web_search · query » with a state dot (running pulse → ok / error) — expandable.498struct ToolCallView: View {499    let call: ToolCall500    let message: Message501    let isBusy: Bool502    let actions: MessageActions503    @State private var expanded = false504    @Environment(\.accessibilityReduceMotion) private var reduceMotion505    @State private var pulse = false506507    private var icon: String {508        switch call.name { case "web_search": "magnifyingglass"; case "fetch_page": "globe"; case "python": "terminal"; case "search_documents": "doc.text.magnifyingglass"; case "generate_image": "photo"; case "save_memory": "brain.head.profile"; default: "wrench.and.screwdriver" }509    }510    private var summary: String {511        let i = call.input512        return i["query"]?.stringValue ?? i["url"]?.stringValue ?? i["prompt"]?.stringValue ?? i["content"]?.stringValue ?? i["code"]?.stringValue?.components(separatedBy: "\n").first ?? ""513    }514    private var dotColor: Color {515        switch call.status { case .running: DS.C.accent; case .ok: DS.C.ok; case .error: DS.C.danger; case .denied: DS.C.muted; case .pendingApproval: DS.C.warn }516    }517    private var statusText: String {518        switch call.status { case .running: "en cours"; case .ok: "terminé"; case .error: "erreur"; case .denied: "refusé"; case .pendingApproval: "en attente d'accord" }519    }520521    var body: some View {522        VStack(alignment: .leading, spacing: 6) {523            Button { withAnimation(DS.Motion.snappy) { expanded.toggle() } } label: {524                HStack(spacing: 7) {525                    Circle().fill(dotColor).frame(width: 6, height: 6).opacity(call.status == .running && pulse ? 0.35 : 1)526                    Image(systemName: icon).font(.system(size: 11)).foregroundStyle(DS.C.text2).frame(width: 14)527                    Text(call.name).font(DS.F.mono(11.5, weight: .medium)).foregroundStyle(DS.C.text2)528                    if !summary.isEmpty { Text("· " + summary).font(.system(size: 12)).foregroundStyle(DS.C.muted).lineLimit(1) }529                    Spacer(minLength: 4)530                    if call.status == .ok, let d = call.durationMs { Text(Format.duration(ms: d)).font(.system(size: 10.5).monospacedDigit()).foregroundStyle(DS.C.muted) }531                    if call.status == .denied || call.status == .pendingApproval || call.status == .error { Text(statusText).font(DS.F.caption).foregroundStyle(dotColor) }532                    Image(systemName: "chevron.right").font(.system(size: 8, weight: .bold)).foregroundStyle(DS.C.muted).rotationEffect(.degrees(expanded ? 90 : 0))533                }534                .contentShape(Rectangle())535            }536            .buttonStyle(.plain)537            if expanded {538                VStack(alignment: .leading, spacing: 6) {539                    CodeBlockView(language: call.name == "python" ? "python" : "json", code: call.name == "python" ? (call.input["code"]?.stringValue ?? call.input.jsonString(pretty: true)) : call.input.jsonString(pretty: true))540                    if let out = call.output, !out.isNull { CodeBlockView(language: "json", code: String((out.stringValue ?? out.jsonString(pretty: true)).prefix(6000))) }541                    if let e = call.error { Text(e).font(.caption).foregroundStyle(DS.C.danger).textSelection(.enabled) }542                }543            }544            if call.status == .pendingApproval {545                HStack {546                    Text("Cet outil demande ton accord.").font(.caption).foregroundStyle(DS.C.text2)547                    Spacer()548                    Button("Refuser") { actions.decideTools(message, [], [call.id]) }549                    Button("Autoriser") { actions.decideTools(message, [call.id], []) }.buttonStyle(.borderedProminent)550                }551                .controlSize(.small).disabled(isBusy)552            }553        }554        .padding(.horizontal, 10).padding(.vertical, 7)555        .background(DS.C.surface.opacity(expanded || call.status == .pendingApproval ? 1 : 0), in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))556        .overlay(RoundedRectangle(cornerRadius: DS.R.control, style: .continuous).strokeBorder(DS.C.border, lineWidth: 1))557        .onChange(of: call.status == .running, initial: true) { _, running in558            if running, !reduceMotion { withAnimation(.easeInOut(duration: 0.8).repeatForever(autoreverses: true)) { pulse = true } } else { pulse = false }559        }560        .accessibilityElement(children: .contain).accessibilityLabel("Appel d'outil \(call.name), \(statusText)")561    }562}563564enum ArtifactIcon {565    static func name(_ type: String) -> String {566        switch type { case "html": "safari"; case "svg": "square.on.circle"; case "react": "atom"; case "mermaid": "point.3.connected.trianglepath.dotted"; case "python": "terminal"; case "markdown": "doc.richtext"; default: "curlybraces" }567    }568}569570/// Images and files attached to a message.571struct AttachmentStrip: View {572    let parts: [MessagePart]573    let actions: MessageActions574    var body: some View {575        HStack(alignment: .top, spacing: 8) {576            ForEach(Array(parts.enumerated()), id: \.offset) { _, part in577                switch part {578                case .image(let id, _, let name): AttachmentImage(attachmentId: id, name: name ?? "image").onTapGesture { actions.openAttachment(id, name ?? "image.png") }579                case .generatedImage(let id, let prompt, _): AttachmentImage(attachmentId: id, name: prompt, maxSide: 360).onTapGesture { actions.openAttachment(id, "image-generee.png") }580                case .file(let id, _, let name, let size, let pages):581                    Button { actions.openAttachment(id, name) } label: {582                        HStack(spacing: 8) {583                            Image(systemName: FileIcon.name(for: name)).font(.title3).foregroundStyle(.secondary)584                            VStack(alignment: .leading, spacing: 1) {585                                Text(name).font(.caption.weight(.medium)).lineLimit(1)586                                Text([Format.bytes(size), pages.map { "\($0) p." }].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")).font(.caption2).foregroundStyle(.secondary)587                            }588                        }589                        .padding(.horizontal, 10).padding(.vertical, 7).frame(maxWidth: 240, alignment: .leading).contentShape(Rectangle())590                    }591                    .buttonStyle(.plain).surface(radius: DS.R.control).help("Ouvrir \(name)").accessibilityLabel("Pièce jointe \(name)")592                default: EmptyView()593                }594            }595        }596    }597}598599enum FileIcon {600    static func name(for filename: String) -> String {601        switch (filename as NSString).pathExtension.lowercased() {602        case "pdf": "doc.richtext"; case "docx", "doc": "doc.text"; case "xlsx", "xls", "csv": "tablecells"; case "mp3", "m4a", "wav", "ogg", "webm": "waveform"603        case "png", "jpg", "jpeg", "gif", "webp", "heic": "photo"; case "json", "md", "txt": "doc.plaintext"; default: "doc"604        }605    }606}607608struct AttachmentImage: View {609    let attachmentId: String610    let name: String611    var maxSide: CGFloat = 220612    @Environment(AppEnvironment.self) private var env613    @State private var image: NSImage?614    @State private var failed = false615    var body: some View {616        Group {617            if let image {618                Image(nsImage: image).resizable().aspectRatio(contentMode: .fit).frame(maxWidth: maxSide, maxHeight: maxSide)619            } else {620                RoundedRectangle(cornerRadius: 10).fill(.quaternary).frame(width: 120, height: 90)621                    .overlay { if failed { Image(systemName: "photo.badge.exclamationmark").foregroundStyle(.secondary) } else { ProgressView().controlSize(.small) } }622            }623        }624        .clipShape(RoundedRectangle(cornerRadius: DS.R.control, style: .continuous)).overlay(RoundedRectangle(cornerRadius: DS.R.control, style: .continuous).strokeBorder(DS.C.border, lineWidth: 1))625        .task(id: attachmentId) { image = await env.files.image(for: attachmentId); failed = image == nil }626        .help(name).accessibilityLabel("Image : \(name)").accessibilityAddTraits(.isButton)627    }628}629630/// Copies an answer as plain Markdown and as formatted text (RTF).631enum MessageCopy {632    static func copy(_ message: Message, fontSize: CGFloat) {633        let text = message.visibleText634        Pasteboard.copy(plain: text, rich: RichText.attributed(markdown: text, baseSize: fontSize))635    }636}637
Files main
Menu

Theme