Repository Public
1//2// VQuant iOS3// File: VQuant/Next/ResearchHub.swift4// Description: The autonomous-research side of the app that is not one live stream: workspaces (research sessions),5// their files, ledger and runs, dataset uploads, and the approval requests the agent is waiting on.6// Everything is computed and stored on the server; the device starts, follows, inspects and resumes.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10//1112import Foundation13import Observation14import VQuantKit1516@MainActor17@Observable18final class ResearchHub {19 struct SessionList: VQJSONDecodable, Sendable { var sessions: [VQResearchSession]; init(json j: VQJSON) { sessions = j.models("sessions") } }2021 private let vq: KitAPI22 private let api: APIClient23 private let fetcher: NextFetcher24 var sessions = NextState<SessionList>()25 private(set) var approvals: [VQResearchApproval] = []26 private(set) var approvalsError: String?27 private(set) var sandbox: VQSandboxStatus?28 /// A pending approval this device had not seen yet (local notification).29 var onApprovalRequested: (@MainActor (VQResearchApproval) -> Void)?30 private var announced: Set<String> = []31 private var pollTask: Task<Void, Never>?3233 init(vq: KitAPI, api: APIClient, fetcher: NextFetcher) { self.vq = vq; self.api = api; self.fetcher = fetcher }3435 var client: VQResearchAgentClient { vq.researchAgent }36 var pending: [VQResearchApproval] { approvals.filter { $0.isAnswerable(now: Date()) } }3738 func refreshSessions() async {39 sessions.begin()40 do { sessions.succeed(try await fetcher.load("research:sessions", .get("/api/v2/research/sessions"))) } catch { sessions.fail(error) }41 }4243 func refreshApprovals() async {44 do {45 let list = try await client.approvals(pendingOnly: true)46 approvals = list; approvalsError = nil47 for a in list where a.isAnswerable(now: Date()) && !announced.contains(a.id) { announced.insert(a.id); onApprovalRequested?(a) }48 } catch { approvalsError = nextMessage(error) }49 }5051 /// An approval seen on a live stream: shown at once, without waiting for the next poll.52 func note(_ approval: VQResearchApproval) {53 if let i = approvals.firstIndex(where: { $0.id == approval.id }) { approvals[i] = approval } else { approvals.insert(approval, at: 0) }54 approvals.removeAll { $0.status != .pending }55 if approval.status == .pending, !announced.contains(approval.id) { announced.insert(approval.id); onApprovalRequested?(approval) }56 }5758 /// The person's answer. The server audits it; a request that is no longer pending answers 404.59 func answer(_ id: String, _ decision: VQResearchApproval.Decision) async -> String? {60 do {61 let a = try await client.answer(approval: id, decision)62 approvals.removeAll { $0.id == a.id }63 return nil64 } catch {65 await refreshApprovals()66 return (error as? VQError)?.kind == .notFound ? "Cette demande n’est plus en attente (déjà traitée ou expirée)." : nextMessage(error)67 }68 }6970 /// False once the server said it has no research agent (the sandbox route answered 404): the mode is then not offered.71 private(set) var researchAvailable = true72 func refreshSandbox() async {73 do { sandbox = try await client.sandbox(); researchAvailable = true }74 catch let e as VQError where e.kind == .notFound { researchAvailable = false }75 catch {} // unreachable: unknown, the mode stays offered and the server will answer76 }7778 /// Polls pending approvals while research is running (there is no push channel: see IOS_ARCHITECTURE §6).79 func startPolling(while active: @escaping @MainActor () -> Bool) {80 guard pollTask == nil else { return }81 pollTask = Task { [weak self] in82 while !Task.isCancelled {83 await self?.refreshApprovals()84 guard let self, active() || !self.pending.isEmpty else { break }85 try? await Task.sleep(for: .seconds(6))86 }87 self?.pollTask = nil88 }89 }90 func stopPolling() { pollTask?.cancel(); pollTask = nil }9192 // MARK: workspace content (kept for offline reading)9394 func detail(_ id: String) async throws -> Loaded<VQResearchSessionDetail> {95 try await fetcher.load("research:detail:\(id)", .get("/api/v2/research/sessions/\(VQRequest.segment(id))", timeout: 60))96 }97 struct RawJSON: VQJSONDecodable, Sendable { var json: VQJSON; init(json j: VQJSON) { json = j } }98 /// The stored conversation as JSON (answers, console outputs, quality gate) for the research view of a finished study.99 func conversation(_ sessionId: String) async throws -> Loaded<RawJSON> {100 try await fetcher.load("research:conv:\(sessionId)", .get("/api/sessions/\(VQRequest.segment(sessionId))", timeout: 60))101 }102 func textFile(_ id: String, path: String) async throws -> Loaded<VQResearchFilePreview> {103 try await fetcher.load("research:text:\(id):\(path)", .get("/api/v2/research/sessions/\(VQRequest.segment(id))/file", [VQQueryItem("path", path), VQQueryItem("limit", "1500")], timeout: 60))104 }105 /// Bytes of a workspace file (figure, export). Cached encrypted: a figure seen once is readable offline.106 func fileData(_ id: String, path: String) async throws -> Data {107 let key = "next:research:file:\(id):\(path)"108 do {109 let d = try await client.fileData(id, path: path)110 await fetcher.cache.save(key, d)111 return d112 } catch {113 if let (d, _) = await fetcher.cache.load(key) { return d }114 throw error115 }116 }117 func inspect(_ id: String, path: String) async throws -> VQDatasetInspection { try await client.inspect(id, path: path) }118119 /// Creates a workspace before the first message, so a dataset can be uploaded into it.120 func createSession(title: String?, projectId: String? = nil) async throws -> (workspace: VQResearchSession, sessionId: String) {121 let r = try await client.createSession(title: title, projectId: projectId)122 return (r.session, r.sessionId)123 }124 func upload(_ id: String, name: String, data: Data) async throws -> VQUploadedFile {125 try await client.upload(id, name: name, data: data, maxBytes: sandbox?.uploadMaxBytes ?? VQDatasetUpload.defaultMaxBytes)126 }127128 func reset() { stopPolling(); sessions = NextState(); approvals = []; announced = []; sandbox = nil }129}130