Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Chat/Panels/TimelinePanel.swift3// Description: Timeline tab: the recorded events of a conversation on a vertical rail, and Replay (previous / play-pause / next, speed, scrubber) that steps through them and scrolls the transcript.4import SwiftUI5import SPChatCore67/// Loads `GET /api/conversations/{id}/timeline` and drives the Replay cursor. Playback waits between two steps for8/// a pause derived from the real gap between the two events (see `ReplayCursor`); nothing is invented.9@Observable final class TimelineModel {10 private(set) var timeline: ConversationTimeline?11 private(set) var cursor = ReplayCursor()12 private(set) var isLoading = false13 private(set) var error: String?14 private(set) var conversationId: String?15 @ObservationIgnored private var generation = 016 @ObservationIgnored private var playTask: Task<Void, Never>?1718 var events: [TimelineEvent] { timeline?.events ?? [] }19 var currentEvent: TimelineEvent? { cursor.index.flatMap { events.indices.contains($0) ? events[$0] : nil } }2021 func load(conversationId id: String?, api: APIClient) async {22 if id != conversationId { stop(); timeline = nil; error = nil; conversationId = id; cursor = ReplayCursor() }23 guard let id else { isLoading = false; return }24 generation += 1; let mine = generation25 isLoading = true26 do {27 let t = try await api.conversationTimeline(id)28 guard mine == generation else { return }29 timeline = t; error = nil30 cursor.reload(times: t.events.map(\.at))31 if !cursor.isPlaying { playTask?.cancel(); playTask = nil }32 } catch {33 guard mine == generation, APIError.from(error).kind != .cancelled else { return }34 self.error = APIError.from(error).message35 }36 if mine == generation { isLoading = false }37 }3839 // MARK: Replay transport4041 func togglePlay() {42 cursor.toggle()43 if cursor.isPlaying { schedule() } else { playTask?.cancel(); playTask = nil }44 }45 func pause() { cursor.pause(); playTask?.cancel(); playTask = nil }46 func stop() { cursor.stop(); playTask?.cancel(); playTask = nil }47 func next() { cursor.stepForward(); reschedule() }48 func previous() { cursor.stepBack(); reschedule() }49 func select(_ event: TimelineEvent) { cursor.seek(to: event.index); reschedule() }50 func scrub(_ progress: Double) { cursor.seek(progress: progress); reschedule() }51 func cycleSpeed() { cursor.cycleSpeed(); reschedule() }5253 /// A manual move while playing restarts the wait from the new position.54 private func reschedule() { if cursor.isPlaying { schedule() } else { playTask?.cancel(); playTask = nil } }5556 private func schedule() {57 playTask?.cancel()58 playTask = Task { [weak self] in59 while let self, self.cursor.isPlaying, let delay = self.cursor.delayToNext {60 try? await Task.sleep(for: .milliseconds(Int(delay * 1000)))61 guard !Task.isCancelled, self.cursor.isPlaying else { return }62 self.cursor.stepForward()63 }64 }65 }66}6768struct TimelinePanel: View {69 let chat: ChatViewModel70 @Bindable var window: WindowModel71 let model: TimelineModel72 @Environment(AppEnvironment.self) private var env73 @Environment(\.accessibilityReduceMotion) private var reduceMotion7475 private struct Trigger: Hashable { var conversation: String?; var messages: Int; var last: String?; var streaming: Bool }76 private var trigger: Trigger { Trigger(conversation: chat.conversationId, messages: chat.messages.count, last: chat.messages.last?.id, streaming: chat.isStreaming) }7778 var body: some View {79 Group {80 if chat.conversationId == nil {81 PanelPlaceholder(systemImage: PanelTab.timeline.systemImage, title: "Nouvelle conversation", message: "La chronologie se construit à partir des événements enregistrés.")82 } else if let t = model.timeline {83 if t.events.isEmpty { PanelPlaceholder(systemImage: PanelTab.timeline.systemImage, title: "Aucun événement enregistré", message: t.note) }84 else { VStack(spacing: 0) { ReplayBar(model: model); Hairline(); list(t) } }85 } else if let error = model.error {86 PanelPlaceholder(systemImage: "exclamationmark.triangle", title: "Chronologie indisponible", message: error, actionTitle: "Réessayer") { Task { await reload() } }87 } else {88 Color.clear.frame(maxWidth: .infinity, maxHeight: .infinity)89 }90 }91 .overlay(alignment: .top) { PanelLoadingLine(active: model.isLoading && model.timeline == nil) }92 .task(id: trigger) { await reload() }93 .onChange(of: model.cursor.index) { _, _ in if let e = model.currentEvent { reveal(e) } }94 .onDisappear { model.pause() }95 .accessibilityIdentifier("panel-timeline")96 }9798 private func reload() async { await model.load(conversationId: chat.conversationId, api: env.api) }99100 /// Brings the message of an event into view in the transcript (only messages of the displayed thread can be reached).101 private func reveal(_ e: TimelineEvent) {102 guard let id = e.messageId, chat.messages.contains(where: { $0.id == id }) else { return }103 chat.scrollTarget = id104 }105106 private func list(_ t: ConversationTimeline) -> some View {107 ScrollViewReader { proxy in108 ScrollView {109 LazyVStack(alignment: .leading, spacing: 0) {110 ForEach(t.events) { e in111 if showsDay(e, in: t.events) { DayRow(date: e.at) }112 TimelineRow(event: e, isCurrent: model.cursor.index == e.index, isFirst: e.index == 0, isLast: e.index == t.events.count - 1,113 reachable: e.messageId.map { id in chat.messages.contains { $0.id == id } } ?? false,114 select: { model.select(e); reveal(e) },115 openBranch: e.conversationId.map { id in { window.open(id) } })116 .id(e.index)117 }118 if let note = t.note, !note.isEmpty {119 Text(note).font(.system(size: 10.5)).foregroundStyle(DS.C.muted).fixedSize(horizontal: false, vertical: true)120 .padding(.horizontal, DS.S.xl).padding(.top, DS.S.l).padding(.bottom, DS.S.xl).frame(maxWidth: .infinity, alignment: .leading)121 }122 }123 .padding(.top, DS.S.m)124 }125 .onChange(of: model.cursor.index) { _, i in126 guard let i else { return }127 // Reduce Motion: the list jumps to the event without an animated scroll128 if reduceMotion { proxy.scrollTo(i, anchor: .center) } else { withAnimation(DS.Motion.smooth) { proxy.scrollTo(i, anchor: .center) } }129 }130 }131 }132133 private func showsDay(_ e: TimelineEvent, in events: [TimelineEvent]) -> Bool {134 guard let at = e.at else { return false }135 guard e.index > 0, let previous = events[..<e.index].last(where: { $0.at != nil })?.at else { return true }136 return !Calendar.current.isDate(previous, inSameDayAs: at)137 }138}139140// MARK: - Replay transport141142private struct ReplayBar: View {143 let model: TimelineModel144 var body: some View {145 let c = model.cursor146 VStack(spacing: DS.S.s) {147 HStack(spacing: DS.S.xs) {148 IconButton(systemImage: "backward.end.fill", label: "Événement précédent") { model.previous() }.disabled(!c.canStepBack)149 IconButton(systemImage: c.isPlaying ? "pause.fill" : "play.fill", label: c.isPlaying ? "Mettre le replay en pause" : "Rejouer la conversation") { model.togglePlay() }150 .disabled(c.count < 2).accessibilityIdentifier("replay-play")151 IconButton(systemImage: "forward.end.fill", label: "Événement suivant") { model.next() }.disabled(!c.canStepForward)152 Spacer(minLength: DS.S.s)153 Text(c.index.map { "\($0 + 1) / \(c.count)" } ?? "\(c.count) événements").font(DS.F.caption.monospacedDigit()).foregroundStyle(DS.C.muted).contentTransition(.numericText())154 .accessibilityLabel(c.index.map { "Événement \($0 + 1) sur \(c.count)" } ?? "\(c.count) événements").padding(.trailing, DS.S.s)155 Button { model.cycleSpeed() } label: { Text(c.speed.label).font(DS.F.caption.monospacedDigit()).frame(minWidth: 18) }156 .buttonStyle(ChipStyle(selected: c.speed != .x1)).help("Vitesse du replay").accessibilityLabel("Vitesse du replay : \(c.speed.label)")157 }158 ReplayScrubber(progress: c.progress, count: c.count, started: c.index != nil) { model.scrub($0) }159 }160 .foregroundStyle(DS.C.text2)161 .padding(.horizontal, DS.S.l).padding(.top, DS.S.xs).padding(.bottom, DS.S.m)162 }163}164165/// Thin scrubber with one tick per recorded event.166private struct ReplayScrubber: View {167 let progress: Double168 let count: Int169 let started: Bool170 let seek: (Double) -> Void171 var body: some View {172 GeometryReader { geo in173 let w = max(geo.size.width, 1)174 ZStack(alignment: .leading) {175 Capsule().fill(DS.C.surface2).frame(height: 3)176 Capsule().fill(DS.C.accent).frame(width: started ? max(3, w * progress) : 0, height: 3)177 if count > 1, count <= 60 {178 ForEach(0..<count, id: \.self) { i in179 Circle().fill(started && Double(i) / Double(count - 1) <= progress + 0.0001 ? DS.C.accent : DS.C.borderStrong).frame(width: 5, height: 5)180 .position(x: 2.5 + (w - 5) * Double(i) / Double(count - 1), y: geo.size.height / 2)181 }182 }183 }184 .frame(height: geo.size.height)185 .contentShape(Rectangle())186 .gesture(DragGesture(minimumDistance: 0).onChanged { g in seek(Double(g.location.x / w)) })187 }188 .frame(height: 14)189 .motion(DS.Motion.snappy, value: progress)190 .accessibilityElement().accessibilityLabel("Position du replay").accessibilityValue("\(Int((progress * 100).rounded())) %")191 .accessibilityAdjustableAction { direction in192 guard count > 1 else { return }193 let step = 1 / Double(count - 1)194 seek(direction == .increment ? progress + step : progress - step)195 }196 .disabled(count < 2)197 }198}199200// MARK: - Rows201202private struct DayRow: View {203 let date: Date?204 var body: some View {205 if let date {206 Text(PanelFormat.day(date).uppercased()).font(DS.F.micro).tracking(0.5).foregroundStyle(DS.C.muted)207 .padding(.leading, DS.S.xl + 28).padding(.top, DS.S.m).padding(.bottom, DS.S.xs).frame(maxWidth: .infinity, alignment: .leading)208 }209 }210}211212private struct TimelineRow: View {213 let event: TimelineEvent214 let isCurrent: Bool215 let isFirst: Bool216 let isLast: Bool217 /// The event's message is in the displayed thread: clicking scrolls the transcript to it.218 let reachable: Bool219 let select: () -> Void220 let openBranch: (() -> Void)?221 @Environment(AppEnvironment.self) private var env222223 var body: some View {224 Button(action: select) {225 HStack(alignment: .top, spacing: DS.S.m) {226 rail227 VStack(alignment: .leading, spacing: 3) {228 HStack(alignment: .firstTextBaseline, spacing: DS.S.s) {229 Text(title).font(DS.F.ui).foregroundStyle(DS.C.text).lineLimit(1)230 if let v = event.variant, let n = event.variants, n > 1 { Text("\(v)/\(n)").font(DS.F.micro.monospacedDigit()).foregroundStyle(DS.C.muted).help("Variante \(v) sur \(n)" + (event.active ? "" : " (non affichée)")) }231 Spacer(minLength: DS.S.xs)232 Text(PanelFormat.time(event.at)).font(.system(size: 10.5).monospacedDigit()).foregroundStyle(DS.C.muted).fixedSize()233 }234 detail235 }236 .padding(.vertical, DS.S.s)237 }238 .padding(.leading, DS.S.xl).padding(.trailing, DS.S.l)239 .background(isCurrent ? DS.C.accentSoft : .clear)240 .contentShape(Rectangle())241 }242 .buttonStyle(.plain)243 .opacity(event.active ? 1 : 0.5)244 .help(reachable ? "Afficher dans la conversation" : (event.active ? title : "Variante non affichée dans le fil"))245 .accessibilityElement(children: .combine)246 .accessibilityLabel(accessibilityText).accessibilityAddTraits(isCurrent ? [.isSelected, .isButton] : .isButton)247 .accessibilityActions { if let openBranch { Button("Ouvrir la branche", action: openBranch) } }248 .accessibilityIdentifier("timeline-event-\(event.index)")249 }250251 /// Hairline rail with the event's glyph; the current replay step is lit in iris.252 private var rail: some View {253 ZStack(alignment: .top) {254 VStack(spacing: 0) {255 Rectangle().fill(isFirst ? Color.clear : DS.C.border).frame(width: 1, height: 9)256 Color.clear.frame(height: 18)257 Rectangle().fill(isLast ? Color.clear : DS.C.border).frame(width: 1).frame(maxHeight: .infinity)258 }259 Image(systemName: glyph).font(.system(size: 9, weight: .semibold)).foregroundStyle(isCurrent ? DS.C.accent : DS.C.text2)260 .frame(width: 18, height: 18)261 .background(Circle().fill(isCurrent ? DS.C.accentSoft : DS.C.surface))262 .overlay(Circle().strokeBorder(isCurrent ? DS.C.accent.opacity(0.6) : DS.C.border, lineWidth: 1))263 .padding(.top, 9)264 }265 .frame(width: 20)266 .accessibilityHidden(true)267 }268269 private var glyph: String {270 switch event.kind {271 case .prompt: "person"272 case .response: "sparkle"273 case .modelSwitch: "arrow.left.arrow.right"274 case .tool: "wrench.and.screwdriver"275 case .file: "doc"276 case .image: "photo"277 case .artifact: "curlybraces"278 case .branch: "arrow.triangle.branch"279 case .unknown: "circle.dotted"280 }281 }282283 private var title: String {284 switch event.kind {285 case .prompt: "Question"286 case .response: "Réponse"287 case .modelSwitch: "Changement de modèle"288 case .tool: event.tool ?? "Outil"289 case .file: "Fichier"290 case .image: "Image"291 case .artifact: "Artefact"292 case .branch: "Branche"293 case .unknown: event.type294 }295 }296297 @ViewBuilder private var detail: some View {298 switch event.kind {299 case .response:300 if let m = event.model { ModelChip(identity: env.catalog.identity(for: m), markSize: 13, font: DS.F.caption) }301 if let p = oneLine(event.preview) { summary(p) }302 let figures = responseFigures303 if !figures.isEmpty { Text(figures).font(.system(size: 10.5).monospacedDigit()).foregroundStyle(DS.C.muted).fixedSize(horizontal: false, vertical: true) }304 if let s = event.status, s != "complete" { Text(statusLabel(s)).font(DS.F.caption).foregroundStyle(s == "error" ? DS.C.danger : DS.C.warn) }305 case .modelSwitch:306 // side by side when both names fit, else one under the other — a model name is never truncated here307 ViewThatFits(in: .horizontal) {308 HStack(spacing: DS.S.xs) { switchChip(event.from); switchArrow; switchChip(event.to) }309 VStack(alignment: .leading, spacing: 3) { switchChip(event.from); HStack(spacing: DS.S.xs) { switchArrow; switchChip(event.to) } }310 }311 case .tool:312 Text([event.status.map(statusLabel), event.durationMs.map { Format.duration(ms: $0) }].compactMap { $0 }.joined(separator: " · "))313 .font(.system(size: 10.5).monospacedDigit()).foregroundStyle(event.status == "error" ? DS.C.danger : DS.C.muted)314 case .artifact:315 if let t = event.title { summary(t) }316 Text([event.artifactType, event.version.map { "v\($0)" }].compactMap { $0 }.joined(separator: " · ")).font(.system(size: 10.5).monospacedDigit()).foregroundStyle(DS.C.muted)317 case .branch:318 if let t = event.title { summary(t) }319 if let openBranch { Button("Ouvrir la branche", action: openBranch).buttonStyle(ChipStyle()).padding(.top, 1) }320 case .file, .image:321 if let n = event.filename ?? event.title ?? oneLine(event.preview) { summary(n) }322 let meta = [event.mime, event.sizeBytes.map { Format.bytes($0) }].compactMap { $0 }.joined(separator: " · ")323 if !meta.isEmpty { Text(meta).font(.system(size: 10.5).monospacedDigit()).foregroundStyle(DS.C.muted) }324 case .prompt:325 if let p = oneLine(event.preview) { summary(p) }326 if let n = event.attachments, n > 0 { Text(n == 1 ? "1 pièce jointe" : "\(n) pièces jointes").font(.system(size: 10.5)).foregroundStyle(DS.C.muted) }327 case .unknown:328 // an event type this version does not know: whatever text the server sent, as-is329 if let p = oneLine(event.preview) ?? event.title ?? event.filename ?? event.tool { summary(p) }330 }331 }332333 @ViewBuilder private func switchChip(_ id: String?) -> some View {334 if let id { ModelChip(identity: env.catalog.identity(for: id, short: true), markSize: 13, font: DS.F.caption).fixedSize() }335 }336 private var switchArrow: some View { Image(systemName: "arrow.right").font(.system(size: 9, weight: .semibold)).foregroundStyle(DS.C.muted) }337338 private func summary(_ text: String) -> some View { Text(text).font(DS.F.caption).foregroundStyle(DS.C.text2).lineLimit(1).truncationMode(.tail).frame(maxWidth: .infinity, alignment: .leading) }339 private func oneLine(_ s: String?) -> String? {340 guard let s else { return nil }341 let flat = PanelFormat.plain(s)342 return flat.isEmpty ? nil : flat343 }344 private func statusLabel(_ s: String) -> String {345 switch s { case "ok": "réussi"; case "complete": "terminée"; case "error": "erreur"; case "cancelled": "interrompue"; case "incomplete": "incomplète"; case "streaming", "running": "en cours"; case "denied": "refusé"; case "pending_approval": "en attente d'approbation"; default: s }346 }347348 /// « 2,2k → 121 jetons · 0.0001 $ estimé · 725 ms · 1er jeton 384 ms · OpenRouter · Google · 6 sources »349 private var responseFigures: String {350 var parts: [String] = []351 if let u = event.usage, u.input > 0 || u.output > 0 { parts.append("\(Format.tokens(u.input)) → \(Format.tokens(u.output)) jetons") }352 if event.model?.hasPrefix("local:") == true { parts.append("local · 0 $") }353 else if let c = event.costUsd, c > 0 { parts.append("\(Format.usd(c)) \(PanelFormat.costBasis(exact: event.isCostExact))") }354 if let l = event.latencyMs { parts.append(Format.duration(ms: l)) }355 if let t = event.ttftMs { parts.append("1er jeton \(Format.duration(ms: t))") }356 if let s = event.servedBy { parts.append(s) }357 if let n = event.citations, n > 0 { parts.append(n == 1 ? "1 source" : "\(n) sources") }358 return parts.joined(separator: " · ")359 }360361 private var accessibilityText: String {362 var parts = [title, PanelFormat.time(event.at)]363 if let m = event.model { parts.append(env.catalog.identity(for: m).accessibilityText) }364 if let p = oneLine(event.preview) ?? event.title { parts.append(p) }365 if !event.active { parts.append("variante non affichée") }366 return parts.joined(separator: ", ")367 }368}369