SPB Git

Repository Public

VQResearchSessionStore.swift 8.5 KB 163 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/ResearchAgent/VQResearchSessionStore.swift3// Description: The observable store of one research study for SwiftUI: fed by the generation stream while it runs,4//              rebuilt from REST when it is over, and the place where approvals are answered.5import Foundation6import Observation78/// One study on screen.9///10/// ```swift11/// @State private var study = VQResearchSessionStore(client: vq.researchAgent)12/// // while the analysis streams (the app's own stream loop; `index` = the SSE id, so re-attaching with ?from=N is safe):13/// study.apply(eventJSON, index: frame.id)14/// // a finished conversation, or a study started on another device:15/// await study.reload(sessionId: conversationId, conversation: storedSessionJSON)16/// ```17@MainActor18@Observable19public final class VQResearchSessionStore {20    /// What the views read.21    public private(set) var state = VQResearchState()22    /// The workspace as REST last returned it (files, library, environment); nil before the first `reload`.23    public private(set) var detail: VQResearchSessionDetail?24    public private(set) var sandbox: VQSandboxStatus?25    public private(set) var isLoading = false26    public private(set) var lastError: VQError?2728    @ObservationIgnored private var live = VQResearchState()29    @ObservationIgnored private var snapshot: VQResearchState?30    @ObservationIgnored private let client: VQResearchAgentClient?3132    /// `client` nil = a store fed by events only (previews, tests).33    public init(client: VQResearchAgentClient? = nil) { self.client = client }3435    /// A store showing a ready-made state (previews, snapshots, tests).36    public init(state: VQResearchState, detail: VQResearchSessionDetail? = nil, sandbox: VQSandboxStatus? = nil) {37        self.client = nil; self.state = state; self.live = state; self.detail = detail; self.sandbox = sandbox38    }3940    // MARK: what the interface shows4142    public var objective: String? { state.objective }43    public var plan: [VQResearchState.PlanStep] { state.plan }44    /// The decisions timeline: every step of the study in order.45    public var timeline: [VQResearchState.TimelineItem] { state.timeline }46    /// Code executions with outputs, errors and durations; failed ones are kept.47    public var executions: [VQResearchState.Execution] { state.executions }48    public var installs: [VQResearchState.Install] { state.installs }49    /// Background and parallel runs.50    public var runs: [VQResearchRun] { state.runs }51    public var experiments: [VQLedgerEntry] { state.experiments }52    /// Findings of the quality gate, open ones first.53    public var gateFindings: [VQQualityGateFinding] { state.gateFindings }54    public var figures: [VQResearchState.Figure] { state.figures }55    public var pendingApprovals: [VQResearchApproval] { state.pendingApprovals }56    /// The answer (as written so far while streaming).57    public var finalReport: String { state.report }58    public var counts: VQResearchState.Counts { state.counts }59    public var isRunning: Bool { !state.isEmpty && !state.finished }60    /// The limits the current (or last) generation runs under.61    public var budgetApplied: VQBudgetApplied? { state.budgetApplied }62    /// The analyses of the workspace as REST lists them (`interrupted` = cut by a server restart).63    public var generations: [VQResearchGeneration] { state.generations }64    public var workspaceId: String? { state.workspaceId }6566    // MARK: stream6768    /// Applies one event of the generation stream. Replays (index at or below the last applied), duplicates and69    /// event types this version does not know are harmless. Returns whether anything visible changed.70    @discardableResult71    public func apply(_ event: VQJSON, index: Int? = nil) -> Bool {72        VQResearchReducer.reduce(&live, event, index: index)73        return publish()74    }7576    @discardableResult77    public func apply(_ event: VQSSEEvent) -> Bool { apply(event.json, index: event.id) }7879    /// Consumes a whole stream (`VQClient.events(...)`), then refreshes from REST when it ends.80    public func follow<S: AsyncSequence & Sendable>(_ events: S) async where S.Element == VQSSEEvent {81        do { for try await e in events { apply(e) } } catch { lastError = error as? VQError }82        if let id = state.workspaceId { await reload(workspaceId: id) }83    }8485    /// Starts over (a new question in the same view). The REST snapshot of earlier generations is kept underneath.86    public func beginGeneration() {87        live = VQResearchState()88        publish()89    }9091    /// Publishes only when something visible changed (stream bookkeeping does not invalidate views).92    @discardableResult93    private func publish() -> Bool {94        var merged = live.isEmpty && live.report.isEmpty ? (snapshot ?? live) : live.merged(over: snapshot)95        merged.lastIndex = live.lastIndex; merged.counter = 0; merged.lastCompletedToolId = nil96        var visible = state; visible.lastIndex = merged.lastIndex97        guard merged != visible else { state.lastIndex = merged.lastIndex; return false }98        state = merged99        return true100    }101102    // MARK: REST103104    /// Rebuilds the study from what the server keeps. Pass the stored conversation (`GET /api/sessions/:id` as JSON)105    /// to recover console outputs, the quality gate and the answer.106    public func reload(workspaceId id: String, conversation: VQJSON? = nil) async {107        guard let client else { return }108        isLoading = true109        defer { isLoading = false }110        do {111            let d = try await client.session(id)112            // the session detail lists pending requests only; the answered ones of this workspace come from the list113            let answered = ((try? await client.approvals(pendingOnly: false)) ?? []).filter { $0.workspaceId == d.session.id }114            install(detail: d, conversation: conversation, approvals: answered)115            if sandbox == nil { sandbox = try? await client.sandbox() }116            lastError = nil117        } catch let e as VQError { lastError = e } catch { lastError = VQError.network(error) }118    }119120    public func reload(sessionId: String, conversation: VQJSON? = nil) async {121        await reload(workspaceId: VQResearchSession.reference(sessionId: sessionId), conversation: conversation)122    }123124    /// Installs a workspace detail already fetched (or a recorded one).125    public func install(detail d: VQResearchSessionDetail, conversation: VQJSON? = nil, sandbox s: VQSandboxStatus? = nil, approvals: [VQResearchApproval] = []) {126        detail = d127        if let s { sandbox = s }128        var snap = VQResearchState(detail: d, conversation: conversation, approvals: approvals)129        if conversation == nil, let old = snapshot {       // a refresh without the conversation keeps what it gave130            snap.gates = old.gates; snap.report = old.report; snap.plan = old.plan; snap.objective = snap.objective ?? old.objective131            for i in snap.executions.indices where snap.executions[i].output == nil { snap.executions[i].output = old.execution(snap.executions[i].key)?.output }132        }133        snapshot = snap134        publish()135    }136137    /// Answers an approval request and reflects the result at once. Returns false when the server no longer accepts138    /// an answer (expired, or answered on another device): the request is then marked expired locally.139    @discardableResult140    public func answer(_ approval: VQResearchApproval, _ decision: VQResearchApproval.Decision) async -> Bool {141        guard let client else { return false }142        do {143            let resolved = try await client.answer(approval: approval.id, decision)144            apply(["type": "approval_resolved", "approval": ["id": .string(resolved.id), "status": .string(resolved.status.rawValue),145                                                             "resolvedAt": .number((resolved.resolvedAt ?? Date()).timeIntervalSince1970 * 1000)]])146            lastError = nil147            return true148        } catch let e as VQError {149            lastError = e150            if e.kind == .notFound { apply(["type": "approval_resolved", "approval": ["id": .string(approval.id), "status": "expired"]]) }151            return false152        } catch { lastError = VQError.network(error); return false }153    }154155    public func cancel(run: VQResearchRun) async {156        guard let client else { return }157        do {158            let r = try await client.cancelRun(run.id)159            apply(["type": "research_run", "run": ["id": .string(r.id), "status": .string(r.status.rawValue)]])160        } catch { lastError = error as? VQError }161    }162}163
Files main
Menu

Theme