SPB Git

Repository Public

ResearchSession.swift 5.5 KB 122 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Features/Research/ResearchSession.swift4//  Description: Follows one deep-research run: starts or resumes it, applies the server's events, re-attaches after a5//               dropped connection (the run lives on the server) and ends on the persisted row.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import Foundation12import Observation1314@MainActor15@Observable16final class ResearchSession {17    /// Live state of the run being followed (nil when nothing is followed).18    private(set) var progress: ResearchProgress?19    private(set) var question = ""20    private(set) var isFollowing = false21    /// The persisted run, loaded when the stream is over (report, sources, resumable state).22    private(set) var finished: ResearchRun?23    var error: String?2425    @ObservationIgnored private let api: ChatAPI26    @ObservationIgnored private let waitUntilOnline: () async -> Void27    @ObservationIgnored private var task: Task<Void, Never>?28    @ObservationIgnored var onFinished: ((ResearchRun?) -> Void)?2930    init(api: ChatAPI, waitUntilOnline: @escaping () async -> Void) { self.api = api; self.waitUntilOnline = waitUntilOnline }3132    var researchId: String? { progress?.researchId ?? finished?.id }3334    func start(question: String, modelId: String, projectId: String?, depth: ResearchDepth) {35        let api = api36        begin(question: question) { try await api.openResearch(question: question, modelId: modelId, projectId: projectId, depth: depth) }37    }3839    func resume(_ run: ResearchRun) {40        let api = api41        begin(question: run.question, seed: run) { try await api.resumeResearch(run.id) }42    }4344    /// Re-attaches to a run still alive on the server (opened from the history): events are replayed from the start.45    func attach(_ run: ResearchRun, liveRunId: String) {46        let api = api47        begin(question: run.question, seed: run) { try await api.attach(runId: liveRunId, after: -1) }48    }4950    private func begin(question: String, seed: ResearchRun? = nil, open: @escaping @Sendable () async throws -> HTTPClient.StreamOpening) {51        task?.cancel()52        self.question = question; finished = nil; error = nil53        var p = ResearchProgress(); p.researchId = seed?.id; p.conversationId = seed?.conversationId; p.model = seed?.modelId; p.depth = seed?.depth54        progress = p; isFollowing = true55        task = Task { [weak self] in await self?.follow(open) }56    }5758    /// Stop = cancel the run on the server (it would otherwise continue), then close the local stream.59    func stop() {60        guard isFollowing else { return }61        let runId = progress?.runId62        let api = api63        task?.cancel(); task = nil64        Task { [weak self] in65            if let runId { try? await api.cancel(runId: runId, messageId: nil) }66            try? await Task.sleep(for: .milliseconds(900))67            await self?.finish()68        }69    }7071    /// Stops observing without cancelling anything (the screen closes; the run continues on the server).72    func detach() { task?.cancel(); task = nil; isFollowing = false }7374    private func follow(_ open: @Sendable () async throws -> HTTPClient.StreamOpening) async {75        do {76            if await consume(try await open()) { await finish(); return }77        } catch let e as APIError {78            if e.kind == .cancelled { return }79            // nothing was started (refused, offline, budget): report and stop80            if progress?.runId == nil { error = e.message; isFollowing = false; progress = nil; return }81        } catch { if progress?.runId == nil { self.error = String(localized: "La recherche n’a pas pu démarrer."); isFollowing = false; progress = nil; return } }82        // the connection dropped while the run goes on: re-attach with the last index applied83        var tries = 084        while !Task.isCancelled, let runId = progress?.runId, tries < 20 {85            await waitUntilOnline()86            if Task.isCancelled { return }87            do {88                if await consume(try await api.attach(runId: runId, after: progress?.lastIndex ?? -1)) { break }89                tries = 090            } catch let e as APIError {91                if e.kind == .cancelled { return }92                if e.status == 404 || e.status == 410 || e.kind == .locked { break }      // the run ended and was forgotten: the row has the result93            } catch { }94            tries += 195            try? await Task.sleep(for: .milliseconds(min(1000 * (1 << min(tries, 4)), 15_000)))96        }97        if Task.isCancelled { return }98        await finish()99    }100101    /// Applies the events of one connection. Returns true when the server sent its terminal `end`.102    private func consume(_ opening: HTTPClient.StreamOpening) async -> Bool {103        guard case .events(let bytes) = opening else { return true }104        do {105            for try await sse in SSEStream.events(from: bytes) {106                if Task.isCancelled { return false }107                progress?.apply(ResearchEvent(sse: sse), index: sse.id)108                if progress?.ended == true { return true }109            }110        } catch { }111        return progress?.ended ?? false112    }113114    private func finish() async {115        // the persisted row first: "no longer following" then always comes with the final state116        if let id = progress?.researchId, let run = try? await api.research(id) { finished = run }117        if let e = progress?.error, finished?.status != "complete" { error = e }118        isFollowing = false; task = nil119        onFinished?(finished)120    }121}122
Files main
Menu

Theme