diff --git a/Sources/SplashGUI/Core/AppConfig.swift b/Sources/SplashGUI/Core/AppConfig.swift
index ba06172..637d8c4 100644
--- a/Sources/SplashGUI/Core/AppConfig.swift
+++ b/Sources/SplashGUI/Core/AppConfig.swift
@@ -396,6 +396,10 @@ struct AppConfig: Codable, Equatable {
var loggingEnabled: Bool = false
var loggingLanClients: Bool = false
var loggingRetentionDays: Int = 90
+ // Performance samples ride the existing /status poll (no extra requests). The interval is
+ // in seconds and the poll ticks once a second; 1/5/10 are the offered choices.
+ var performanceLoggingEnabled: Bool = false
+ var performanceLogInterval: Int = 5
init() {}
@@ -408,6 +412,7 @@ struct AppConfig: Codable, Equatable {
case engineMode
case startOnLaunch
case loggingEnabled, loggingLanClients, loggingRetentionDays
+ case performanceLoggingEnabled, performanceLogInterval
}
init(from decoder: Decoder) throws {
@@ -429,6 +434,8 @@ struct AppConfig: Codable, Equatable {
loggingEnabled = try c.decodeIfPresent(Bool.self, forKey: .loggingEnabled) ?? false
loggingLanClients = try c.decodeIfPresent(Bool.self, forKey: .loggingLanClients) ?? false
loggingRetentionDays = try c.decodeIfPresent(Int.self, forKey: .loggingRetentionDays) ?? 90
+ performanceLoggingEnabled = try c.decodeIfPresent(Bool.self, forKey: .performanceLoggingEnabled) ?? false
+ performanceLogInterval = try c.decodeIfPresent(Int.self, forKey: .performanceLogInterval) ?? 5
}
func enginePinOverride() -> EnginePin? {
@@ -696,6 +703,15 @@ final class ConfigStore {
}
cfg.run.schemaVersion = 6
}
+ if (cfg.run.schemaVersion ?? 1) < 7 {
+ // Prefer a Homebrew-installed engine when one is present: it updates with
+ // `brew upgrade splash` and needs no duplicate download. Only the untouched
+ // default (.pinned) flips; an explicit .latest/.custom choice stays.
+ if cfg.engineMode == .pinned, EngineInstaller.externalEngineVersion() != nil {
+ cfg.engineMode = .homebrew
+ }
+ cfg.run.schemaVersion = 7
+ }
return cfg
}
return AppConfig()
diff --git a/Sources/SplashGUI/Core/AppModel.swift b/Sources/SplashGUI/Core/AppModel.swift
index 874e791..29713ef 100644
--- a/Sources/SplashGUI/Core/AppModel.swift
+++ b/Sources/SplashGUI/Core/AppModel.swift
@@ -12,7 +12,11 @@ enum ServerPhase: Equatable {
@MainActor
final class AppModel: ObservableObject {
@Published var config: AppConfig {
- didSet { ConfigStore.shared.save(config) }
+ didSet {
+ ConfigStore.shared.save(config)
+ // The Logging tab's LAN toggle is live: the proxy reads its policy per request.
+ proxy?.updatePolicy(.init(logLocal: true, logLAN: config.loggingLanClients))
+ }
}
@Published var phase: ServerPhase = .stopped
@Published var logTail: [String] = []
@@ -29,6 +33,9 @@ final class AppModel: ObservableObject {
@Published var engineProgress: Double = 0
@Published var engineVersion: String?
@Published var engineResolvedVersion: String?
+ // The Homebrew-casked engine's version, if one is installed. Read on demand: `brew
+ // upgrade`/`uninstall` can change it while the app runs, and the picker should follow.
+ var homebrewEngineVersion: String? { EngineInstaller.externalEngineVersion() }
private var engineCancels: Set<AnyCancellable> = []
// Depth of the 27B arch every catalog model shares; used only to scale the load-progress bar.
private static let modelLayerCount = 66.0
@@ -200,10 +207,12 @@ final class AppModel: ObservableObject {
}
private var client: SplashClient { SplashClient(port: frontedEnginePort ?? config.run.port) }
private var pollTask: Task<Void, Never>?
+ private var pollTick = 0
private var logTimer: Timer?
// Session logging (spec-logging-proxy). When the serve is fronted, the proxy holds the
// PUBLIC port and the engine runs on `frontedEnginePort`; status polling goes direct.
let sessionLog = SessionLog()
+ let performanceLog = PerformanceLog()
@Published var frontedEnginePort: Int?
private var proxy: SessionProxy?
// The Logging tab's "applies on next Start" hint: what the running serve was started with.
@@ -266,6 +275,7 @@ final class AppModel: ObservableObject {
refreshModelSizeCache()
// Retention sweep on launch; day-file names older than the window are deleted.
SessionLog.purge(dir: sessionLog.dir, retentionDays: config.loggingRetentionDays)
+ SessionLog.purge(dir: performanceLog.dir, retentionDays: config.loggingRetentionDays)
engineVersion = engine.installedVersion
engine.step = EngineInstaller.isInstalled ? .ready : .idle
@@ -480,20 +490,35 @@ final class AppModel: ObservableObject {
return Int(t)
}
- func clientConfigText(for client: ProviderClient) -> String {
+ func clientConfigText(for client: ProviderClient, useLAN: Bool = false) -> String {
let (tokens, _) = providerContextTokens
let modalities = phase == .ready
? status?.inputModalities ?? (config.run.languageOnly ? ["text"] : ["text", "image", "pdf"])
: (config.run.languageOnly ? ["text"] : ["text", "image", "pdf"])
+ // LAN configs are for another machine on this network; without a leased address (or
+ // with LAN serving off) they fall back to loopback rather than write a broken URL.
+ let host = useLAN && config.run.lanAccess
+ ? (MachineInfo.lanIPv4Address ?? "127.0.0.1") : "127.0.0.1"
// The served name, when set, is the name clients should use: the API answers to it and,
// with announce, reports it. The full Hub ID stays the profile key and the /status name.
let apiName = config.run.servedModelName.isEmpty ? config.run.modelID : config.run.servedModelName
+ let off: SamplingDefaults? = catalogEntry.map { e in
+ var s = SamplingDefaults()
+ s.temperature = e.cardOffTemperature
+ s.topP = e.cardOffTopP
+ s.topK = e.cardOffTopK
+ s.presencePenalty = e.cardOffPresencePenalty
+ s.minP = e.cardOffMinP
+ return s
+ }
let ctx = ClientConfigContext(client: client, modelID: apiName,
label: catalogEntry?.label ?? savedEntry?.label ?? config.run.modelID,
- port: config.run.port, contextTokens: tokens,
+ host: host, port: config.run.port, contextTokens: tokens,
inputModalities: modalities,
sampling: config.sampling,
- efforts: catalogEntry?.supportedEfforts ?? CatalogModel.allEfforts)
+ offSampling: off,
+ efforts: catalogEntry?.supportedEfforts ?? CatalogModel.allEfforts,
+ laterSystem: status?.rendersLaterSystem ?? false)
return ClientConfigs.text(for: ctx)
}
@@ -588,9 +613,10 @@ final class AppModel: ObservableObject {
// fields, and .latest keeps the installed engine on a failed check — the compiled-in pin
// would silently DOWNGRADE — while nothing-installed falls back to the compiled pin.
// `externalVersion` (Homebrew, if present) satisfies .pinned/.latest without a download
- // when it is at or above the wanted build; .custom names an explicit payload and never
- // accepts a stand-in. When external is true, start() adopts it (points `current` at the
- // brew libexec) instead of calling ensureInstalled.
+ // when it is at or above the wanted build; .homebrew takes it at ANY version (that is the
+ // point: brew can lag the pin) and falls back to pinned behavior when brew is absent.
+ // .custom names an explicit payload and never accepts a stand-in. When external is true,
+ // start() adopts it (points `current` at the brew libexec) instead of calling ensureInstalled.
nonisolated static func enginePlan(mode: EngineMode, customOverride: EnginePin?, installed: Bool,
checkUpdate: Bool, latest: EnginePin?,
pinnedVersion: String, externalVersion: String?)
@@ -598,7 +624,7 @@ final class AppModel: ObservableObject {
var ensure = !installed || checkUpdate
var override: EnginePin?
switch mode {
- case .pinned:
+ case .pinned, .homebrew:
break
case .custom:
override = customOverride
@@ -612,7 +638,9 @@ final class AppModel: ObservableObject {
}
}
var external = false
- if mode != .custom, let ext = externalVersion {
+ if mode == .homebrew {
+ external = externalVersion != nil
+ } else if mode != .custom, let ext = externalVersion {
let wanted = override?.version ?? pinnedVersion
if EngineInstaller.versionOrder(ext, wanted) != .orderedAscending { external = true }
}
@@ -660,6 +688,9 @@ final class AppModel: ObservableObject {
if !ensure, !external, case .latest = self.config.engineMode {
self.server.note("- engine update check: GitHub unreachable, keeping the installed engine")
}
+ if !external, case .homebrew = self.config.engineMode {
+ self.server.note("- engine: no Homebrew install found; using the pinned engine")
+ }
if external {
// Skip the download: point `current` at the Homebrew payload.
do {
@@ -694,8 +725,14 @@ final class AppModel: ObservableObject {
? SessionProxy.pickInternalPort(publicPort: self.config.run.port) : nil
let plan = Self.frontingPlan(enabled: self.config.loggingEnabled,
adopted: false, pickedInternalPort: picked)
+ // The engine's Host allow-list is its bind address plus loopback; a LAN client
+ // reaches this Mac by its LAN address, so name that address explicitly.
+ let lanHosts = self.config.run.lanAccess
+ ? [MachineInfo.lanIPv4Address].compactMap { $0 } : []
if plan.front, let internalPort = plan.enginePort {
run.port = internalPort
+ // The proxy is the only LAN-facing listener; keep the engine on loopback.
+ run.lanAccess = false
} else if self.config.loggingEnabled, picked == nil {
self.server.note("- session logging: no free internal port near \(self.config.run.port); serving directly")
}
@@ -703,7 +740,8 @@ final class AppModel: ObservableObject {
revision: self.catalogEntry?.revision,
local: local.map {
SplashServer.LocalLaunch(modelDir: $0.path, mmproj: $0.mmproj)
- })
+ },
+ allowedHosts: lanHosts)
if plan.front, let internalPort = plan.enginePort {
let px = try SessionProxy(
publicPort: self.config.run.port, internalPort: internalPort,
@@ -791,6 +829,7 @@ final class AppModel: ObservableObject {
private func startPolling() {
pollTask?.cancel()
+ pollTick = 0
pollTask = Task { [weak self] in
while !Task.isCancelled {
guard let self else { return }
@@ -841,8 +880,39 @@ final class AppModel: ObservableObject {
stage: stage
)
self.history.append(sample)
- if self.history.count > 240 { self.history.removeFirst(self.history.count - 240) }
+ if self.history.count > 480 { self.history.removeFirst(self.history.count - 480) }
self.currentStage = stage
+ // Performance logging rides this poll: the same /status data the Status
+ // tab shows, written every Nth tick. No extra requests to the engine.
+ self.pollTick += 1
+ if self.config.performanceLoggingEnabled, stage != nil,
+ PerformanceLog.shouldSample(tick: self.pollTick,
+ interval: self.config.performanceLogInterval) {
+ self.performanceLog.write(PerformanceSample(
+ ts: sample.time,
+ model: self.effectiveModel ?? self.config.run.modelID,
+ engine: self.engineVersion,
+ stage: stage.map { $0 == .prefill ? "prefill" : "decode" },
+ ttftP50: snap?.ttftP50,
+ ttftP95: snap?.ttftP95,
+ itlP50: snap?.itlP50,
+ itlP95: snap?.itlP95,
+ decodeTps: decodeTps,
+ prefillTps: prefillTps,
+ draftAcceptance: draft,
+ cacheHitRate: snap?.cacheHitRate,
+ reusedTokens: snap?.reusedTokens,
+ cacheLookups: snap?.cacheLookups,
+ queued: snap?.queued,
+ prefilling: snap?.prefilling,
+ decoding: snap?.decoding,
+ kvPagesActive: snap?.kvPagesActive,
+ kvBlockTokens: snap?.kvBlockTokens,
+ hardBudgetBytes: snap?.hardBudgetBytes,
+ contextTokens: snap?.maxContextTokens,
+ physicalRAM: MachineInfo.physicalRAM,
+ metalMaxWorkingSet: MachineInfo.metalMaxWorkingSet))
+ }
} else if self.phase == .starting {
let alive = self.adoptedPID.map { kill(Int32($0), 0) == 0 } ?? self.server.isRunning
if !alive {
@@ -855,7 +925,7 @@ final class AppModel: ObservableObject {
let snap = await self.client.fetchStatus()
self.status = snap
}
- try? await Task.sleep(nanoseconds: 2_000_000_000)
+ try? await Task.sleep(nanoseconds: 1_000_000_000)
}
}
}
diff --git a/Sources/SplashGUI/Core/ClientConfigs.swift b/Sources/SplashGUI/Core/ClientConfigs.swift
index e6dcd33..0485e0d 100644
--- a/Sources/SplashGUI/Core/ClientConfigs.swift
+++ b/Sources/SplashGUI/Core/ClientConfigs.swift
@@ -9,6 +9,7 @@ enum ProviderClient: String, CaseIterable, Identifiable {
case zed = "Zed"
case claudeCode = "Claude Code"
case codex = "Codex"
+ case pi = "Pi"
var id: String { rawValue }
@@ -18,13 +19,14 @@ enum ProviderClient: String, CaseIterable, Identifiable {
// Which sampling fields actually reach this client's requests. OpenCode merges the model's
// `body` into the request body verbatim (V2; verified live against 2.2.2 with an echo
- // server); Zed carries temperature only (agent.model_parameters); Claude Code and Codex
- // expose no sampling knobs — their requests set what they themselves want.
+ // server); Zed carries temperature only (agent.model_parameters); Claude Code, Codex and
+ // Pi expose no sampling knobs — their requests set what they themselves want.
func carries(_ field: SamplingField) -> Bool {
switch self {
case .opencode: return field != .maxTokens
case .zed: return field == .temperature
case .claudeCode, .codex: return false
+ case .pi: return field != .maxTokens
}
}
@@ -34,6 +36,7 @@ enum ProviderClient: String, CaseIterable, Identifiable {
case .zed: return "settings.json for Zed (AI section)"
case .claudeCode: return "settings.json: the env block for ~/.claude/settings.json"
case .codex: return "config.toml for ~/.codex/config.toml"
+ case .pi: return "models.json: merge this providers block into ~/.pi/agent/models.json"
}
}
@@ -43,6 +46,7 @@ enum ProviderClient: String, CaseIterable, Identifiable {
case .zed: return "zed-splash-settings.json"
case .claudeCode: return "claude-code-splash-env.json"
case .codex: return "codex-splash-config.toml"
+ case .pi: return "pi-splash-models.json"
}
}
@@ -64,12 +68,19 @@ struct ClientConfigContext {
let client: ProviderClient
let modelID: String
let label: String
+ // The machine the client runs on: loopback for this Mac, the LAN address for another one.
+ var host: String = "127.0.0.1"
let port: Int
let contextTokens: Int
let inputModalities: [String]
let sampling: SamplingDefaults
+ // The model card's thinking-off set, when the model has a card. Pi writes it as
+ // samplingParamsByThinkingLevel.off so no-think turns can use different values.
+ var offSampling: SamplingDefaults? = nil
// Reasoning levels this model accepts; defaults to every level Splash's API takes.
var efforts: [String] = CatalogModel.allEfforts
+ // Whether the server renders a later system message in place (Pi's compat flag).
+ var laterSystem: Bool = false
}
enum ClientConfigs {
@@ -85,6 +96,7 @@ enum ClientConfigs {
case .zed: return zed(ctx)
case .claudeCode: return claudeCode(ctx)
case .codex: return codex(ctx)
+ case .pi: return pi(ctx)
}
}
@@ -165,7 +177,7 @@ enum ClientConfigs {
"name": "SplashGUI",
"package": "@opencode/ai/providers/openai-compatible",
"settings": [
- "baseURL": "http://127.0.0.1:\(ctx.port)/v1",
+ "baseURL": "http://\(ctx.host):\(ctx.port)/v1",
"apiKey": "local",
],
"models": [ctx.modelID: model],
@@ -204,7 +216,7 @@ enum ClientConfigs {
"language_models": [
"openai_compatible": [
"splash": [
- "api_url": "http://127.0.0.1:\(ctx.port)/v1",
+ "api_url": "http://\(ctx.host):\(ctx.port)/v1",
"available_models": [model],
]
]
@@ -228,7 +240,7 @@ enum ClientConfigs {
// bare server URL — Claude Code appends /v1/messages itself. No sampling fields:
// Claude Code sets its own per request.
let env: [String: Any] = [
- "ANTHROPIC_BASE_URL": "http://127.0.0.1:\(ctx.port)",
+ "ANTHROPIC_BASE_URL": "http://\(ctx.host):\(ctx.port)",
"ANTHROPIC_AUTH_TOKEN": "local",
"ANTHROPIC_MODEL": ctx.modelID,
"ANTHROPIC_DEFAULT_OPUS_MODEL": ctx.modelID,
@@ -255,9 +267,72 @@ enum ClientConfigs {
[model_providers.splash]
name = "Splash"
- base_url = "http://127.0.0.1:\(ctx.port)/v1"
+ base_url = "http://\(ctx.host):\(ctx.port)/v1"
env_key = "SPLASH_API_KEY"
wire_api = "responses"
"""
}
+
+ // MARK: - Pi
+
+ // Mirrors the engine's `splash pi` connector (install/clients.py _write_pi_provider):
+ // a provider named for the server, an openai-completions endpoint, and one model entry.
+ // Pi reads custom providers from models.json in its agent directory; the block merges
+ // beside the user's other providers.
+ private static func pi(_ ctx: ClientConfigContext) -> String {
+ let provider = ctx.port == 8095 ? "splash" : "splash-\(ctx.port)"
+ var model: [String: Any] = [
+ "id": ctx.modelID,
+ "reasoning": true,
+ // Pi sends no effort when thinking is off, which leaves the template's default;
+ // "none" turns thinking off.
+ "thinkingLevelMap": ["off": "none"],
+ // Pi accepts only text and image; any other entry invalidates the whole file.
+ "input": ctx.inputModalities.contains("image") ? ["text", "image"] : ["text"],
+ "contextWindow": ctx.contextTokens,
+ // Pi lowers this per request to what its context leaves; the engine writes the
+ // same 32,768 allowance.
+ "maxTokens": 32_768,
+ ]
+ if ctx.laterSystem {
+ // Pi otherwise folds the system messages it adds as a session goes on into the
+ // first one, which changes the prompt from its start and makes the server read
+ // it all again.
+ model["compat"] = ["supportsMidConvoSystemMessages": true]
+ }
+ // Pi's free-form sampling defaults, merged into every request. The card's thinking-off
+ // set rides beside them so no-think turns can use different values (Pi's level key is
+ // "off"; Splash's effort name is "none").
+ var sampling: [String: Any] = [
+ "temperature": decimal(ctx.sampling.temperature),
+ "top_p": decimal(ctx.sampling.topP),
+ "top_k": ctx.sampling.topK,
+ "presence_penalty": decimal(ctx.sampling.presencePenalty),
+ "min_p": decimal(ctx.sampling.minP),
+ ]
+ if let seed = ctx.sampling.seed { sampling["seed"] = seed }
+ model["samplingParams"] = sampling
+ if let off = ctx.offSampling {
+ model["samplingParamsByThinkingLevel"] = [
+ "off": [
+ "temperature": decimal(off.temperature),
+ "top_p": decimal(off.topP),
+ "top_k": off.topK,
+ "presence_penalty": decimal(off.presencePenalty),
+ "min_p": decimal(off.minP),
+ ]
+ ]
+ }
+ let root: [String: Any] = [
+ "providers": [
+ provider: [
+ "baseUrl": "http://\(ctx.host):\(ctx.port)/v1",
+ "api": "openai-completions",
+ "apiKey": "local",
+ "models": [model],
+ ]
+ ]
+ ]
+ return json(root)
+ }
}
diff --git a/Sources/SplashGUI/Core/EngineInstaller.swift b/Sources/SplashGUI/Core/EngineInstaller.swift
index a39c534..6bc4fc0 100644
--- a/Sources/SplashGUI/Core/EngineInstaller.swift
+++ b/Sources/SplashGUI/Core/EngineInstaller.swift
@@ -27,9 +27,9 @@ final class EngineInstaller: ObservableObject {
// Bumping the engine is an app release; AppConfig's engine*Override fields are the escape hatch.
static let defaultPin = EnginePin(
- version: "1.6.0",
- sha256: "da3aef0a581491b0eb4c1168bda07f520e5ca8368764abff426d95ac1c77e5c4",
- url: "https://github.com/incoai/splash/releases/download/1.6.0/splash-1.6.0-arm64-macos26.tar.gz"
+ version: "1.6.1",
+ sha256: "0ed408a781f951a13ff58bed95c9e8c1d1dc67ab9d649fcaf365972b6720ce6c",
+ url: "https://github.com/incoai/splash/releases/download/1.6.1/splash-1.6.1-arm64-macos26.tar.gz"
)
static let fm = FileManager.default
diff --git a/Sources/SplashGUI/Core/EngineResolver.swift b/Sources/SplashGUI/Core/EngineResolver.swift
index 343344a..90fc2e3 100644
--- a/Sources/SplashGUI/Core/EngineResolver.swift
+++ b/Sources/SplashGUI/Core/EngineResolver.swift
@@ -3,6 +3,7 @@ import Foundation
// How the app decides which engine build to run.
enum EngineMode: String, Codable, Equatable {
case pinned // the build this SplashGUI shipped with (EngineInstaller.defaultPin)
+ case homebrew // the engine Homebrew installed, whatever version it is; no download
case latest // newest GitHub release, checked on every start; falls back below
case custom // the three override fields (AppConfig.enginePinOverride)
}
diff --git a/Sources/SplashGUI/Core/PerformanceLog.swift b/Sources/SplashGUI/Core/PerformanceLog.swift
new file mode 100644
index 0000000..e0f9150
--- /dev/null
+++ b/Sources/SplashGUI/Core/PerformanceLog.swift
@@ -0,0 +1,149 @@
+import Foundation
+
+// One /status sample, as the Status tab already reads it. Written to JSONL day files so a
+// throughput report can be built without eyeballing the page. Every field is optional except
+// the timestamp: an idle sample still records the scheduler and memory, with no rates.
+nonisolated struct PerformanceSample: Codable {
+ var ts: Date
+ var model: String? = nil
+ var engine: String? = nil
+ var stage: String? = nil // "prefill" | "decode" | nil (idle)
+ var ttftP50: Double? = nil
+ var ttftP95: Double? = nil
+ var itlP50: Double? = nil
+ var itlP95: Double? = nil
+ var decodeTps: Double? = nil
+ var prefillTps: Double? = nil
+ var draftAcceptance: Double? = nil
+ var cacheHitRate: Double? = nil
+ var reusedTokens: Int? = nil
+ var cacheLookups: Int? = nil
+ var queued: Int? = nil
+ var prefilling: Int? = nil
+ var decoding: Int? = nil
+ var kvPagesActive: Int? = nil
+ var kvBlockTokens: Int? = nil
+ var hardBudgetBytes: Int? = nil
+ var contextTokens: Int? = nil
+ var physicalRAM: Int? = nil
+ var metalMaxWorkingSet: Int? = nil
+}
+
+// JSONL performance store: logs/performance/YYYY-MM-DD.jsonl under the app data dir. The
+// sampler rides the existing /status poll, so enabling it adds no requests to the engine.
+final class PerformanceLog: @unchecked Sendable {
+ let dir: URL
+ private let queue = DispatchQueue(label: "splashgui.performancelog")
+ private let iso = ISO8601DateFormatter()
+ var lastWriteError: String?
+
+ init(dir: URL? = nil) {
+ self.dir = dir ?? AppPaths.dataDir.appendingPathComponent("logs/performance", isDirectory: true)
+ }
+
+ nonisolated static func encodeLine(_ sample: PerformanceSample) -> String? {
+ let e = JSONEncoder()
+ e.dateEncodingStrategy = .iso8601
+ guard let data = try? e.encode(sample) else { return nil }
+ return String(decoding: data, as: UTF8.self) + "\n"
+ }
+
+ nonisolated static func decodeLine(_ line: String) -> PerformanceSample? {
+ let d = JSONDecoder()
+ d.dateDecodingStrategy = .iso8601
+ return try? d.decode(PerformanceSample.self, from: Data(line.utf8))
+ }
+
+ // The poll runs once a second; sample on every Nth tick. A zero/negative interval is
+ // treated as every tick rather than dividing by zero.
+ nonisolated static func shouldSample(tick: Int, interval: Int) -> Bool {
+ interval <= 1 || tick % interval == 0
+ }
+
+ func write(_ sample: PerformanceSample) {
+ guard let line = Self.encodeLine(sample) else {
+ lastWriteError = "encode failed"
+ return
+ }
+ queue.async {
+ do {
+ try FileManager.default.createDirectory(at: self.dir, withIntermediateDirectories: true)
+ let url = self.dir.appendingPathComponent(SessionLog.dayFileName(sample.ts))
+ if !FileManager.default.fileExists(atPath: url.path) {
+ FileManager.default.createFile(atPath: url.path, contents: nil)
+ }
+ let h = try FileHandle(forWritingTo: url)
+ defer { try? h.close() }
+ h.seekToEndOfFile()
+ h.write(Data(line.utf8))
+ self.lastWriteError = nil
+ } catch {
+ self.lastWriteError = "\(error)"
+ }
+ }
+ }
+
+ struct Stats { var samplesToday = 0; var totalBytes = 0; var fileCount = 0 }
+
+ static func stats(dir: URL, now: Date = Date()) -> Stats {
+ let fm = FileManager.default
+ var s = Stats()
+ guard let names = (try? fm.contentsOfDirectory(atPath: dir.path))?
+ .filter({ $0.hasSuffix(".jsonl") }).sorted() else { return s }
+ s.fileCount = names.count
+ for n in names {
+ let u = dir.appendingPathComponent(n)
+ s.totalBytes += (try? u.resourceValues(forKeys: [.fileSizeKey]))?.fileSize ?? 0
+ if n == SessionLog.dayFileName(now), let data = try? Data(contentsOf: u) {
+ s.samplesToday = data.filter { $0 == UInt8(ascii: "\n") }.count
+ }
+ }
+ return s
+ }
+
+ // Every retained sample as CSV, oldest first. The header is stable so a community report
+ // can paste the file straight into a spreadsheet.
+ static func csv(dir: URL) -> String {
+ let header = [
+ "timestamp", "model", "engine", "stage",
+ "ttft_p50_ms", "ttft_p95_ms", "itl_p50_ms", "itl_p95_ms",
+ "decode_tps", "prefill_tps", "draft_acceptance", "cache_hit_rate",
+ "reused_tokens", "cache_lookups", "queued", "prefilling", "decoding",
+ "kv_pages_active", "kv_block_tokens", "hard_budget_bytes", "context_tokens",
+ "physical_ram_bytes", "metal_max_working_set_bytes",
+ ].joined(separator: ",")
+ let fm = FileManager.default
+ let names = ((try? fm.contentsOfDirectory(atPath: dir.path))?
+ .filter { $0.hasSuffix(".jsonl") } ?? []).sorted()
+ var samples: [PerformanceSample] = []
+ for n in names {
+ guard let data = try? Data(contentsOf: dir.appendingPathComponent(n)),
+ let text = String(data: data, encoding: .utf8) else { continue }
+ samples += text.split(separator: "\n", omittingEmptySubsequences: true)
+ .compactMap { decodeLine(String($0)) }
+ }
+ samples.sort { $0.ts < $1.ts }
+ let iso = ISO8601DateFormatter()
+ func cell(_ s: String?) -> String {
+ guard let s else { return "" }
+ if s.contains(",") || s.contains("\"") || s.contains("\n") {
+ return "\"" + s.replacingOccurrences(of: "\"", with: "\"\"") + "\""
+ }
+ return s
+ }
+ func num(_ v: Double?) -> String { v.map { String($0) } ?? "" }
+ func int(_ v: Int?) -> String { v.map { String($0) } ?? "" }
+ let rows = samples.map { s in
+ [
+ iso.string(from: s.ts), cell(s.model), cell(s.engine), cell(s.stage),
+ num(s.ttftP50), num(s.ttftP95), num(s.itlP50), num(s.itlP95),
+ num(s.decodeTps), num(s.prefillTps), num(s.draftAcceptance), num(s.cacheHitRate),
+ int(s.reusedTokens), int(s.cacheLookups), int(s.queued), int(s.prefilling),
+ int(s.decoding), int(s.kvPagesActive), int(s.kvBlockTokens),
+ int(s.hardBudgetBytes), int(s.contextTokens), int(s.physicalRAM),
+ int(s.metalMaxWorkingSet),
+ ].joined(separator: ",")
+ }
+ return ([header] + rows).joined(separator: "\n") + "\n"
+ }
+}
diff --git a/Sources/SplashGUI/Core/SessionProxy.swift b/Sources/SplashGUI/Core/SessionProxy.swift
index ad7fca7..09c66ad 100644
--- a/Sources/SplashGUI/Core/SessionProxy.swift
+++ b/Sources/SplashGUI/Core/SessionProxy.swift
@@ -329,14 +329,22 @@ final class SessionProxy: @unchecked Sendable {
private let listener: NWListener
private let queue = DispatchQueue(label: "splashgui.sessionproxy")
private var flows: [ObjectIdentifier: Flow] = [:]
- private let policy: Policy
+ // The policy is mutable so the Logging tab's "Also record LAN clients" toggle takes effect
+ // on the next request, not the next Start. Guarded because the UI writes it on the main
+ // thread while the proxy queue reads it.
+ private let policyLock = NSLock()
+ private var storedPolicy: Policy
+ private var policy: Policy {
+ policyLock.lock(); defer { policyLock.unlock() }
+ return storedPolicy
+ }
private let log: SessionLog
var onNote: ((String) -> Void)? // fires on a background queue; callers hop
init(publicPort: Int, internalPort: Int, lanBind: Bool, policy: Policy, log: SessionLog) throws {
self.publicPort = publicPort
self.internalPort = internalPort
- self.policy = policy
+ self.storedPolicy = policy
self.log = log
guard let port = NWEndpoint.Port(rawValue: UInt16(publicPort)) else {
throw InstallError.preflight("Logging proxy port \(publicPort) is out of range.")
@@ -361,12 +369,17 @@ final class SessionProxy: @unchecked Sendable {
flows.removeAll()
}
+ // Live policy change from the Logging tab; applies to requests that arrive after it.
+ func updatePolicy(_ p: Policy) {
+ policyLock.lock(); storedPolicy = p; policyLock.unlock()
+ }
+
private func accept(_ client: NWConnection) {
- var loopback = true
- if case let .hostPort(host, _) = client.endpoint {
- let h = String(describing: host)
- loopback = h.hasPrefix("127.") || h == "::1" || h == "localhost"
- }
+ // `endpoint` is the peer for a listener-accepted connection; `currentPath` is the
+ // authoritative source once the path exists. Unknown shapes count as remote, so a
+ // LAN client is never recorded by accident when the toggle is off.
+ let peer = client.currentPath?.remoteEndpoint ?? client.endpoint
+ let loopback = Self.isLoopbackEndpoint(peer)
let upstream = NWConnection(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: UInt16(internalPort))!, using: .tcp)
let flow = Flow(client: client, upstream: upstream, loopback: loopback,
policy: policy, log: log, queue: queue,
@@ -383,6 +396,14 @@ final class SessionProxy: @unchecked Sendable {
loopbackPeer ? policy.logLocal : policy.logLAN
}
+ // Loopback peers are this Mac's own clients. IPv4-mapped IPv6 normalizes to "127.x" in
+ // NWEndpoint.Host's description, so the prefix check covers it.
+ nonisolated static func isLoopbackEndpoint(_ endpoint: NWEndpoint) -> Bool {
+ guard case let .hostPort(host, _) = endpoint else { return false }
+ let h = String(describing: host).lowercased()
+ return h == "localhost" || h == "::1" || h.hasPrefix("127.")
+ }
+
// Free-port pick for the engine behind the proxy: probe-bind starting at public+1.
nonisolated static func pickInternalPort(publicPort: Int, tries: Int = 32) -> Int? {
for candidate in (publicPort + 1)...(publicPort + tries) {
diff --git a/Sources/SplashGUI/Core/SplashClient.swift b/Sources/SplashGUI/Core/SplashClient.swift
index 851c473..7e8f49d 100644
--- a/Sources/SplashGUI/Core/SplashClient.swift
+++ b/Sources/SplashGUI/Core/SplashClient.swift
@@ -55,6 +55,20 @@ struct StatusSnapshot {
var kvBlockTokens: Int? { int("kv", "block_tokens") }
// What the running server accepts: ["text"] or ["text","image","pdf"].
var inputModalities: [String]? { self[["input_modalities"]] as? [String] }
+ // Whether every chat template renders a later system message in place. The engine's Pi
+ // connector advertises this as compat.supportsMidConvoSystemMessages; /status reports
+ // "native"/"patched" per template (or one string when there is a single template).
+ var rendersLaterSystem: Bool? {
+ guard let t = self[["chat_template", "later_system"]] else { return nil }
+ if let s = t as? String { return s == "native" || s == "patched" }
+ if let d = t as? [String: Any] {
+ return !d.isEmpty && d.values.allSatisfy {
+ guard let s = $0 as? String else { return false }
+ return s == "native" || s == "patched"
+ }
+ }
+ return nil
+ }
// Live fraction of the granted context window occupied by active requests' KV:
// resident tokens (active pages x tokens-per-page) over the ceiling. Server-wide, so it
diff --git a/Sources/SplashGUI/Core/SplashServer.swift b/Sources/SplashGUI/Core/SplashServer.swift
index f9a8b59..d88492e 100644
--- a/Sources/SplashGUI/Core/SplashServer.swift
+++ b/Sources/SplashGUI/Core/SplashServer.swift
@@ -112,7 +112,8 @@ final class SplashServer {
return nil
}
- func launch(config: RunConfig, revision: String?, local: LocalLaunch? = nil) throws {
+ func launch(config: RunConfig, revision: String?, local: LocalLaunch? = nil,
+ allowedHosts: [String] = []) throws {
guard process == nil else { return }
guard let target = Self.resolveLaunch() else {
throw ServerError.missingExecutable
@@ -120,7 +121,8 @@ final class SplashServer {
let p = Process()
p.executableURL = URL(fileURLWithPath: target.executable)
- p.arguments = target.prefixArgs + Self.buildArguments(for: config, revision: revision, local: local)
+ p.arguments = target.prefixArgs + Self.buildArguments(for: config, revision: revision,
+ local: local, allowedHosts: allowedHosts)
var env = ProcessInfo.processInfo.environment
env["PYTHONUNBUFFERED"] = "1"
env["TERM"] = "dumb"
@@ -195,7 +197,7 @@ final class SplashServer {
}
static func buildArguments(for config: RunConfig, revision: String? = nil,
- local: LocalLaunch? = nil) -> [String] {
+ local: LocalLaunch? = nil, allowedHosts: [String] = []) -> [String] {
var args = ["serve", "--model", config.modelID, "--port", String(config.port)]
if let local {
// Local serving: --model stays the ID the API reports, --model-dir names the files.
@@ -204,9 +206,13 @@ final class SplashServer {
args += ["--model-dir", local.modelDir]
if !local.mmproj.isEmpty && !config.languageOnly { args += ["--mmproj", local.mmproj] }
}
- // LAN serving: bind every IPv4 interface. The engine accepts IP-address Host headers
- // by default, so no --allowed-host is needed for clients connecting by address.
+ // LAN serving: bind every IPv4 interface. The engine's Host allow-list is the bind
+ // address plus loopback, and 0.0.0.0 is excluded — so a client reaching this Mac by
+ // its LAN address needs that address named with --allowed-host (1.6.x refuses it
+ // otherwise). Behind the logging proxy the engine binds loopback and the proxy is the
+ // only LAN-facing listener; the allowed host still has to be passed through.
if config.lanAccess { args += ["--host", "0.0.0.0"] }
+ for host in allowedHosts where !host.isEmpty { args += ["--allowed-host", host] }
// A catalog entry pins an exact HF commit, so the pull is reproducible and a later
// re-upload under the same name cannot change what this Mac loads. The engine refuses
// --revision with --model-dir, so a local launch never carries one.
diff --git a/Sources/SplashGUI/Views/LoggingTab.swift b/Sources/SplashGUI/Views/LoggingTab.swift
index c186325..eea2270 100644
--- a/Sources/SplashGUI/Views/LoggingTab.swift
+++ b/Sources/SplashGUI/Views/LoggingTab.swift
@@ -1,5 +1,6 @@
import SwiftUI
import AppKit
+import UniformTypeIdentifiers
// Session logging controls and the live tail (scratch/spec-logging-proxy.md). Logging is
// opt-in and full-fidelity: whole prompts, replies, reasoning and tool calls as JSONL,
@@ -8,6 +9,7 @@ import AppKit
struct LoggingTab: View {
@EnvironmentObject var model: AppModel
@State private var stats = SessionLog.Stats()
+ @State private var perfStats = PerformanceLog.Stats()
@State private var tail: [SessionRecord] = []
var body: some View {
@@ -27,6 +29,7 @@ struct LoggingTab: View {
Divider()
Toggle("Also record LAN clients", isOn: $model.config.loggingLanClients)
.disabled(!model.config.run.lanAccess)
+ .help("Takes effect immediately while the proxy is running. Off keeps LAN clients working through the proxy but unrecorded.")
if model.config.run.lanAccess && model.config.loggingEnabled {
Label(model.config.loggingLanClients
? "LAN clients are recorded: machines on your network have their turns logged too."
@@ -45,7 +48,7 @@ struct LoggingTab: View {
}
.frame(maxWidth: 240, alignment: .leading)
HStack(spacing: 16) {
- Text("\(stats.sessionsToday) sessions today · \(bytes(stats.totalBytes)) in \(stats.fileCount) file(s)")
+ Text("\(String(stats.sessionsToday)) sessions today · \(bytes(stats.totalBytes)) in \(String(stats.fileCount)) file(s)")
Button("Open log folder") { NSWorkspace.shared.open(model.sessionLog.dir) }
Button("Refresh") { load() }
}
@@ -55,7 +58,39 @@ struct LoggingTab: View {
.font(.callout)
.foregroundStyle(.orange)
}
- Text("Full prompts, replies, reasoning and tool calls, one JSON object per request at \(model.sessionLog.dir.path). Point clients at http://127.0.0.1:\(model.config.run.port)/v1 as always; while logging is on, the app sits between them and the engine.")
+ Text(verbatim: "Full prompts, replies, reasoning and tool calls, one JSON object per request at \(model.sessionLog.dir.path). Point clients at http://127.0.0.1:\(model.config.run.port)/v1 as always; while logging is on, the app sits between them and the engine.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ SettingsSection("Performance") {
+ Toggle("Log performance samples", isOn: $model.config.performanceLoggingEnabled)
+ .help("Writes the same /status numbers the Status tab shows — TTFT, prefill/decode tok/s, draft acceptance, cache hit, scheduler and memory — to a JSONL day file while the server is prefilling or generating. It rides the existing status poll, so it adds no requests to the engine.")
+ HStack(spacing: 6) {
+ Text("Sample every")
+ .fixedSize(horizontal: true, vertical: false)
+ Picker("Sample every", selection: $model.config.performanceLogInterval) {
+ Text("1 second").tag(1)
+ Text("5 seconds").tag(5)
+ Text("10 seconds").tag(10)
+ }
+ .labelsHidden()
+ .fixedSize()
+ .disabled(!model.config.performanceLoggingEnabled)
+ Spacer()
+ }
+ HStack(spacing: 16) {
+ Text("\(String(perfStats.samplesToday)) samples today · \(bytes(perfStats.totalBytes)) in \(String(perfStats.fileCount)) file(s)")
+ Button("Open folder") { NSWorkspace.shared.open(model.performanceLog.dir) }
+ Button("Export CSV…") { exportPerformanceCSV() }
+ Button("Refresh") { load() }
+ }
+ .font(.callout)
+ if let err = model.performanceLog.lastWriteError {
+ Label("Performance log write problem: \(err)", systemImage: "exclamationmark.triangle")
+ .font(.callout)
+ .foregroundStyle(.orange)
+ }
+ Text("One JSON object per sample at \(model.performanceLog.dir.path), written while the server is prefilling or generating (idle periods are gaps). Retention follows the Storage setting above. Export CSV writes every retained sample, oldest first.")
.font(.caption)
.foregroundStyle(.secondary)
}
@@ -94,15 +129,35 @@ struct LoggingTab: View {
private func load() {
let log = model.sessionLog
+ let perf = model.performanceLog
Task.detached(priority: .utility) {
let s = SessionLog.stats(dir: log.dir)
let t = SessionLog.tail(dir: log.dir, limit: 20)
+ let ps = PerformanceLog.stats(dir: perf.dir)
await MainActor.run {
stats = s
tail = t
+ perfStats = ps
}
}
}
+
+ private func exportPerformanceCSV() {
+ let panel = NSSavePanel()
+ panel.nameFieldStringValue = "splash-performance-\(Self.dayStamp()).csv"
+ panel.allowedContentTypes = [.commaSeparatedText]
+ panel.begin { response in
+ guard response == .OK, let url = panel.url else { return }
+ let csv = PerformanceLog.csv(dir: model.performanceLog.dir)
+ try? csv.write(to: url, atomically: true, encoding: .utf8)
+ }
+ }
+
+ private static func dayStamp() -> String {
+ let f = DateFormatter()
+ f.dateFormat = "yyyy-MM-dd"
+ return f.string(from: Date())
+ }
}
// One collapsed line per record; expanded shows the full JSON of the turn.
@@ -125,7 +180,7 @@ private struct SessionRow: View {
Text(e).font(.caption).foregroundStyle(.red)
}
if let u = record.usage {
- Text("\(u.input ?? 0)→\(u.output ?? 0)t").font(.caption).foregroundStyle(.secondary)
+ Text("\(String(u.input ?? 0))→\(String(u.output ?? 0))t").font(.caption).foregroundStyle(.secondary)
}
Text(record.finishReason ?? (record.status.map { "\($0)" } ?? ""))
.font(.caption).foregroundStyle(.secondary)
diff --git a/Sources/SplashGUI/Views/ProviderTab.swift b/Sources/SplashGUI/Views/ProviderTab.swift
index 2284d62..c279c11 100644
--- a/Sources/SplashGUI/Views/ProviderTab.swift
+++ b/Sources/SplashGUI/Views/ProviderTab.swift
@@ -6,6 +6,7 @@ import AppKit
struct ProviderTab: View {
@EnvironmentObject var model: AppModel
@State private var client: ProviderClient = .opencode
+ @State private var useLAN = false
var body: some View {
SettingsPage {
@@ -22,6 +23,25 @@ struct ProviderTab: View {
.help(client.tooltip)
Spacer()
}
+ Toggle("Use LAN IP for other machines", isOn: $useLAN)
+ .disabled(!lanConfigAvailable)
+ .help("Write the configs with this Mac's LAN address instead of 127.0.0.1, so another machine on the same network can point at this server. Needs Serve on LAN on the Run tab. The API has no key, so only use it on a trusted network.")
+ if !model.config.run.lanAccess {
+ Text("Serve on LAN is off (Run tab); these configs only work on this Mac.")
+ .font(.caption2)
+ .foregroundStyle(.secondary)
+ } else if let ip = MachineInfo.lanIPv4Address {
+ // verbatim: a LocalizedStringKey Text would group the port as "8,095".
+ Text(verbatim: useLAN
+ ? "Configs point at http://\(ip):\(model.config.run.port). Keep this Mac on the same network."
+ : "Configs point at http://127.0.0.1:\(model.config.run.port) (this Mac). Turn the toggle on for another machine.")
+ .font(.caption2)
+ .foregroundStyle(.secondary)
+ } else {
+ Text("No LAN address is leased right now; configs keep 127.0.0.1.")
+ .font(.caption2)
+ .foregroundStyle(.secondary)
+ }
}
// Sampling and the config preview sit side by side: sampling is a narrow fixed
@@ -88,7 +108,7 @@ struct ProviderTab: View {
.opacity(client.carries(.seed) ? 1 : 0.4)
Spacer()
}
- .help("Fixed seed reproduces outputs, reliably only when the request runs alone with identical cached prefixes; concurrency changes batching and can change results. Written into the OpenCode config's model options.")
+ .help("Fixed seed reproduces outputs, reliably only when the request runs alone with identical cached prefixes; concurrency changes batching and can change results. Written into the OpenCode config's model options and Pi's samplingParams.")
if let off = cardOffLinkLabel {
HStack(spacing: 6) {
Button(off) { model.applyCardOffSampling() }
@@ -121,7 +141,7 @@ struct ProviderTab: View {
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
ScrollView {
- Text(model.clientConfigText(for: client))
+ Text(model.clientConfigText(for: client, useLAN: useLAN))
.font(.system(size: 11, design: .monospaced))
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
@@ -137,7 +157,7 @@ struct ProviderTab: View {
HStack(spacing: 10) {
Button("Copy") {
NSPasteboard.general.clearContents()
- NSPasteboard.general.setString(model.clientConfigText(for: client),
+ NSPasteboard.general.setString(model.clientConfigText(for: client, useLAN: useLAN),
forType: .string)
}
Button("Save…") { saveConfig() }
@@ -167,9 +187,19 @@ struct ProviderTab: View {
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
+ if client == .pi {
+ Text("Merge the providers block into ~/.pi/agent/models.json. `splash pi` writes the same entry and launches Pi with --provider splash. Sampling rides in samplingParams; the card's thinking-off set rides in samplingParamsByThinkingLevel.off.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
}
}
+ private var lanConfigAvailable: Bool {
+ model.config.run.lanAccess && MachineInfo.lanIPv4Address != nil
+ }
+
private var configCaption: String {
var text = client.configCaption
if model.providerContextTokens.estimate {
@@ -213,7 +243,7 @@ struct ProviderTab: View {
panel.allowedContentTypes = client == .codex ? [.plainText] : [.json]
panel.begin { response in
guard response == .OK, let url = panel.url else { return }
- try? model.clientConfigText(for: client).write(to: url, atomically: true, encoding: .utf8)
+ try? model.clientConfigText(for: client, useLAN: useLAN).write(to: url, atomically: true, encoding: .utf8)
}
}
}
diff --git a/Sources/SplashGUI/Views/RootView.swift b/Sources/SplashGUI/Views/RootView.swift
index 854d054..7b0d559 100644
--- a/Sources/SplashGUI/Views/RootView.swift
+++ b/Sources/SplashGUI/Views/RootView.swift
@@ -42,9 +42,9 @@ struct SplashGUIApp: App {
struct RootView: View {
enum Section: String, CaseIterable, Identifiable {
case run = "Run"
+ case logging = "Logging"
case provider = "Provider"
case status = "Status"
- case logging = "Logging"
var id: String { rawValue }
diff --git a/Sources/SplashGUI/Views/RunTab.swift b/Sources/SplashGUI/Views/RunTab.swift
index 5faf680..94a947f 100644
--- a/Sources/SplashGUI/Views/RunTab.swift
+++ b/Sources/SplashGUI/Views/RunTab.swift
@@ -26,6 +26,8 @@ struct RunTab: View {
.fixedSize(horizontal: true, vertical: false)
Picker("Engine source", selection: $model.config.engineMode) {
Text("This build's pin (\(EngineInstaller.defaultPin.version))").tag(EngineMode.pinned)
+ Text(model.homebrewEngineVersion.map { "Homebrew install (\($0))" }
+ ?? "Homebrew install (not found)").tag(EngineMode.homebrew)
Text("Always latest release").tag(EngineMode.latest)
Text("Custom pin").tag(EngineMode.custom)
}
@@ -33,13 +35,17 @@ struct RunTab: View {
.fixedSize()
Spacer()
}
- .help("Pinned: always run the engine version this SplashGUI was released and tested with; bumping it takes a new app build. Latest: before every start, check GitHub's newest Splash release and install it (checksum verified against the release's own .sha256); if GitHub can't be reached the installed engine stays. Custom: install the exact build named by the three fields below.")
+ .help("Pinned: always run the engine version this SplashGUI was released and tested with; bumping it takes a new app build. A Homebrew-installed engine at or above that version is used instead of downloading a copy. Homebrew: use the engine `brew install splash` put on this Mac, whatever version it is — `brew upgrade splash` updates it and no copy is downloaded. Latest: before every start, check GitHub's newest Splash release and install it (checksum verified against the release's own .sha256); if GitHub can't be reached the installed engine stays. Homebrew is not consulted here. Custom: install the exact build named by the three fields below.")
switch model.config.engineMode {
case .pinned:
Toggle("Check for engine update on start", isOn: $model.config.checkEngineUpdate)
.help("On: each start installs the engine this SplashGUI build pins if a different one is installed. Off: only download if no engine is installed yet.")
+ case .homebrew:
+ Text("Uses the engine Homebrew installed at /opt/homebrew/opt/splash, whatever version it is; `brew upgrade splash` updates it. No download. If Homebrew's copy is missing, the pinned engine is used.")
+ .font(.caption2)
+ .foregroundStyle(.secondary)
case .latest:
- Text("Checks GitHub on every start; a newer release downloads before the server launches. Unreachable GitHub keeps the installed engine.")
+ Text("Checks GitHub on every start; a newer release downloads before the server launches. Unreachable GitHub keeps the installed engine. Homebrew installs are not consulted.")
.font(.caption2)
.foregroundStyle(.secondary)
case .custom:
@@ -57,7 +63,7 @@ struct RunTab: View {
HStack {
Text("Installed engine")
Spacer()
- Text(model.engineVersion ?? "not installed")
+ Text(installedEngineText)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
}
@@ -231,16 +237,16 @@ struct RunTab: View {
private func catalogStatusRow(_ entry: CatalogModel) -> some View {
VStack(alignment: .leading, spacing: 4) {
- HStack(spacing: 6) {
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
Image(systemName: entry.onDisk ? "checkmark.circle.fill" : "arrow.down.circle")
.foregroundStyle(entry.onDisk ? Color.green : Color.orange)
- Text(entry.onDisk
- ? "installed, maps from disk"
- : "not installed, first start pulls it from Hugging Face")
+ // One Text, not two: separate Texts wrap independently, so on a narrow window
+ // the note dropped to its own line instead of flowing after the status.
+ Text("\(entry.onDisk ? "installed, maps from disk" : "not installed, first start pulls it from Hugging Face") · \(entry.note)")
.font(.caption)
.foregroundStyle(.secondary)
- Text("· \(entry.note)").font(.caption).foregroundStyle(.secondary)
- Spacer()
+ .fixedSize(horizontal: false, vertical: true)
+ Spacer(minLength: 0)
}
.help((entry.downloadURL.map { "pulls, pinned to commit \($0). " } ?? "")
+ "serve --revision pins the download to this exact commit, so a later re-upload under the same file name cannot change what loads. The catalog also carries its sha256; the app checks it against the digest Splash records before starting.")
@@ -360,6 +366,11 @@ struct RunTab: View {
}
}
+ private var installedEngineText: String {
+ let version = model.engineVersion ?? "not installed"
+ return EngineInstaller.currentIsExternal ? "\(version) · Homebrew" : version
+ }
+
private func openWebChat() {
if let url = URL(string: "http://127.0.0.1:" + String(model.config.run.port)) {
NSWorkspace.shared.open(url)
diff --git a/Sources/SplashGUI/Views/StatusWidgets.swift b/Sources/SplashGUI/Views/StatusWidgets.swift
index 39c69d3..f5f46e0 100644
--- a/Sources/SplashGUI/Views/StatusWidgets.swift
+++ b/Sources/SplashGUI/Views/StatusWidgets.swift
@@ -128,7 +128,7 @@ struct ServerToolbarControls: View {
.font(.caption)
.foregroundStyle(.secondary)
Spacer()
- Text("\(snap.contextUsedTokens ?? 0)/\(max / 1024)K")
+ Text("\(String(snap.contextUsedTokens ?? 0))/\(String(max / 1024))K")
.font(.caption)
.monospacedDigit()
.foregroundStyle(.secondary)
diff --git a/scripts/profile-test/main.swift b/scripts/profile-test/main.swift
index 7418726..c0bc41f 100644
--- a/scripts/profile-test/main.swift
+++ b/scripts/profile-test/main.swift
@@ -21,7 +21,11 @@ func runTests() {
check("old config decodes — typed values survived",
cfg.run.maxContext == "100K" && cfg.sampling.temperature == 0.23,
"\(cfg.run.maxContext) / \(cfg.sampling.temperature)")
- check("schemaVersion migrated to 6", cfg.run.schemaVersion == 6, "\(cfg.run.schemaVersion ?? -1)")
+ check("schemaVersion migrated to 7", cfg.run.schemaVersion == 7, "\(cfg.run.schemaVersion ?? -1)")
+ let brew = EngineInstaller.externalEngineVersion()
+ check("schema 7 prefers a Homebrew engine when one is installed",
+ brew == nil ? cfg.engineMode == .pinned : cfg.engineMode == .homebrew,
+ "\(cfg.engineMode) brew \(brew ?? "none")")
// v2 flipped int8→bf16, v3 flipped bf16→auto; v6 then resolved the still-auto KV because
// the typed maxContext keeps Auto off. The endpoint that matters: a concrete KV pick.
check("typed serve fields migrate to Auto off", cfg.run.auto == false)
@@ -118,7 +122,7 @@ func runTests() {
"\(reread.modelProfiles[B]?.sampling.temperature ?? -1)")
check("typed temp 0.55 survives a save", reread.sampling.temperature == 0.55,
"\(reread.sampling.temperature)")
- check("schemaVersion stays 6", reread.run.schemaVersion == 6)
+ check("schemaVersion stays 7", reread.run.schemaVersion == 7)
// startOnLaunch is absent from this v2 fixture — the tolerant decoder must default it
// false, not throw the whole config back to factory (the Codable missing-key trap).
check("startOnLaunch defaults false when the key is absent", reread.startOnLaunch == false)
@@ -156,6 +160,13 @@ func runTests() {
check("LAN on: --host 0.0.0.0 reaches the engine",
lanArgs.firstIndex(of: "--host").map { $0 + 1 < lanArgs.count && lanArgs[$0 + 1] == "0.0.0.0" } == true,
lanArgs.joined(separator: " "))
+ let lanHostArgs = SplashServer.buildArguments(for: lan, allowedHosts: ["10.0.0.221"])
+ check("LAN on: --allowed-host carries the LAN address",
+ lanHostArgs.firstIndex(of: "--allowed-host").map {
+ $0 + 1 < lanHostArgs.count && lanHostArgs[$0 + 1] == "10.0.0.221"
+ } == true, lanHostArgs.joined(separator: " "))
+ check("no --allowed-host when none is passed",
+ !SplashServer.buildArguments(for: lan).contains("--allowed-host"))
let noLan = #"{"run":{"port":8123,"modelID":"someone/Model:x"}}"#
if let nd = noLan.data(using: .utf8),
let ncfg = try? JSONDecoder().decode(AppConfig.self, from: nd) {
@@ -329,7 +340,7 @@ func runTests() {
check("all-auto schema 5 migrates to Auto on", migrated.run.auto == true)
check("all-auto migration leaves KV at auto",
migrated.run.kvFormat == "auto", migrated.run.kvFormat)
- check("all-auto migration lands on schema 6", migrated.run.schemaVersion == 6)
+ check("all-auto migration lands on schema 7", migrated.run.schemaVersion == 7)
} else {
check("all-auto schema 5 migrates to Auto on", false, "fixture write failed")
}
@@ -424,6 +435,65 @@ func runTests() {
xtext.contains("wire_api = \"responses\"") && xtext.contains("env_key = \"SPLASH_API_KEY\"")
&& xtext.contains("model_auto_compact_token_limit = 58982")
&& xtext.contains("model_provider = \"splash\""))
+ var offSam = SamplingDefaults()
+ offSam.temperature = 0.7; offSam.topP = 0.8; offSam.topK = 20
+ offSam.presencePenalty = 1.5; offSam.minP = 0.05
+ let pctx = ClientConfigContext(client: .pi, modelID: base.modelID, label: base.label,
+ port: base.port, contextTokens: base.contextTokens,
+ inputModalities: base.inputModalities, sampling: base.sampling,
+ offSampling: offSam, laterSystem: true)
+ if let data = ClientConfigs.text(for: pctx).data(using: .utf8),
+ let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let provider = (root["providers"] as? [String: Any])?["splash"] as? [String: Any],
+ let models = provider["models"] as? [[String: Any]],
+ let model = models.first {
+ let sp = model["samplingParams"] as? [String: Any]
+ let byLevel = model["samplingParamsByThinkingLevel"] as? [String: Any]
+ let off = byLevel?["off"] as? [String: Any]
+ check("Pi: provider shape matches splash pi",
+ (provider["baseUrl"] as? String) == "http://127.0.0.1:8095/v1"
+ && (provider["api"] as? String) == "openai-completions"
+ && (provider["apiKey"] as? String) == "local"
+ && (model["id"] as? String) == "someone/Model:x"
+ && (model["reasoning"] as? Bool) == true
+ && (model["contextWindow"] as? Int) == 65_536
+ && (model["maxTokens"] as? Int) == 32_768
+ && (model["input"] as? [String]) == ["text", "image"]
+ && ((model["thinkingLevelMap"] as? [String: Any])?["off"] as? String) == "none"
+ && ((model["compat"] as? [String: Any])?["supportsMidConvoSystemMessages"] as? Bool) == true)
+ check("Pi: samplingParams carry the model's sampling",
+ (sp?["temperature"] as? Double) == 1.0 && (sp?["top_p"] as? Double) == 0.95
+ && (sp?["top_k"] as? Int) == 20 && (sp?["presence_penalty"] as? Double) == 0
+ && (sp?["min_p"] as? Double) == 0 && (sp?["seed"] as? UInt64) == 12_345_678_901)
+ check("Pi: thinking-off set rides samplingParamsByThinkingLevel.off",
+ (off?["temperature"] as? Double) == 0.7 && (off?["top_p"] as? Double) == 0.8
+ && (off?["top_k"] as? Int) == 20 && (off?["presence_penalty"] as? Double) == 1.5
+ && (off?["min_p"] as? Double) == 0.05)
+ } else {
+ check("Pi: provider shape matches splash pi", false, "config did not parse")
+ }
+ let pOff = ClientConfigContext(client: .pi, modelID: base.modelID, label: base.label,
+ port: 9000, contextTokens: base.contextTokens,
+ inputModalities: ["text"], sampling: base.sampling)
+ let pOffText = ClientConfigs.text(for: pOff)
+ check("Pi: off-default port names the provider splash-<port>, text-only, no compat",
+ pOffText.contains("\"splash-9000\"") && pOffText.contains("\"text\"")
+ && !pOffText.contains("image")
+ && !pOffText.contains("supportsMidConvoSystemMessages")
+ && !pOffText.contains("samplingParamsByThinkingLevel"))
+ // The Provider tab's LAN toggle swaps the loopback host for this Mac's LAN address in
+ // every client's endpoint (the API has no key; the caption warns about that).
+ var lanBase = base
+ lanBase.host = "10.0.0.221"
+ let lanClaude = ClientConfigContext(client: .claudeCode, modelID: base.modelID,
+ label: base.label, host: "10.0.0.221", port: base.port,
+ contextTokens: base.contextTokens,
+ inputModalities: base.inputModalities,
+ sampling: base.sampling)
+ check("LAN host reaches every client endpoint",
+ ClientConfigs.text(for: lanBase).contains("http://10.0.0.221:8095/v1")
+ && ClientConfigs.text(for: lanClaude).contains("http://10.0.0.221:8095\"")
+ && !ClientConfigs.text(for: lanClaude).contains("127.0.0.1"))
// The served name, when set, replaces the Hub ID in the configs the Provider tab writes.
let priorID = m.config.run.modelID
@@ -583,6 +653,18 @@ func runTests() {
checkUpdate: false, latest: nil, pinnedVersion: PIN, externalVersion: "9.9.9")
check("custom mode never substitutes the brew engine",
!extCustom.external && extCustom.ensure == true && extCustom.override == stale)
+ let brewMode = AppModel.enginePlan(mode: .homebrew, customOverride: nil, installed: true,
+ checkUpdate: true, latest: nil, pinnedVersion: PIN, externalVersion: "1.5.0")
+ check("homebrew mode takes a brew engine older than the pin, no download",
+ brewMode.external && brewMode.ensure == false)
+ let brewMissing = AppModel.enginePlan(mode: .homebrew, customOverride: nil, installed: true,
+ checkUpdate: false, latest: nil, pinnedVersion: PIN, externalVersion: nil)
+ check("homebrew mode without brew keeps the installed engine",
+ !brewMissing.external && brewMissing.ensure == false)
+ let brewMissingFresh = AppModel.enginePlan(mode: .homebrew, customOverride: nil, installed: false,
+ checkUpdate: false, latest: nil, pinnedVersion: PIN, externalVersion: nil)
+ check("homebrew mode without brew and nothing installed installs the pin",
+ !brewMissingFresh.external && brewMissingFresh.ensure == true)
// Dotted version compare: numeric segments, not lexicographic.
check("versionOrder is numeric per segment",
@@ -833,6 +915,7 @@ func runTests() {
checkLoggingParses()
checkLoggingStore()
+ checkPerformanceLog()
checkLoggingPlanning()
checkLoggingE2E()
@@ -1031,6 +1114,45 @@ func checkLoggingStore() {
try? FileManager.default.removeItem(at: tmp)
}
+func checkPerformanceLog() {
+ let tmp = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
+ .appendingPathComponent("splash-perf-\(UUID().uuidString)", isDirectory: true)
+ var s = PerformanceSample(ts: Date())
+ s.model = "someone/Model:x"; s.engine = "1.6.1"; s.stage = "decode"
+ s.ttftP50 = 120; s.ttftP95 = 300; s.itlP50 = 18; s.itlP95 = 40
+ s.decodeTps = 42.5; s.prefillTps = 900; s.draftAcceptance = 0.72
+ s.cacheHitRate = 0.5; s.reusedTokens = 1234; s.cacheLookups = 9
+ s.queued = 0; s.prefilling = 0; s.decoding = 1
+ s.kvPagesActive = 12; s.kvBlockTokens = 256; s.hardBudgetBytes = 40_000_000_000
+ s.contextTokens = 65_536; s.physicalRAM = 64_000_000_000
+ s.metalMaxWorkingSet = 48_000_000_000
+ let line = PerformanceLog.encodeLine(s)
+ check("performance sample round-trips through JSONL",
+ line != nil && PerformanceLog.decodeLine(line!)?.decodeTps == 42.5
+ && PerformanceLog.decodeLine(line!)?.stage == "decode")
+ check("performance sampling follows the tick interval",
+ PerformanceLog.shouldSample(tick: 1, interval: 1)
+ && !PerformanceLog.shouldSample(tick: 4, interval: 5)
+ && PerformanceLog.shouldSample(tick: 5, interval: 5)
+ && PerformanceLog.shouldSample(tick: 10, interval: 10)
+ && PerformanceLog.shouldSample(tick: 3, interval: 0))
+ let log = PerformanceLog(dir: tmp)
+ log.write(s)
+ var idle = PerformanceSample(ts: Date().addingTimeInterval(1))
+ idle.model = "someone/Model:x"; idle.stage = nil
+ log.write(idle)
+ check("performance day file lands and stats count it",
+ lgWaitUntil(4) { PerformanceLog.stats(dir: tmp).samplesToday == 2 }
+ && PerformanceLog.stats(dir: tmp).fileCount == 1)
+ let csv = PerformanceLog.csv(dir: tmp)
+ let rows = csv.split(separator: "\n")
+ check("performance CSV has a stable header and one row per sample",
+ rows.count == 3 && rows[0].hasPrefix("timestamp,model,engine,stage")
+ && rows[1].contains("42.5") && rows[1].contains("decode")
+ && rows[2].contains("someone/Model:x"))
+ try? FileManager.default.removeItem(at: tmp)
+}
+
func checkLoggingPlanning() {
let p = AppModel.frontingPlan(enabled: true, adopted: false, pickedInternalPort: 8199)
check("fronting only when enabled, app-launched and a port was picked",
@@ -1043,6 +1165,11 @@ func checkLoggingPlanning() {
SessionProxy.shouldRecord(policy: pol, loopbackPeer: true)
&& !SessionProxy.shouldRecord(policy: pol, loopbackPeer: false)
&& SessionProxy.shouldRecord(policy: .init(logLocal: true, logLAN: true), loopbackPeer: false))
+ check("loopback peer detection covers IPv4, IPv6 and localhost",
+ SessionProxy.isLoopbackEndpoint(.hostPort(host: "127.0.0.1", port: 1))
+ && SessionProxy.isLoopbackEndpoint(.hostPort(host: "::1", port: 1))
+ && SessionProxy.isLoopbackEndpoint(.hostPort(host: "localhost", port: 1))
+ && !SessionProxy.isLoopbackEndpoint(.hostPort(host: "10.0.0.5", port: 1)))
let occupied = (41000 + Int.random(in: 0..<9000))
if SessionProxy.isPortFree(occupied) {
diff --git a/scripts/profile-test/run.sh b/scripts/profile-test/run.sh
index 5a96db0..a6f6c55 100755
--- a/scripts/profile-test/run.sh
+++ b/scripts/profile-test/run.sh
@@ -37,6 +37,7 @@ c['run']['modelID'] = 'unsloth/Qwen3.8-27B-GGUF:UD-IQ3_XXS'
c['run']['maxCacheDisk'] = '0'
c['run'].pop('idleRelease', None)
c['run'].pop('persistentCache', None)
+c['engineMode'] = 'pinned' # the schema-7 migration flips this when Homebrew is present
c['startOnLaunch'] = False # live config may have it on; the fixture must stay inert
c['sampling']['temperature'] = 0.23
c.pop('modelProfiles', None)
@@ -47,6 +48,6 @@ swiftc -swift-version 5 -o /tmp/splashgui-profiletest \
"$CORE"/AppConfig.swift "$CORE"/AppModel.swift "$CORE"/ClientConfigs.swift \
"$CORE"/EngineInstaller.swift "$CORE"/EngineResolver.swift \
"$CORE"/MachineInfo.swift "$CORE"/SessionLog.swift "$CORE"/SessionProxy.swift \
- "$CORE"/SplashClient.swift "$CORE"/SplashServer.swift main.swift
+ "$CORE"/PerformanceLog.swift "$CORE"/SplashClient.swift "$CORE"/SplashServer.swift main.swift
/tmp/splashgui-profiletest
UAT round 1: Homebrew engine source, LAN host allow-list, live logging policy, Pi, performance logging
- Engine source gains a Homebrew mode (any version, no download; falls back to the pin) and schema 7 flips the untouched pinned default to it when brew is detected. - LAN serving passes --allowed-host <LAN IP> (engine 1.6.x excludes 0.0.0.0 from its Host allow-list); a fronted engine binds loopback so the proxy is the only LAN-facing listener. - The logging LAN toggle is live (mutable proxy policy) and peer detection uses currentPath.remoteEndpoint with a privacy-safe non-loopback default. - Pi joins the Provider tab, matching splash pi's models.json entry, with samplingParams and the card's thinking-off set under samplingParamsByThinkingLevel. - Provider configs gain a LAN-host toggle; endpoints follow ClientConfigContext.host. - Performance logging rides the existing /status poll (no extra requests), writes active-only JSONL samples every 1/5/10 ticks, and exports CSV. Poll 2s -> 1s; chart history 240 -> 480. - Engine pin 1.6.1; tab order Run > Logging > Provider > Status; model status note flows inline; Int interpolations no longer localize (port "8,095"). - Harness 169 -> 185.
f133cf6e97dca70b1914f53e1f8257e485007853
cjosie <administrator@josie-c.com> · 2026-11-12T17:23 ·
browse files at this commit
parents:
76681fe