Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,10 @@ jobs:
# Stand-in servers that only list models, one with TGI's metrics, a KoboldCpp, a TabbyAPI and one behind a key:
# what each card shows, and that nothing is asked that makes a model work.
run: sh Linux/tests/other-engine.sh .build/release/tokenmeter
- name: Models page and Will it fit
# Model folders of Ollama, LM Studio, Hugging Face and llama.cpp in a home folder of its own: the files are
# found with their sizes, and a model that never ran gets an estimate from its file. No model is loaded.
run: sh Linux/tests/models.sh .build/release/tokenmeter
- name: The idle service stays within its budget
# Processor time, wake-ups, open files and memory of a service with nothing to watch, over a minute.
# The stand-in engines of the steps above are stopped first: with them it has work to do.
Expand Down
2 changes: 1 addition & 1 deletion Android/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ platform=${ANDROID_PLATFORM:-35}
jar=$sdk/platforms/android-$platform/android.jar
[ -f "$jar" ] || { echo "No $jar: install the platform with sdkmanager \"platforms;android-$platform\"." >&2; exit 1; }
tools=$(ls -d "$sdk"/build-tools/* | sort -V | tail -1)
version=${APP_VERSION:-0.9.9}
version=${APP_VERSION:-0.9.10}
IFS=. read -r major minor patch <<<"$version.0.0"
code=$((major * 10000 + minor * 100 + ${patch%%[^0-9]*}))

Expand Down
1 change: 1 addition & 0 deletions App/App.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ struct MainWindow: View {
case .insights: InsightsView()
case .usage: UsageView()
case .performance: PerformanceView()
case .models: ModelsView()
case .sessions: SessionsView()
case .lab: LabView()
case .gizmo: GizmoView()
Expand Down
1 change: 1 addition & 0 deletions App/CommandPalette.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ enum CommandPalette {
]
if platform == .linux { pages.append(Page(id: "engines", title: "Engines", keywords: "saved servers ports add", key: nil)) }
pages.append(Page(id: "agents", title: "Agents", keywords: "coding agents reporters claude codex hooks docker vm", key: nil))
pages.append(Page(id: "models", title: "Models", keywords: "model files disk downloaded unused will it fit memory context ollama lm studio hugging face gguf", key: nil))
pages.append(Page(id: "setup", title: "Setup", keywords: "how agents reach models tools engine proxy mcp proxy reporter ports lines improve tour", key: nil))
pages.append(Page(id: "mesh", title: "Mesh", keywords: "other machines add machine join allow wants to join found network fleet share usage history ignore", key: nil))
return pages
Expand Down
2 changes: 2 additions & 0 deletions App/Insights.swift
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,8 @@ enum Insights {
/// Compares the engines and machines with the last reading and keeps what changed.
func observe(now: Date = Date()) {
let servers = EngineMonitor.shared.servers.map(StatusReport.server)
// The same look feeds "Will it fit?": what each loaded model holds in memory (App/ModelsPage.swift).
ModelFootprintStore.shared.note(servers, now: now)
let peers = FleetStore.shared.peers.map { ChangeWatch.Peer(address: $0.address, name: $0.report?.host ?? $0.address,
online: $0.isOnline, problem: $0.problem) }
let known = watch.seeded ? [] : RequestLogStore.shared.models()
Expand Down
187 changes: 187 additions & 0 deletions App/ModelFiles.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
import Foundation

/// A model as it lies on this machine's disk: what a model manager downloaded, whether or not it ever ran.
struct ModelFile: Codable, Equatable, Identifiable {
/// The folder or file it is, so two managers holding the same model are two rows.
var id: String { path }
/// "qwen3-coder:30b", "mlx-community/Qwen3-8B-4bit", "Qwen3-Coder-30B-Q4_K_M.gguf".
var name: String
/// "Ollama", "LM Studio", "Hugging Face cache" or "llama.cpp".
var source: String
var path: String
var bytes: Int
/// When the files were last written (downloaded or updated), seconds since 1970.
var modified: Double
/// When a request for it last finished, where the request log knows a model that matches; nil when none does.
var lastRan: Double? = nil
}

/// Reads what the model managers keep on disk: Ollama's manifests, LM Studio's folders, the Hugging Face cache and
/// llama.cpp's download cache. It lists folders and reads file sizes and Ollama's small manifest files; no model
/// file is opened. A scan is kept ten minutes, and runs off the main line.
enum ModelFiles {
/// How long a model may go without a request before the page marks it as not used lately.
static let idleDays = 30.0
static let keepSeconds: TimeInterval = 600

private static let kept = Locked<(files: [ModelFile], at: Date, scanning: Bool)>(([], .distantPast, false))

/// The last scan, and whether one has finished yet. Starts a new one in the background when it is stale.
static func current(now: Date = Date()) -> (files: [ModelFile], at: Date?) {
let state = kept.with { state -> (files: [ModelFile], at: Date, start: Bool) in
let stale = now.timeIntervalSince(state.at) >= keepSeconds && !state.scanning
if stale { state.scanning = true }
return (state.files, state.at, stale)
}
if state.start {
DispatchQueue.global(qos: .utility).async {
let found = scan()
kept.with { $0 = (found, Date(), false) }
}
}
return (state.files, state.at == .distantPast ? nil : state.at)
}

/// Everything found under a home folder. `environment` moves the folders as the managers' own variables do.
static func scan(home: String? = nil, environment: [String: String] = ProcessInfo.processInfo.environment) -> [ModelFile] {
// (On Linux NSHomeDirectory doesn't follow HOME, so the variable is read first.)
let home = home ?? environment["HOME"].flatMap { $0.isEmpty ? nil : $0 } ?? NSHomeDirectory()
var found: [ModelFile] = []
var ollama = [home + "/.ollama/models", "/usr/share/ollama/.ollama/models", "/var/lib/ollama/.ollama/models"]
if let moved = environment["OLLAMA_MODELS"], !moved.isEmpty { ollama.insert(moved, at: 0) }
for folder in unique(ollama) { found += self.ollama(folder) }
for folder in unique([home + "/.lmstudio/models", home + "/.cache/lm-studio/models"]) { found += lmStudio(folder) }
var hub = [home + "/.cache/huggingface/hub"]
if let moved = environment["HF_HUB_CACHE"], !moved.isEmpty { hub.insert(moved, at: 0) }
else if let moved = environment["HF_HOME"], !moved.isEmpty { hub.insert(moved + "/hub", at: 0) }
for folder in unique(hub) { found += huggingFace(folder) }
var llama = [home + "/.cache/llama.cpp", home + "/Library/Caches/llama.cpp"]
if let moved = environment["LLAMA_CACHE"], !moved.isEmpty { llama.insert(moved, at: 0) }
for folder in unique(llama) { found += llamaCpp(folder) }
return found.sorted { ($0.bytes, $1.path) > ($1.bytes, $0.path) }
}

private static func unique(_ paths: [String]) -> [String] {
var seen = Set<String>()
return paths.map { URL(fileURLWithPath: $0).standardizedFileURL.path }.filter { seen.insert($0).inserted }
}

private static func children(_ folder: String) -> [String] {
((try? FileManager.default.contentsOfDirectory(atPath: folder)) ?? []).filter { !$0.hasPrefix(".") }.sorted()
}

private static func isFolder(_ path: String) -> Bool {
var folder: ObjCBool = false
return FileManager.default.fileExists(atPath: path, isDirectory: &folder) && folder.boolValue
}

private static func facts(_ path: String) -> (bytes: Int, modified: Double)? {
guard let attributes = try? FileManager.default.attributesOfItem(atPath: path) else { return nil }
let bytes = (attributes[.size] as? NSNumber)?.intValue ?? 0
return (bytes, (attributes[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0)
}

/// The plain files under a folder, added up. Links are not followed, so a cache that links to its own
/// files (Hugging Face's snapshots) is counted once.
private static func total(_ folder: String) -> (bytes: Int, modified: Double) {
var bytes = 0, modified = 0.0
guard let walker = FileManager.default.enumerator(atPath: folder) else { return (0, 0) }
for case let name as String in walker {
let attributes = walker.fileAttributes
guard !name.isEmpty, attributes?[.type] as? FileAttributeType == .typeRegular else { continue }
bytes += (attributes?[.size] as? NSNumber)?.intValue ?? 0
modified = max(modified, (attributes?[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0)
}
return (bytes, modified)
}

/// Ollama: `manifests/<registry>/<namespace>/<model>/<tag>` is a small JSON file naming the layers and their
/// sizes. Layers shared by two tags are counted under each.
static func ollama(_ folder: String) -> [ModelFile] {
var found: [ModelFile] = []
let manifests = folder + "/manifests"
for registry in children(manifests) {
for namespace in children(manifests + "/" + registry) {
for model in children(manifests + "/" + registry + "/" + namespace) {
let place = manifests + "/" + registry + "/" + namespace + "/" + model
for tag in children(place) {
let path = place + "/" + tag
guard let data = FileManager.default.contents(atPath: path), data.count < 1_000_000,
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { continue }
let layers = (json["layers"] as? [[String: Any]]) ?? []
let bytes = layers.reduce(0) { $0 + (JSONValue.int($1["size"]) ?? 0) } + (JSONValue.int((json["config"] as? [String: Any])?["size"]) ?? 0)
guard bytes > 0 else { continue }
let name = (namespace == "library" ? "" : namespace + "/") + model + ":" + tag
found.append(ModelFile(name: name, source: "Ollama", path: path, bytes: bytes, modified: facts(path)?.modified ?? 0))
}
}
}
}
return found
}

/// LM Studio: `<publisher>/<repository>/` holds the model's files.
static func lmStudio(_ folder: String) -> [ModelFile] {
var found: [ModelFile] = []
for publisher in children(folder) where isFolder(folder + "/" + publisher) {
for repository in children(folder + "/" + publisher) where isFolder(folder + "/" + publisher + "/" + repository) {
let path = folder + "/" + publisher + "/" + repository
let sum = total(path)
if sum.bytes > 0 {
found.append(ModelFile(name: publisher + "/" + repository, source: "LM Studio", path: path, bytes: sum.bytes, modified: sum.modified))
}
}
}
return found
}

/// The Hugging Face cache: `models--<organisation>--<name>/blobs` holds the files, `snapshots` links to them.
static func huggingFace(_ folder: String) -> [ModelFile] {
children(folder).filter { $0.hasPrefix("models--") }.compactMap { entry in
let path = folder + "/" + entry
let sum = total(path + "/blobs")
guard sum.bytes > 0 else { return nil }
let name = entry.dropFirst("models--".count).replacingOccurrences(of: "--", with: "/")
return ModelFile(name: name, source: "Hugging Face cache", path: path, bytes: sum.bytes, modified: sum.modified)
}
}

/// llama.cpp's download cache: each `.gguf` file is a model.
static func llamaCpp(_ folder: String) -> [ModelFile] {
children(folder).filter { $0.lowercased().hasSuffix(".gguf") }.compactMap { entry in
let path = folder + "/" + entry
guard let facts = facts(path), facts.bytes > 0 else { return nil }
return ModelFile(name: entry, source: "llama.cpp", path: path, bytes: facts.bytes, modified: facts.modified)
}
}

// MARK: Which requests a file answers for

/// A model's name in pieces, without its publisher, its file ending and the words that say nothing
/// ("latest", "gguf"): "bartowski/Qwen3-Coder-30B-Q4_K_M.gguf" is qwen3, coder, 30b, q4, k, m.
static func pieces(_ name: String) -> Set<String> {
var name = name.lowercased()
if let slash = name.lastIndex(of: "/") { name = String(name[name.index(after: slash)...]) }
let parts = name.split { !($0.isLetter || $0.isNumber) }.map(String.init)
return Set(parts.filter { !["gguf", "latest", "mlx", "safetensors", "bin"].contains($0) })
}

/// Whether a model named in the request log is this file's: every piece of the shorter name is in the longer
/// one, and they share at least two pieces (or are the same single piece), so "llama" alone matches nothing.
static func same(_ file: String, _ model: String) -> Bool {
let a = pieces(file), b = pieces(model)
guard !a.isEmpty, !b.isEmpty else { return false }
let (short, long) = a.count <= b.count ? (a, b) : (b, a)
guard short.isSubset(of: long) else { return false }
return short.count >= 2 || long.count == 1
}

/// The files with when each last ran, from when each model in the log last finished a request.
static func marked(_ files: [ModelFile], lastRan: [String: Double]) -> [ModelFile] {
files.map { file in
var file = file
file.lastRan = lastRan.filter { same(file.name, $0.key) }.values.max()
return file
}
}
}
Loading
Loading