SPB Git

Repository Public

StudioStore.swift 8.5 KB 179 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Studio/StudioStore.swift3// Description: State of the Research Studio: project bundles (items resolved by the server), project memory, the pick lists for adding existing things to a project, exports, and the writes of synced project and note objects.4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89extension AppEnvironment {10    var studio: StudioStore { store { StudioStore(app: self) } }11}1213@Observable final class StudioStore: SessionScoped {14    private(set) var bundles: [String: VQProjectBundle] = [:]15    private(set) var bundleErrors: [String: String] = [:]16    private(set) var memory: VQMemoryOverview?17    private(set) var memoryError: String?18    private(set) var memoryLoading = false19    /// Quant jobs offered when adding an existing computation to a project.20    private(set) var jobs: [VQQuantJob] = []2122    @ObservationIgnored private unowned let app: AppEnvironment23    init(app: AppEnvironment) { self.app = app }24    func reset() { bundles = [:]; bundleErrors = [:]; memory = nil; memoryError = nil; jobs = [] }2526    private var projects: VQSyncedCollection<VQProject>? { app.sync.active?.projects }27    private var notes: VQSyncedCollection<VQNote>? { app.sync.active?.notes }2829    // MARK: bundle3031    /// Pushes pending local edits first: the bundle is the server's reading of the project.32    func loadBundle(_ id: String) async {33        await app.sync.syncNow()34        do { bundles[id] = try await app.vq.research.bundle(project: id); bundleErrors[id] = nil }35        catch let e as VQError { if e.kind != .notFound || bundles[id] == nil { bundleErrors[id] = e.userMessage } }36        catch is CancellationError {} catch { bundleErrors[id] = error.localizedDescription }37    }3839    func resolved(_ project: String, item: String) -> VQProjectBundle.Resolved? { bundles[project]?.items.first { $0.id == item }?.resolved }40    /// The server has looked at this item (so a nil `resolved` means "not found", not "not asked yet").41    func isResolvedByServer(_ project: String, item: String) -> Bool { bundles[project]?.items.contains { $0.id == item } == true }4243    // MARK: projects4445    @discardableResult func createProject(title: String) async -> String? {46        guard let projects else { return nil }47        var p = VQProject(title: title)48        p.status = .known(.active)49        let id = await projects.create(p)50        if let e = projects.lastError { app.toasts.show(e.userMessage, error: true); return nil }51        return id52    }5354    func update(_ id: String, _ change: (inout VQProject) -> Void) {55        guard let projects, var p = projects[id]?.data else { return }56        let before = p57        change(&p)58        guard p != before else { return }59        Task { await projects.save(p, id: id); if let e = projects.lastError { app.toasts.show(e.userMessage, error: true) } }60    }6162    func deleteProject(_ id: String) async {63        guard let projects else { return }64        await projects.delete(id)65        if let e = projects.lastError { app.toasts.show(e.userMessage, error: true) }66        bundles[id] = nil67    }6869    func addItems(_ id: String, _ items: [VQProject.Item]) {70        update(id) { p in71            var list = p.items72            for it in items where !list.contains(where: { $0.type == it.type && $0.ref == it.ref }) { list.append(it) }73            p.items = list74        }75    }7677    func removeItem(_ id: String, item: String) { update(id) { p in p.items = p.items.filter { $0.id != item } } }7879    /// Moves an item so that it sits just before `target` (or at the end when `target` is nil).80    func moveItem(_ id: String, item: String, before target: String?) {81        update(id) { p in82            var list = p.items83            guard item != target, let from = list.firstIndex(where: { $0.id == item }) else { return }84            let moved = list.remove(at: from)85            let to = target.flatMap { t in list.firstIndex { $0.id == t } } ?? list.count86            list.insert(moved, at: to)87            p.items = list88        }89    }9091    func moveItem(_ id: String, item: String, by offset: Int) {92        update(id) { p in93            var list = p.items94            guard let from = list.firstIndex(where: { $0.id == item }) else { return }95            let to = min(list.count - 1, max(0, from + offset))96            guard to != from else { return }97            list.insert(list.remove(at: from), at: to)98            p.items = list99        }100    }101102    // MARK: notes103104    /// Creates a note in the project and lists it among the project's items.105    @discardableResult func createNote(project id: String, title: String, body: String = "") async -> String? {106        guard let notes else { return nil }107        let noteId = await notes.create(VQNote(title: title, body: body, projectId: id))108        if let e = notes.lastError { app.toasts.show(e.userMessage, error: true); return nil }109        addItems(id, [VQProject.Item(type: .note, ref: noteId, title: title, addedAt: Date())])110        return noteId111    }112113    func deleteNote(_ noteId: String, project id: String) async {114        guard let notes else { return }115        await notes.delete(noteId)116        update(id) { p in p.items = p.items.filter { !($0.type == .note && $0.ref == noteId) } }117    }118119    // MARK: pick lists120121    func loadJobs() async { if let l = try? await app.vq.lab.jobs() { jobs = l.jobs } }122123    static func jobTitle(_ j: VQQuantJob) -> String {124        let subject = j.params["symbol"]?.stringValue ?? j.params["symbols"]?.arrayValue?.compactMap(\.stringValue).prefix(4).joined(separator: ", ")125            ?? j.params["positions"]?.arrayValue?.compactMap { $0["symbol"]?.stringValue }.prefix(4).joined(separator: ", ")126        return j.tool.replacingOccurrences(of: "_", with: " ").capitalized + (subject.map { $0.isEmpty ? "" : " · \($0)" } ?? "")127    }128129    // MARK: memory (CONTRACT §6)130131    func loadMemory() async {132        memoryLoading = true; defer { memoryLoading = false }133        do { memory = try await app.vq.research.memory(); memoryError = nil }134        catch let e as VQError { memoryError = e.userMessage } catch is CancellationError {} catch { memoryError = error.localizedDescription }135    }136137    func memories(project id: String) -> [VQMemory] {138        (memory?.groups.first { $0.scope == .project(id) }?.memories ?? []).sorted { ($0.pinned ? 0 : 1, $1.createdAt ?? .distantPast) < ($1.pinned ? 0 : 1, $0.createdAt ?? .distantPast) }139    }140141    func addMemory(project id: String, content: String, kind: VQMemory.Kind, pinned: Bool, expiresAt: Date?) async {142        await memoryCall { _ = try await self.app.vq.research.addMemory(content: content, change: VQMemoryChange(kind: kind, scope: .project(id), pinned: pinned, expiresAt: expiresAt.map { .some($0) })) }143    }144    func updateMemory(_ id: String, _ change: VQMemoryChange) async { await memoryCall { _ = try await self.app.vq.research.updateMemory(id, change) } }145    func deleteMemory(_ id: String) async { await memoryCall { try await self.app.api.deleteMemory(id) } }146147    private func memoryCall(_ work: () async throws -> Void) async {148        do { try await work() } catch let e as VQError { app.toasts.show(e.userMessage, error: true) } catch { app.toasts.error(error) }149        await loadMemory()150    }151152    // MARK: export153154    struct ExportedFile { var info: VQProjectExport; var data: Data }155156    /// Builds the document on the server, then downloads it. A refusal comes back as the server's own sentence.157    func export(project id: String, format: VQExportFormat, include: [String]?) async throws -> ExportedFile {158        await app.sync.syncNow()159        let info = try await app.vq.research.export(project: id, format: format, include: include)160        let data = try await app.vq.client.data(.get(info.url, timeout: 120))161        return ExportedFile(info: info, data: data)162    }163}164165extension VQProject.Item.ItemType {166    var title: String {167        switch self {168        case .conversation: "Conversation"; case .quantJob: "Computation"; case .note: "Note"; case .chart: "Chart"; case .report: "Report"; case .notebook: "Notebook"169        case .dataset: "Dataset"; case .review: "Review"; case .portfolio: "Portfolio"; case .watchlist: "Watchlist"170        }171    }172    var symbol: String {173        switch self {174        case .conversation: "bubble.left.and.text.bubble.right"; case .quantJob: "function"; case .note: "note.text"; case .chart: "chart.xyaxis.line"; case .report: "doc.richtext"175        case .notebook: "book.closed"; case .dataset: "tablecells"; case .review: "checkmark.seal"; case .portfolio: "briefcase"; case .watchlist: "star"176        }177    }178}179
Files main
Menu

Theme