SPB Git

Repository Public

TimelineSheet.swift 13.2 KB 223 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Features/Panels/TimelineSheet.swift4//  Description: Conversation Timeline + Replay — the recorded events of a conversation (prompts, answers, model5//               switches, tools, files, branches) in order, with a replay cursor. Nothing is reconstructed client-side.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import SwiftUI1213struct TimelineSheet: View {14    let session: ChatSession15    let onJump: (String) -> Void16    @Environment(AppEnvironment.self) private var env17    @Environment(\.dismiss) private var dismiss18    @Environment(\.accessibilityReduceMotion) private var reduceMotion19    @State private var timeline: ConversationTimeline?20    @State private var error: String?21    @State private var replay = TimelineReplay(count: 0)22    @State private var replaying = false2324    var body: some View {25        VStack(spacing: 0) {26            SheetHeader(title: String(localized: "Chronologie"), subtitle: timeline.map { String(localized: "Événements enregistrés · \($0.events.count)") }, onClose: { dismiss() })27            if let t = timeline {28                if t.events.isEmpty {29                    ContentUnavailableView { Label("Aucun événement", systemImage: "clock") } description: { Text(t.note ?? String(localized: "Cette conversation n’a pas encore d’événement enregistré.")) }30                } else { list(t) }31            } else if let error {32                ContentUnavailableView { Label("Chronologie indisponible", systemImage: "wifi.slash") } description: { Text(error) } actions: { Button("Réessayer") { Task { await load() } } }33            } else { Spacer(); ProgressView(); Spacer() }34        }35        .background(Color.appBackground)36        .safeAreaInset(edge: .bottom, spacing: 0) { if let t = timeline, t.events.count > 1 { controls(t) } }37        .task { await load() }38        // Replay: a real timer advances the cursor, one recorded event at a time39        .task(id: replay.isPlaying) {40            guard replay.isPlaying else { return }41            while !Task.isCancelled && replay.isPlaying {42                try? await Task.sleep(for: .milliseconds(1200))43                if Task.isCancelled || !replay.isPlaying { return }44                withAnimation(Motion.snappy(reduceMotion)) { replay.step(1) }45                env.haptics.selection()46            }47        }48    }4950    private func load() async {51        guard let id = session.conversationId else { error = String(localized: "La conversation n’a pas encore de message."); return }52        do {53            let t = try await env.api.timeline(conversation: id)54            timeline = t; error = nil55            if replay.count != t.events.count { replay = TimelineReplay(count: t.events.count); replay.seek(max(t.events.count - 1, 0)) }56        } catch let e { if timeline == nil { error = (e as? APIError)?.message ?? String(localized: "Chargement impossible.") } }57    }5859    // MARK: events6061    private func list(_ t: ConversationTimeline) -> some View {62        ScrollViewReader { proxy in63            ScrollView {64                LazyVStack(alignment: .leading, spacing: 0) {65                    ForEach(t.events) { e in66                        row(e, isLast: e.id == t.events.last?.id).id(e.id)67                    }68                    if let note = t.note { SourceNote(text: note).padding(.top, 12).padding(.leading, 4) }69                }70                .padding(.horizontal, 16).padding(.top, 8).padding(.bottom, 20)71            }72            .onChange(of: replay.position) { _, p in73                guard replaying else { return }74                withAnimation(Motion.smooth(reduceMotion)) { proxy.scrollTo(p, anchor: .center) }75            }76        }77    }7879    private func row(_ e: TimelineEvent, isLast: Bool) -> some View {80        let current = replaying && e.id == replay.position81        let future = replaying && e.id > replay.position82        return Button {83            env.haptics.selection()84            if let id = e.messageId { dismiss(); onJump(id) }85            else if e.kind == .branch, let c = e.conversationId { dismiss(); env.open(c) }86        } label: {87            HStack(alignment: .top, spacing: 12) {88                VStack(spacing: 0) {89                    Image(systemName: symbol(e)).font(.system(size: 12, weight: .semibold))90                        .foregroundStyle(current ? Color.white : tint(e))91                        .frame(width: 28, height: 28)92                        .background(current ? Color.accentColor : tint(e).opacity(0.14), in: .circle)93                    if !isLast { Rectangle().fill(Color.hairline).frame(width: 1).frame(maxHeight: .infinity) }94                }95                VStack(alignment: .leading, spacing: 5) {96                    HStack(spacing: 6) {97                        Text(title(e)).font(.subheadline.weight(.semibold)).foregroundStyle(Color.textPrimary).lineLimit(1)98                        if !e.active { Text("autre version").font(.spMicro).foregroundStyle(Color.muted).padding(.horizontal, 6).padding(.vertical, 2).background(Color.surface2, in: .capsule) }99                        Spacer(minLength: 4)100                        if let at = e.at { Text(at, format: .dateTime.hour().minute().second()).font(.caption2.monospacedDigit()).foregroundStyle(Color.muted) }101                    }102                    detail(e)103                }104                .padding(.bottom, 16)105            }106            .padding(.horizontal, 8).padding(.top, 8)107            .background(current ? Color.accentSoft : Color.clear, in: .rect(cornerRadius: Radius.control, style: .continuous))108            .opacity(future ? 0.38 : 1)109            .contentShape(.rect)110        }111        .buttonStyle(.plain)112        .accessibilityElement(children: .combine)113        .accessibilityHint(e.messageId != nil ? String(localized: "Affiche ce message dans la conversation") : "")114        .accessibilityAddTraits(current ? .isSelected : [])115        .accessibilityIdentifier("timeline.event")116    }117118    @ViewBuilder private func detail(_ e: TimelineEvent) -> some View {119        switch e.kind {120        case .prompt:121            if let p = e.preview, !p.isEmpty { Text(p).font(.footnote).foregroundStyle(Color.textSecondary).lineLimit(3).multilineTextAlignment(.leading) }122        case .response:123            if let m = e.model { chip(m) }124            if let p = e.preview, !p.isEmpty { Text(Self.plain(p)).font(.footnote).foregroundStyle(Color.textSecondary).lineLimit(3).multilineTextAlignment(.leading) }125            let facts: [String] = [126                e.inputTokens.flatMap { i in e.outputTokens.map { "\(Format.tokens(i)) → \(Format.tokens($0))" } },127                e.costUsd.map(Format.usd), e.latencyMs.map { Format.duration(ms: $0) },128                e.ttftMs.map { String(localized: "1ᵉʳ jeton \(Format.duration(ms: $0))") },129                e.citations.flatMap { $0 > 0 ? String(localized: "\($0) source(s)") : nil },130                e.variants.flatMap { n in n > 1 ? String(localized: "version \(e.variant ?? 1) / \(n)") : nil },131                e.status.flatMap { $0 == "complete" ? nil : $0 }, e.servedBy,132            ].compactMap { $0 }133            if !facts.isEmpty { Text(facts.joined(separator: " · ")).font(.caption2.monospacedDigit()).foregroundStyle(Color.muted).multilineTextAlignment(.leading) }134        case .modelSwitch:135            HStack(spacing: 8) {136                if let f = e.from { chip(f) }137                Image(systemName: "arrow.right").font(.system(size: 10, weight: .bold)).foregroundStyle(Color.muted)138                if let t = e.to { chip(t) }139            }140        case .tool:141            Text([e.tool.map { ServerTool(name: $0).label }, e.status.flatMap { $0 == "ok" ? nil : $0 }, e.durationMs.map { Format.duration(ms: $0) }].compactMap { $0 }.joined(separator: " · ")).font(.footnote).foregroundStyle(Color.textSecondary)142        case .file, .image, .artifact, .branch, .other:143            if let n = e.name ?? e.preview, !n.isEmpty { Text(n).font(.footnote).foregroundStyle(Color.textSecondary).lineLimit(2).multilineTextAlignment(.leading) }144        }145    }146147    /// A preview is one line of the recorded text: Markdown marks are dropped for reading, nothing else changes.148    static func plain(_ s: String) -> String {149        s.replacing(/\[([^\]]+)\]\([^)]*\)?/) { String($0.1) }.replacingOccurrences(of: "**", with: "").replacingOccurrences(of: "`", with: "").replacingOccurrences(of: "\n", with: " ")150    }151152    private func chip(_ modelId: String) -> some View {153        let i = ModelIdentity(model: env.catalog.model(modelId), modelId: modelId, provider: nil)154        return ModelChip(logo: i.logo, creatorName: i.creatorName, name: i.name, route: i.route, markSize: 14, font: .spCaption)155    }156157    private func title(_ e: TimelineEvent) -> String {158        switch e.kind {159        case .prompt: String(localized: "Message"); case .response: String(localized: "Réponse"); case .modelSwitch: String(localized: "Changement de modèle")160        case .tool: String(localized: "Outil"); case .file: String(localized: "Fichier"); case .image: String(localized: "Image"); case .artifact: String(localized: "Artefact")161        case .branch: String(localized: "Branche"); case .other: e.rawType162        }163    }164    private func symbol(_ e: TimelineEvent) -> String {165        switch e.kind {166        case .prompt: "person.fill"; case .response: "sparkles"; case .modelSwitch: "arrow.left.arrow.right"; case .tool: "wrench.and.screwdriver.fill"167        case .file: "doc.fill"; case .image: "photo.fill"; case .artifact: "doc.richtext.fill"; case .branch: "arrow.triangle.branch"; case .other: "circle.fill"168        }169    }170    private func tint(_ e: TimelineEvent) -> Color {171        if e.kind == .response, let s = e.status, s == "error" || s == "incomplete" { return .danger }172        if e.kind == .tool, let s = e.status, s != "ok" { return .warning }173        return e.kind == .prompt ? .textSecondary : .accentColor174    }175176    // MARK: replay controls177178    private func controls(_ t: ConversationTimeline) -> some View {179        VStack(spacing: 6) {180            if replaying {181                Slider(value: Binding(get: { Double(replay.position) }, set: { v in replay.isPlaying = false; replay.seek(Int(v.rounded())) }), in: 0...Double(max(t.events.count - 1, 1)), step: 1)182                    .tint(.accentColor)183                    .accessibilityLabel(String(localized: "Position de la relecture"))184                    .accessibilityValue(String(localized: "événement \(replay.position + 1) sur \(t.events.count)"))185                    .accessibilityIdentifier("timeline.scrubber")186            }187            HStack(spacing: 4) {188                Text(replaying ? "\(replay.position + 1) / \(t.events.count)" : String(localized: "Relecture")).font(.spCaption).monospacedDigit().foregroundStyle(Color.textSecondary).contentTransition(.numericText()).frame(minWidth: 70, alignment: .leading)189                Spacer(minLength: 0)190                control("backward.end.fill", String(localized: "Événement précédent")) { begin(); replay.isPlaying = false; withAnimation(Motion.snappy(reduceMotion)) { replay.step(-1) } }191                    .disabled(replaying && replay.position == 0)192                Button {193                    env.haptics.tap()194                    if !replaying { replaying = true; replay.seek(0); replay.isPlaying = true } else { replay.togglePlay() }195                } label: {196                    Image(systemName: replay.isPlaying ? "pause.fill" : "play.fill").font(.system(size: 15, weight: .bold)).foregroundStyle(.white)197                        .frame(width: 40, height: 40).background(Color.accentColor, in: .circle).frame(width: 48, height: 44).contentShape(.rect)198                        .contentTransition(.symbolEffect(.replace))199                }200                .buttonStyle(PressScale())201                .accessibilityLabel(replay.isPlaying ? String(localized: "Mettre la relecture en pause") : String(localized: "Lancer la relecture"))202                .accessibilityIdentifier("timeline.play")203                control("forward.end.fill", String(localized: "Événement suivant")) { begin(); replay.isPlaying = false; withAnimation(Motion.snappy(reduceMotion)) { replay.step(1) } }204                    .disabled(replaying && replay.isAtEnd)205                Spacer(minLength: 0)206                Button { replay.isPlaying = false; withAnimation(Motion.snappy(reduceMotion)) { replaying = false } } label: { Text("Terminer").font(.spCaption).foregroundStyle(Color.textSecondary).frame(minWidth: 70, minHeight: 44, alignment: .trailing).contentShape(.rect) }207                    .buttonStyle(.plain).opacity(replaying ? 1 : 0).disabled(!replaying)208            }209        }210        .padding(.horizontal, 14).padding(.vertical, 6)211        .floatSurface(cornerRadius: Radius.float)212        .padding(.horizontal, 12).padding(.bottom, 8)213        .animation(Motion.smooth(reduceMotion), value: replaying)214    }215216    private func begin() { if !replaying { replaying = true } }217218    private func control(_ symbol: String, _ label: String, action: @escaping () -> Void) -> some View {219        Button { env.haptics.selection(); action() } label: { Image(systemName: symbol).font(.system(size: 14, weight: .semibold)).foregroundStyle(Color.textPrimary).frame(width: 44, height: 44).contentShape(.rect) }220            .buttonStyle(PressScale()).accessibilityLabel(label)221    }222}223
Files main
Menu

Theme