SPB Git

Repository Public

StreamReducer.swift 12.0 KB 262 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Chat9// File             : SPChat-iOS/Core/Streaming/StreamReducer.swift10// Description      : Pure reducer that applies generation events to the11//                    on-screen thread (optimistic bubbles, replays, end12//                    states).13// Module           : SPChat-iOS14// Repository       : https://git.spboucher.ai/sp-chat-ios15// Created          : 2026-11-1916// Last Modified    : 2026-11-1917//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation9192/// The mutable picture of one conversation while a generation is observed. A value type: trivially testable.93struct ThreadState: Equatable, Sendable {94    var conversationId: String?95    var title: String?96    var messages: [ChatMessage] = []97    var artifacts: [Artifact] = []98    var runId: String?99    var warning: String?100    var error: String?101    var errorCode: String?102    /// Id of the assistant message being written by the run that is followed.103    var assistantId: String?104    var ended = false105    /// Set when the server asked for a full reload (`resync`) or created the conversation.106    var needsReload = false107    var createdConversation = false108    /// Index of the last event applied (resume point after a dropped connection).109    var lastIndex = -1110}111112/// What the client knows about the turn it started (absent when it merely re-attaches to a run).113struct TurnContext: Equatable, Sendable {114    var optimisticUserId: String?115    var replaceAssistantId: String?116    var parentMessageId: String?117}118119enum StreamReducer {120    /// Applies one event. Returns `true` when the change is structural (must be shown at once) and `false` for121    /// high-frequency deltas the UI may coalesce.122    @discardableResult123    static func apply(_ item: StreamItem, to s: inout ThreadState, context: TurnContext = TurnContext()) -> Bool {124        if let i = item.index {125            // events replayed after a reconnection are skipped: an index is applied exactly once126            if i <= s.lastIndex { return false }127            s.lastIndex = i128        }129        func mutateAssistant(_ body: (inout ChatMessage) -> Void) {130            guard let id = s.assistantId, let idx = s.messages.lastIndex(where: { $0.id == id }) else { return }131            body(&s.messages[idx])132        }133        switch item.event {134        case .run(let id):135            s.runId = id136            return true137138        case .resync:139            s.needsReload = true; s.assistantId = nil140            return true141142        case .conversation(let id, let created, let userMessageId, let regenerated, let edited):143            s.conversationId = id144            if created { s.createdConversation = true }145            if let old = regenerated ?? edited, let idx = s.messages.firstIndex(where: { $0.id == old }) {146                // the previous branch leaves the active thread (kept server-side as an inactive sibling)147                let optimistic = context.optimisticUserId.flatMap { oid in s.messages.first { $0.id == oid } }148                s.messages.removeSubrange(idx...)149                if edited != nil, let optimistic, !s.messages.contains(where: { $0.id == optimistic.id }) { s.messages.append(optimistic) }150            }151            if let tmp = context.optimisticUserId, let uid = userMessageId, let idx = s.messages.firstIndex(where: { $0.id == tmp }) {152                s.messages[idx].id = uid; s.messages[idx].conversationId = id153            }154            return true155156        case .start(let messageId, let model, let provider, let routing, let applied):157            if s.assistantId == messageId, s.messages.contains(where: { $0.id == messageId }) { return false }   // replay158            s.messages.removeAll { $0.id == context.replaceAssistantId || $0.id == messageId }159            s.messages.append(ChatMessage(id: messageId, conversationId: s.conversationId ?? "", parentId: context.parentMessageId, role: .assistant, parts: [], modelId: model, provider: provider,160                                          applied: applied, routing: routing, usage: nil, costUsd: nil, latencyMs: nil, ttftMs: nil, status: .streaming, error: nil, errorCode: nil, active: true, createdAt: Date()))161            s.assistantId = messageId162            return true163164        case .text(let delta):165            mutateAssistant { m in166                // a new text part starts after a tool call, so text and tool cards stay in chronological order167                if case .text(let t)? = m.parts.last { m.parts[m.parts.count - 1] = .text(t + delta) }168                else { m.parts.append(.text(delta)) }169            }170            return false171172        case .reasoning(let delta):173            mutateAssistant { m in174                if let idx = m.parts.firstIndex(where: { if case .reasoning = $0 { return true } else { return false } }), case .reasoning(let t, let sum) = m.parts[idx] {175                    m.parts[idx] = .reasoning(text: t + delta, summarized: sum)176                } else { m.parts.insert(.reasoning(text: delta, summarized: true), at: 0) }177            }178            return false179180        case .toolCall(let call):181            mutateAssistant { m in182                let exists = m.parts.contains { if case .toolCall(let t) = $0 { return t.id == call.id } else { return false } }183                if !exists { m.parts.append(.toolCall(call)) }184            }185            return true186187        case .toolResult(let id, let status, let output, let error, let durationMs):188            mutateAssistant { m in189                guard let idx = m.parts.firstIndex(where: { if case .toolCall(let t) = $0 { return t.id == id } else { return false } }), case .toolCall(var t) = m.parts[idx] else { return }190                t.status = status; t.output = output; t.error = error; t.durationMs = durationMs191                m.parts[idx] = .toolCall(t)192            }193            return true194195        case .part(let part):196            mutateAssistant { m in197                // a citation is one source: the same URL replayed or returned by two searches is shown once198                if case .citation(let url, _, _) = part, m.parts.contains(where: { if case .citation(let u, _, _) = $0 { return u == url } else { return false } }) { return }199                m.parts.append(part)200            }201            return true202203        case .artifacts(let list):204            let assistant = s.assistantId205            mutateAssistant { m in206                for a in list where !m.parts.contains(where: { if case .artifact(let id, _, _, _) = $0 { return id == a.id } else { return false } }) {207                    m.parts.append(.artifact(artifactId: a.id, title: a.title, artifactType: a.type, language: a.language))208                }209            }210            s.artifacts.removeAll { old in list.contains { $0.id == old.id } }211            s.artifacts.append(contentsOf: list.map { var a = $0; a.messageId = assistant; return a })212            return true213214        case .usage(let usage, let cost, let latency, let ttft, let exact):215            mutateAssistant { m in m.usage = usage; m.costUsd = cost; m.latencyMs = latency; m.ttftMs = ttft; m.exactCost = exact || usage?.costUsd != nil }216            return true217218        case .followups(let messageId, let suggestions):219            // arrives after `status`: attach to the answer it names (the one being followed when unnamed)220            if let id = messageId ?? s.assistantId, let idx = s.messages.lastIndex(where: { $0.id == id }) { s.messages[idx].followups = Array(suggestions.prefix(3)) }221            return true222223        case .status(let status, let error, let code):224            mutateAssistant { m in m.status = MessageStatus(server: status); m.error = error; m.errorCode = code }225            return true226227        case .meta(let servedBy, let retrying):228            if let servedBy { mutateAssistant { m in var r = m.routing ?? MessageRouting(); r.servedBy = servedBy; m.routing = r } }229            if let retrying { s.warning = String(localized: "Connexion au fournisseur instable : nouvelle tentative (\(retrying))…") }230            return true231232        case .title(let title):233            s.title = title234            return true235236        case .warning(let message):237            s.warning = message238            return true239240        case .error(let message, let code, let partial):241            if s.assistantId != nil, s.messages.contains(where: { $0.id == s.assistantId }) {242                mutateAssistant { m in243                    if m.status == .streaming { m.status = partial ? .incomplete : .error }244                    m.error = message; m.errorCode = code245                }246            } else { s.error = message; s.errorCode = code }247            return true248249        case .done(let status):250            mutateAssistant { m in if m.status == .streaming { m.status = MessageStatus(server: status ?? "complete") } }251            return true252253        case .end:254            s.ended = true255            return true256257        case .unknown:258            return false259        }260    }261}262
Files main
Menu

Theme