Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Core/Streaming/Lens.swift3// Description: Typed events of a Response Lens run (`POST /api/lens`, SSE) and the pure accumulator that builds what the panel shows from them.4import Foundation56/// Events of a lens run. Unknown events are kept (`unknown`) and ignored by the accumulator.7public enum LensEvent: Sendable, Equatable {8 /// Server-side run id: `POST /api/chat/cancel {runId}` really stops the model call.9 case run(runId: String)10 case start(lens: String?, model: String?, provider: String?)11 /// A stage of the lens (`verify`: extracting the claims, searching, reading…). The last one received is the one in progress.12 case step(id: String, label: String)13 case sources([LensSource])14 case text(String)15 case done(StoredLens)16 case error(message: String, code: String?)17 case end18 case unknown(String)1920 public init(_ sse: SSEEvent) {21 let d = JSONValue.parse(Data(sse.data.utf8)) ?? .null22 func decode<T: Decodable>(_ type: T.Type, _ v: JSONValue?) -> T? {23 guard let v, !v.isNull, let data = try? JSONEncoder().encode(v) else { return nil }24 return try? JSONDecoder.api().decode(T.self, from: data)25 }26 func text(_ v: JSONValue?) -> String? { v?.stringValue ?? v?.intValue.map(String.init) }27 switch sse.event {28 case "run": self = .run(runId: d["runId"]?.stringValue ?? "")29 case "start": self = .start(lens: d["lens"]?.stringValue, model: d["model"]?.stringValue, provider: d["provider"]?.stringValue)30 case "step":31 let label = d["label"]?.stringValue ?? text(d["step"]) ?? ""32 self = .step(id: text(d["step"]) ?? label, label: label)33 case "sources": self = .sources((d["sources"]?.arrayValue ?? d.arrayValue ?? []).compactMap { decode(LensSource.self, $0) }.filter { !$0.url.isEmpty })34 case "text": self = .text(d["delta"]?.stringValue ?? "")35 case "done": if let l = decode(StoredLens.self, d) { self = .done(l) } else { self = .unknown("done") }36 case "error": self = .error(message: d["message"]?.stringValue ?? d["error"]?.stringValue ?? "Erreur", code: d["code"]?.stringValue)37 case "end": self = .end38 default: self = .unknown(sse.event)39 }40 }41}4243/// State of one lens run, built from its events. Pure and deterministic; nothing is shown that an event did not carry.44public struct LensAccumulator: Sendable, Equatable {45 public struct Step: Sendable, Equatable, Identifiable {46 public enum State: Sendable, Equatable { case running, done, failed }47 public var id: String48 public var label: String49 public var state: State50 }5152 public private(set) var runId: String?53 /// Lens kind requested (confirmed by `start`).54 public private(set) var lens: String55 /// Model that really runs the lens, as announced by `start`.56 public private(set) var modelId: String?57 public private(set) var steps: [Step] = []58 public private(set) var sources: [LensSource] = []59 public private(set) var text = ""60 /// The stored lens sent by `done` (its `content` is authoritative).61 public private(set) var result: StoredLens?62 public private(set) var error: String?63 public private(set) var errorCode: String?64 public private(set) var started = false65 /// The stream said its last word (`done`, `error` or `end`).66 public private(set) var isFinished = false6768 public init(lens: String, modelId: String? = nil) { self.lens = lens; self.modelId = modelId }6970 public var isRunning: Bool { !isFinished }71 public var failed: Bool { error != nil }72 /// Text to render: the stored content once the run is done, the streamed text before.73 public var displayText: String { result.map { $0.content.isEmpty ? text : $0.content } ?? text }74 public var displaySources: [LensSource] { result.map { $0.sources.isEmpty ? sources : $0.sources } ?? sources }7576 /// Returns true when something visible changed.77 @discardableResult78 public mutating func apply(_ event: LensEvent) -> Bool {79 switch event {80 case .run(let id): runId = id.isEmpty ? runId : id; return false81 case .start(let l, let model, _):82 if let l, !l.isEmpty { lens = l }83 if let model { modelId = model }84 started = true; return true85 case .step(let id, let label):86 guard !label.isEmpty else { return false }87 // a step that is announced again is not duplicated; a new step closes the previous one88 if let last = steps.indices.last, steps[last].id == id { steps[last].label = label; return true }89 for i in steps.indices where steps[i].state == .running { steps[i].state = .done }90 steps.append(Step(id: id, label: label, state: .running)); return true91 case .sources(let s):92 var seen = Set(sources.map(\.id)); let fresh = s.filter { seen.insert($0.id).inserted }93 guard !fresh.isEmpty else { return false }94 sources.append(contentsOf: fresh); return true95 case .text(let delta):96 guard !delta.isEmpty else { return false }97 text += delta; return true98 case .done(let stored):99 result = stored100 if let m = stored.modelId { modelId = m }101 if let e = stored.error, !e.isEmpty { error = e }102 for i in steps.indices where steps[i].state == .running { steps[i].state = error == nil ? .done : .failed }103 isFinished = true; return true104 case .error(let message, let code):105 error = message; errorCode = code106 for i in steps.indices where steps[i].state == .running { steps[i].state = .failed }107 isFinished = true; return true108 case .end:109 guard !isFinished else { return false }110 // the stream closed without `done`: nothing was stored111 if result == nil, error == nil { error = "Le flux s'est terminé sans résultat." }112 for i in steps.indices where steps[i].state == .running { steps[i].state = .failed }113 isFinished = true; return true114 case .unknown: return false115 }116 }117118 /// The connection dropped (or the owner cancelled) before the run ended.119 public mutating func interrupt(_ message: String) {120 guard !isFinished else { return }121 error = message122 for i in steps.indices where steps[i].state == .running { steps[i].state = .failed }123 isFinished = true124 }125}126