SPB Git

Repository Public

MACOS_ARCHITECTURE.md 14.4 KB

# VQuant for macOS 2.0.0 — architecture

Native client (Swift 6, SwiftUI, AppKit where it earns its place) of the existing VQuant server (vquant.spboucher.ai, repository vquant.git, Express + SQLite + Python on the MacLustr node chosen by mld). No web view, no JavaScript engine, no third-party dependency: Scripts/verify-release.sh checks the signed bundle for both.

# What the repository analysis found (2026-11-18, backend v5.7.0 → v5.8.0)

The brief described VQuant as a trading and research platform with a component named Pyrus, WebSocket market feeds and strategy/backtesting modules. The repository says otherwise, and this application follows the repository:

Brief Repository Consequence here
"Pyrus" computation service No file, route, package or process named Pyrus (grep -ri pyrus matches only conversation text in the database). The server-side computation layer that exists is a Python engine (server/services/python/*: GARCH, VaR, Monte Carlo, options, optimiser, risk metrics, and a persistent notebook kernel) used by the agent. The Quant Engine section exposes that Python engine through server jobs (/api/quant/*, added in v5.8.0). Nothing is named Pyrus.
WebSocket / streaming market data None. Market data is a REST proxy to Financial Modeling Prep (/api/fmp/*). The only streams are server-sent events of analysis jobs. Quotes are polled over HTTPS and labelled by age; nothing is called "live". URLSessionWebSocketTask is not used because there is nothing to connect it to.
Live trading, orders None. portfolio_positions is a record of holdings the agent reads. No order entry. Portfolio says so on screen.
Strategies, backtesting No module. The agent can write a backtest in its notebook on request. No section; reachable through Research.
Research platform An AI research agent (POST /api/chat), four modes, sub-analysts, memory, watches, PDF/DOCX/slides. Research, Agent, Jobs, Documents.
Electron desktop app desktop/ in the repository is an Electron wrapper that spawns the server locally with API keys in a config file. Not reused. It is the opposite of what was asked.

# 2.0.0 "VQuant Next" in one page

2.0.0 is an upgrade of 1.0.1, not a rewrite: the 1.x core, authentication, runner and cache are unchanged, and the app now also links the shared Swift package VQuantKit (../VQuantKit, used by the iOS app too) for everything backend 6 adds (contract: vquant-next/docs/next/CONTRACT.md). The client header is vquant-macos/2.0.0, which is what makes the server return the 19 Quant Lab engines and the cancelled job status.

VQuant is, at its core, the autonomous research agent; the terminal, the lab, the portfolios and the studio are surfaces around it. The sidebar says so: Research · Research Studio, then Terminal (Overview, Markets, Watchlists, Charting, Statements, Data Explorer), Quant (Quant Lab, Jobs), Portfolio (Portfolios, Risk Analytics), Workspace (Agent, Documents). There is still no trading: the backend has no brokerage connection.

# Layers

text
App (SwiftUI/AppKit, MainActor)              VQuantCore (SwiftPM "Core/", Sendable, no UI)        VQuantKit (shared package)
 ├ VQuantApp       scenes, commands           ├ Networking  HTTPTransport, APIClient, SSEParser     ├ VQuantKit   transport seam, sync engine,
 ├ AppEnvironment  dependency container       ├ Auth        AuthService, TokenStore, Passkey…       │             models of every v6 route, Lab
 │   ├ api   1.x client (VQuantCore)          ├ Services    VQuantAPI (1.x routes), GenerationRunner│             form and jobs, research agent
 │   ├ vq    kit clients (VQNextAPI)          ├ Models      Market, Research, Workspace, Quant      │             state, formatting
 │   ├ sync  SyncStore → VQSyncEngine         ├ Cache       DiskCache (AES-GCM), Freshness          ├ VQuantUI    design tokens (VQTokens),
 │   └ store{…} feature stores (registry)     ├ Analytics   Indicators, Downsampler, ChartDrawings, │             components, LabResultView,
 ├ SessionStore    sign-in, lock, expiry      │             PortfolioImport, CSV, DataTable         │             ResearchActivityView family
 ├ App/Next        KitBridge, SyncStore,      ├ Markdown    blocks, editing                         └ VQuantKitTesting  fakes (tests only)
 │                 StudyStore, Commands,      ├ Terminal    RowSelection, StatementMath, Palette
 │                 WorkspaceMapping, MacLogic ├ Lab         LabSupport
 ├ Features/*      one folder per section     └ Stores      legacy local stores (migration source)
 └ Components      shared views
  • Two clients, one session. app.api is the 1.x VQuantAPI; app.vq is the kit's entry point. The kit never sees a URL or a token: MacVQTransport (App/Next/KitBridge.swift) serves its VQTransport with the app's own APIClient (same base URL, Keychain token, X-VQ-Client, never an Origin), honours VQRequest.contentType (multipart dataset upload) and runs the app's sign-out path on a 401.
  • Dependency injection. AppEnvironment is built once and passed explicitly (let app: AppEnvironment) to every view. @Environment(Model.self) is deliberately avoided: on macOS 27 it traps inside table cells, menus, sheets and toolbars. Feature stores are created on first use through app.store { … } and emptied at sign-out when they conform to SessionScoped.
  • Concurrency. Core and kit are Sendable, Swift 6 mode, complete checking; the app target defaults to MainActor. Long work is async; the main thread never waits on the network.
  • Server responsibilities stay on the server: model inference, the research sandbox, every quantitative engine, rendering of exports, persistence, per-person authorisation. The client computes only display aids from data it was sent (chart indicators, descriptive statistics, statement comparisons) and labels them as such.

# One account, synced (CONTRACT §1)

SyncStore (App/Next/SyncStore.swift) owns one VQSyncEngine per signed-in person.

  • Replica. Application Support/VQuant/sync-<host>/<person>/, every file sealed by CacheCipher — the kit's cipher hook implemented with DiskCache.seal/open, i.e. AES-GCM under the same Keychain key as the cache —, excluded from backups.
  • Lifecycle. Started at sign-in (and unlock): load, open /api/v2/sync/stream, pull, replay the queue. Lock: the stream stops, the sealed replica stays. Sign-out, or a session ended by the server (401): replica, write queue and conflict records are erased, like the cache — queued offline edits are lost in that case (the 1.x rule "a 401 erases what this Mac keeps" was preferred to keeping a queue for a session that no longer exists).
  • Conflict policy (shared with the web and iOS clients): lists merge element-wise (watchlist symbols, portfolio positions and cash, project.items, chart.drawings; local edit wins per element); other fields are last-writer-wins per field (Configuration.granularity = .field); workspace objects are whole-object last-writer-wins. Notices that discarded something are listed in the toolbar's sync popover and in Settings › Sync with "Keep the other version" / "Keep mine".
  • What is synced. watchlist (Watchlists), portfolio (Portfolios; main is the agent's and is bridged by the server from the legacy positions), chart (one per symbol, id sym-<SYMBOL>: interval, type, indicators, comparisons, drawings), workspace (saved window layouts that map — see below), project, note, review (server-written), preference/default.
  • Preferences. Up/down colour pair, default model and mode, routing, budget, memory settings and recent searches sync. Light/dark is a per-device choice: preference.theme is neither applied nor written. Refresh cadence, app lock, notifications and chart defaults are Mac-only (UserDefaults).
  • Migration of 1.x local data (once per person and Mac, after the first complete pull): each local watchlist becomes object mac-<uuid of the list> (a re-run writes the same ids: no duplicate), the file is renamed watchlists.migrated-1x.json (nothing is deleted). Saved window layouts become workspace objects when every window has a panel type in the shared model (WorkspaceMapping); a layout containing Agent, Jobs or Documents windows has no such type and stays local, listed "This Mac only". Mac-specific data (window frames, the section) travels in panel.config.mac; web conventions (activeSymbol, config.symbol, config.linked, percentage sizes) are read and preserved.
  • Hints. hint events of the sync stream refresh conversations, running analyses and the quant job list; slow polling remains as a fallback.

# Research (CONTRACT §2, §9)

  • The composer reads the server's model registry (/api/v2/models), offers Auto (the model_routed event is shown with its reason), the five modes — Research only when /api/v2/research/sandbox answers —, budgets and dataset attachment (create workspace → multipart upload → inspection card).
  • A generation's events are decoded twice from the same frames: by the 1.x GenerationEvent (the live run view that 1.0.1 had) and by the kit's VQResearchSessionStore (the cockpit). Replay from the last event index is unchanged.
  • The cockpit is the report plus an inspector — Activity · Code · Experiments · Figures · Files · Environment — composed from the kit's ResearchActivityView family over a ResearchDataSource; the Mac adds the file tree, Quick Look, drag-out, Save As. A study reopened later, or started on another device, is rebuilt from REST (/api/v2/research/sessions/:id) and, while it runs, by attaching to the generation stream.
  • Approvals (§9.7) appear as a banner, a sheet and — when the app is in the background — a notification whose click is routed to the conversation (WindowRouter).
  • StudyStore reads every workspace resource network-first and keeps it in the encrypted cache for offline reading.

# Windows

  • WindowGroup(id: "main", for: MainSpec.self) — any number of workstation windows. Each has its own WindowModel (section, symbol, conversation, computation, project, portfolio, watchlist, palette). The MainSpec value is only what the window was opened with; what it shows afterwards is kept in @SceneStorage, which macOS restores per window (writing navigation back into the WindowGroup value re-creates the window content: the 1.0.0 defect).
  • WindowGroup(id: "chart", for: ChartSpec.self) — detached chart windows, bound to the same per-symbol chart object.
  • Settings scene (grouped sidebar, 20 panes) and a MenuBarExtra (market session, a few indices, running analyses and jobs, a quick ask that opens Research with the question prefilled and never sends by itself).
  • Menus: View lists the 14 destinations (⌘1…⌘9 for the first nine), Research and Lab menus act on the frontmost window through focused values (App/Next/Commands.swift); every shortcut comes from one table (AppShortcuts) with a unit-tested collision check. ⌘K opens the command palette (/api/v2/search + local commands).
  • Saved layouts: synced workspace objects when they map, local otherwise (see sync above).

# Charting

ChartCanvas draws with Core Graphics through SwiftUI Canvas; ChartInteraction is an NSView that turns pointer, scroll, pinch and keyboard input into pan and zoom, and into the drawing gestures. Swift Charts is used for result figures (frontier, distributions, volatility forecast, allocation, drawdown).

  • Data. Bars come from GET /api/v2/data/bars/:symbol (app.vq.data.bars), with the provenance the data layer states (provider, fallback, adjustment really applied, time zone, currency, gaps, truncation) shown by the chip and its popover. The 1.x provider proxy is asked only when v2 answers 404 or 502, and the chip says "1.x route". A network failure returns the last series from the encrypted cache, marked "Cached".
  • Reduction. When more bars are visible than fit, Downsampler.ohlcAligned merges neighbours for drawing only (first open, last close, extreme high and low, summed volume — tested), indicator lines are reduced to first/low/high/last per mark (Downsampler.envelope), both cached per zoom level in ChartModel; the chart states "1 mark = n bars", and CSV export writes the source bars.
  • Drawings (Core/Analytics/ChartDrawings.swift, ChartDrawingRender) are anchored at t (epoch seconds of a bar) and p (price), never pixels: trend line, horizontal line, ray, rectangle, Fibonacci retracement, text note, measure. An anchor is displayed on the bar that contains its time, so drawings survive an interval change without being rewritten. Every edit goes through the window's UndoManager.
  • Persistence (ChartSync). One synced chart object per symbol, id sym-<SYMBOL> derived exactly like the web client does (^GSPC → sym-_5eGSPC). It is created at the first change, never by viewing; saved with a 0.7 s debounce by editing the typed properties of the stored value, so keys, indicators and drawings written by other clients survive. A change made on another device is applied live.
  • Metal was measured and not adopted: see docs/CHART_PERFORMANCE.md.

# Data freshness

Freshness has five states and one rule each: Recent (provider timestamp < 2 min), Delayed (older), Historical (bars, statements), Cached (server unreachable; last value this Mac received), Unavailable. The provider's timestamp is shown; the time of the request never replaces it.

# Offline

DiskCache.fetch is network-first; only a network failure falls back to the last stored value, marked as cached. A server refusal is always an error. Files are AES-GCM sealed under a Keychain key, excluded from backups, bound to their cache key, and erased at sign-out or when another person signs in. Analyses and computations are refused offline with an explanation. Edits of synced objects (watchlists, portfolios, charts, projects, notes, preferences) are the exception since 2.0: they are queued durably by the sync engine and sent, in order, when the connection returns.

# Minimum system

macOS 14: @Observable, SectorMark, onChange(of:initial:), SettingsLink, typed WindowGroup restoration. Universal binary (arm64 + x86_64).

Files main
Menu

Theme