Repository Public
1//2// VQuant iOS3// File: VQuant/App/Stores.swift4// Description: Observable stores of the app: market data, analyses (server jobs and their streams), quantitative5// computations, the agent workspace and the device watchlist. All data comes from the VQuant backend.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import Foundation12import Observation13import VQuantKit14import WidgetKit1516/// A value being loaded for a screen: what is shown, where it came from, and the last failure if any.17struct LoadState<Value: Sendable>: Sendable {18 var loaded: Loaded<Value>?19 var isLoading = false20 var error: APIError?21 var value: Value? { loaded?.value }22 /// Nothing to show and the last attempt failed.23 var isUnavailable: Bool { loaded == nil && error != nil && !isLoading }24}2526// MARK: - Markets2728@MainActor29@Observable30final class MarketStore {31 private let api: VQuantAPI32 private let fetcher: CachedFetcher3334 var indices = LoadState<[Quote]>()35 var hours = LoadState<[ExchangeHours]>()36 var movers: [MoverKind: LoadState<[Quote]>] = [:]37 private(set) var quotes: [String: Loaded<Quote>] = [:]38 private(set) var quoteErrors: [String: APIError] = [:]39 /// Freshness the data layer of backend 6 stated for each quote (`/api/v2/data/quotes`): kind, provider, as-of.40 private(set) var quoteFreshness: [String: VQFreshness] = [:]41 /// Batched quotes of backend 6. Nil in unit tests of the 1.0 routes.42 var kit: KitAPI?4344 init(api: VQuantAPI, fetcher: CachedFetcher) { self.api = api; self.fetcher = fetcher }4546 /// Whether the US cash session is open, according to the server's exchange hours (nil when unknown).47 var usMarketOpen: Bool? {48 guard let list = hours.value else { return nil }49 return list.first { $0.exchange == "NASDAQ" }?.isMarketOpen ?? list.first { $0.exchange == "NYSE" }?.isMarketOpen50 }5152 func freshness(of symbol: String) -> DataFreshness {53 guard let q = quotes[symbol] else { return quoteErrors[symbol] == nil ? .historical(asOf: nil) : .unavailable }54 return DataFreshness.classify(origin: q.origin, quoteTime: q.value.timestamp, marketOpen: usMarketOpen)55 }56 func freshness(of state: LoadState<[Quote]>) -> DataFreshness {57 guard let l = state.loaded else { return state.error == nil ? .historical(asOf: nil) : .unavailable }58 return DataFreshness.classify(origin: l.origin, quoteTime: l.value.compactMap(\.timestamp).max(), marketOpen: usMarketOpen)59 }6061 func refreshOverview() async {62 async let a: Void = refreshIndices()63 async let b: Void = refreshHours()64 _ = await (a, b)65 }6667 private func refreshIndices() async {68 indices.isLoading = true69 do { indices.loaded = try await fetcher.load("indices") { [api] in try await api.indices() }; indices.error = nil }70 catch { let e = APIError.from(error); if e.kind != .cancelled { indices.error = e } }71 indices.isLoading = false72 }7374 private func refreshHours() async {75 hours.isLoading = true76 do { hours.loaded = try await fetcher.load("hours") { [api] in try await api.marketHours() }; hours.error = nil }77 catch { let e = APIError.from(error); if e.kind != .cancelled { hours.error = e } }78 hours.isLoading = false79 }8081 func refreshMovers(_ kind: MoverKind) async {82 var s = movers[kind] ?? LoadState(); s.isLoading = true; movers[kind] = s83 do { s.loaded = try await fetcher.load("movers:\(kind.rawValue)") { [api] in try await api.movers(kind) }; s.error = nil }84 catch { s.error = APIError.from(error) }85 s.isLoading = false; movers[kind] = s86 }8788 @discardableResult89 func refreshQuote(_ symbol: String) async -> Loaded<Quote>? {90 do {91 let l = try await fetcher.load("quote:\(symbol)") { [api] in try await api.quote(symbol) }92 quotes[symbol] = l; quoteErrors[symbol] = nil93 return l94 } catch {95 let e = APIError.from(error)96 if e.kind != .cancelled { quoteErrors[symbol] = e }97 return nil98 }99 }100101 /// Refreshes several quotes: one batched request to the data layer (`/api/v2/data/quotes`, 60 symbols at most102 /// per call, each quote with its provider and freshness). When that route fails, the per-symbol 1.0 route is used.103 func refreshQuotes(_ symbols: [String]) async {104 let unique = Array(Set(symbols)).sorted()105 guard !unique.isEmpty else { return }106 if let kit {107 var failed = false108 for start in stride(from: 0, to: unique.count, by: 60) {109 let chunk = Array(unique[start..<min(start + 60, unique.count)])110 do {111 let r = try await kit.data.quotes(chunk)112 let now = Date()113 for q in r.quotes {114 guard let price = q.price else { continue }115 let quote = Quote(symbol: q.symbol, name: q.name, price: price, change: q.change, changePercent: q.changePct, volume: q.volume, dayLow: q.dayLow, dayHigh: q.dayHigh,116 yearLow: q.yearLow, yearHigh: q.yearHigh, marketCap: q.marketCap, exchange: q.exchange, open: q.open, previousClose: q.previousClose, timestamp: q.providerTimestamp)117 quotes[q.symbol] = Loaded(value: quote, origin: .network, fetchedAt: now); quoteErrors[q.symbol] = nil118 quoteFreshness[q.symbol] = VQFreshness(kind: q.freshness?.known ?? r.freshness?.kind.known ?? .polled, asOf: q.providerTimestamp,119 provider: q.provider ?? r.freshness?.provider, retrievedAt: r.freshness?.retrievedAt ?? now)120 if let data = try? JSONEncoder().encode(quote) { await fetcher.cache.save("quote:\(q.symbol)", data) }121 }122 for s in r.missing { quoteErrors[s] = APIError(kind: .notFound, message: "Aucune cotation pour \(s).") }123 } catch { failed = true; break }124 }125 if !failed { return }126 }127 await withTaskGroup(of: Void.self) { group in128 var it = unique.makeIterator()129 for _ in 0..<min(4, unique.count) { if let s = it.next() { group.addTask { await self.refreshQuote(s) } } }130 while await group.next() != nil { if let s = it.next() { group.addTask { await self.refreshQuote(s) } } }131 }132 }133134 /// Provenance the data layer stated for the bars of a symbol and range (provider, adjustment, gaps, freshness).135 private(set) var barProvenance: [String: VQBarSeries.Provenance] = [:]136 func provenance(_ symbol: String, range: ChartRange) -> VQBarSeries.Provenance? { barProvenance["\(symbol)|\(range.rawValue)"] }137138 /// Bars for a chart, oldest first, from the data layer of backend 6 (`/api/v2/data/bars`, with provenance): one139 /// provider per series, never mixed. When that route is unreachable the 1.0 route answers (no provenance then).140 func bars(_ symbol: String, range: ChartRange) async throws -> Loaded<[Bar]> {141 try await fetcher.load("bars:\(symbol):\(range.rawValue)") { [api, kit] in142 if let kit {143 do {144 let from = MarketDate.day(Date().addingTimeInterval(-Double(range.lookbackDays) * 86_400))145 let series = try await kit.data.bars(symbol, interval: ChartTime.interval(range), from: from, to: nil, adjust: nil, limit: 20_000)146 var bars = ChartTime.bars(series, intraday: range.isIntraday)147 if range == .day, let last = bars.last { // one session only: the most recent trading day148 let day = MarketDate.day(last.date)149 bars = bars.filter { MarketDate.day($0.date) == day }150 }151 await MainActor.run { self.barProvenance["\(symbol)|\(range.rawValue)"] = series.provenance }152 return bars153 } catch let e as VQError where e.kind == .notFound || e.kind == .rejected {154 throw APIError(kind: .notFound, message: e.message.isEmpty ? "Aucune donnée pour \(symbol)." : e.message)155 } catch {}156 }157 return try await api.bars(symbol, range: range)158 }159 }160 func profile(_ symbol: String) async throws -> Loaded<CompanyProfile?> {161 try await fetcher.load("profile:\(symbol)") { [api] in try await api.profile(symbol) }162 }163 func news(_ symbol: String) async throws -> Loaded<[NewsItem]> {164 try await fetcher.load("news:\(symbol)") { [api] in try await api.news(symbol) }165 }166 func fundamentals(_ table: FundamentalTable, symbol: String) async throws -> Loaded<[FundamentalRecord]> {167 try await fetcher.load("fund:\(table.rawValue):\(symbol)") { [api] in try await api.fundamentals(table, symbol: symbol) }168 }169 func search(_ text: String) async throws -> [SymbolMatch] { try await api.search(text) }170171 func reset() { indices = LoadState(); hours = LoadState(); movers = [:]; quotes = [:]; quoteErrors = [:]; quoteFreshness = [:] }172}173174// MARK: - Watchlist (synced objects; 1.0 kept it on the device)175176/// The watchlist the app shows: one of the person's synced `watchlist` objects. Edits go to the sync engine's durable177/// queue first, so they work offline and reach the other devices when the connection returns.178@MainActor179@Observable180final class WatchlistStore {181 private let sync: SyncCenter182 private let defaults: UserDefaults183 /// The list shown on Home, in Markets and in the widget. Nil = the device's default choice.184 var selectedId: String? { didSet { defaults.set(selectedId, forKey: "watchlist.selected") } }185 private var chain: Task<Void, Never>?186187 init(sync: SyncCenter, defaults: UserDefaults = .standard) {188 self.sync = sync; self.defaults = defaults189 selectedId = defaults.string(forKey: "watchlist.selected")190 }191192 var lists: [VQObject<VQWatchlist>] { sync.watchlists.items.sorted { $0.data.name.localizedCaseInsensitiveCompare($1.data.name) == .orderedAscending } }193 var active: VQObject<VQWatchlist>? {194 if let id = selectedId, let l = sync.watchlists[id] { return l }195 return sync.watchlists[sync.watchlistId] ?? lists.first196 }197 var isLoaded: Bool { sync.watchlists.isLoaded }198 var isPending: Bool { active.map { sync.watchlists.pendingIDs.contains($0.id) } ?? false }199200 var symbols: [String] { active?.data.symbols ?? [] }201 var entries: [WatchlistFile.Entry] { symbols.map { WatchlistFile.Entry(symbol: $0, name: nil, addedAt: active?.updatedAt ?? .distantPast) } }202 func contains(_ symbol: String) -> Bool { symbols.contains(symbol) }203 func toggle(_ symbol: String, name: String?) { contains(symbol) ? remove(symbol) : add(symbol, name: name) }204205 func add(_ symbol: String, name: String?) {206 guard let s = WatchlistFile.normalise(symbol) else { return }207 mutate { $0.add(s) }208 }209 func remove(_ symbol: String) { mutate { $0.remove(symbol.uppercased()) } }210 func move(from: IndexSet, to: Int) { mutate { var l = $0.symbols; l.move(fromOffsets: from, toOffset: to); $0.symbols = l } }211 func remove(at offsets: IndexSet) { mutate { var l = $0.symbols; l.remove(atOffsets: offsets); $0.symbols = l } }212213 /// Edits are applied one after the other (each reads the list the previous one wrote). With no list yet, the214 /// device's own list is created.215 private func mutate(_ change: @escaping @Sendable (inout VQWatchlist) -> Void) {216 let previous = chain217 let sync = self.sync218 let id = active?.id ?? sync.watchlistId219 chain = Task {220 await previous?.value221 await sync.edit(VQWatchlist.self, id: id, create: VQWatchlist(name: "Liste de suivi", symbols: []), change)222 await sync.watchlists.refresh()223 WidgetCenter.shared.reloadTimelines(ofKind: "VQuantWatchlist")224 }225 }226 /// Waits for the edits in flight (tests).227 func settle() async { await chain?.value }228229 func create(name: String) async -> String {230 let id = sync.newId()231 await sync.watchlists.save(VQWatchlist(name: name, symbols: []), id: id)232 selectedId = id233 return id234 }235 func rename(_ id: String, to name: String) async { await sync.watchlists.update(id) { $0.name = name } }236 func delete(_ id: String) async { await sync.watchlists.delete(id); if selectedId == id { selectedId = nil } }237}238239// MARK: - Analyses240241/// Follows one analysis job on the server. The job lives on the server: this object only watches it, and re-attaches242/// from the last event it applied whenever the connection drops or the app returns to the foreground.243@MainActor244@Observable245final class RunController: Identifiable {246 private(set) var run = AnalysisRun()247 /// The autonomous-research view of the same stream (workspace, ledger, runs, figures, approvals, quality gate),248 /// reduced by the shared kit from the raw events (and, once the stream is over, from what the server keeps).249 /// Empty for an analysis that never used the workspace.250 let store: VQResearchSessionStore251 var research: VQResearchState { store.state }252 /// Which model the router chose when `auto` was asked, the budgets that were hit, the usage at the end.253 private(set) var routed: VQRouteDecision?254 private(set) var usage: VQUsage?255 private(set) var provenance: [VQProvenanceSource] = []256 /// Mode and model the person asked for (shown while the stream has not said more).257 private(set) var mode: String?258 private(set) var requestedModel: String?259 /// An approval request seen on the stream (shown at once, notified).260 var onApproval: (@MainActor (VQResearchApproval) -> Void)?261 private(set) var isConnected = false262 private(set) var connectionNote: String?263 let startedAt = Date()264 nonisolated let id = UUID()265266 private let api: VQuantAPI267 private var task: Task<Void, Never>?268 private var onFinish: (@MainActor (RunController) -> Void)?269 private var attempts = 0270271 init(api: VQuantAPI, kit: KitAPI? = nil, onFinish: (@MainActor (RunController) -> Void)? = nil) {272 self.api = api; self.onFinish = onFinish273 store = VQResearchSessionStore(client: kit?.researchAgent)274 }275276 var jobId: String? { run.jobId }277278 /// Submits a new analysis and follows it.279 func start(_ request: ChatRequest) {280 run.query = request.query281 run.sessionId = request.sessionId282 mode = request.mode; requestedModel = request.model283 follow(api.startAnalysis(request), isSubmission: true)284 }285286 /// Follows a job that already exists (opened from the list, a notification, or after relaunching the app).287 func attach(jobId: String, query: String = "") {288 run.jobId = jobId289 if run.query.isEmpty { run.query = query }290 follow(api.streamGeneration(jobId, from: run.nextIndex), isSubmission: false)291 }292293 private func follow(_ stream: AsyncThrowingStream<StreamItem, Error>, isSubmission: Bool) {294 task?.cancel()295 task = Task { [weak self] in296 guard let self else { return }297 do {298 for try await item in stream {299 if Task.isCancelled { return }300 self.isConnected = true; self.connectionNote = nil; self.attempts = 0301 self.applyNext(item)302 self.run.apply(item)303 }304 self.isConnected = false305 if self.run.isFinished { self.finished() }306 else if self.run.jobId == nil {307 // The response ended before the server announced a job: nothing is known to be running.308 self.run.error = "Le serveur n’a pas confirmé la création de l’analyse. Vérifiez la liste des analyses avant de relancer."309 self.run.isFinished = true; self.finished()310 }311 else { await self.reattach(after: nil) } // the stream closed without `done`: look again312 } catch {313 self.isConnected = false314 if Task.isCancelled { return }315 let e = APIError.from(error)316 if isSubmission && self.run.jobId == nil {317 // The server refused the submission (limit reached, conversation busy…) or was unreachable before318 // creating a job: nothing runs, and nothing is retried on the user's behalf.319 self.run.error = e.message; self.run.isFinished = true; self.finished()320 } else if e.kind == .notFound {321 // The job left the server's memory (more than 20 minutes after it ended): the result is in the conversation.322 self.run.isFinished = true; self.finished()323 } else if e.kind == .unauthorized {324 self.connectionNote = e.message325 } else { await self.reattach(after: e) }326 }327 }328 }329330 /// Backend 6 events: the research reducer of the kit reads the raw JSON (replays are ignored by index, like331 /// `AnalysisRun`), the generation extras are kept for the header.332 private func applyNext(_ item: StreamItem) {333 if let i = item.index, i < run.nextIndex { return }334 guard let raw = item.raw, let json = try? VQJSON.parse(raw) else { return }335 let before = store.pendingApprovals.map(\.id)336 store.apply(json, index: item.index)337 for a in store.pendingApprovals where !before.contains(a.id) { onApproval?(a) }338 switch VQGenerationEvent(json: json) {339 case .modelRouted(let d): routed = d340 case .provenance(let p): provenance = p341 case .done(_, let u): if let u { usage = u }342 default: break343 }344 }345346 private func reattach(after error: APIError?) async {347 guard let jobId = run.jobId else { return }348 attempts += 1349 connectionNote = error?.kind == .offline ? "Hors ligne. L’analyse continue sur le serveur." : "Reconnexion… L’analyse continue sur le serveur."350 try? await Task.sleep(for: .seconds(min(30, 1 << min(attempts, 5))))351 if Task.isCancelled { return }352 follow(api.streamGeneration(jobId, from: run.nextIndex), isSubmission: false)353 }354355 /// Stops watching (the job itself is untouched).356 func detach() { task?.cancel(); task = nil; isConnected = false }357358 /// Called when the app becomes active again: iOS has closed the socket while suspended.359 func resumeIfNeeded() {360 guard !run.isFinished, run.jobId != nil, task == nil || !isConnected else { return }361 if let jobId = run.jobId { attempts = 0; follow(api.streamGeneration(jobId, from: run.nextIndex), isSubmission: false) }362 }363364 /// The Stop button: asks the server to end the job.365 func cancel() async {366 guard let jobId = run.jobId else { return }367 try? await api.cancelGeneration(jobId)368 }369370 private func finished() {371 task = nil372 // The stream is over: what the server keeps (ledger, runs, files) completes what the events said.373 if let id = store.workspaceId { Task { await store.reload(workspaceId: id) } }374 onFinish?(self); onFinish = nil375 }376}377378@MainActor379@Observable380final class ResearchStore {381 private let api: VQuantAPI382 private let fetcher: CachedFetcher383 private let cache: DiskCache384385 var generations = LoadState<[Generation]>()386 var conversations = LoadState<[ConversationSummary]>()387 var library = LoadState<[SharedReportSummary]>()388 private(set) var controllers: [RunController] = []389 /// Why the server refused the last submission (limit reached, conversation busy, unreachable). Shown once.390 var submissionError: String?391 /// Called when a followed analysis ends (local notification, list refresh).392 var onRunFinished: (@MainActor (AnalysisRun) -> Void)?393 /// Called when a followed stream shows an approval request of the research agent.394 var onApproval: (@MainActor (VQResearchApproval) -> Void)?395 /// The kit API (workspace files, ledger, approvals) for the research view of each run.396 var kit: KitAPI?397 private var pollTask: Task<Void, Never>?398399 init(api: VQuantAPI, fetcher: CachedFetcher, cache: DiskCache) { self.api = api; self.fetcher = fetcher; self.cache = cache }400401 var running: [Generation] { (generations.value ?? []).filter { $0.status == .running } }402403 func controller(forJob id: String) -> RunController? { controllers.first { $0.jobId == id } }404405 /// Starts an analysis on the server. The returned controller streams it; the analysis itself does not depend on it.406 func start(query: String, mode: AnalysisMode, sessionId: String? = nil, history: [Exchange] = [], imageData: Data? = nil, imageMime: String? = nil,407 model: String? = nil, budget: ChatRequest.Budget? = nil, projectId: String? = nil) -> RunController {408 let c = RunController(api: api, kit: kit) { [weak self] c in self?.runEnded(c) }409 c.onApproval = onApproval410 let turns = history.suffix(8).map { ChatRequest.Turn(question: $0.question, answer: $0.answer) }411 c.start(ChatRequest(query: query, history: turns, sessionId: sessionId, mode: mode.rawValue, model: model, imageData: imageData?.base64EncodedString(), imageMimeType: imageMime,412 budget: budget, projectId: projectId))413 controllers.insert(c, at: 0)414 startPolling()415 return c416 }417418 /// A controller watching an existing job (reused if one is already attached).419 func watch(jobId: String, query: String = "") -> RunController {420 if let c = controller(forJob: jobId) { c.resumeIfNeeded(); return c }421 let c = RunController(api: api, kit: kit) { [weak self] c in self?.runEnded(c) }422 c.onApproval = onApproval423 c.attach(jobId: jobId, query: query)424 controllers.insert(c, at: 0)425 return c426 }427428 private func runEnded(_ c: RunController) {429 onRunFinished?(c.run)430 if let sid = c.run.sessionId { Task { await cache.remove("conv:\(sid)") } }431 Task { await refreshGenerations(); await refreshConversations() }432 }433434 func refreshGenerations() async {435 generations.isLoading = true436 do {437 let list = try await api.generations()438 generations.loaded = Loaded(value: list.generations, origin: .network, fetchedAt: Date()); generations.error = nil439 } catch { let e = APIError.from(error); if e.kind != .cancelled { generations.error = e } }440 generations.isLoading = false441 }442443 func refreshConversations(search: String? = nil) async {444 conversations.isLoading = true445 do {446 if let search, !search.isEmpty {447 conversations.loaded = Loaded(value: try await api.conversations(search: search), origin: .network, fetchedAt: Date())448 } else {449 conversations.loaded = try await fetcher.load("conversations") { [api] in try await api.conversations() }450 }451 conversations.error = nil452 } catch { let e = APIError.from(error); if e.kind != .cancelled { conversations.error = e } }453 conversations.isLoading = false454 }455456 func refreshLibrary() async {457 library.isLoading = true458 do { library.loaded = Loaded(value: try await api.sharedReports(), origin: .network, fetchedAt: Date()); library.error = nil }459 catch { let e = APIError.from(error); if e.kind != .cancelled { library.error = e } }460 library.isLoading = false461 }462463 /// A conversation with its reports. Kept encrypted on the device for offline reading (large base64 figures are464 /// dropped from the device copy: figures are re-fetched or shown as unavailable offline).465 func conversation(_ id: String) async throws -> Loaded<Conversation> {466 try await fetcher.load("conv:\(id)") { [api] in467 var c = try await api.conversation(id)468 for i in c.exchanges.indices { for j in c.exchanges[i].figures.indices where !c.exchanges[i].figures[j].figureUrls.isEmpty { c.exchanges[i].figures[j].figures = [] } }469 return c470 }471 }472473 func rename(_ id: String, title: String) async throws { try await api.renameConversation(id, title: title); await refreshConversations() }474 func setPinned(_ id: String, _ pinned: Bool) async throws { try await api.pinConversation(id, pinned: pinned); await refreshConversations() }475 func delete(_ id: String) async throws {476 try await api.deleteConversation(id)477 await cache.remove("conv:\(id)")478 await refreshConversations()479 }480481 /// Polls the job list while something is running and the app is active. Stopped in the background: iOS suspends482 /// the app, and the server does not need the app to keep working.483 func startPolling() {484 guard pollTask == nil else { return }485 pollTask = Task { [weak self] in486 while !Task.isCancelled {487 await self?.refreshGenerations()488 guard let self, !self.running.isEmpty || self.controllers.contains(where: { !$0.run.isFinished }) else { break }489 try? await Task.sleep(for: .seconds(5))490 }491 self?.pollTask = nil492 }493 }494 func stopPolling() { pollTask?.cancel(); pollTask = nil }495496 func becameActive() {497 for c in controllers { c.resumeIfNeeded() }498 startPolling()499 }500 func enteredBackground() {501 stopPolling()502 for c in controllers where !c.run.isFinished { c.detach() }503 }504505 func reset() {506 stopPolling()507 for c in controllers { c.detach() }508 controllers = []; generations = LoadState(); conversations = LoadState(); library = LoadState()509 }510}511512// MARK: - Quantitative computations513514@MainActor515@Observable516final class QuantStore {517 private let api: VQuantAPI518 private let fetcher: CachedFetcher519520 var tools = LoadState<QuantToolList>()521 var jobs = LoadState<[QuantJob]>()522 var onJobFinished: (@MainActor (QuantJob) -> Void)?523 private var pollTask: Task<Void, Never>?524 private var knownRunning: Set<String> = []525526 init(api: VQuantAPI, fetcher: CachedFetcher) { self.api = api; self.fetcher = fetcher }527528 var running: [QuantJob] { (jobs.value ?? []).filter { $0.status == .running } }529 func tool(_ id: String) -> QuantTool? { tools.value?.tools.first { $0.id == id } }530531 func refreshTools() async {532 tools.isLoading = true533 do { tools.loaded = try await fetcher.load("quant:tools") { [api] in try await api.quantTools() }; tools.error = nil }534 catch { let e = APIError.from(error); if e.kind != .cancelled { tools.error = e } }535 tools.isLoading = false536 }537538 func refreshJobs() async {539 jobs.isLoading = true540 do {541 let l = try await fetcher.load("quant:jobs") { [api] in try await api.quantJobs().jobs }542 if !l.isFromCache {543 let nowRunning = Set(l.value.filter { $0.status == .running }.map(\.id))544 for id in knownRunning.subtracting(nowRunning) { if let j = l.value.first(where: { $0.id == id }) { onJobFinished?(j) } }545 knownRunning = nowRunning546 }547 jobs.loaded = l; jobs.error = nil548 } catch { let e = APIError.from(error); if e.kind != .cancelled { jobs.error = e } }549 jobs.isLoading = false550 }551552 /// Submits a computation. The server validates the parameters and writes out the defaults it applied.553 func submit(tool: String, params: [String: JSONValue]) async throws -> QuantJob {554 let job = try await api.startQuantJob(tool: tool, params: params)555 knownRunning.insert(job.id)556 await refreshJobs()557 startPolling()558 return job559 }560561 /// A job with its code and result; finished jobs are kept for offline reading.562 func job(_ id: String) async throws -> Loaded<QuantJob> {563 if let hit: Loaded<QuantJob> = await fetcher.cached("quant:job:\(id)"), hit.value.status != .running, hit.value.result != nil || hit.value.error != nil {564 // A finished job never changes: the device copy is the job. Refresh only confirms it still exists.565 return Loaded(value: hit.value, origin: .network, fetchedAt: hit.fetchedAt)566 }567 return try await fetcher.load("quant:job:\(id)") { [api] in try await api.quantJob(id) }568 }569570 func delete(_ id: String) async throws { try await api.deleteQuantJob(id); await refreshJobs() }571572 func startPolling() {573 guard pollTask == nil else { return }574 pollTask = Task { [weak self] in575 while !Task.isCancelled {576 await self?.refreshJobs()577 guard let self, !self.running.isEmpty else { break }578 try? await Task.sleep(for: .seconds(3))579 }580 self?.pollTask = nil581 }582 }583 func stopPolling() { pollTask?.cancel(); pollTask = nil }584 func reset() { stopPolling(); tools = LoadState(); jobs = LoadState(); knownRunning = [] }585}586587// MARK: - Workspace (memory, portfolio, watches)588589@MainActor590@Observable591final class WorkspaceStore {592 private let api: VQuantAPI593 private let fetcher: CachedFetcher594 var state = LoadState<Workspace>()595596 init(api: VQuantAPI, fetcher: CachedFetcher) { self.api = api; self.fetcher = fetcher }597598 var positions: [Position] { state.value?.positions ?? [] }599 var memories: [Memory] { state.value?.memories ?? [] }600 var watches: [Watch] { state.value?.watches ?? [] }601602 func refresh() async {603 state.isLoading = true604 do { state.loaded = try await fetcher.load("workspace") { [api] in try await api.workspace() }; state.error = nil }605 catch { let e = APIError.from(error); if e.kind != .cancelled { state.error = e } }606 state.isLoading = false607 }608609 // Every mutation goes to the server first and the screen shows the server's answer: nothing is queued offline.610 func savePosition(symbol: String, quantity: Double, costBasis: Double?, note: String?) async throws {611 _ = try await api.upsertPosition(symbol: symbol, quantity: quantity, costBasis: costBasis, note: note); await refresh()612 }613 func removePosition(_ symbol: String) async throws { try await api.removePosition(symbol); await refresh() }614 func addMemory(_ content: String, category: String) async throws { _ = try await api.addMemory(content: content, category: category); await refresh() }615 func deleteMemory(_ id: String) async throws { try await api.deleteMemory(id); await refresh() }616 func createWatch(_ draft: VQuantAPI.WatchDraft) async throws { _ = try await api.createWatch(draft); await refresh() }617 func updateWatch(_ id: String, _ patch: VQuantAPI.WatchPatch) async throws { _ = try await api.updateWatch(id, patch); await refresh() }618 func deleteWatch(_ id: String) async throws { try await api.deleteWatch(id); await refresh() }619 func runWatch(_ id: String) async throws { try await api.runWatch(id) }620621 func reset() { state = LoadState() }622}623624/// Time conventions shared by the bars and the drawings anchored on them. A daily bar of the data layer is stamped625/// 00:00 UTC of its session date; the app shows market days in exchange time, so a daily bar's `date` is midnight in626/// New York of that same calendar day. A drawing point's `t` is always the data layer's stamp (what the web stores).627enum ChartTime {628 static func interval(_ range: ChartRange) -> String {629 switch range { case .day: "5m"; case .week: "15m"; case .month: "1h"; default: "1d" }630 }631 private static var utc: Calendar { var c = Calendar(identifier: .gregorian); c.timeZone = TimeZone(identifier: "UTC")!; return c }632633 static func bars(_ series: VQBarSeries, intraday: Bool) -> [Bar] {634 series.bars.compactMap { b in635 guard let o = b.open, let h = b.high, let l = b.low, let c = b.close else { return nil } // an incomplete bar is not drawn as zeros636 let date: Date637 if intraday { date = b.date } else {638 let d = utc.dateComponents([.year, .month, .day], from: b.date)639 date = MarketDate.calendar.date(from: d) ?? b.date640 }641 return Bar(date: date, open: o, high: h, low: l, close: c, volume: b.volume)642 }643 }644 /// The data layer's stamp (epoch seconds) of a bar shown by the app.645 static func t(_ bar: Bar, intraday: Bool) -> Double {646 if intraday { return bar.date.timeIntervalSince1970 }647 let d = MarketDate.calendar.dateComponents([.year, .month, .day], from: bar.date)648 return (utc.date(from: d) ?? bar.date).timeIntervalSince1970649 }650 /// Fractional index of time `t` on the bars (interpolated between neighbours, extrapolated at the median step651 /// outside), like the web's `timeToIndex`: a point placed on a daily chart lands where it belongs on an intraday one.652 static func index(of t: Double, times: [Double]) -> Double {653 guard let first = times.first, let last = times.last else { return 0 }654 let step = medianStep(times)655 if times.count == 1 { return (t - first) / step }656 if t <= first { return (t - first) / step }657 if t >= last { return Double(times.count - 1) + (t - last) / step }658 var lo = 0, hi = times.count - 1659 while hi - lo > 1 { let mid = (lo + hi) / 2; if times[mid] <= t { lo = mid } else { hi = mid } }660 let span = times[hi] - times[lo]661 return Double(lo) + (span > 0 ? (t - times[lo]) / span : 0)662 }663 static func time(at index: Double, times: [Double]) -> Double {664 guard let first = times.first, let last = times.last else { return 0 }665 let step = medianStep(times)666 if index <= 0 { return first + index * step }667 if index >= Double(times.count - 1) { return last + (index - Double(times.count - 1)) * step }668 let lo = Int(index.rounded(.down)), f = index - Double(lo)669 return times[lo] + (times[lo + 1] - times[lo]) * f670 }671 static func medianStep(_ times: [Double]) -> Double {672 guard times.count > 1 else { return 86_400 }673 let diffs = zip(times.dropFirst(), times).map { $0 - $1 }.filter { $0 > 0 }.sorted()674 return diffs.isEmpty ? 86_400 : diffs[diffs.count / 2]675 }676}677