new features

This commit is contained in:
Mark Gregory
2026-11-18 13:55:47 +00:00
parent 17bcf178a9
commit a07ddf4d6d
29 changed files with 3457 additions and 306 deletions
+58 -5
View File
@@ -7,6 +7,16 @@
objects = { objects = {
/* Begin PBXBuildFile section */ /* Begin PBXBuildFile section */
CA00000000000000000000BB = {isa = PBXBuildFile; fileRef = CA00000000000000000000BA; };
CA00000000000000000000AB = {isa = PBXBuildFile; fileRef = CA00000000000000000000AA; };
CA000000000000000000009B = {isa = PBXBuildFile; fileRef = CA000000000000000000009A; };
CA000000000000000000008B = {isa = PBXBuildFile; productRef = CA000000000000000000008A; };
CA000000000000000000007B = {isa = PBXBuildFile; fileRef = CA000000000000000000007A; };
CA000000000000000000006B = {isa = PBXBuildFile; fileRef = CA000000000000000000006A; };
CA000000000000000000004B = {isa = PBXBuildFile; productRef = CA000000000000000000004A; };
CA000000000000000000003B = {isa = PBXBuildFile; fileRef = CA000000000000000000003A; };
CA000000000000000000002B = {isa = PBXBuildFile; fileRef = CA000000000000000000002A; };
CA000000000000000000001B = {isa = PBXBuildFile; fileRef = CA000000000000000000001A; };
00000000000000000000000B /* Inference.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000001 /* Inference.swift */; }; 00000000000000000000000B /* Inference.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000001 /* Inference.swift */; };
00000000000000000000000C /* Ollama.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000002 /* Ollama.swift */; }; 00000000000000000000000C /* Ollama.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000002 /* Ollama.swift */; };
00000000000000000000000D /* MLXProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000003 /* MLXProvider.swift */; }; 00000000000000000000000D /* MLXProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000003 /* MLXProvider.swift */; };
@@ -37,6 +47,14 @@
/* End PBXContainerItemProxy section */ /* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */ /* Begin PBXFileReference section */
CA00000000000000000000BA = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CreativeWorkspace.swift; sourceTree = "<group>"; };
CA00000000000000000000AA = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CoreMLLibrary.swift; sourceTree = "<group>"; };
CA000000000000000000009A = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CoreMLProvider.swift; sourceTree = "<group>"; };
CA000000000000000000007A = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GGUFDownloads.swift; sourceTree = "<group>"; };
CA000000000000000000006A = {isa = PBXFileReference; lastKnownFileType = text; path = "Resources/llama.cpp-LICENSE.txt"; sourceTree = "<group>"; };
CA000000000000000000003A = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GGUFModels.swift; sourceTree = "<group>"; };
CA000000000000000000002A = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GGUFProvider.swift; sourceTree = "<group>"; };
CA000000000000000000001A = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GGUFHeader.swift; sourceTree = "<group>"; };
000000000000000000000001 /* Inference.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Inference.swift; sourceTree = "<group>"; }; 000000000000000000000001 /* Inference.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Inference.swift; sourceTree = "<group>"; };
000000000000000000000002 /* Ollama.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Ollama.swift; sourceTree = "<group>"; }; 000000000000000000000002 /* Ollama.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Ollama.swift; sourceTree = "<group>"; };
000000000000000000000003 /* MLXProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MLXProvider.swift; sourceTree = "<group>"; }; 000000000000000000000003 /* MLXProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MLXProvider.swift; sourceTree = "<group>"; };
@@ -62,7 +80,9 @@
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
000000000000000000000023 /* MLXLLM in Frameworks */, 000000000000000000000023 /* MLXLLM in Frameworks */,
CA000000000000000000004B,
000000000000000000000024 /* MLXLMCommon in Frameworks */, 000000000000000000000024 /* MLXLMCommon in Frameworks */,
CA000000000000000000008B,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
@@ -73,6 +93,13 @@
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
000000000000000000000001 /* Inference.swift */, 000000000000000000000001 /* Inference.swift */,
CA000000000000000000003A,
CA000000000000000000007A,
CA00000000000000000000BA,
CA00000000000000000000AA,
CA000000000000000000009A,
CA000000000000000000002A,
CA000000000000000000001A,
000000000000000000000002 /* Ollama.swift */, 000000000000000000000002 /* Ollama.swift */,
000000000000000000000003 /* MLXProvider.swift */, 000000000000000000000003 /* MLXProvider.swift */,
000000000000000000000004 /* Store.swift */, 000000000000000000000004 /* Store.swift */,
@@ -110,6 +137,7 @@
00000000000000000000000A /* Sources */, 00000000000000000000000A /* Sources */,
000000000000000000000016 /* Tests */, 000000000000000000000016 /* Tests */,
00000000000000000000001F /* Resources/AIStudio.icns */, 00000000000000000000001F /* Resources/AIStudio.icns */,
CA000000000000000000006A,
A17A00000000000000000004 /* train-mlx.py */, A17A00000000000000000004 /* train-mlx.py */,
A17A00000000000000000008 /* pegasus-index.py */, A17A00000000000000000008 /* pegasus-index.py */,
00000000000000000000001E /* Products */, 00000000000000000000001E /* Products */,
@@ -133,8 +161,10 @@
); );
name = AIStudio; name = AIStudio;
packageProductDependencies = ( packageProductDependencies = (
CA000000000000000000004A,
00000000000000000000001A /* MLXLLM */, 00000000000000000000001A /* MLXLLM */,
00000000000000000000001B /* MLXLMCommon */, 00000000000000000000001B /* MLXLMCommon */,
CA000000000000000000008A,
); );
productName = AIStudio; productName = AIStudio;
productReference = 00000000000000000000001C /* AIStudio.app */; productReference = 00000000000000000000001C /* AIStudio.app */;
@@ -175,6 +205,8 @@
); );
mainGroup = 000000000000000000000022; mainGroup = 000000000000000000000022;
packageReferences = ( packageReferences = (
CA000000000000000000008C,
CA000000000000000000005A,
000000000000000000000019 /* XCRemoteSwiftPackageReference "mlx-swift-lm" */, 000000000000000000000019 /* XCRemoteSwiftPackageReference "mlx-swift-lm" */,
); );
productRefGroup = 00000000000000000000001E /* Products */; productRefGroup = 00000000000000000000001E /* Products */;
@@ -193,6 +225,7 @@
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
000000000000000000000020 /* Resources/AIStudio.icns in Resources */, 000000000000000000000020 /* Resources/AIStudio.icns in Resources */,
CA000000000000000000006B,
A17A00000000000000000002 /* train-mlx.py in Resources */, A17A00000000000000000002 /* train-mlx.py in Resources */,
A17A00000000000000000006 /* pegasus-index.py in Resources */, A17A00000000000000000006 /* pegasus-index.py in Resources */,
); );
@@ -206,6 +239,13 @@
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
00000000000000000000000B /* Inference.swift in Sources */, 00000000000000000000000B /* Inference.swift in Sources */,
CA000000000000000000003B,
CA000000000000000000007B,
CA00000000000000000000BB,
CA00000000000000000000AB,
CA000000000000000000009B,
CA000000000000000000002B,
CA000000000000000000001B,
00000000000000000000000C /* Ollama.swift in Sources */, 00000000000000000000000C /* Ollama.swift in Sources */,
00000000000000000000000D /* MLXProvider.swift in Sources */, 00000000000000000000000D /* MLXProvider.swift in Sources */,
00000000000000000000000E /* Store.swift in Sources */, 00000000000000000000000E /* Store.swift in Sources */,
@@ -244,14 +284,15 @@
CLANG_ENABLE_OBJC_WEAK = YES; CLANG_ENABLE_OBJC_WEAK = YES;
CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 15; CURRENT_PROJECT_VERSION = 27;
DEAD_CODE_STRIPPING = YES; DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 39R6U3437D; DEVELOPMENT_TEAM = 39R6U3437D;
ENABLE_HARDENED_RUNTIME = NO; ENABLE_HARDENED_RUNTIME = NO;
ENABLE_TESTABILITY = YES; ENABLE_TESTABILITY = YES;
INFOPLIST_FILE = Info.plist; INFOPLIST_FILE = Info.plist;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools"; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
MARKETING_VERSION = 1.1.13; LD_RUNPATH_SEARCH_PATHS = ("$(inherited)", "@executable_path/../Frameworks");
MARKETING_VERSION = 1.1.25;
OTHER_LDFLAGS = ( OTHER_LDFLAGS = (
"$(inherited)", "$(inherited)",
"-lsqlite3", "-lsqlite3",
@@ -269,13 +310,14 @@
CLANG_ENABLE_OBJC_WEAK = YES; CLANG_ENABLE_OBJC_WEAK = YES;
CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 15; CURRENT_PROJECT_VERSION = 27;
DEAD_CODE_STRIPPING = YES; DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 39R6U3437D; DEVELOPMENT_TEAM = 39R6U3437D;
ENABLE_HARDENED_RUNTIME = YES; ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = Info.plist; INFOPLIST_FILE = Info.plist;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools"; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
MARKETING_VERSION = 1.1.13; LD_RUNPATH_SEARCH_PATHS = ("$(inherited)", "@executable_path/../Frameworks");
MARKETING_VERSION = 1.1.25;
OTHER_LDFLAGS = ( OTHER_LDFLAGS = (
"$(inherited)", "$(inherited)",
"-lsqlite3", "-lsqlite3",
@@ -432,18 +474,29 @@
}; };
/* End XCConfigurationList section */ /* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
CA000000000000000000005A = {isa = XCLocalSwiftPackageReference; relativePath = Dependencies/LlamaRuntime; };
/* End XCLocalSwiftPackageReference section */
/* Begin XCRemoteSwiftPackageReference section */ /* Begin XCRemoteSwiftPackageReference section */
CA000000000000000000008C = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/huggingface/swift-transformers";
requirement = {kind = exactVersion; version = 1.3.0; };
};
000000000000000000000019 /* XCRemoteSwiftPackageReference "mlx-swift-lm" */ = { 000000000000000000000019 /* XCRemoteSwiftPackageReference "mlx-swift-lm" */ = {
isa = XCRemoteSwiftPackageReference; isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/ml-explore/mlx-swift-lm.git"; repositoryURL = "https://github.com/ml-explore/mlx-swift-lm.git";
requirement = { requirement = {
kind = exactVersion; kind = exactVersion;
version = 2.29.3; version = 3.32.3;
}; };
}; };
/* End XCRemoteSwiftPackageReference section */ /* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */ /* Begin XCSwiftPackageProductDependency section */
CA000000000000000000008A = {isa = XCSwiftPackageProductDependency; package = CA000000000000000000008C; productName = Tokenizers; };
CA000000000000000000004A = {isa = XCSwiftPackageProductDependency; package = CA000000000000000000005A; productName = LlamaRuntime; };
00000000000000000000001A /* MLXLLM */ = { 00000000000000000000001A /* MLXLLM */ = {
isa = XCSwiftPackageProductDependency; isa = XCSwiftPackageProductDependency;
package = 000000000000000000000019 /* XCRemoteSwiftPackageReference "mlx-swift-lm" */; package = 000000000000000000000019 /* XCRemoteSwiftPackageReference "mlx-swift-lm" */;
@@ -1,13 +1,22 @@
{ {
"originHash" : "298fd28cf781413de50d2a62a2a600b5c08b621e84908714aabaee4590c300f7", "originHash" : "ef43211a806dc3b1203a70e2fddbbc947d43c024c152fe597e1e3f24086be4d3",
"pins" : [ "pins" : [
{
"identity" : "eventsource",
"kind" : "remoteSourceControl",
"location" : "https://github.com/mattt/EventSource.git",
"state" : {
"revision" : "bb4b61273b5a976bb571859c17f903ebc3439df1",
"version" : "1.6.0"
}
},
{ {
"identity" : "mlx-swift", "identity" : "mlx-swift",
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
"location" : "https://github.com/ml-explore/mlx-swift", "location" : "https://github.com/ml-explore/mlx-swift",
"state" : { "state" : {
"revision" : "072b684acaae80b6a463abab3a103732f33774bf", "revision" : "19601207e9a0de51e03ee6ec0c3c5f3784275075",
"version" : "0.29.1" "version" : "0.32.3"
} }
}, },
{ {
@@ -15,8 +24,8 @@
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
"location" : "https://github.com/ml-explore/mlx-swift-lm.git", "location" : "https://github.com/ml-explore/mlx-swift-lm.git",
"state" : { "state" : {
"revision" : "5064b8c5d8ed3b0bbb71385c4124f0fc102e74a2", "revision" : "3b339ad6e3b3f44c8121ecff5131c7fd55e075e6",
"version" : "2.29.3" "version" : "3.32.3"
} }
}, },
{ {
@@ -46,6 +55,15 @@
"version" : "4.5.2" "version" : "4.5.2"
} }
}, },
{
"identity" : "swift-huggingface",
"kind" : "remoteSourceControl",
"location" : "https://github.com/huggingface/swift-huggingface.git",
"state" : {
"revision" : "f0a0cb43cb1b402d2bbf6fb10d8981328c449c48",
"version" : "0.13.0"
}
},
{ {
"identity" : "swift-jinja", "identity" : "swift-jinja",
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
@@ -64,13 +82,22 @@
"version" : "1.1.1" "version" : "1.1.1"
} }
}, },
{
"identity" : "swift-syntax",
"kind" : "remoteSourceControl",
"location" : "https://github.com/swiftlang/swift-syntax.git",
"state" : {
"revision" : "79e4b74a295b6eb74a8b585e3a39d29e70c1dbd1",
"version" : "603.0.2"
}
},
{ {
"identity" : "swift-transformers", "identity" : "swift-transformers",
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
"location" : "https://github.com/huggingface/swift-transformers", "location" : "https://github.com/huggingface/swift-transformers",
"state" : { "state" : {
"revision" : "150169bfba0889c229a2ce7494cf8949f18e6906", "revision" : "b38443e44d93eca770f2eb68e2a4d0fa100f9aa2",
"version" : "1.1.9" "version" : "1.3.0"
} }
}, },
{ {
+15
View File
@@ -0,0 +1,15 @@
// swift-tools-version: 5.10
import PackageDescription
let package = Package(
name: "LlamaRuntime",
platforms: [.macOS(.v14)],
products: [.library(name: "LlamaRuntime", targets: ["llama"])],
targets: [
.binaryTarget(
name: "llama",
url: "https://github.com/ggml-org/llama.cpp/releases/download/b12248/llama-b12248-xcframework.zip",
checksum: "fe38916b41f2a144115db39df860cb2f6f98a476589d5072b0cc3f51dbaf8c10"
)
]
)
+132
View File
@@ -0,0 +1,132 @@
# Local model roadmap
| Phase | Scope |
| --- | --- |
| 1. GGUF engine | Pin and bundle llama.cpp. Run text chat with Metal and retain the existing MLX, Ollama, and compatible API routes. |
| 2. Unified Model Library | Show GGUF files and MLX folders under On This Mac. Keep the Ollama catalog available and show the model selected or in use. |
| 3. Model Import | Accept Finder drops and inspect file contents or folder layout. Register valid models in place and report invalid files. |
| 4. Model Downloads | Look up public Hugging Face repositories by ID. List standalone GGUF assets with file sizes, show progress, support cancellation, and validate downloads before publishing them. |
| 5. Performance | **Next.** Measure and display actual process memory during loading and generation. Add load, prefill, and decode timing and tune model residency. |
| 6. Additional Formats | Core ML text chat available for compatible stateful exports. Apple Foundation Models, ONNX, and additional checkpoints remain on the roadmap. |
| 7. Ollama Independence | Audit startup, onboarding, settings, and recovery for a local-first default. Retain optional Ollama connections. |
| 8. Final Polish | Review accessibility, light and dark appearance, release verification, and documentation. |
## Model families
The pinned [llama.cpp architecture list](https://github.com/ggml-org/llama.cpp/blob/b12248/src/llama-arch.cpp)
includes Meta Llama, MosaicML MPT, Apple OpenELM, Qwen, and Gemma. The installed
GGUF list reads the architecture from the file. Each checkpoint must use a
supported architecture and embedded chat template. Llama has a Metal smoke test.
MPT and OpenELM architecture labels have automated coverage. Generation with
those families still needs a compatible checkpoint smoke test.
[Apple Intelligence's on-device model](https://developer.apple.com/documentation/foundationmodels)
uses Apple's Foundation Models framework. Its listing and inference integration
are pending. OpenELM is a separately distributed model family.
GGUF text chat loads model weights per request, with a default context of up to
4,096 tokens. The current engine uses templates recognized by llama.cpp's native
chat-template implementation. GGUF image inputs, JSON mode, and split GGUF
downloads are outside the current workflow. The Metal working-set number is
a device recommendation. Per-model allocation metrics are part of Phase 5.
## Verification
Run the existing suite with `Scripts/test.sh`. The tests for real Metal inference,
GGUF import by file contents, and atomic download installation take a compatible
local model via `TEST_RUNNER_AISTUDIO_TEST_GGUF_PATH`. The tests use a Llama
architecture model. The downloaded SmolLM2 file can also serve as the local fixture. Use a task-specific temporary build root. The optional network smoke test resolves the repository, downloads
the listed asset with byte progress, validates it, and generates text on Metal.
```sh
TEST_RUNNER_AISTUDIO_TEST_GGUF_HUB_REPO=bartowski/SmolLM2-135M-Instruct-GGUF \
TEST_RUNNER_AISTUDIO_TEST_GGUF_HUB_FILE=SmolLM2-135M-Instruct-Q4_K_M.gguf \
Scripts/test.sh
```
### 18 November 2026 · AI Studio 1.1.20 (22)
Phases 1–4 reached their automated verification milestones. The new GGUF
header, library selection, import, and Hub cases were run in their failing
states before the corresponding implementation. A standalone app check
caught the framework runpath and ad-hoc hardened-runtime problems. Both
Debug and Release now resolve the embedded runtime on direct execution.
The final Xcode suite passed 115 tests with 13 opt-in skips and zero failures.
The local GGUF fixture offloaded 6 of 6 layers. The live Hugging Face test
downloaded 105,454,432 bytes of SmolLM2, checked the Hub checksum, and
generated on Metal with 31 of 31 layers offloaded. The existing native MLX
load, routing fallback, and eviction test passed with the local Qwen model.
Ollama and compatible API regressions ran against the loopback fixtures.
The ARM64 release archive passed its SHA-256 check, strict signature
verification, and standalone executable smoke test after extraction.
The archive used ad-hoc signing. Developer ID signing, notarization,
and interactive visual and Finder gesture checks remain open.
### 18 November 2026 · AI Studio 1.1.21 (23)
The bundled llama.cpp update adds Qwen3.5 GGUF support. The previous runtime
rejected `qwen35` as an unknown architecture. The supplied Qwen3.5-9B Q4_K_M
model generated on Metal with 33 of 33 layers offloaded after the update.
Use **Import LM Studio Library** to register models from `~/.lmstudio/models`.
The scan leaves files in place and skips multimodal projectors. GGUF now supports
browsing and model-name search on Hugging Face alongside direct repository
lookup. MLX search queries the public MLX catalog across publishers.
The Xcode run passed 116 tests with 14 opt-in skips and zero failures. It
covered live Hub discovery for both formats, scanning the actual LM Studio
library, and existing native Qwen2.5 MLX generation and fallback.
### 18 November 2026 · AI Studio 1.1.22 (24)
Build scripts now key compiled output to the bundled llama.cpp manifest. This
avoids reusing framework modules compiled against the previous llama.cpp
binary. The old compiled directory stays available.
MLX Swift LM 3.32.3 adds support for the installed Qwen3.5 MLX architecture.
**Import MLX Models…** scans either a single checkpoint or a parent directory.
The LM Studio scan found both installed MLX checkpoints. Qwen3.5 9B MLX,
Mistral Nemo MLX, and the existing Qwen2.5 Coder MLX all generated successfully.
The installed Qwen3.5 GGUF also completed a chat through the Studio chat
controller with all 33 layers offloaded. The full suite passed 116 tests
with 14 opt-in skips and zero failures.
### 18 November 2026 · AI Studio 1.1.23 (25)
Local GGUF and MLX inference coalesces adjacent turns before rendering a
chat template. This handles histories such as a stopped user turn followed
by a new message. The saved conversation remains intact. The Mistral Nemo
checkpoint reproduced the Jinja exception before the fix.
The chat model button shows the selected backend. Library rows show the
format when available. Compatible Qwen-style GGUF thinking templates expose
Default, Off, and On. Thinking On and Off use the model template’s respective
assistant prefixes. Reasoning streams separately from the answer.
The full Xcode run passed 118 tests with 14 opt-in skips and zero failures.
The installed Mistral Nemo checkpoint passed the consecutive-user regression.
A live Qwen3.5 GGUF chat produced an answer with Thinking Off and emitted
separate reasoning with Thinking On. The installed Qwen3.5 MLX checkpoint
also passed the repeated-turn generation and fallback smoke test.
### 18 November 2026 · AI Studio 1.1.24 (26)
Core ML uses the stateful `inputIds`, `causalMask`, and `logits` contract
documented by [Hugging Face](https://github.com/huggingface/blog/blob/main/mistral-coreml.md)
and published in [Apple’s Mistral model](https://huggingface.co/apple/mistral-coreml).
It keeps a fresh cache per generation using [Core ML state](https://developer.apple.com/documentation/coreml/mlstate).
Source packages compile at load time. Import a compiled model to skip that
step. The direct Hub download includes the matching tokenizer and checks
revision, size, and the published weight checksums.
The red warnings compare weight bytes with the recommended GPU working set
for GGUF and MLX, physical memory for Core ML, and the optional configured
MLX weight limit. A model underneath the budget still needs runtime and
context memory. Remote models depend on the server’s hardware.
The full suite passed 120 tests with 15 opt-in skips and no failures. The
Core ML smoke test used Apple’s published Mistral Int4 weights, generated a
reply through the Studio chat controller, and fetched live Hugging Face
search results. GGUF Metal generation and native MLX generation also passed.
+1 -1
View File
@@ -4,7 +4,7 @@
Run `./Scripts/test.sh`, then `./Scripts/release.sh` from the project directory. The release script builds the arm64 Release configuration, checks the app's code signature, and creates `AIStudio-<version>-macOS-arm64.zip` in the temporary build directory’s `dist` folder with a SHA-256 checksum alongside it. Pass an output directory as the first argument to override `dist`. The default package is ad-hoc signed for local verification. Run `./Scripts/test.sh`, then `./Scripts/release.sh` from the project directory. The release script builds the arm64 Release configuration, checks the app's code signature, and creates `AIStudio-<version>-macOS-arm64.zip` in the temporary build directory’s `dist` folder with a SHA-256 checksum alongside it. Pass an output directory as the first argument to override `dist`. The default package is ad-hoc signed for local verification.
The scripts keep build products, Swift package checkouts and test results under the OS temporary directory. Set `AISTUDIO_BUILD_ROOT` to reuse a specific temporary build directory across runs. Increment `MARKETING_VERSION` and `CURRENT_PROJECT_VERSION` in the app target’s Debug and Release settings for each completed change. Verify the values in the built app and include both in the completion message. The scripts keep build products, Swift package checkouts and test results under the OS temporary directory. Set `AISTUDIO_BUILD_ROOT` to reuse a specific temporary build directory across runs. The scripts keep a separate compiled build directory for each bundled llama.cpp dependency to prevent Xcode from reusing older framework modules. If Xcode itself reports a stale framework module after updating llama.cpp, use **Product → Clean Build Folder** in Xcode. Increment `MARKETING_VERSION` and `CURRENT_PROJECT_VERSION` in the app target’s Debug and Release settings for each completed change. Verify the values in the built app and include both in the completion message.
## Developer ID distribution ## Developer ID distribution
+11 -1
View File
@@ -6,7 +6,7 @@ Use the repository's `Scripts/train-mlx.py` to validate a local chat dataset, tr
## Use the tools in AI Studio ## Use the tools in AI Studio
1. Open **Settings → Model Library → MLX → MLX Tools…**. For an installed model, use **Clone & Train…** to preselect its weights. 1. Open **Training & Images** from the main window toolbar and select **Training**. Use **Tools**, **Convert**, and **Train** to move between setup and a run. From **Settings → Model Library**, **Clone & Train…** still opens the tools with an installed model preselected.
2. Use **Install MLX Tools** once. It uses a native Apple Silicon Python 3.11 or newer to install MLX LM with its training dependencies into a dedicated AI Studio environment. If automatic selection picks the wrong interpreter, use **Choose Python…**. 2. Use **Install MLX Tools** once. It uses a native Apple Silicon Python 3.11 or newer to install MLX LM with its training dependencies into a dedicated AI Studio environment. If automatic selection picks the wrong interpreter, use **Choose Python…**.
3. Use **Clone Base…** to write a separate copy to a new folder and add it to the library. Training can also use the original checkpoint while writing adapter weights to a separate run folder. 3. Use **Clone Base…** to write a separate copy to a new folder and add it to the library. Training can also use the original checkpoint while writing adapter weights to a separate run folder.
4. Choose a dataset folder and a run folder. Use **Validate Dataset**, **Train Adapter**, and **Evaluate**. Use **Fuse and Register** to create and register the final checkpoint. The run folder contains the adapter at `adapter` and the fused output at `trained-model`. Pick a fresh run folder for a new experiment. 4. Choose a dataset folder and a run folder. Use **Validate Dataset**, **Train Adapter**, and **Evaluate**. Use **Fuse and Register** to create and register the final checkpoint. The run folder contains the adapter at `adapter` and the fused output at `trained-model`. Pick a fresh run folder for a new experiment.
@@ -142,3 +142,13 @@ Keep it private unless you intend to publish it.
Sources: [MLX LM LoRA guide](https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/LORA.md) · Sources: [MLX LM LoRA guide](https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/LORA.md) ·
[Hugging Face Hub download guide](https://huggingface.co/docs/huggingface_hub/guides/download) · [Hugging Face Hub download guide](https://huggingface.co/docs/huggingface_hub/guides/download) ·
[Ollama import guide](https://docs.ollama.com/import) [Ollama import guide](https://docs.ollama.com/import)
## Verification · AI Studio 1.1.25 (27)
A one-iteration LoRA run against the local Qwen3 0.6B MLX model validated
the synthetic datasets, wrote an adapter, evaluated it, and fused a
checkpoint. The UI uses the same bundled runner. The Xcode suite passed
121 tests with 16 opt-in skips, including run logging, cancellation,
composer thinking options, and PNG preview generation. The ARM64
archive passed checksum, signature, and startup verification. The
interactive Apple Image Playground sheet remains a manual check.
+15 -5
View File
@@ -1,18 +1,24 @@
# AI Studio # AI Studio
Native SwiftUI chat for Apple silicon Macs running macOS 14 or later. Open `AIStudio.xcodeproj` and run the shared **AIStudio** scheme on **My Mac**. Xcode resolves the pinned Swift packages on the first build. Native SwiftUI chat for Apple silicon Macs running macOS 14 or later. Open `AIStudio.xcodeproj` in Xcode with Swift 6.3 or later and run the shared **AIStudio** scheme on **My Mac**. Xcode resolves the pinned Swift packages on the first build.
## 1. Set up a model ## 1. Set up a model
- **GGUF** models run locally. In **Settings → Model Library → On This Mac**, drop a GGUF chat model from Finder or use **Import…**. Choose **Use** to set the default for chat. The library shows architecture, predominant tensor format, file size, selection, and the recommended Metal working set. Bundled llama.cpp runs GGUF chat on Metal without an Ollama service. Models need a supported embedded chat template.
- To download a **GGUF** model, open **Hugging Face · GGUF**, choose **Browse**, search by model name, or enter a public `owner/model` ID. Open a result’s files and choose a standalone download. AI Studio pins the repository revision, shows byte progress and cancellation, validates the available size and checksum, then registers the model. Private or gated repositories and sharded GGUF downloads are outside this workflow.
- **Core ML** chat requires macOS 15 or later. In **Settings → Model Library → On This Mac → Core ML**, download the Apple Mistral model or import a compatible stateful Core ML model with its matching `tokenizer.json` and `tokenizer_config.json` beside it. Choose **Use** or pick the **Core ML** entry in chat. Search lists public Hugging Face model cards. The import currently targets the stateful text-generation contract used by [Apple’s Mistral export](https://huggingface.co/apple/mistral-coreml).
- **Ollama:** In **Settings → Models**, refresh the installed list and select a tag. The default server is `http://127.0.0.1:11434`. Use the same pane to pull, inspect, and delete models. Enter a remote HTTP or HTTPS base URL to use another server. The optional bearer token stays in memory and requires HTTPS for remote servers. - **Ollama:** In **Settings → Models**, refresh the installed list and select a tag. The default server is `http://127.0.0.1:11434`. Use the same pane to pull, inspect, and delete models. Enter a remote HTTP or HTTPS base URL to use another server. The optional bearer token stays in memory and requires HTTPS for remote servers.
- **OpenAI-compatible:** In **Settings → Models**, choose the compatible backend, enter the API base URL (for example `http://127.0.0.1:1234/v1` for LM Studio), then refresh models and select the exact model ID. Remote URLs require HTTPS. An optional bearer token stays in memory and is cleared when the endpoint changes. The server manages model loading. Chat Completions streams the reply and any separately reported reasoning. - **OpenAI-compatible:** In **Settings → Models**, choose the compatible backend, enter the API base URL (for example `http://127.0.0.1:1234/v1` for LM Studio), then refresh models and select the exact model ID. Remote URLs require HTTPS. An optional bearer token stays in memory and is cleared when the endpoint changes. The server manages model loading. Chat Completions streams the reply and any separately reported reasoning.
- **MLX:** In **Settings → Model Library**, browse or search Hugging Face for public MLX Community text-generation checkpoints. Switch to **Ollama** for models installed on your server and the public Ollama catalog. Download a checkpoint and choose **Load Model** to load it for on-device inference. **Settings → Models** also accepts a local model folder with configuration, tokenizer files, and safetensors weights. **Prefer Ollama** can fall back to the configured MLX folder when Ollama fails before emitting output. - **MLX:** In **Settings → Model Library**, drop an MLX folder or browse and search Hugging Face for public MLX Community text-generation checkpoints. Switch to **Ollama** for models installed on your server and the public Ollama catalog. Download a checkpoint and choose **Load Model** to load it for on-device inference. **Settings → Models** also accepts a local model folder with configuration, tokenizer files, and safetensors weights. **Prefer Ollama** can fall back to the configured MLX folder when Ollama fails before emitting output.
- **Thinking:** The composer sends Boolean or named effort settings to Ollama. Supported MLX templates expose Default, Off, and On. Reported reasoning appears in an expandable section. If an Ollama request is interrupted after emitting text, reasoning, or a tool call, the router keeps that backend. **Stop** cancels generation and retains any partial output. - **Thinking:** The composer sends Boolean or named effort settings to Ollama. The composer keeps Thinking visible. Supported MLX and GGUF templates expose Default, Off, and On. Backends that manage thinking themselves show Default. The model button shows the selected backend beside the model name. Reported reasoning appears in an expandable section. If an Ollama request is interrupted after emitting text, reasoning, or a tool call, the router keeps that backend. **Stop** cancels generation and retains any partial output.
**Import LM Studio Library** in **On This Mac** scans `~/.lmstudio/models` for GGUF chat models and MLX folders and registers them in place. Use **Import MLX Models…** to select an individual checkpoint or scan a folder of checkpoints.
Model Library shows red warnings when the model files alone exceed the applicable memory budget or the configured MLX weight limit. Generation also needs memory for its context.
Use **Settings → Agents** to enable or create reusable roles, then turn on **Agents** in the composer. The [Agents guide](Docs/Agents.md) covers setup, model routing, supervised MCP calls, and run limits. Use **Settings → Agents** to enable or create reusable roles, then turn on **Agents** in the composer. The [Agents guide](Docs/Agents.md) covers setup, model routing, supervised MCP calls, and run limits.
Use the model button in the chat composer to choose an installed Ollama Use the model button in the chat composer to choose an installed GGUF, MLX, Core ML, or Ollama model, or a model from your compatible API. AI Studio remembers the
or MLX model or a model from your compatible API. AI Studio remembers the
choice for that conversation. **Use Default** returns to the model in Settings. choice for that conversation. **Use Default** returns to the model in Settings.
Use **Resources** beside the model button to select a Knowledge Stack, Skill, Use **Resources** beside the model button to select a Knowledge Stack, Skill,
@@ -20,6 +26,10 @@ Context, Web Clip, or Prompt Template for the current chat. **Insert Saved Promp
copies a saved prompt into the composer for editing. Use **Open Workspace** to copies a saved prompt into the composer for editing. Use **Open Workspace** to
manage these resources. manage these resources.
See [Local Model Roadmap](Docs/LOCAL-MODELS.md) for supported families, verification, and the next phase.
Open **Training & Images** from the main window toolbar. **Training** contains the MLX conversion and LoRA workflow with live run output. **Images** opens Apple Image Playground on supported Macs and can preview an existing image or export a PNG preview. [MLX fine-tuning guide](Docs/TRAINING.md) · [Apple Image Playground](https://developer.apple.com/documentation/imageplayground)
## 2. Chat with documents ## 2. Chat with documents
Use **Documents** in the conversation toolbar to import PDF, UTF-8 text, Use **Documents** in the conversation toolbar to import PDF, UTF-8 text,
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023-2024 The ggml authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+5
View File
@@ -0,0 +1,5 @@
# Source from the project root. A binary framework change needs fresh compiled
# modules and object files, even if the framework keeps the same module name.
base="${AISTUDIO_BUILD_ROOT:-/private/tmp/AIStudio-build-$(id -u)}"
runtime_key="$(shasum -a 256 Dependencies/LlamaRuntime/Package.swift | cut -d ' ' -f 1)"
derived="$base/Derived-$runtime_key"
+4 -4
View File
@@ -11,12 +11,12 @@ case "$configuration" in
Debug|Release) ;; Debug|Release) ;;
*) echo "Usage: $0 [Debug|Release] [--no-launch]" >&2; exit 2 ;; *) echo "Usage: $0 [Debug|Release] [--no-launch]" >&2; exit 2 ;;
esac esac
base="${AISTUDIO_BUILD_ROOT:-/private/tmp/AIStudio-build-$(id -u)}" source Scripts/build-paths.sh
mkdir -p "$base" mkdir -p "$base"
xcodebuild ARCHS=arm64 CODE_SIGN_IDENTITY=- CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM= -project AIStudio.xcodeproj -scheme AIStudio -configuration "$configuration" \ xcodebuild ARCHS=arm64 ENABLE_HARDENED_RUNTIME=NO CODE_SIGN_IDENTITY=- CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM= -project AIStudio.xcodeproj -scheme AIStudio -configuration "$configuration" \
-destination 'platform=macOS,arch=arm64' -derivedDataPath "$base/Derived" \ -destination 'platform=macOS,arch=arm64' -derivedDataPath "$derived" \
-clonedSourcePackagesDirPath "$base/Packages" -disablePackageRepositoryCache build -clonedSourcePackagesDirPath "$base/Packages" -disablePackageRepositoryCache build
app="$base/Derived/Build/Products/$configuration/AIStudio.app" app="$derived/Build/Products/$configuration/AIStudio.app"
printf 'App: %s\n' "$app" printf 'App: %s\n' "$app"
if [[ "$launch" != "--no-launch" ]]; then if [[ "$launch" != "--no-launch" ]]; then
open -n "$app" open -n "$app"
+6 -4
View File
@@ -5,19 +5,21 @@ if [[ -n "${NOTARY_PROFILE:-}" && -z "${SIGN_IDENTITY:-}" ]]; then
echo "Notarization requires SIGN_IDENTITY." >&2 echo "Notarization requires SIGN_IDENTITY." >&2
exit 2 exit 2
fi fi
export AISTUDIO_BUILD_ROOT="${AISTUDIO_BUILD_ROOT:-/private/tmp/AIStudio-build-$(id -u)}" source Scripts/build-paths.sh
destination="${1:-$AISTUDIO_BUILD_ROOT/dist}" destination="${1:-$base/dist}"
./Scripts/build.sh Release --no-launch ./Scripts/build.sh Release --no-launch
stage="$(mktemp -d "$AISTUDIO_BUILD_ROOT/release.XXXXXXXX")" stage="$(mktemp -d "$base/release.XXXXXXXX")"
trap 'rm -rf -- "$stage"' EXIT trap 'rm -rf -- "$stage"' EXIT
app="$stage/AIStudio.app" app="$stage/AIStudio.app"
ditto "$AISTUDIO_BUILD_ROOT/Derived/Build/Products/Release/AIStudio.app" "$app" ditto "$derived/Build/Products/Release/AIStudio.app" "$app"
if [[ "$(xcrun lipo -archs "$app/Contents/MacOS/AIStudio")" != "arm64" ]]; then if [[ "$(xcrun lipo -archs "$app/Contents/MacOS/AIStudio")" != "arm64" ]]; then
echo "Expected an arm64-only release executable." >&2 echo "Expected an arm64-only release executable." >&2
exit 1 exit 1
fi fi
version="$(/usr/libexec/PlistBuddy -c 'Print CFBundleShortVersionString' "$app/Contents/Info.plist")" version="$(/usr/libexec/PlistBuddy -c 'Print CFBundleShortVersionString' "$app/Contents/Info.plist")"
if [[ -n "${SIGN_IDENTITY:-}" ]]; then if [[ -n "${SIGN_IDENTITY:-}" ]]; then
# The hardened app and its embedded framework must share a signing team.
codesign --force --timestamp --options runtime --sign "$SIGN_IDENTITY" "$app/Contents/Frameworks/llama.framework"
codesign --force --timestamp --options runtime --sign "$SIGN_IDENTITY" "$app" codesign --force --timestamp --options runtime --sign "$SIGN_IDENTITY" "$app"
else else
codesign --force --sign - "$app" codesign --force --sign - "$app"
+2 -2
View File
@@ -1,7 +1,7 @@
#!/bin/bash #!/bin/bash
set -euo pipefail set -euo pipefail
cd "$(dirname "$0")/.." cd "$(dirname "$0")/.."
base="${AISTUDIO_BUILD_ROOT:-/private/tmp/AIStudio-build-$(id -u)}" source Scripts/build-paths.sh
mkdir -p "$base" mkdir -p "$base"
results="$(mktemp -d "$base/test.XXXXXXXX")" results="$(mktemp -d "$base/test.XXXXXXXX")"
if [[ -z "${TEST_RUNNER_AISTUDIO_TEST_MCP_URLS:-}" || -z "${TEST_RUNNER_AISTUDIO_TEST_OLLAMA_FIXTURE_URL:-}" || -z "${TEST_RUNNER_AISTUDIO_TEST_OLLAMA_GATEWAY_URL:-}" || -z "${TEST_RUNNER_AISTUDIO_TEST_COMPATIBLE_URL:-}" || -z "${TEST_RUNNER_AISTUDIO_TEST_WEB_URL:-}" ]]; then if [[ -z "${TEST_RUNNER_AISTUDIO_TEST_MCP_URLS:-}" || -z "${TEST_RUNNER_AISTUDIO_TEST_OLLAMA_FIXTURE_URL:-}" || -z "${TEST_RUNNER_AISTUDIO_TEST_OLLAMA_GATEWAY_URL:-}" || -z "${TEST_RUNNER_AISTUDIO_TEST_COMPATIBLE_URL:-}" || -z "${TEST_RUNNER_AISTUDIO_TEST_WEB_URL:-}" ]]; then
@@ -32,6 +32,6 @@ export TEST_RUNNER_AISTUDIO_TEST_STDIO_PYTHON="$(command -v python3)"
export TEST_RUNNER_AISTUDIO_TEST_STDIO_FIXTURE="$PWD/Tests/Fixtures/stdio_server.py" export TEST_RUNNER_AISTUDIO_TEST_STDIO_FIXTURE="$PWD/Tests/Fixtures/stdio_server.py"
xcodebuild CODE_SIGN_IDENTITY=- CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM= -project AIStudio.xcodeproj -scheme AIStudio -configuration Debug \ xcodebuild CODE_SIGN_IDENTITY=- CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM= -project AIStudio.xcodeproj -scheme AIStudio -configuration Debug \
-destination 'platform=macOS,arch=arm64' -derivedDataPath "$base/Derived" \ -destination 'platform=macOS,arch=arm64' -derivedDataPath "$derived" \
-clonedSourcePackagesDirPath "$base/Packages" -disablePackageRepositoryCache \ -clonedSourcePackagesDirPath "$base/Packages" -disablePackageRepositoryCache \
-parallel-testing-enabled NO -resultBundlePath "$results/AIStudio.xcresult" test -parallel-testing-enabled NO -resultBundlePath "$results/AIStudio.xcresult" test
+243 -46
View File
@@ -41,6 +41,7 @@ struct AIStudioApp: App {
.task { .task {
await Task.yield() await Task.yield()
studio.open() studio.open()
try? await studio.refreshLocalMLXModels()
} }
} }
.defaultSize(width: 1000, height: 700) .defaultSize(width: 1000, height: 700)
@@ -53,6 +54,12 @@ struct AIStudioApp: App {
Button("Cycle Workspace Mode") { mode = nextValue(mode) }.keyboardShortcut(StudioShortcut.workspaceMode.shortcut(in: shortcutData)) Button("Cycle Workspace Mode") { mode = nextValue(mode) }.keyboardShortcut(StudioShortcut.workspaceMode.shortcut(in: shortcutData))
} }
} }
Window("Training & Images", id: "creativeWorkspace") {
CreativeWorkspace()
.preferredColorScheme(theme.colorScheme)
.tint(StudioCustomTheme.selected(customThemeID, in: customThemesData)?.accentColor ?? accent.color)
}
.defaultSize(width: 990, height: 690)
Settings { Settings {
StudioSettingsView(studio: studio) StudioSettingsView(studio: studio)
.preferredColorScheme(theme.colorScheme) .preferredColorScheme(theme.colorScheme)
@@ -67,6 +74,9 @@ struct AIStudioApp: App {
} }
struct ChatView: View { struct ChatView: View {
@Environment(\.openWindow) private var openWindow
@State private var checkedThinkingModel: ChatModelChoice?
@State private var inspectedThinkingSupport = false
@ObservedObject var studio: StudioModel @ObservedObject var studio: StudioModel
@AppStorage("endpoint") private var endpoint = "http://127.0.0.1:11434" @AppStorage("endpoint") private var endpoint = "http://127.0.0.1:11434"
@AppStorage("ollamaModel") private var model = "" @AppStorage("ollamaModel") private var model = ""
@@ -89,6 +99,8 @@ struct ChatView: View {
@AppStorage("mlxPath") private var mlxPath = "" @AppStorage("mlxPath") private var mlxPath = ""
@AppStorage("thinking") private var thinking = Thinking.automatic @AppStorage("thinking") private var thinking = Thinking.automatic
@AppStorage("failover") private var failover = true @AppStorage("failover") private var failover = true
@AppStorage("defaultCoreMLPath") private var defaultCoreMLPath = ""
@AppStorage("defaultGGUFPath") private var defaultGGUFPath = ""
@AppStorage("mlxOnly") private var mlxOnly = false @AppStorage("mlxOnly") private var mlxOnly = false
@AppStorage("compatibleEnabled") private var compatibleEnabled = false @AppStorage("compatibleEnabled") private var compatibleEnabled = false
@AppStorage("compatibleEndpoint") private var compatibleEndpoint = "http://127.0.0.1:1234/v1" @AppStorage("compatibleEndpoint") private var compatibleEndpoint = "http://127.0.0.1:1234/v1"
@@ -127,10 +139,13 @@ struct ChatView: View {
@State private var newTitle = "" @State private var newTitle = ""
@AppStorage(ChatModelChoice.settingsKey) private var chatModelData = Data() @AppStorage(ChatModelChoice.settingsKey) private var chatModelData = Data()
@AppStorage(GGUFModelMetadata.libraryKey) private var registeredGGUF = Data()
@AppStorage("mlxRegisteredPaths") private var registeredMLX = Data() @AppStorage("mlxRegisteredPaths") private var registeredMLX = Data()
@AppStorage("managedMLXModels") private var managedMLX = Data() @AppStorage("managedMLXModels") private var managedMLX = Data()
private var defaultChatModel: ChatModelChoice { private var defaultChatModel: ChatModelChoice {
if !defaultCoreMLPath.isEmpty { return ChatModelChoice(backend: .coreML, model: defaultCoreMLPath) }
if !defaultGGUFPath.isEmpty { return ChatModelChoice(backend: .gguf, model: defaultGGUFPath) }
if mlxOnly { return ChatModelChoice(backend: .mlx, model: mlxPath) } if mlxOnly { return ChatModelChoice(backend: .mlx, model: mlxPath) }
if compatibleEnabled { return ChatModelChoice(backend: .compatible, model: compatibleModel) } if compatibleEnabled { return ChatModelChoice(backend: .compatible, model: compatibleModel) }
return ChatModelChoice(backend: .ollama, model: model) return ChatModelChoice(backend: .ollama, model: model)
@@ -138,6 +153,29 @@ struct ChatView: View {
private var chatChoices: [UUID: ChatModelChoice] { ChatModelChoice.read(chatModelData) } private var chatChoices: [UUID: ChatModelChoice] { ChatModelChoice.read(chatModelData) }
private var chatModel: ChatModelChoice { modelForChat(studio.selected) } private var chatModel: ChatModelChoice { modelForChat(studio.selected) }
private var thinkingModes: [Thinking] {
let choice = chatModel
let registered = choice.backend == .gguf && GGUFModelMetadata.library(in: registeredGGUF).contains {
$0.path == choice.model && $0.supportsThinking
}
return ChatThinkingControl.options(backend: choice.backend,
supportsLocalThinking: registered || (checkedThinkingModel == choice && inspectedThinkingSupport))
}
private func inspectThinking(_ choice: ChatModelChoice) async {
let supported = await Task.detached(priority: .utility) {
guard !choice.model.isEmpty else { return false }
switch choice.backend {
case .mlx: return ThinkingOutput.supportsMLX(choice.model)
case .gguf:
return (try? GGUFModelMetadata.read(URL(fileURLWithPath: choice.model)).supportsThinking) == true
case .ollama, .compatible, .coreML: return false
}
}.value
guard !Task.isCancelled, chatModel == choice else { return }
inspectedThinkingSupport = supported
checkedThinkingModel = choice
}
private var backendName: String { chatModel.backend.rawValue } private var backendName: String { chatModel.backend.rawValue }
private func modelForChat(_ id: UUID?) -> ChatModelChoice { private func modelForChat(_ id: UUID?) -> ChatModelChoice {
@@ -159,9 +197,11 @@ struct ChatView: View {
private var mlxChoices: [String] { private var mlxChoices: [String] {
let registered = (try? JSONDecoder().decode([String].self, from: registeredMLX)) ?? [] let registered = (try? JSONDecoder().decode([String].self, from: registeredMLX)) ?? []
let managed = (try? JSONDecoder().decode([CatalogModel].self, from: managedMLX)) ?? [] let managed = (try? JSONDecoder().decode([CatalogModel].self, from: managedMLX)) ?? []
let paths = (managed + CatalogModel.all).map { $0.localFolder.path } + registered + [mlxPath] let saved = (managed + CatalogModel.all).map { $0.localFolder.path } + registered + [mlxPath]
let installed = paths.filter { !$0.isEmpty && MLXLibrary.isModel(at: URL(fileURLWithPath: $0)) } let installed = saved.filter { !$0.isEmpty && MLXLibrary.isModel(at: URL(fileURLWithPath: $0)) }
return Array(Set(installed)).sorted { $0.localizedStandardCompare($1) == .orderedAscending } return Set((installed + studio.discoveredMLXPaths).map {
URL(fileURLWithPath: $0).resolvingSymlinksInPath().path
}).sorted { $0.localizedStandardCompare($1) == .orderedAscending }
} }
private func modelPicker(for id: UUID?, running: Bool) -> some View { private func modelPicker(for id: UUID?, running: Bool) -> some View {
@@ -204,15 +244,25 @@ struct ChatView: View {
@State private var replacingFile = false @State private var replacingFile = false
@AppStorage("chatFileAccessFolder") private var chatFileScope = "" @AppStorage("chatFileAccessFolder") private var chatFileScope = ""
@AppStorage("chatFileWriteEnabled") private var chatFileWriteEnabled = false @AppStorage("chatFileWriteEnabled") private var chatFileWriteEnabled = false
@State private var filePreview: ChatFilePreview? private struct PendingAttachment: Identifiable {
let preview: ChatFilePreview
let target: StudioModel
let conversation: UUID?
var id: UUID { preview.id }
}
@State private var filePreview: PendingAttachment?
@State private var preparingFilePreview = false @State private var preparingFilePreview = false
@State private var fileError = "" @State private var fileError = ""
@State private var splitFileError = ""
var body: some View { var body: some View {
NavigationSplitView(columnVisibility: $columns) { NavigationSplitView(columnVisibility: $columns) {
List(visibleChats, selection: $studio.selected) { chat in List(visibleChats, selection: $studio.selected) { chat in
Label(chat.title, systemImage: "bubble.left").tag(chat.id) Label(chat.title, systemImage: "bubble.left").tag(chat.id)
.contextMenu { .contextMenu {
Button("Export Chat as Markdown…", systemImage: "square.and.arrow.up") {
exportChat(chat)
}
Button("Delete Chat", systemImage: "trash", role: .destructive) { Button("Delete Chat", systemImage: "trash", role: .destructive) {
chatToDelete = chat chatToDelete = chat
confirmDelete = true confirmDelete = true
@@ -223,6 +273,9 @@ struct ChatView: View {
.disabled(studio.running || splitStudio.running) .disabled(studio.running || splitStudio.running)
.navigationSplitViewColumnWidth(min: 180, ideal: 235) .navigationSplitViewColumnWidth(min: 180, ideal: 235)
.toolbar { .toolbar {
Button("Training & Images", systemImage: "slider.horizontal.3") {
openWindow(id: "creativeWorkspace")
}
Button("New Chat", systemImage: "square.and.pencil") { Button("New Chat", systemImage: "square.and.pencil") {
search = "" search = ""
studio.newChat() studio.newChat()
@@ -233,6 +286,12 @@ struct ChatView: View {
renaming = true renaming = true
} }
.disabled(studio.running || splitStudio.running || studio.selected == nil) .disabled(studio.running || splitStudio.running || studio.selected == nil)
Button("Export Chat as Markdown…", systemImage: "square.and.arrow.up") {
if let chat = studio.conversations.first(where: { $0.id == studio.selected }) {
exportChat(chat)
}
}
.disabled(studio.running || splitStudio.running || studio.selected == nil)
Button("Delete Chat", systemImage: "trash") { Button("Delete Chat", systemImage: "trash") {
chatToDelete = studio.conversations.first { $0.id == studio.selected } chatToDelete = studio.conversations.first { $0.id == studio.selected }
confirmDelete = chatToDelete != nil confirmDelete = chatToDelete != nil
@@ -286,7 +345,9 @@ struct ChatView: View {
.sheet(isPresented: $showingLibrary) { DocumentLibraryView(studio: studio) } .sheet(isPresented: $showingLibrary) { DocumentLibraryView(studio: studio) }
.sheet(isPresented: $showingPerformance) { PerformanceDashboard(studio: studio) } .sheet(isPresented: $showingPerformance) { PerformanceDashboard(studio: studio) }
.sheet(isPresented: $showingWorkspace) { WorkspaceResourcesView(studio: studio) } .sheet(isPresented: $showingWorkspace) { WorkspaceResourcesView(studio: studio) }
.sheet(item: $filePreview) { preview in .sheet(item: $filePreview) { pending in
let preview = pending.preview
let target = pending.target
VStack(alignment: .leading, spacing: 12) { VStack(alignment: .leading, spacing: 12) {
Text(preview.name).font(.headline) Text(preview.name).font(.headline)
ScrollView { ScrollView {
@@ -295,7 +356,7 @@ struct ChatView: View {
.frame(maxWidth: 520, maxHeight: 260) .frame(maxWidth: 520, maxHeight: 260)
.accessibilityLabel("Attachment preview") .accessibilityLabel("Attachment preview")
} }
if preview.imagePNG == nil || chatModel.backend == .mlx { if preview.imagePNG == nil || modelForChat(target.selected).backend == .mlx {
Text(preview.text.isEmpty && preview.imagePNG != nil Text(preview.text.isEmpty && preview.imagePNG != nil
? "No readable text detected. Choose a vision-capable model to analyze this image." ? "No readable text detected. Choose a vision-capable model to analyze this image."
: preview.text) : preview.text)
@@ -306,8 +367,10 @@ struct ChatView: View {
Spacer() Spacer()
Button("Cancel") { filePreview = nil }.keyboardShortcut(.cancelAction) Button("Cancel") { filePreview = nil }.keyboardShortcut(.cancelAction)
Button("Attach to Next Message") { Button("Attach to Next Message") {
studio.attachToolResult(name: preview.name, output: preview.text, if target.selected == pending.conversation {
target.attachToolResult(name: preview.name, output: preview.text,
isDocument: true, isPDF: preview.isPDF, imagePNG: preview.imagePNG) isDocument: true, isPDF: preview.isPDF, imagePNG: preview.imagePNG)
}
filePreview = nil filePreview = nil
}.keyboardShortcut(.defaultAction) }.keyboardShortcut(.defaultAction)
} }
@@ -328,6 +391,8 @@ struct ChatView: View {
} }
.onChange(of: studio.modelSelectionRevision) { .onChange(of: studio.modelSelectionRevision) {
let defaults = UserDefaults.standard let defaults = UserDefaults.standard
defaultCoreMLPath = defaults.string(forKey: "defaultCoreMLPath") ?? ""
defaultGGUFPath = defaults.string(forKey: "defaultGGUFPath") ?? ""
mlxPath = defaults.string(forKey: "mlxPath") ?? "" mlxPath = defaults.string(forKey: "mlxPath") ?? ""
model = defaults.string(forKey: "ollamaModel") ?? "" model = defaults.string(forKey: "ollamaModel") ?? ""
mlxOnly = defaults.bool(forKey: "mlxOnly") mlxOnly = defaults.bool(forKey: "mlxOnly")
@@ -411,11 +476,13 @@ struct ChatView: View {
.font(chatFont.font(size: chatSize)) .font(chatFont.font(size: chatSize))
Divider() Divider()
VStack(alignment: .leading, spacing: 6) { VStack(alignment: .leading, spacing: 6) {
let feedback = [showDebugOutput ? "" : splitStudio.webStatus, splitStudio.status] attachmentLabel(for: splitStudio)
let feedback = [splitFileError, showDebugOutput ? "" : splitStudio.webStatus, splitStudio.status]
.filter { !$0.isEmpty }.joined(separator: " · ") .filter { !$0.isEmpty }.joined(separator: " · ")
if !feedback.isEmpty { Text(feedback).font(.caption).foregroundStyle(.secondary) } if !feedback.isEmpty { Text(feedback).font(.caption).foregroundStyle(.secondary) }
ChatComposerInput(text: $splitStudio.prompt, canSend: !splitStudio.running, spellCheck: spellCheck, ChatComposerInput(text: $splitStudio.prompt, canSend: !splitStudio.running, spellCheck: spellCheck,
autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendSplitMessage) autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendSplitMessage,
pasteAttachment: { pasteAttachment($0, into: splitStudio) })
.frame(height: 54) .frame(height: 54)
HStack { HStack {
resourceMenu(for: splitStudio) resourceMenu(for: splitStudio)
@@ -474,18 +541,7 @@ struct ChatView: View {
.font(.caption) .font(.caption)
.disabled(studio.running) .disabled(studio.running)
} }
if let attachment = studio.toolAttachment { attachmentLabel(for: studio)
HStack {
Label("\(attachment.name) attached to next message", systemImage: "paperclip")
if attachment.imagePNG != nil && chatModel.backend == .mlx {
Text("Extracted text only").foregroundStyle(.secondary)
}
if chatModel.backend != .mlx { Text("Sent to \(backendName)").foregroundStyle(.secondary) }
Spacer()
Button("Remove", systemImage: "xmark.circle") { studio.removeToolAttachment() }
}
.font(.caption)
}
let activity = [preparingFilePreview ? "Preparing attachment preview…" : fileError, let activity = [preparingFilePreview ? "Preparing attachment preview…" : fileError,
showDebugOutput ? "" : studio.webStatus, studio.status].filter { !$0.isEmpty } showDebugOutput ? "" : studio.webStatus, studio.status].filter { !$0.isEmpty }
if !activity.isEmpty { if !activity.isEmpty {
@@ -496,7 +552,8 @@ struct ChatView: View {
Link("Open in Browser", destination: link).font(.caption) Link("Open in Browser", destination: link).font(.caption)
} }
ChatComposerInput(text: $studio.prompt, canSend: !studio.running, spellCheck: spellCheck, ChatComposerInput(text: $studio.prompt, canSend: !studio.running, spellCheck: spellCheck,
autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendMessage) autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendMessage,
pasteAttachment: { pasteAttachment($0, into: studio) })
.frame(height: 62) .frame(height: 62)
.padding(5) .padding(5)
.background(.background, in: RoundedRectangle(cornerRadius: 8)) .background(.background, in: RoundedRectangle(cornerRadius: 8))
@@ -541,16 +598,17 @@ struct ChatView: View {
HStack(spacing: 10) { HStack(spacing: 10) {
modelPicker(for: studio.selected, running: studio.running) modelPicker(for: studio.selected, running: studio.running)
Spacer() Spacer()
if chatModel.backend == .ollama || (chatModel.backend == .mlx && MLXThinking.supports(chatModel.model)) { let modes = thinkingModes
let modes: [Thinking] = chatModel.backend == .mlx ? [.automatic, .off, .on] : Thinking.allCases
Picker("Thinking", selection: Binding( Picker("Thinking", selection: Binding(
get: { modes.contains(thinking) ? thinking : .automatic }, get: { modes.contains(thinking) ? thinking : .automatic },
set: { thinking = $0 } set: { thinking = $0 }
)) { )) {
ForEach(modes) { Text($0.rawValue.capitalized).tag($0) } ForEach(modes) { Text($0.rawValue.capitalized).tag($0) }
} }
.fixedSize().disabled(studio.running) .fixedSize()
} .disabled(studio.running || modes.count == 1)
.help(modes.count == 1 ? "This backend controls its own thinking mode." : "Set thinking for the selected model.")
.task(id: chatModel) { await inspectThinking(chatModel) }
Toggle("Agents", isOn: $agentWorkflowEnabled) Toggle("Agents", isOn: $agentWorkflowEnabled)
.toggleStyle(.checkbox) .toggleStyle(.checkbox)
.fixedSize() .fixedSize()
@@ -572,6 +630,38 @@ struct ChatView: View {
} }
.padding(16) .padding(16)
} }
@ViewBuilder private func attachmentLabel(for target: StudioModel) -> some View {
if let attachment = target.toolAttachment {
let backend = modelForChat(target.selected).backend
HStack {
Label("\(attachment.name) attached to next message", systemImage: "paperclip")
if backend != .mlx { Text("Sent to \(backend.rawValue)").foregroundStyle(.secondary) }
else if attachment.imagePNG != nil { Text("Extracted text only").foregroundStyle(.secondary) }
Spacer()
Button("Remove", systemImage: "xmark.circle") { target.removeToolAttachment() }
}
.font(.caption)
}
}
private func exportChat(_ chat: Conversation) {
let panel = NSSavePanel()
panel.allowedContentTypes = [UTType(filenameExtension: "md") ?? .plainText]
panel.canCreateDirectories = true
let name = chat.title.components(separatedBy: CharacterSet.controlCharacters.union(CharacterSet(charactersIn: "/:")))
.joined(separator: " ").trimmingCharacters(in: .whitespacesAndNewlines.union(CharacterSet(charactersIn: ".")))
panel.nameFieldStringValue = (name.isEmpty ? "Chat" : String(name.prefix(80))) + ".md"
panel.begin { response in
guard response == .OK, let url = panel.url else { return }
do {
try studio.exportChat(chat.id, to: url)
fileError = "Exported \(url.lastPathComponent)."
} catch {
fileError = error.localizedDescription
}
}
}
private func pickLocalFile() { private func pickLocalFile() {
let panel = NSOpenPanel() let panel = NSOpenPanel()
panel.canChooseFiles = true panel.canChooseFiles = true
@@ -580,16 +670,27 @@ struct ChatView: View {
panel.prompt = "Preview" panel.prompt = "Preview"
panel.begin { response in panel.begin { response in
guard response == .OK, let url = panel.url else { return } guard response == .OK, let url = panel.url else { return }
Task { @MainActor in pasteAttachment(.files([url]), into: studio)
let conversation = studio.selected }
}
private func pasteAttachment(_ item: ComposerPaste, into target: StudioModel) {
guard !target.running, !preparingFilePreview, filePreview == nil else { return }
let conversation = target.selected
let isMain = target === studio
preparingFilePreview = true preparingFilePreview = true
fileError = "" if isMain { fileError = "" }
else { splitFileError = "Preparing attachment preview…" }
Task { @MainActor in
defer { preparingFilePreview = false } defer { preparingFilePreview = false }
do { do {
let preview = try await Task.detached { try ChatFilePreview.read(url) }.value let preview = try await Task.detached { try item.preview() }.value
guard studio.selected == conversation, !studio.running else { return } if !isMain { splitFileError = "" }
filePreview = preview guard target.selected == conversation, !target.running else { return }
} catch { fileError = error.localizedDescription } filePreview = PendingAttachment(preview: preview, target: target, conversation: conversation)
} catch {
if isMain { fileError = error.localizedDescription }
else { splitFileError = error.localizedDescription }
} }
} }
} }
@@ -632,7 +733,7 @@ struct ChatView: View {
recall: recall, useDocuments: useDocuments, instructions: promptMode.instructions(custom: customPrompt), recall: recall, useDocuments: useDocuments, instructions: promptMode.instructions(custom: customPrompt),
settings: GenerationSettings.read(generationSettings), agents: selectedAgents, agentTools: allowAgentTools, settings: GenerationSettings.read(generationSettings), agents: selectedAgents, agentTools: allowAgentTools,
ragEnabled: ragEnabled, lmStudioPlugins: pluginsEnabled && pluginEndpoint == compatibleEndpoint ragEnabled: ragEnabled, lmStudioPlugins: pluginsEnabled && pluginEndpoint == compatibleEndpoint
? CompatibleEndpoint.pluginIDs(pluginIDs) : []) ? CompatibleEndpoint.pluginIDs(pluginIDs) : [], gguf: choice.backend == .gguf, coreML: choice.backend == .coreML)
} }
} }
@@ -750,6 +851,7 @@ private struct ChatModelPicker: View {
let compatibleDefault: String let compatibleDefault: String
let select: (ChatModelChoice?) -> Void let select: (ChatModelChoice?) -> Void
@AppStorage(CoreMLLibrary.key) private var coreMLLibrary = Data()
@State private var showing = false @State private var showing = false
@State private var compatibleModels: [String] = [] @State private var compatibleModels: [String] = []
@State private var compatibleStatus = "" @State private var compatibleStatus = ""
@@ -759,11 +861,17 @@ private struct ChatModelPicker: View {
Button { Button {
showing.toggle() showing.toggle()
} label: { } label: {
Label(choice.displayName, systemImage: choice.backend == .mlx ? "cpu" : "server.rack") HStack(spacing: 6) {
Label(choice.displayName, systemImage: [.mlx, .gguf, .coreML].contains(choice.backend) ? "cpu" : "server.rack")
.lineLimit(1) .lineLimit(1)
Text(choice.backend.rawValue)
.font(.caption.weight(.semibold))
.foregroundStyle(.secondary)
.fixedSize()
}
} }
.buttonStyle(.bordered) .buttonStyle(.bordered)
.accessibilityLabel("Chat model: " + choice.displayName) .accessibilityLabel("Chat model: \(choice.displayName), \(choice.backend.rawValue)")
.help("Switch models for this conversation") .help("Switch models for this conversation")
.popover(isPresented: $showing) { .popover(isPresented: $showing) {
Form { Form {
@@ -774,6 +882,14 @@ private struct ChatModelPicker: View {
optionLabel("Use Default · " + defaultChoice.displayName, selected: !hasOverride) optionLabel("Use Default · " + defaultChoice.displayName, selected: !hasOverride)
} }
} }
GGUFModels(selection: choice.backend == .gguf ? choice.model : nil) {
choose(ChatModelChoice(backend: .gguf, model: $0))
}
if #available(macOS 15, *), !CoreMLLibrary.read(coreMLLibrary).isEmpty {
Section("Core ML") {
ForEach(CoreMLLibrary.read(coreMLLibrary)) { model in modelButton(.coreML, model.path) }
}
}
Section("Ollama") { Section("Ollama") {
let installed = studio.modelListEndpoint == endpoint ? studio.models.map(\.name) : [] let installed = studio.modelListEndpoint == endpoint ? studio.models.map(\.name) : []
ForEach(names(installed + [ollamaDefault]), id: \.self) { name in ForEach(names(installed + [ollamaDefault]), id: \.self) { name in
@@ -808,7 +924,7 @@ private struct ChatModelPicker: View {
.formStyle(.grouped) .formStyle(.grouped)
.frame(width: 340, height: 420) .frame(width: 340, height: 420)
.task { .task {
if studio.modelListEndpoint != endpoint { studio.refresh(endpoint: endpoint) } if choice.backend == .ollama && studio.modelListEndpoint != endpoint { studio.refresh(endpoint: endpoint) }
} }
.onChange(of: compatibleEndpoint) { .onChange(of: compatibleEndpoint) {
compatibleModels = [] compatibleModels = []
@@ -976,6 +1092,8 @@ struct BackendSettings: View {
@AppStorage("ollamaModel") private var model = "" @AppStorage("ollamaModel") private var model = ""
@AppStorage("mlxPath") private var mlxPath = "" @AppStorage("mlxPath") private var mlxPath = ""
@AppStorage("failover") private var failover = true @AppStorage("failover") private var failover = true
@AppStorage("defaultCoreMLPath") private var defaultCoreMLPath = ""
@AppStorage("defaultGGUFPath") private var defaultGGUFPath = ""
@AppStorage("mlxOnly") private var mlxOnly = false @AppStorage("mlxOnly") private var mlxOnly = false
@AppStorage("compatibleEnabled") private var compatibleEnabled = false @AppStorage("compatibleEnabled") private var compatibleEnabled = false
@AppStorage("compatibleEndpoint") private var compatibleEndpoint = "http://127.0.0.1:1234/v1" @AppStorage("compatibleEndpoint") private var compatibleEndpoint = "http://127.0.0.1:1234/v1"
@@ -990,8 +1108,10 @@ struct BackendSettings: View {
Form { Form {
Section("Inference") { Section("Inference") {
Picker("Backend", selection: Binding( Picker("Backend", selection: Binding(
get: { mlxOnly ? "mlx" : (compatibleEnabled ? "compatible" : "ollama") }, get: { !defaultCoreMLPath.isEmpty ? "coreML" : !defaultGGUFPath.isEmpty ? "gguf" : mlxOnly ? "mlx" : (compatibleEnabled ? "compatible" : "ollama") },
set: { mode in set: { mode in
if mode != "gguf" { defaultGGUFPath = "" }
if mode != "coreML" { defaultCoreMLPath = "" }
mlxOnly = mode == "mlx" mlxOnly = mode == "mlx"
compatibleEnabled = mode == "compatible" compatibleEnabled = mode == "compatible"
} }
@@ -999,11 +1119,14 @@ struct BackendSettings: View {
Text("Prefer Ollama").tag("ollama") Text("Prefer Ollama").tag("ollama")
Text("OpenAI-compatible").tag("compatible") Text("OpenAI-compatible").tag("compatible")
Text("MLX only").tag("mlx") Text("MLX only").tag("mlx")
if !defaultCoreMLPath.isEmpty { Text("Core ML").tag("coreML") }
if !defaultGGUFPath.isEmpty { Text("Local GGUF").tag("gguf") }
} }
Toggle("Fall back to MLX before output begins", isOn: $failover) Toggle("Fall back to MLX before output begins", isOn: $failover)
.disabled(mlxOnly) .disabled(mlxOnly || !defaultGGUFPath.isEmpty || !defaultCoreMLPath.isEmpty)
Toggle("Recall older matching messages in this conversation", isOn: $recall) Toggle("Recall older matching messages in this conversation", isOn: $recall)
} }
GGUFModels(selection: defaultGGUFPath, selectionDisabled: studio.running) { studio.selectGGUFModel($0) }
Section("Ollama") { Section("Ollama") {
TextField("Server URL", text: $endpoint) TextField("Server URL", text: $endpoint)
.disabled(studio.managing) .disabled(studio.managing)
@@ -1030,11 +1153,13 @@ struct BackendSettings: View {
Spacer() Spacer()
Text(ModelLibrarySize.label(entry.size)) Text(ModelLibrarySize.label(entry.size))
.foregroundStyle(.secondary).font(.caption) .foregroundStyle(.secondary).font(.caption)
Button(model == entry.name && !mlxOnly && !compatibleEnabled ? "Selected" : "Use Model") { Button(defaultCoreMLPath.isEmpty && defaultGGUFPath.isEmpty && model == entry.name && !mlxOnly && !compatibleEnabled ? "Selected" : "Use Model") {
model = entry.name model = entry.name
defaultCoreMLPath = ""
defaultGGUFPath = ""
mlxOnly = false mlxOnly = false
compatibleEnabled = false compatibleEnabled = false
}.disabled(model == entry.name && !mlxOnly && !compatibleEnabled) }.disabled(defaultCoreMLPath.isEmpty && defaultGGUFPath.isEmpty && model == entry.name && !mlxOnly && !compatibleEnabled)
} }
} }
} }
@@ -1066,7 +1191,7 @@ struct BackendSettings: View {
} }
.formStyle(.grouped) .formStyle(.grouped)
.onAppear { .onAppear {
if !mlxOnly && !compatibleEnabled && studio.modelListEndpoint != endpoint { if defaultCoreMLPath.isEmpty && defaultGGUFPath.isEmpty && !mlxOnly && !compatibleEnabled && studio.modelListEndpoint != endpoint {
studio.refresh(endpoint: endpoint) studio.refresh(endpoint: endpoint)
} }
} }
@@ -1074,8 +1199,8 @@ struct BackendSettings: View {
.fileImporter(isPresented: $pickingFolder, allowedContentTypes: [.folder]) { result in .fileImporter(isPresented: $pickingFolder, allowedContentTypes: [.folder]) { result in
do { do {
let url = try result.get() let url = try result.get()
guard FileManager.default.fileExists(atPath: url.appending(path: "config.json").path) else { guard MLXLibrary.isModel(at: url) else {
throw StudioError("This folder does not contain an MLX config.json.") throw StudioError("Choose a complete model folder with a readable config.json and all safetensors weight files.")
} }
mlxPath = url.path mlxPath = url.path
folderError = "" folderError = ""
@@ -1973,6 +2098,68 @@ struct RuntimeSettingsView: View {
} }
} }
enum ComposerPaste: Equatable, Sendable {
case files([URL])
case image(Data)
@MainActor static func read(_ pasteboard: NSPasteboard) -> Self? {
if pasteboard.types?.contains(.fileURL) == true,
let urls = pasteboard.readObjects(forClasses: [NSURL.self],
options: [.urlReadingFileURLsOnly: true]) as? [URL],
!urls.isEmpty {
return .files(urls)
}
if let type = imageType(on: pasteboard), let data = pasteboard.data(forType: type) {
return .image(data)
}
return nil
}
@MainActor private static func imageType(on pasteboard: NSPasteboard) -> NSPasteboard.PasteboardType? {
let types = pasteboard.types ?? []
if let preferred = [NSPasteboard.PasteboardType.png, .tiff].first(where: types.contains) {
return preferred
}
return types.first { UTType($0.rawValue)?.conforms(to: .image) == true }
}
@MainActor static func isAvailable(on pasteboard: NSPasteboard) -> Bool {
pasteboard.types?.contains(.fileURL) == true || imageType(on: pasteboard) != nil
}
func preview() throws -> ChatFilePreview {
switch self {
case .files(let urls):
guard urls.count == 1, let url = urls.first else {
throw StudioError("Paste one file at a time.")
}
return try ChatFilePreview.read(url)
case .image(let data):
return try ChatFilePreview.pastedImage(data)
}
}
}
private final class ComposerTextView: NSTextView {
var pasteAttachment: ((ComposerPaste) -> Void)?
override func paste(_ sender: Any?) {
if let pasteAttachment, let item = ComposerPaste.read(.general) {
pasteAttachment(item)
} else {
super.paste(sender)
}
}
override func validateUserInterfaceItem(_ item: any NSValidatedUserInterfaceItem) -> Bool {
if item.action == #selector(paste(_:)), isEditable, pasteAttachment != nil,
ComposerPaste.isAvailable(on: .general) {
return true
}
return super.validateUserInterfaceItem(item)
}
}
struct ChatComposerInput: NSViewRepresentable { struct ChatComposerInput: NSViewRepresentable {
@Binding var text: String @Binding var text: String
var canSend: Bool var canSend: Bool
@@ -1980,15 +2167,25 @@ struct ChatComposerInput: NSViewRepresentable {
var autoCorrect: Bool var autoCorrect: Bool
var font: NSFont var font: NSFont
var send: () -> Void var send: () -> Void
var pasteAttachment: (ComposerPaste) -> Void
func makeCoordinator() -> Coordinator { Coordinator(self) } func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeNSView(context: Context) -> NSScrollView { func makeNSView(context: Context) -> NSScrollView {
let scroll = NSTextView.scrollableTextView() let scroll = NSScrollView()
guard let editor = scroll.documentView as? NSTextView else { return scroll } scroll.hasVerticalScroller = true
let editor = ComposerTextView(frame: scroll.contentView.bounds)
editor.isVerticallyResizable = true
editor.isHorizontallyResizable = false
editor.autoresizingMask = [.width]
editor.textContainer?.widthTracksTextView = true
scroll.documentView = editor
editor.isRichText = false editor.isRichText = false
editor.font = font editor.font = font
editor.delegate = context.coordinator editor.delegate = context.coordinator
editor.pasteAttachment = { [weak coordinator = context.coordinator] item in
coordinator?.parent.pasteAttachment(item)
}
editor.drawsBackground = false editor.drawsBackground = false
scroll.drawsBackground = false scroll.drawsBackground = false
editor.setAccessibilityLabel("Message") editor.setAccessibilityLabel("Message")
+251
View File
@@ -0,0 +1,251 @@
import SwiftUI
import UniformTypeIdentifiers
import Metal
import CryptoKit
enum ModelMemoryBudget {
static let gpu = MTLCreateSystemDefaultDevice().map { Int64($0.recommendedMaxWorkingSetSize) }
static let system = Int64(ProcessInfo.processInfo.physicalMemory)
static func exceeds(bytes: Int64?, budget: Int64?) -> Bool {
guard let bytes, let budget, budget > 0 else { return false }
return bytes > budget
}
}
struct ModelMemoryWarning: View {
let bytes: Int64?
var coreML = false
var mlx = false
@AppStorage(MLXRuntimeLimits.weightKey) private var mlxGiB = 0
var body: some View {
let configured = mlxGiB > 0 && mlxGiB <= Int64.max / 1_073_741_824 ? Int64(mlxGiB) * 1_073_741_824 : nil
let overMLXLimit = mlx && ModelMemoryBudget.exceeds(bytes: bytes, budget: configured)
if overMLXLimit || ModelMemoryBudget.exceeds(bytes: bytes, budget: coreML ? ModelMemoryBudget.system : ModelMemoryBudget.gpu) {
Label(overMLXLimit ? "Exceeds MLX weight limit" : coreML ? "Exceeds Mac memory" : "Exceeds GPU memory budget",
systemImage: "exclamationmark.triangle.fill")
.font(.caption.weight(.semibold))
.foregroundStyle(.red)
.help("The model files alone exceed this budget. Generation also uses memory for context.")
}
}
}
struct CoreMLLibrary: Codable, Identifiable, Sendable {
static let key = "coreMLLibrary"
let path: String
let bytes: Int64
var id: String { path }
static func read(_ data: Data) -> [Self] { (try? JSONDecoder().decode([Self].self, from: data)) ?? [] }
static func inspect(_ source: URL) throws -> Self {
let extensions = ["mlpackage", "mlmodelc", "mlmodel"]
var package = source.resolvingSymlinksInPath()
guard package.isFileURL else { throw StudioError("Choose a local Core ML model.") }
if !extensions.contains(package.pathExtension.lowercased()) {
let entries = try FileManager.default.contentsOfDirectory(at: package, includingPropertiesForKeys: nil)
.filter { extensions.contains($0.pathExtension.lowercased()) }
guard entries.count == 1, let match = entries.first else {
throw StudioError("Choose a Core ML model or a folder containing one model package.")
}
package = match
}
let tokenizer = package.deletingLastPathComponent()
guard MLXLibrary.hasFile("tokenizer.json", in: tokenizer), MLXLibrary.hasFile("tokenizer_config.json", in: tokenizer) else {
throw StudioError("Put the matching tokenizer.json and tokenizer_config.json beside the Core ML model.")
}
let manager = FileManager.default
let properties: Set<URLResourceKey> = [.isRegularFileKey, .fileSizeKey]
let values = try package.resourceValues(forKeys: properties)
var size = Int64(values.fileSize ?? 0)
if values.isRegularFile != true {
size = 0
if let entries = manager.enumerator(at: package, includingPropertiesForKeys: Array(properties)) {
for case let file as URL in entries {
let attributes = try file.resourceValues(forKeys: properties)
if attributes.isRegularFile == true { size += Int64(attributes.fileSize ?? 0) }
}
}
}
guard size > 0 else { throw StudioError("The Core ML package is empty.") }
return Self(path: package.path, bytes: size)
}
}
struct CoreMLDownloads {
static let repository = "apple/mistral-coreml"
static let modelBytes: Int64 = 4_078_518_656
static let package = "StatefulMistral7BInstructInt4.mlpackage"
private static let hashes = [
"model.mlmodel": "aa0d5b06e1fe50cbdb095b846c1f30fb69aef08550db309ef6fc48d43ea51ad6",
"weight.bin": "1fa5158e6a1c5d3d131a1b08cb8dd3a4030c682a5fefa625e37a289f34d7a7ff"
]
static func install(in destination: URL, progress: @escaping HubGGUFAsset.ProgressUpdate) async throws -> CoreMLLibrary {
let checkpoint = destination.appending(path: package)
if let installed = try? CoreMLLibrary.inspect(checkpoint) { return installed }
let fileManager = FileManager.default
let parent = destination.deletingLastPathComponent()
try fileManager.createDirectory(at: parent, withIntermediateDirectories: true)
let stage = parent.appending(path: ".download-" + UUID().uuidString)
defer { try? fileManager.removeItem(at: stage) }
let hf = URL(string: "https://huggingface.co")!
let weights = hf.appending(path: "apple/mistral-coreml/resolve/ef561211ae2c829934011eec8b396776bf24df9b")
let tokenizer = hf.appending(path: "mistralai/Mistral-7B-Instruct-v0.3/resolve/c170c708c41dac9275d15a8fff4eca08d52bab71")
let files: [(URL, String, Int64)] = [
(weights, package + "/Manifest.json", 617),
(weights, package + "/Data/com.apple.CoreML/model.mlmodel", 984_023),
(weights, package + "/Data/com.apple.CoreML/weights/weight.bin", 4_077_534_016),
(tokenizer, "tokenizer.json", 1_961_548),
(tokenizer, "tokenizer_config.json", 140_874),
(tokenizer, "config.json", 601)
]
let total = files.reduce(0) { $0 + $1.2 }
var written: Int64 = 0
for (base, path, bytes) in files {
try Task.checkCancellation()
let file = stage.appending(path: path)
try fileManager.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
let offset = written
try await HubGGUFTransfer.download(base.appending(path: path), file) { count, _ in progress(offset + count, total) }
guard try file.resourceValues(forKeys: [.fileSizeKey]).fileSize.map(Int64.init) == bytes else {
throw StudioError("The Core ML download returned an unexpected file size.")
}
if let expected = hashes[file.lastPathComponent] {
let handle = try FileHandle(forReadingFrom: file)
defer { try? handle.close() }
var hash = SHA256()
while let chunk = try handle.read(upToCount: 1_048_576), !chunk.isEmpty {
try Task.checkCancellation()
hash.update(data: chunk)
}
guard hash.finalize().map({ String(format: "%02x", $0) }).joined() == expected else {
throw StudioError("The Core ML download checksum does not match Hugging Face.")
}
}
written += bytes
}
_ = try CoreMLLibrary.inspect(stage.appending(path: package))
try Task.checkCancellation()
try fileManager.moveItem(at: stage, to: destination)
return try CoreMLLibrary.inspect(checkpoint)
}
}
struct CoreMLModels: View {
let selection: String
let disabled: Bool
let select: (String) -> Void
@AppStorage(CoreMLLibrary.key) private var stored = Data()
@State private var importing = false
@State private var status = ""
@State private var search = ""
@State private var searching = false
@State private var results: [HubGGUFAsset.RepositoryResult] = []
@State private var download: Task<Void, Never>?
@State private var received: Int64 = 0
@State private var total: Int64?
var body: some View {
Section("Core ML") {
if #available(macOS 15, *) {
Button("Import Core ML Model…", systemImage: "plus") { importing = true }.disabled(disabled)
ForEach(CoreMLLibrary.read(stored)) { model in
HStack {
VStack(alignment: .leading) {
Text(URL(fileURLWithPath: model.path).deletingPathExtension().lastPathComponent)
Text("Core ML · " + ModelLibrarySize.label(model.bytes)).font(.caption).foregroundStyle(.secondary)
ModelMemoryWarning(bytes: model.bytes, coreML: true)
}
Spacer()
Button(selection == model.path ? "Active" : "Use") { select(model.path) }
.disabled(disabled || selection == model.path || !FileManager.default.fileExists(atPath: model.path))
if selection != model.path {
Button("Remove", systemImage: "minus.circle") {
do { stored = try JSONEncoder().encode(CoreMLLibrary.read(stored).filter { $0.path != model.path }) }
catch { status = error.localizedDescription }
}.labelStyle(.iconOnly)
}
}
}
HStack {
VStack(alignment: .leading) {
Text("Apple Mistral 7B Instruct")
Text("Core ML · Int4 · " + ModelLibrarySize.label(CoreMLDownloads.modelBytes))
.font(.caption).foregroundStyle(.secondary)
ModelMemoryWarning(bytes: CoreMLDownloads.modelBytes, coreML: true)
}
Spacer()
if let download { Button("Cancel") { download.cancel() } }
else { Button("Download from Hugging Face", action: startDownload) }
}
if download != nil {
if let total { ProgressView(value: Double(min(total, received)), total: Double(total)) }
else { ProgressView("Starting download…") }
}
HStack {
TextField("Search Hugging Face", text: $search, prompt: Text("Core ML text-generation models"))
.onSubmit(find)
Button(search.isEmpty ? "Browse" : "Search", action: find).disabled(searching)
if searching { ProgressView().controlSize(.small) }
}
ForEach(results) { result in
Link(result.id, destination: URL(string: "https://huggingface.co")!.appending(path: result.id))
}
if !status.isEmpty { Text(status).font(.caption).foregroundStyle(.secondary) }
} else {
Text("Core ML chat requires macOS 15 or later.").foregroundStyle(.secondary)
}
}
.fileImporter(isPresented: $importing, allowedContentTypes: [.folder] + ["mlpackage", "mlmodel", "mlmodelc"].compactMap { UTType(filenameExtension: $0) }) { result in
do {
let url = try result.get()
let access = url.startAccessingSecurityScopedResource()
defer { if access { url.stopAccessingSecurityScopedResource() } }
try register(CoreMLLibrary.inspect(url))
} catch { status = error.localizedDescription }
}
}
private func register(_ model: CoreMLLibrary) throws {
stored = try JSONEncoder().encode(CoreMLLibrary.read(stored).filter { $0.path != model.path } + [model])
status = "Core ML model added."
}
private func find() {
guard !searching else { return }
searching = true
status = ""
Task {
defer { searching = false }
do {
results = try await HubGGUFAsset.search(search.trimmingCharacters(in: .whitespaces), format: "coreml")
if results.isEmpty { status = "No public Core ML text-generation models found." }
} catch { status = error.localizedDescription }
}
}
private func startDownload() {
received = 0
total = nil
status = ""
download = Task {
defer { download = nil }
do {
let path = URL.applicationSupportDirectory.appending(path: "AIStudio/Models/CoreML/Apple-Mistral-7B")
let model = try await CoreMLDownloads.install(in: path) { written, expected in
Task { @MainActor in
guard download != nil, written >= received else { return }
received = written
total = expected
}
}
try register(model)
} catch {
status = Task.isCancelled ? "Download cancelled." : error.localizedDescription
}
}
}
}
+181
View File
@@ -0,0 +1,181 @@
import Foundation
import CoreML
import Tokenizers
enum CoreMLInputs {
static func mask(queryCount: Int, pastCount: Int) -> [Float16] {
let width = queryCount + pastCount
return (0..<queryCount).flatMap { query in
(0..<width).map { $0 > pastCount + query ? -Float16.greatestFiniteMagnitude : 0 }
}
}
}
struct CoreMLProvider: InferenceProvider {
private static let engine = CoreMLEngine()
func generate(_ request: InferenceRequest) -> AsyncThrowingStream<Delta, Error> {
streaming { output in
guard #available(macOS 15, *) else { throw StudioError("Core ML chat requires macOS 15 or later.") }
try await Self.engine.generate(request, output: output)
}
}
}
private actor CoreMLEngine {
@available(macOS 15, *)
func generate(_ request: InferenceRequest, output: AsyncThrowingStream<Delta, Error>.Continuation) async throws {
guard !request.messages.contains(where: { $0.imagePNG != nil }), !request.parameters.json else {
throw StudioError("Use text input and turn off JSON mode for this Core ML model.")
}
try Task.checkCancellation()
output.yield(.backend("Core ML"))
let entry = try CoreMLLibrary.inspect(URL(fileURLWithPath: request.model))
let package = URL(fileURLWithPath: entry.path)
let compiled = package.pathExtension.lowercased() == "mlmodelc" ? package : try await MLModel.compileModel(at: package)
defer { if compiled != package { try? FileManager.default.removeItem(at: compiled) } }
let config = MLModelConfiguration()
config.computeUnits = .cpuAndGPU
let model = try await MLModel.load(contentsOf: compiled, configuration: config)
let description = model.modelDescription
let ids = description.inputDescriptionsByName["inputIds"]?.multiArrayConstraint
let mask = description.inputDescriptionsByName["causalMask"]?.multiArrayConstraint
let logits = description.outputDescriptionsByName["logits"]?.multiArrayConstraint
guard Set(description.inputDescriptionsByName.keys) == ["inputIds", "causalMask"],
ids?.dataType == .int32, mask?.dataType == .float16, logits != nil,
!description.stateDescriptionsByName.isEmpty,
let width = mask?.shapeConstraint.sizeRangeForDimension.last as? NSRange,
width.location == 1, width.length > 1 else {
throw StudioError("This package does not match the supported stateful Core ML chat model inputs.")
}
let tokenizer = try await AutoTokenizer.from(modelFolder: package.deletingLastPathComponent())
let context = min(width.length, request.parameters.context ?? width.length)
let outputReserve = min(request.parameters.maxTokens ?? 256, max(1, context / 4))
let tokens = try preparePrompt(request.messages, tokenizer: tokenizer, capacity: context - outputReserve)
let state = model.makeState()
let limit = min(request.parameters.maxTokens ?? 256, context - tokens.count)
var scores: MLMultiArray?
for offset in stride(from: 0, to: tokens.count, by: 256) {
try Task.checkCancellation()
scores = try await predict(model, state: state, tokens: Array(tokens[offset..<min(tokens.count, offset + 256)]), past: offset)
}
var generated: [Int] = []
var decoded = ""
var stop = StopMatcher(sequences: request.parameters.stop)
let start = ContinuousClock.now
for index in 0..<limit {
try Task.checkCancellation()
if stop.stopped { break }
guard let currentScores = scores else { throw StudioError("Core ML did not return token scores.") }
let next = try choose(currentScores, parameters: request.parameters)
if next == tokenizer.eosTokenId { break }
generated.append(next)
let text = tokenizer.decode(tokens: generated, skipSpecialTokens: true)
let valid = String(text.reversed().drop(while: { $0 == "�" }).reversed())
if valid.hasPrefix(decoded) {
let visible = stop.append(String(valid.dropFirst(decoded.count)))
decoded = valid
if !visible.isEmpty { output.yield(.answer(visible)) }
}
if index + 1 < limit && !stop.stopped {
scores = try await predict(model, state: state, tokens: [next], past: tokens.count + index)
}
}
let remainder = stop.finish()
if !remainder.isEmpty { output.yield(.answer(remainder)) }
let elapsed = (ContinuousClock.now - start).components
output.yield(.metrics(.init(tokens: generated.count, seconds: Double(elapsed.seconds) + Double(elapsed.attoseconds) / 1e18)))
}
private func preparePrompt(_ messages: [Message], tokenizer: any Tokenizer, capacity: Int) throws -> [Int] {
func encode(_ messages: [Message]) throws -> [Int] {
do {
return try tokenizer.applyChatTemplate(messages: messages.map {
["role": $0.role.rawValue, "content": $0.content]
})
} catch {
throw StudioError("The Core ML tokenizer could not render this chat. Check that its chat template matches the model.")
}
}
let normalized = LocalChatHistory.prepare(messages)
var system = Array(normalized.prefix(while: { $0.role == .system }))
var turns = Array(normalized.dropFirst(system.count))
var tokens = try encode(system + turns)
while tokens.count > capacity && turns.count > 1 {
turns.removeFirst(min(2, turns.count - 1))
tokens = try encode(system + turns)
}
if tokens.count > capacity, let instructions = system.first {
let userTokens = try encode(turns)
guard userTokens.count <= capacity else {
throw StudioError("The latest message needs \(userTokens.count) tokens. This Core ML model has \(capacity) prompt tokens available.")
}
let characters = Array(instructions.content)
var low = 0
var high = characters.count
tokens = userTokens
while low < high {
let length = low + (high - low + 1) / 2
system[0].content = String(characters.prefix(length))
let candidate = try encode(system + turns)
if candidate.count <= capacity {
tokens = candidate
low = length
} else {
high = length - 1
}
}
}
guard !tokens.isEmpty, tokens.count <= capacity else {
throw StudioError("The Core ML prompt uses \(tokens.count) tokens. The available prompt budget is \(capacity).")
}
return tokens
}
@available(macOS 15, *)
private func predict(_ model: MLModel, state: MLState, tokens: [Int], past: Int) async throws -> MLMultiArray {
let input = try MLMultiArray(shape: [1, NSNumber(value: tokens.count)], dataType: .int32)
for (index, token) in tokens.enumerated() { input[index] = NSNumber(value: token) }
let attention = try MLMultiArray(shape: [1, 1, NSNumber(value: tokens.count), NSNumber(value: past + tokens.count)], dataType: .float16)
let values = CoreMLInputs.mask(queryCount: tokens.count, pastCount: past)
attention.withUnsafeMutableBytes { buffer, _ in
_ = buffer.bindMemory(to: Float16.self).update(from: values)
}
let features = try MLDictionaryFeatureProvider(dictionary: ["inputIds": input, "causalMask": attention])
let result = try await model.prediction(from: features, using: state)
guard let logits = result.featureValue(for: "logits")?.multiArrayValue else { throw StudioError("Core ML returned no logits.") }
return logits
}
private func choose(_ logits: MLMultiArray, parameters: GenerationParameters) throws -> Int {
let dimensions = logits.shape.map(\.intValue)
guard dimensions.count == 3, dimensions[0] == 1, dimensions[1] > 0, dimensions[2] > 0 else {
throw StudioError("Core ML returned an unsupported logits shape.")
}
let position = NSNumber(value: dimensions[1] - 1)
let scores = (0..<dimensions[2]).map { index in logits[[0, position, NSNumber(value: index)]].doubleValue }
let temperature = parameters.temperature ?? 0
guard let best = scores.indices.filter({ scores[$0].isFinite }).max(by: { scores[$0] < scores[$1] }) else {
throw StudioError("Core ML returned invalid token scores.")
}
guard temperature > 0 else { return best }
let candidates = scores.indices.filter { scores[$0].isFinite }.sorted { scores[$0] > scores[$1] }
let top = candidates.prefix(max(1, parameters.topK.flatMap { $0 > 0 ? $0 : nil } ?? 50))
let weights = top.map { exp((scores[$0] - scores[best]) / temperature) }
let total = weights.reduce(0, +)
let cutoff = total * (parameters.topP ?? 1)
var mass = 0.0
let retained = weights.prefix { weight in
guard mass == 0 || mass < cutoff else { return false }
mass += weight
return true
}
var draw = Double.random(in: 0..<mass)
for (token, weight) in zip(top, retained) {
draw -= weight
if draw <= 0 { return token }
}
return best
}
}
+197
View File
@@ -0,0 +1,197 @@
import AppKit
import ImageIO
import ImagePlayground
import SwiftUI
import UniformTypeIdentifiers
struct StudioImagePreview: Sendable {
let name: String
let width: Int
let height: Int
let png: Data
init(data: Data, name: String, maxDimension: Int = 2048) throws {
guard let source = CGImageSourceCreateWithData(data as CFData, nil),
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
let width = properties[kCGImagePropertyPixelWidth] as? Int,
let height = properties[kCGImagePropertyPixelHeight] as? Int,
let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: max(1, maxDimension)
] as CFDictionary) else {
throw StudioError("This file could not be opened as an image.")
}
let output = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(output, UTType.png.identifier as CFString, 1, nil) else {
throw StudioError("Could not create the PNG preview.")
}
CGImageDestinationAddImage(destination, image, nil)
guard CGImageDestinationFinalize(destination) else { throw StudioError("Could not encode the PNG preview.") }
self.name = name
self.width = width
self.height = height
self.png = output as Data
}
}
struct CreativeWorkspace: View {
private enum Area: String, CaseIterable, Identifiable {
case training = "Training"
case images = "Images"
var id: Self { self }
var icon: String { self == .training ? "cpu" : "photo" }
}
@State private var area: Area = .training
@AppStorage("mlxRegisteredPaths") private var registered = Data()
var body: some View {
HStack(spacing: 0) {
VStack(alignment: .leading, spacing: 5) {
ForEach(Area.allCases) { item in
Button { area = item } label: {
Label(item.rawValue, systemImage: item.icon)
.font(.headline)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 12)
.padding(.vertical, 9)
.background(area == item ? Color.accentColor.opacity(0.15) : .clear,
in: RoundedRectangle(cornerRadius: 8))
}
.buttonStyle(.plain)
.accessibilityAddTraits(area == item ? .isSelected : [])
}
Spacer()
}
.padding(12)
.frame(width: 158)
.background(.regularMaterial)
Divider()
ZStack {
ModelWorkshopView(workshop: ModelWorkshop(base: nil), embedded: true, register: register)
.opacity(area == .training ? 1 : 0)
.allowsHitTesting(area == .training)
.accessibilityHidden(area != .training)
ImageWorkspace()
.opacity(area == .images ? 1 : 0)
.allowsHitTesting(area == .images)
.accessibilityHidden(area != .images)
}
}
.frame(minWidth: 835, minHeight: 560)
}
private func register(_ url: URL) {
let paths = (try? JSONDecoder().decode([String].self, from: registered)) ?? []
let updated = Set(paths + [url.resolvingSymlinksInPath().path]).sorted()
if let data = try? JSONEncoder().encode(updated) { registered = data }
}
}
private struct ImageWorkspace: View {
@State private var prompt = ""
@State private var preview: StudioImagePreview?
@State private var importing = false
@State private var status = ""
var body: some View {
HStack(spacing: 0) {
VStack(alignment: .leading, spacing: 14) {
Text("Images").font(.largeTitle.weight(.semibold))
Text("Image description").font(.headline)
TextField("Describe the image to generate", text: $prompt, axis: .vertical)
.textFieldStyle(.roundedBorder)
.lineLimit(3...6)
if #available(macOS 15.1, *) {
PlaygroundAction(prompt: prompt) { receive($0) }
} else {
Label("Image generation requires Image Playground.", systemImage: "info.circle")
.font(.caption).foregroundStyle(.secondary)
}
Divider()
Button("Open Image…", systemImage: "folder") { importing = true }
Button("Export Preview PNG…", systemImage: "square.and.arrow.up", action: export)
.disabled(preview == nil)
if !status.isEmpty {
Text(status).font(.callout).foregroundStyle(.secondary).textSelection(.enabled)
}
Spacer()
}
.padding(24)
.frame(width: 280)
Divider()
VStack(alignment: .leading, spacing: 12) {
HStack {
Text("Preview").font(.headline)
Spacer()
if let preview {
Text("\(preview.width) × \(preview.height) px")
.monospacedDigit().foregroundStyle(.secondary)
}
}
if let preview, let image = NSImage(data: preview.png) {
Image(nsImage: image).resizable().scaledToFit()
.frame(maxWidth: .infinity, maxHeight: .infinity)
.accessibilityLabel(preview.name)
} else {
ContentUnavailableView("No image selected", systemImage: "photo.on.rectangle",
description: Text("Generate an image or open one to preview."))
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
.padding(24)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color(nsColor: .controlBackgroundColor))
}
.fileImporter(isPresented: $importing, allowedContentTypes: [.image]) {
switch $0 {
case .success(let url): receive(url)
case .failure(let error): status = error.localizedDescription
}
}
}
private func receive(_ url: URL) {
let access = url.startAccessingSecurityScopedResource()
defer { if access { url.stopAccessingSecurityScopedResource() } }
do {
preview = try StudioImagePreview(data: Data(contentsOf: url, options: .mappedIfSafe),
name: url.deletingPathExtension().lastPathComponent)
status = ""
} catch { status = error.localizedDescription }
}
private func export() {
guard let preview else { return }
let panel = NSSavePanel()
panel.allowedContentTypes = [.png]
panel.nameFieldStringValue = preview.name + "-preview.png"
guard panel.runModal() == .OK, let url = panel.url else { return }
do {
try preview.png.write(to: url, options: .atomic)
status = "Saved \(url.lastPathComponent)"
} catch { status = error.localizedDescription }
}
}
@available(macOS 15.1, *)
private struct PlaygroundAction: View {
let prompt: String
let completion: (URL) -> Void
@Environment(\.supportsImagePlayground) private var supported
@State private var showing = false
var body: some View {
let description = prompt.trimmingCharacters(in: .whitespacesAndNewlines)
if supported {
Button("Generate Image", systemImage: "sparkles") { showing = true }
.buttonStyle(.borderedProminent)
.disabled(description.isEmpty)
.imagePlaygroundSheet(isPresented: $showing, concepts: [.text(description)], onCompletion: completion)
} else {
Label("Image Playground is unavailable on this Mac.", systemImage: "info.circle")
.font(.caption).foregroundStyle(.secondary)
}
}
}
+351
View File
@@ -0,0 +1,351 @@
import Foundation
import SwiftUI
import CryptoKit
struct HubGGUFAsset: Identifiable, Equatable, Sendable {
let repository: String
let revision: String
let filename: String
let bytes: Int64?
let sha256: String?
var id: String { repository + "@" + revision + "/" + filename }
var url: URL {
URL(string: "https://huggingface.co")!
.appending(path: repository).appending(path: "resolve/\(revision)/\(filename)")
}
var destination: URL {
URL.applicationSupportDirectory
.appending(path: "AIStudio/Models/GGUF/\(repository)/\(revision)/\(filename)")
}
struct RepositoryResult: Decodable, Identifiable {
let id: String
let downloads: Int?
let gated: CatalogModel.HubGating?
let isPrivate: Bool?
enum CodingKeys: String, CodingKey {
case id, downloads, gated
case isPrivate = "private"
}
}
static func search(_ query: String, format: String = "gguf") async throws -> [RepositoryResult] {
var parts = URLComponents()
parts.scheme = "https"
parts.host = "huggingface.co"
parts.path = "/api/models"
parts.queryItems = [
.init(name: "filter", value: format), .init(name: "pipeline_tag", value: "text-generation"),
.init(name: "sort", value: "downloads"), .init(name: "direction", value: "-1"),
.init(name: "limit", value: "25"), .init(name: "search", value: query),
.init(name: "expand", value: "downloads"), .init(name: "expand", value: "gated"),
.init(name: "expand", value: "private")
]
guard let url = parts.url else { throw StudioError("Invalid Hugging Face search.") }
let response = try await WebFetch.load(url, types: ["application/json"])
return try decodeSearch(response.data)
}
static func decodeSearch(_ data: Data) throws -> [RepositoryResult] {
var seen = Set<String>()
return try JSONDecoder().decode([RepositoryResult].self, from: data).filter {
CatalogModel.repositoryParts($0.id) != nil && $0.gated != .restricted &&
$0.isPrivate != true && seen.insert($0.id.lowercased()).inserted
}
}
static func resolve(_ repository: String) async throws -> [Self] {
guard CatalogModel.repositoryParts(repository) != nil else {
throw StudioError("Enter a Hugging Face model ID in owner/model format.")
}
var parts = URLComponents()
parts.scheme = "https"
parts.host = "huggingface.co"
parts.path = "/api/models/" + repository
parts.queryItems = [.init(name: "blobs", value: "true")]
guard let url = parts.url else { throw StudioError("Invalid Hugging Face model ID.") }
let response = try await WebFetch.load(url, types: ["application/json"])
return try decodeRepository(response.data, requested: repository)
}
static func decodeRepository(_ data: Data, requested: String) throws -> [Self] {
struct Repository: Decodable {
enum CodingKeys: String, CodingKey {
case id, sha, gated, siblings
case isPrivate = "private"
}
let id: String
let sha: String
let isPrivate: Bool?
let gated: CatalogModel.HubGating?
let siblings: [HubModelMetadata.File]
}
let info = try JSONDecoder().decode(Repository.self, from: data)
guard info.id.caseInsensitiveCompare(requested) == .orderedSame,
CatalogModel.repositoryParts(info.id) != nil, isHex(info.sha, count: 40),
info.isPrivate != true, info.gated != .restricted else {
throw StudioError("Select a public Hugging Face GGUF repository.")
}
var seen = Set<String>()
let models: [Self] = info.siblings.compactMap { file in
let name = file.rfilename
let lowercase = name.lowercased()
guard CatalogModel.safeComponent(name), lowercase.hasSuffix(".gguf"),
!lowercase.hasPrefix("mmproj"), !lowercase.contains("adapter"),
lowercase.range(of: #"-[0-9]{5}-of-[0-9]{5}\.gguf$"#, options: .regularExpression) == nil,
seen.insert(name).inserted else { return nil }
let bytes = file.lfs?.size ?? file.size
let sha = file.lfs?.sha256.flatMap { isHex($0, count: 64) ? $0.lowercased() : nil }
return Self(repository: info.id, revision: info.sha, filename: name,
bytes: bytes.flatMap { $0 > 0 ? $0 : nil }, sha256: sha)
}
guard !models.isEmpty else { throw StudioError("This repository has no standalone GGUF model files.") }
return models.sorted { $0.filename.localizedStandardCompare($1.filename) == .orderedAscending }
}
private static func isHex(_ text: String, count: Int) -> Bool {
text.count == count && text.allSatisfy { $0.isASCII && $0.isHexDigit }
}
typealias ProgressUpdate = @Sendable (Int64, Int64?) -> Void
typealias Transfer = @Sendable (URL, URL, @escaping ProgressUpdate) async throws -> Void
func install(to destination: URL, progress: @escaping ProgressUpdate,
transfer: Transfer = HubGGUFTransfer.download) async throws -> GGUFModelMetadata {
let manager = FileManager.default
let parent = destination.deletingLastPathComponent()
try manager.createDirectory(at: parent, withIntermediateDirectories: true)
if manager.fileExists(atPath: destination.path) {
return try validatedModel(at: destination)
}
let staging = parent.appending(path: ".download-\(UUID())")
defer { try? manager.removeItem(at: staging) }
try await transfer(url, staging, { written, expected in progress(written, self.bytes ?? expected) })
try Task.checkCancellation()
let model = try validatedModel(at: staging)
try Task.checkCancellation()
try manager.moveItem(at: staging, to: destination)
return GGUFModelMetadata(path: destination.resolvingSymlinksInPath().path, version: model.version,
tensorFormat: model.tensorFormat, architecture: model.architecture,
hasThinkingTemplate: model.hasThinkingTemplate)
}
private func validatedModel(at file: URL) throws -> GGUFModelMetadata {
let fileSize = try file.resourceValues(forKeys: [.fileSizeKey]).fileSize.map(Int64.init)
if let bytes, fileSize != bytes {
throw StudioError("The downloaded file size does not match the repository metadata.")
}
if let sha256 {
let handle = try FileHandle(forReadingFrom: file)
defer { try? handle.close() }
var digest = SHA256()
while let chunk = try handle.read(upToCount: 1_048_576), !chunk.isEmpty {
try Task.checkCancellation()
digest.update(data: chunk)
}
let actual = digest.finalize().map { String(format: "%02x", $0) }.joined()
guard actual == sha256 else { throw StudioError("The download checksum does not match Hugging Face.") }
}
return try GGUFModelMetadata.read(file)
}
}
enum HubGGUFTransfer {
static let download: HubGGUFAsset.Transfer = { source, destination, progress in
let config = URLSessionConfiguration.ephemeral
config.timeoutIntervalForRequest = 60
config.timeoutIntervalForResource = 3600
let result = AsyncThrowingStream<Void, Error>.makeStream()
let observer = Observer(destination: destination, progress: progress, result: result.continuation)
let session = URLSession(configuration: config, delegate: observer, delegateQueue: nil)
defer { session.finishTasksAndInvalidate() }
let task = session.downloadTask(with: source)
// Wait for the delegate to release the temporary file even if the caller cancels.
let completion = Task.detached { for try await _ in result.stream {} }
try await withTaskCancellationHandler {
task.resume()
try await completion.value
} onCancel: {
task.cancel()
}
try Task.checkCancellation()
}
private final class Observer: NSObject, URLSessionDownloadDelegate {
let destination: URL
let progress: HubGGUFAsset.ProgressUpdate
let result: AsyncThrowingStream<Void, Error>.Continuation
init(destination: URL, progress: @escaping HubGGUFAsset.ProgressUpdate,
result: AsyncThrowingStream<Void, Error>.Continuation) {
self.destination = destination
self.progress = progress
self.result = result
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
guard let http = downloadTask.response as? HTTPURLResponse,
http.statusCode == 200, http.url?.scheme == "https" else {
let status = (downloadTask.response as? HTTPURLResponse).map { " (HTTP \($0.statusCode))" } ?? ""
result.finish(throwing: StudioError("Could not download the GGUF file\(status)."))
return
}
do { try FileManager.default.moveItem(at: location, to: destination) }
catch { result.finish(throwing: error) }
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
result.finish(throwing: error)
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
progress(totalBytesWritten, totalBytesExpectedToWrite > 0 ? totalBytesExpectedToWrite : nil)
}
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
completionHandler(request.url?.scheme == "https" ? request : nil)
}
}
}
struct HubGGUFDownloads: View {
@AppStorage(GGUFModelMetadata.libraryKey) private var stored = Data()
@State private var repository = ""
@State private var repositories: [HubGGUFAsset.RepositoryResult] = []
@State private var assets: [HubGGUFAsset] = []
@State private var lookupInProgress = false
@State private var download: Task<Void, Never>?
@State private var downloadingID: String?
@State private var written: Int64 = 0
@State private var expected: Int64?
@State private var notice: String?
@State private var failure: String?
var body: some View {
Section("Hugging Face · GGUF") {
HStack {
TextField("Search Hugging Face", text: $repository, prompt: Text("Model name or owner/model"))
.textFieldStyle(.roundedBorder)
.onSubmit(lookup)
Button(repository.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? "Browse" : "Search", action: lookup)
.disabled(lookupInProgress || download != nil)
if lookupInProgress { ProgressView().controlSize(.small) }
}
ForEach(repositories) { result in
HStack {
VStack(alignment: .leading, spacing: 3) {
Text(result.id).lineLimit(1).help(result.id)
if let downloads = result.downloads {
Text("\(downloads.formatted()) downloads").font(.caption).foregroundStyle(.secondary)
}
}
Spacer()
Button("View Files") { lookup(result.id) }.disabled(lookupInProgress || download != nil)
}
}
ForEach(assets) { asset in
VStack(alignment: .leading, spacing: 6) {
HStack {
VStack(alignment: .leading, spacing: 3) {
Text(asset.filename).fontWeight(.medium).lineLimit(1).help(asset.filename)
Text("GGUF · " + ModelLibrarySize.label(asset.bytes))
.font(.caption).foregroundStyle(.secondary)
ModelMemoryWarning(bytes: asset.bytes)
}
Spacer()
if downloadingID == asset.id {
Button("Cancel") { download?.cancel() }
} else if isRegistered(asset) {
Label("Installed", systemImage: "checkmark.circle.fill").foregroundStyle(.secondary)
} else {
Button("Download") { start(asset) }.disabled(download != nil)
}
}
if downloadingID == asset.id {
let label = ByteCountFormatter.string(fromByteCount: written, countStyle: .file)
if let expected, expected > 0 {
ProgressView(label, value: Double(min(written, expected)), total: Double(expected))
.accessibilityLabel("Downloading " + asset.filename)
} else {
ProgressView("Downloading · " + label)
}
}
}
.padding(.vertical, 3)
}
if let notice { Label(notice, systemImage: "checkmark.circle").foregroundStyle(.secondary) }
if let failure { Label(failure, systemImage: "exclamationmark.triangle").foregroundStyle(.orange) }
}
}
private func isRegistered(_ asset: HubGGUFAsset) -> Bool {
let path = asset.destination.resolvingSymlinksInPath().path
return GGUFModelMetadata.library(in: stored).contains { $0.path == path } &&
FileManager.default.fileExists(atPath: path)
}
private func lookup() { lookup(repository) }
private func lookup(_ term: String) {
let query = term.trimmingCharacters(in: .whitespacesAndNewlines)
guard !lookupInProgress, download == nil else { return }
lookupInProgress = true
failure = nil
notice = nil
assets = []
repositories = []
Task {
defer { lookupInProgress = false }
do {
if query.contains("/") {
repository = query
assets = try await HubGGUFAsset.resolve(query)
} else {
repositories = try await HubGGUFAsset.search(query)
if repositories.isEmpty { notice = "No public GGUF repositories found." }
}
} catch { failure = error.localizedDescription }
}
}
private func start(_ asset: HubGGUFAsset) {
guard download == nil else { return }
downloadingID = asset.id
written = 0
expected = asset.bytes
notice = nil
failure = nil
download = Task {
defer {
download = nil
downloadingID = nil
}
do {
let model = try await asset.install(to: asset.destination, progress: { bytes, expectedBytes in
Task { @MainActor in
guard downloadingID == asset.id, bytes >= written else { return }
written = bytes
expected = expectedBytes
}
})
stored = try GGUFModelMetadata.register([model], in: stored)
notice = "Installed \(asset.filename)"
} catch {
if Task.isCancelled { notice = "Download cancelled" }
else { failure = error.localizedDescription }
}
}
}
}
+28
View File
@@ -0,0 +1,28 @@
import Foundation
enum GGUFHeader {
enum ValidationError: LocalizedError {
case invalidMagic
case unsupportedVersion(UInt32)
var errorDescription: String? {
switch self {
case .invalidMagic: "The file does not have a valid GGUF header."
case .unsupportedVersion(let version): "GGUF version \(version) is unsupported."
}
}
}
static func version(in data: Data) throws -> UInt32 {
guard data.count >= 8, data.prefix(4).elementsEqual("GGUF".utf8) else {
throw ValidationError.invalidMagic
}
let version = data.withUnsafeBytes { bytes in
UInt32(littleEndian: bytes.loadUnaligned(fromByteOffset: 4, as: UInt32.self))
}
guard version == 2 || version == 3 else {
throw ValidationError.unsupportedVersion(version)
}
return version
}
}
+277
View File
@@ -0,0 +1,277 @@
import SwiftUI
import UniformTypeIdentifiers
import Metal
import llama
struct GGUFModelMetadata: Codable, Equatable, Sendable {
static let libraryKey = "ggufLibrary"
let path: String
let version: UInt32
let tensorFormat: String
let architecture: String
var hasThinkingTemplate: Bool? = nil
var supportsThinking: Bool {
hasThinkingTemplate ?? ["qwen35", "qwen35moe"].contains(architecture)
}
var architectureName: String {
switch architecture {
case "llama": "Llama"
case "qwen35", "qwen35moe": "Qwen3.5"
case "mpt": "MPT"
case "openelm": "OpenELM"
default: architecture
}
}
static func library(in data: Data) -> [Self] {
(try? JSONDecoder().decode([Self].self, from: data)) ?? []
}
static func register(_ additions: [Self], in data: Data) throws -> Data {
var entries = library(in: data)
for model in additions {
entries.removeAll { $0.path == model.path }
entries.append(model)
}
return try JSONEncoder().encode(entries.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending })
}
static func read(_ url: URL) throws -> Self {
let file = try FileHandle(forReadingFrom: url)
defer { try? file.close() }
let version = try GGUFHeader.version(in: file.read(upToCount: 8) ?? Data())
guard let model = gguf_init_from_file(url.path, .init(no_alloc: true, ctx: nil)) else {
throw StudioError("Could not read the GGUF metadata.")
}
defer { gguf_free(model) }
let architectureKey = gguf_find_key(model, "general.architecture")
let tensorCount = gguf_get_n_tensors(model)
guard tensorCount > 0, architectureKey >= 0, gguf_get_kv_type(model, architectureKey) == GGUF_TYPE_STRING,
let architecture = gguf_get_val_str(model, architectureKey) else {
throw StudioError("This GGUF file does not contain model weights and architecture metadata.")
}
let templateKey = gguf_find_key(model, "tokenizer.chat_template")
guard templateKey >= 0, gguf_get_kv_type(model, templateKey) == GGUF_TYPE_STRING,
let template = gguf_get_val_str(model, templateKey), template.pointee != 0 else {
throw StudioError("This model has no embedded chat template. Choose a GGUF chat or instruct model.")
}
let fileSize = try file.seekToEnd()
let dataOffset = UInt64(gguf_get_data_offset(model))
guard dataOffset < fileSize else { throw StudioError("This GGUF file is incomplete.") }
let dataSize = fileSize - dataOffset
var bytesByType: [String: UInt64] = [:]
for index in 0..<tensorCount {
let type = String(cString: ggml_type_name(gguf_get_tensor_type(model, index))).uppercased()
let offset = UInt64(gguf_get_tensor_offset(model, index))
let size = UInt64(gguf_get_tensor_size(model, index))
guard offset <= dataSize, size <= dataSize - offset,
bytesByType[type, default: 0] <= dataSize - size else {
throw StudioError("This GGUF file contains incomplete tensor data.")
}
bytesByType[type, default: 0] += size
}
let primary = bytesByType.sorted {
$0.value == $1.value ? $0.key < $1.key : $0.value > $1.value
}.first?.key ?? "Unknown"
return Self(path: url.path, version: version, tensorFormat: primary, architecture: String(cString: architecture),
hasThinkingTemplate: GGUFThinking.supports(String(cString: template)))
}
}
enum LocalModelImport: Equatable, Sendable {
case mlx(String)
case gguf(GGUFModelMetadata)
static var lmStudioFolder: URL { URL.homeDirectory.appending(path: ".lmstudio/models") }
static func discover(in folder: URL) throws -> [Self] {
let files = FileManager.default
guard let entries = files.enumerator(at: folder, includingPropertiesForKeys: [.isDirectoryKey],
options: [.skipsHiddenFiles, .skipsPackageDescendants]) else {
throw StudioError("Could not open the model library folder.")
}
var models: [Self] = []
for case let url as URL in entries {
try Task.checkCancellation()
if (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true {
if MLXLibrary.isModel(at: url) {
models.append(.mlx(url.resolvingSymlinksInPath().path))
entries.skipDescendants()
}
} else if url.pathExtension.lowercased() == "gguf",
!url.lastPathComponent.lowercased().hasPrefix("mmproj"),
let model = try? inspect(url) {
models.append(model)
}
}
return models
}
static func inspect(_ source: URL) throws -> Self {
guard source.isFileURL else { throw StudioError("Choose a local model file or folder.") }
let scoped = source.startAccessingSecurityScopedResource()
defer { if scoped { source.stopAccessingSecurityScopedResource() } }
let url = source.resolvingSymlinksInPath().standardizedFileURL
let values = try url.resourceValues(forKeys: [.isDirectoryKey, .isRegularFileKey])
if values.isDirectory == true {
guard MLXLibrary.isModel(at: url) else {
throw StudioError("Choose a complete MLX folder with a readable configuration and all safetensors weights.")
}
return .mlx(url.path)
}
guard values.isRegularFile == true else {
throw StudioError("Choose a regular GGUF file or an MLX model folder.")
}
return .gguf(try GGUFModelMetadata.read(url))
}
}
struct GGUFModels: View {
let selection: String?
var inUse = false
var filter = ""
var selectionDisabled = false
let select: (String) -> Void
@AppStorage(GGUFModelMetadata.libraryKey) private var stored = Data()
@State private var showingImporter = false
@State private var inspecting = false
@State private var error: String?
@State private var notice: String?
private var models: [GGUFModelMetadata] {
GGUFModelMetadata.library(in: stored)
}
private var filteredModels: [GGUFModelMetadata] {
let query = filter.trimmingCharacters(in: .whitespacesAndNewlines)
return models.filter { model in
query.isEmpty || [URL(fileURLWithPath: model.path).lastPathComponent,
model.architectureName, model.tensorFormat, "GGUF"].contains {
$0.localizedStandardContains(query)
}
}
}
var body: some View {
Section {
HStack {
VStack(alignment: .leading, spacing: 4) {
Label("Local GGUF", systemImage: "cpu")
.font(.headline)
memorySummary
}
Spacer()
Button("Import…", systemImage: "plus") { showingImporter = true }
.disabled(inspecting)
.accessibilityLabel("Import GGUF model")
}
if models.isEmpty && !inspecting {
Text("Import a GGUF chat model to run it on this Mac.")
.foregroundStyle(.secondary)
}
if !models.isEmpty && filteredModels.isEmpty {
Text("No matching GGUF models").foregroundStyle(.secondary)
}
ForEach(filteredModels, id: \.path) { model in
modelRow(model)
}
if inspecting {
ProgressView("Inspecting model…").controlSize(.small)
} else if let error {
Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(.orange)
} else if let notice {
Label(notice, systemImage: "checkmark.circle").foregroundStyle(.secondary)
}
}
.fileImporter(isPresented: $showingImporter, allowedContentTypes: [UTType(filenameExtension: "gguf") ?? .data]) {
switch $0 {
case .success(let url): Task { await importModel(url) }
case .failure(let failure): error = failure.localizedDescription
}
}
}
private var memorySummary: some View {
let systemMemory = ByteCountFormatter.string(fromByteCount: Int64(ProcessInfo.processInfo.physicalMemory), countStyle: .memory)
let recommended = MTLCreateSystemDefaultDevice().map {
ByteCountFormatter.string(fromByteCount: Int64($0.recommendedMaxWorkingSetSize), countStyle: .memory)
}
return Text(recommended.map { "Metal budget \($0) · Unified memory \(systemMemory)" } ?? "Metal unavailable")
.font(.caption)
.foregroundStyle(.secondary)
.help("Metal budget is the GPU’s recommended working set. Model weights and the context cache share system memory.")
}
private func importModel(_ url: URL) async {
inspecting = true
error = nil
notice = nil
defer { inspecting = false }
do {
let metadata = try await Task.detached(priority: .userInitiated) {
guard case .gguf(let model) = try LocalModelImport.inspect(url) else {
throw StudioError("Choose a GGUF chat model file.")
}
return model
}.value
stored = try GGUFModelMetadata.register([metadata], in: stored)
notice = "Added \(url.lastPathComponent)"
} catch {
self.error = error.localizedDescription
}
}
private func modelRow(_ model: GGUFModelMetadata) -> some View {
let url = URL(fileURLWithPath: model.path)
let name = url.deletingPathExtension().lastPathComponent
let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize
let active = selection.map {
URL(fileURLWithPath: $0).resolvingSymlinksInPath().standardizedFileURL.path ==
url.resolvingSymlinksInPath().standardizedFileURL.path
} ?? false
return HStack(spacing: 11) {
Image(systemName: active ? "checkmark.circle.fill" : "shippingbox")
.font(.title3)
.foregroundStyle(active ? Color.accentColor : Color.secondary)
.frame(width: 24)
VStack(alignment: .leading, spacing: 4) {
Text(name).fontWeight(active ? .semibold : .regular).lineLimit(1)
Text([
"GGUF v\(model.version)", model.architectureName, model.tensorFormat,
size.map { ByteCountFormatter.string(fromByteCount: Int64($0), countStyle: .file) } ?? "File missing"
].joined(separator: " · "))
.font(.caption)
.foregroundStyle(.secondary)
.help("Architecture: \(model.architecture). Quantisation shows the tensor format that accounts for the most weight bytes.")
ModelMemoryWarning(bytes: size.map(Int64.init))
}
Spacer()
if active {
Text(inUse ? "In use" : "Active")
.font(.caption.weight(.semibold))
.foregroundStyle(Color.accentColor)
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(Color.accentColor.opacity(0.12), in: Capsule())
} else {
Button("Use") { select(model.path) }.disabled(size == nil || selectionDisabled)
Button {
do { stored = try JSONEncoder().encode(models.filter { $0.path != model.path }) }
catch { self.error = error.localizedDescription }
} label: {
Image(systemName: "minus.circle")
}
.buttonStyle(.borderless)
.disabled(selectionDisabled)
.accessibilityLabel("Remove \(name) from library")
}
}
.padding(.vertical, 6)
.listRowBackground(active ? Color.accentColor.opacity(0.10) : nil)
.help(model.path)
}
}
+190
View File
@@ -0,0 +1,190 @@
import Foundation
import llama
struct GGUFProvider: InferenceProvider {
private static let engine = GGUFEngine()
func generate(_ request: InferenceRequest) -> AsyncThrowingStream<Delta, Error> {
streaming { continuation in
try await Self.engine.generate(request, continuation)
}
}
}
private actor GGUFEngine {
init() { llama_backend_init() }
func generate(_ request: InferenceRequest, _ output: AsyncThrowingStream<Delta, Error>.Continuation) throws {
try Task.checkCancellation()
guard !request.messages.contains(where: { $0.imagePNG != nil }) else {
throw StudioError("This GGUF backend supports text input.")
}
guard !request.parameters.json else {
throw StudioError("JSON mode is unavailable for local GGUF chat. Turn it off in Generation settings.")
}
guard ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU) != nil else { throw StudioError("Metal acceleration is unavailable.") }
let file = URL(fileURLWithPath: request.model)
guard FileManager.default.isReadableFile(atPath: file.path) else {
throw StudioError("Cannot read \(file.lastPathComponent). Import the model again if it was moved.")
}
var modelSettings = llama_model_default_params()
modelSettings.n_gpu_layers = .max
guard let model = llama_model_load_from_file(request.model, modelSettings) else {
throw StudioError("llama.cpp could not load \(file.lastPathComponent). Check that the download is complete and the file contains chat model weights.")
}
defer { llama_model_free(model) }
try Task.checkCancellation()
let vocab = llama_model_get_vocab(model)
let formatted = try format(LocalChatHistory.prepare(request.messages), model: model)
let thinking = GGUFThinking.prepare(formatted.prompt, template: formatted.template, mode: request.thinking)
let prompt = thinking.prompt
var thinkingOutput = ThinkingOutput(prefilled: thinking.prefilled)
func emit(_ text: String) {
if thinking.supported {
for delta in thinkingOutput.append(text) { output.yield(delta) }
} else if !text.isEmpty {
output.yield(.answer(text))
}
}
var tokens = [llama_token](repeating: 0, count: prompt.utf8.count + 32)
var count = tokenize(prompt, vocab: vocab, tokens: &tokens)
if count < 0 {
tokens = [llama_token](repeating: 0, count: -Int(count))
count = tokenize(prompt, vocab: vocab, tokens: &tokens)
}
let settings = request.parameters
var contextSettings = llama_context_default_params()
contextSettings.n_ctx = UInt32(min(settings.context ?? 4096, Int(llama_model_n_ctx_train(model))))
contextSettings.n_batch = min(512, contextSettings.n_ctx)
contextSettings.n_ubatch = min(contextSettings.n_ubatch, contextSettings.n_batch)
guard count > 0, UInt32(count) < contextSettings.n_ctx else {
throw StudioError("The prompt exceeds the GGUF model’s context window.")
}
guard let context = llama_init_from_model(model, contextSettings) else {
throw StudioError("llama.cpp could not allocate the GGUF context.")
}
defer { llama_free(context) }
let sampler = llama_sampler_chain_init(llama_sampler_chain_default_params())
defer { llama_sampler_free(sampler) }
llama_sampler_chain_add(sampler, llama_sampler_init_penalties(
llama_vocab_n_tokens(vocab), Int32(settings.repeatLastN ?? 64), Float(settings.repeatPenalty ?? 1),
Float(settings.frequencyPenalty ?? 0), Float(settings.presencePenalty ?? 0)))
if settings.temperature == 0 {
llama_sampler_chain_add(sampler, llama_sampler_init_greedy())
} else {
llama_sampler_chain_add(sampler, llama_sampler_init_top_k(Int32(settings.topK ?? 40)))
llama_sampler_chain_add(sampler, llama_sampler_init_top_p(Float(settings.topP ?? 0.95), 1))
llama_sampler_chain_add(sampler, llama_sampler_init_min_p(Float(settings.minP ?? 0), 1))
llama_sampler_chain_add(sampler, llama_sampler_init_temp(Float(settings.temperature ?? 0.8)))
llama_sampler_chain_add(sampler, llama_sampler_init_dist(settings.seed.map { UInt32(truncatingIfNeeded: $0) } ?? UInt32.max))
}
output.yield(.backend("GGUF · Metal"))
try tokens.withUnsafeMutableBufferPointer { buffer in
for offset in stride(from: 0, to: Int(count), by: Int(contextSettings.n_batch)) {
try Task.checkCancellation()
let length = min(Int(contextSettings.n_batch), Int(count) - offset)
try decode(context, buffer.baseAddress?.advanced(by: offset), count: Int32(length))
}
}
var pending = Data()
var produced = 0
var heldText = ""
let stops = settings.stop.filter { !$0.isEmpty }
let start = ContinuousClock.now
let limit = min(settings.maxTokens ?? 1024, Int(contextSettings.n_ctx) - Int(count))
for index in 0..<limit {
try Task.checkCancellation()
var token = llama_sampler_sample(sampler, context, -1)
if llama_vocab_is_eog(vocab, token) { break }
produced += 1
var bytes = [Int8](repeating: 0, count: 128)
var size = llama_token_to_piece(vocab, token, &bytes, Int32(bytes.count), 0, false)
if size < 0 {
bytes = [Int8](repeating: 0, count: -Int(size))
size = llama_token_to_piece(vocab, token, &bytes, Int32(bytes.count), 0, false)
}
if size > 0 {
pending.append(contentsOf: bytes.prefix(Int(size)).map { UInt8(bitPattern: $0) })
}
if let text = String(data: pending, encoding: .utf8), !text.isEmpty {
pending.removeAll(keepingCapacity: true)
heldText += text
if let end = stops.compactMap({ heldText.range(of: $0)?.lowerBound }).min() {
let visible = String(heldText[..<end])
if !visible.isEmpty { emit(visible) }
heldText = ""
break
}
let maxPrefix = stops.map(\.count).max() ?? 1
let keep = min(heldText.count, maxPrefix - 1)
let visible = String(heldText.dropLast(keep))
heldText = String(heldText.suffix(keep))
if !visible.isEmpty { emit(visible) }
}
if index + 1 < limit { try decode(context, &token, count: 1) }
}
try Task.checkCancellation()
heldText += String(decoding: pending, as: UTF8.self)
if !heldText.isEmpty { emit(heldText) }
if thinking.supported {
for delta in thinkingOutput.finish() { output.yield(delta) }
}
let elapsed = (ContinuousClock.now - start).components
let seconds = Double(elapsed.seconds) + Double(elapsed.attoseconds) / 1e18
output.yield(.metrics(.init(tokens: produced, seconds: seconds)))
}
private func decode(_ context: OpaquePointer, _ tokens: UnsafeMutablePointer<llama_token>?, count: Int32) throws {
guard llama_decode(context, llama_batch_get_one(tokens, count)) == 0 else {
throw StudioError("llama.cpp could not decode the GGUF prompt or response.")
}
}
private func tokenize(_ prompt: String, vocab: OpaquePointer?, tokens: inout [llama_token]) -> Int32 {
llama_tokenize(vocab, prompt, Int32(prompt.utf8.count), &tokens, Int32(tokens.count), true, true)
}
private func format(_ messages: [Message], model: OpaquePointer) throws -> (prompt: String, template: String) {
let roles = messages.map { strdup($0.role.rawValue) }
let contents = messages.map { strdup($0.content.replacingOccurrences(of: "\0", with: "�")) }
defer {
roles.forEach { free($0) }
contents.forEach { free($0) }
}
let chat = zip(roles, contents).map { llama_chat_message(role: UnsafePointer($0), content: UnsafePointer($1)) }
guard let template = llama_model_chat_template(model, nil) else {
throw StudioError("This GGUF file has no chat template. Import an instruct or chat model.")
}
let size = llama_chat_apply_template(template, chat, chat.count, true, nil, 0)
guard size > 0 else { throw StudioError("llama.cpp does not support this GGUF chat template.") }
var buffer = [CChar](repeating: 0, count: Int(size) + 1)
let written = llama_chat_apply_template(template, chat, chat.count, true, &buffer, Int32(buffer.count))
guard written == size else { throw StudioError("llama.cpp could not format the chat.") }
return (String(cString: buffer), String(cString: template))
}
}
enum GGUFThinking {
private static let assistantMarker = "<|im_start|>assistant\n"
static func supports(_ template: String) -> Bool {
["enable_thinking", "<think>", "</think>", "<|im_start|>assistant"].allSatisfy { template.contains($0) }
}
static func prepare(_ prompt: String, template: String, mode: Thinking) -> (prompt: String, supported: Bool, prefilled: Bool) {
let supported = supports(template)
guard supported, prompt.hasSuffix(assistantMarker) else {
return (prompt, supported, supported && prompt.hasSuffix("<think>\n"))
}
switch mode {
case .on: return (prompt + "<think>\n", true, true)
case .off: return (prompt + "<think>\n\n</think>\n\n", true, false)
default: return (prompt, true, false)
}
}
}
+90 -4
View File
@@ -12,6 +12,8 @@ struct ChatModelChoice: Equatable, Codable {
enum Backend: String, Codable { enum Backend: String, Codable {
case ollama = "Ollama" case ollama = "Ollama"
case mlx = "MLX" case mlx = "MLX"
case gguf = "GGUF"
case coreML = "Core ML"
case compatible = "Compatible API" case compatible = "Compatible API"
} }
@@ -20,7 +22,8 @@ struct ChatModelChoice: Equatable, Codable {
var displayName: String { var displayName: String {
guard !model.isEmpty else { return "Choose Model" } guard !model.isEmpty else { return "Choose Model" }
return backend == .mlx ? URL(fileURLWithPath: model).lastPathComponent : model if [.gguf, .coreML].contains(backend) { return URL(fileURLWithPath: model).deletingPathExtension().lastPathComponent }
return backend == .mlx ? MLXLibrary.displayName(for: URL(fileURLWithPath: model)) : model
} }
static func read(_ data: Data) -> [UUID: Self] { static func read(_ data: Data) -> [UUID: Self] {
@@ -28,11 +31,21 @@ struct ChatModelChoice: Equatable, Codable {
} }
func thinkingMode(_ mode: Thinking) -> Thinking { func thinkingMode(_ mode: Thinking) -> Thinking {
if backend == .mlx && ![Thinking.automatic, .off, .on].contains(mode) { return .automatic } if [.mlx, .gguf].contains(backend) && ![Thinking.automatic, .off, .on].contains(mode) { return .automatic }
return mode return mode
} }
} }
enum ChatThinkingControl {
static func options(backend: ChatModelChoice.Backend, supportsLocalThinking: Bool) -> [Thinking] {
switch backend {
case .ollama: Thinking.allCases
case .gguf, .mlx: supportsLocalThinking ? [.automatic, .off, .on] : [.automatic]
case .compatible, .coreML: [.automatic]
}
}
}
enum Role: String, Codable, Sendable { case system, user, assistant } enum Role: String, Codable, Sendable { case system, user, assistant }
struct WebReplySource: Identifiable, Equatable, Codable, Sendable { struct WebReplySource: Identifiable, Equatable, Codable, Sendable {
@@ -59,12 +72,38 @@ struct Message: Identifiable, Equatable, Sendable {
var documentNames: [String] = [] var documentNames: [String] = []
var documentCitations: [DocumentCitation] = [] var documentCitations: [DocumentCitation] = []
var imagePNG: Data? = nil var imagePNG: Data? = nil
var performance: GenerationMeasurement? = nil
var imageDataURL: String? { var imageDataURL: String? {
imagePNG.map { "data:image/png;base64," + $0.base64EncodedString() } imagePNG.map { "data:image/png;base64," + $0.base64EncodedString() }
} }
} }
enum LocalChatHistory {
static func prepare(_ messages: [Message]) -> [Message] {
var system: [String] = []
var earlierReplies: [String] = []
var turns: [Message] = []
for message in messages {
if message.role == .system {
system.append(message.inferenceContent)
} else if turns.isEmpty && message.role == .assistant {
earlierReplies.append(message.inferenceContent)
} else if turns.last?.role == message.role, let last = turns.indices.last {
turns[last].content += "\n\n" + message.inferenceContent
} else {
turns.append(.init(role: message.role, content: message.inferenceContent))
}
}
if !earlierReplies.isEmpty, let first = turns.indices.first {
let context = earlierReplies.joined(separator: "\n\n")
turns[first].content = "Earlier assistant replies:\n" + context + "\n\nUser messages:\n" + turns[first].content
}
if !system.isEmpty { turns.insert(.init(role: .system, content: system.joined(separator: "\n\n")), at: 0) }
return turns
}
}
private extension Message { private extension Message {
var inferenceContent: String { var inferenceContent: String {
guard !documentCitations.isEmpty else { return content } guard !documentCitations.isEmpty else { return content }
@@ -196,18 +235,30 @@ enum Router {
continuation.yield(delta) continuation.yield(delta)
} }
try Task.checkCancellation() try Task.checkCancellation()
if !committed { throw StudioError("The model returned an empty response.") }
} catch { } catch {
try Task.checkCancellation() try Task.checkCancellation()
guard !committed, !(error is CancellationError), (error as? URLError)?.code != .cancelled, guard !committed, !(error is CancellationError), (error as? URLError)?.code != .cancelled,
let fallback else { throw error } let fallback else { throw error }
do { do {
var producedOutput = false
for try await delta in fallback() { for try await delta in fallback() {
try Task.checkCancellation() try Task.checkCancellation()
switch delta {
case .answer(let text), .thinking(let text):
producedOutput = producedOutput || !text.isEmpty
case .committed: producedOutput = true
case .backend, .metrics: break
}
continuation.yield(delta) continuation.yield(delta)
} }
try Task.checkCancellation()
if !producedOutput { throw StudioError("The model returned an empty response.") }
} catch let fallbackError { } catch let fallbackError {
try Task.checkCancellation() try Task.checkCancellation()
if fallbackError is CancellationError { throw fallbackError } if fallbackError is CancellationError || (fallbackError as? URLError)?.code == .cancelled {
throw fallbackError
}
throw StudioError("\(primaryName): \(error.localizedDescription) MLX: \(fallbackError.localizedDescription)") throw StudioError("\(primaryName): \(error.localizedDescription) MLX: \(fallbackError.localizedDescription)")
} }
} }
@@ -226,7 +277,7 @@ struct ProviderMetrics: Codable, Equatable, Sendable {
} }
} }
struct GenerationMeasurement: Codable, Identifiable { struct GenerationMeasurement: Codable, Identifiable, Equatable, Sendable {
var id = UUID() var id = UUID()
static let key = "generationMeasurements" static let key = "generationMeasurements"
let backend: String let backend: String
@@ -235,6 +286,13 @@ struct GenerationMeasurement: Codable, Identifiable {
let characters: Int let characters: Int
let provider: ProviderMetrics? let provider: ProviderMetrics?
let outcome: String let outcome: String
var model: String? = nil
var recordedAt: Date? = nil
var benchmark: Bool? = nil
static func history(_ data: Data) -> [Self] {
(try? JSONDecoder().decode([Self].self, from: data)) ?? []
}
var charactersPerSecond: Double? { var charactersPerSecond: Double? {
guard let firstOutput, seconds > firstOutput, characters > 0 else { return nil } guard let firstOutput, seconds > firstOutput, characters > 0 else { return nil }
@@ -243,6 +301,34 @@ struct GenerationMeasurement: Codable, Identifiable {
} }
} }
struct GenerationCapture {
let start: Double
private(set) var firstOutput: Double?
private(set) var characters = 0
private var backend: String?
private var provider: ProviderMetrics?
mutating func observe(_ delta: Delta, at time: Double) {
switch delta {
case .answer(let text), .thinking(let text):
if !text.isEmpty {
if firstOutput == nil { firstOutput = max(0, time - start) }
characters += text.count
}
case .backend(let name): backend = name
case .metrics(let metrics): provider = metrics
case .committed: break
}
}
func finish(at time: Double, requested: String, model: String?, outcome: String,
benchmark: Bool = false) -> GenerationMeasurement {
GenerationMeasurement(backend: backend ?? requested, firstOutput: firstOutput,
seconds: max(0, time - start), characters: characters, provider: provider, outcome: outcome,
model: model, recordedAt: Date(), benchmark: benchmark)
}
}
enum PromptMode: String, CaseIterable, Identifiable { enum PromptMode: String, CaseIterable, Identifiable {
case standard = "Default" case standard = "Default"
case concise = "Concise" case concise = "Concise"
+16 -6
View File
@@ -783,9 +783,10 @@ enum GiteaRepositoryLookup {
static func entries(client: any MCPToolClient) async throws -> [String] { static func entries(client: any MCPToolClient) async throws -> [String] {
let data = try await client.callTool("list_repositories", argumentsJSON: Data("{}".utf8)) let data = try await client.callTool("list_repositories", argumentsJSON: Data("{}".utf8))
guard let result = try JSONSerialization.jsonObject(with: data) as? [String: Any], try MCPToolResponse.check(data, tool: "list_repositories")
result["isError"] as? Bool != true else { let result = try JSONSerialization.jsonObject(with: data)
throw StudioError("The connected Gitea server could not list its repositories.") guard result is [String: Any] || result is [Any] else {
throw StudioError("Gitea returned an unexpected repository response.")
} }
var entries: [String] = [] var entries: [String] = []
var seen: Set<String> = [] var seen: Set<String> = []
@@ -796,7 +797,7 @@ enum GiteaRepositoryLookup {
let link = object["html_url"] as? String let link = object["html_url"] as? String
entries.append(link.map { "\(name) — \($0)" } ?? name) entries.append(link.map { "\(name) — \($0)" } ?? name)
} else { } else {
for field in ["result", "structuredContent", "content", "text"] { for field in ["structuredContent", "result", "data", "repositories", "content", "text"] {
if let nested = object[field] { collect(nested) } if let nested = object[field] { collect(nested) }
} }
} }
@@ -955,7 +956,16 @@ struct ChatFilePreview: Identifiable, Sendable {
guard values.isRegularFile == true, let size = values.fileSize, size <= 20_000_000 else { guard values.isRegularFile == true, let size = values.fileSize, size <= 20_000_000 else {
throw StudioError("Choose an image file up to 20 MB.") throw StudioError("Choose an image file up to 20 MB.")
} }
guard let source = CGImageSourceCreateWithURL(url as CFURL, nil), return try imagePreview(source: CGImageSourceCreateWithURL(url as CFURL, nil), name: url.lastPathComponent)
}
static func pastedImage(_ data: Data) throws -> Self {
guard data.count <= 20_000_000 else { throw StudioError("Choose an image up to 20 MB.") }
return try imagePreview(source: CGImageSourceCreateWithData(data as CFData, nil), name: "Pasted Image.png")
}
private static func imagePreview(source: CGImageSource?, name: String) throws -> Self {
guard let source,
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
let width = properties[kCGImagePropertyPixelWidth] as? Int, let width = properties[kCGImagePropertyPixelWidth] as? Int,
let height = properties[kCGImagePropertyPixelHeight] as? Int, width > 0, height > 0 else { let height = properties[kCGImagePropertyPixelHeight] as? Int, width > 0, height > 0 else {
@@ -983,7 +993,7 @@ struct ChatFilePreview: Identifiable, Sendable {
throw StudioError("The image exceeds 20 MB when converted to PNG.") throw StudioError("The image exceeds 20 MB when converted to PNG.")
} }
let text = (try? recognizeText(in: image)) ?? "" let text = (try? recognizeText(in: image)) ?? ""
return Self(name: url.lastPathComponent, text: text, imagePNG: png as Data) return Self(name: name, text: text, imagePNG: png as Data)
} }
private static func pdfText(at url: URL) throws -> String { private static func pdfText(at url: URL) throws -> String {
+11
View File
@@ -850,6 +850,17 @@ struct RemoteKnowledgeStack: Identifiable {
let supportsInventory: Bool let supportsInventory: Bool
} }
enum MCPToolResponse {
static func check(_ data: Data, tool: String) throws {
guard let result = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
result["isError"] as? Bool == true else { return }
let content = result["content"] as? [[String: Any]] ?? []
let details = content.compactMap { $0["text"] as? String }.joined(separator: "\n")
let message = details.isEmpty ? "The server reported a tool error." : String(details.prefix(4_000))
throw StudioError("\(tool) failed. \(message)")
}
}
struct MCPConnectionState { struct MCPConnectionState {
var toolset: ActiveToolset? = nil var toolset: ActiveToolset? = nil
var progress: String? = nil var progress: String? = nil
+60 -12
View File
@@ -1,6 +1,7 @@
import Foundation import Foundation
import MLXLLM import MLXLLM
import MLXLMCommon import MLXLMCommon
import Tokenizers
actor MLXProvider: InferenceProvider { actor MLXProvider: InferenceProvider {
private var loaded: (directory: String, container: ModelContainer)? private var loaded: (directory: String, container: ModelContainer)?
@@ -20,6 +21,8 @@ actor MLXProvider: InferenceProvider {
loaded.map { URL(fileURLWithPath: $0.directory).lastPathComponent } loaded.map { URL(fileURLWithPath: $0.directory).lastPathComponent }
} }
func modelDirectory() -> String? { loaded?.directory }
func unload() { func unload() {
guard !active else { return } guard !active else { return }
eviction?.cancel() eviction?.cancel()
@@ -59,15 +62,15 @@ actor MLXProvider: InferenceProvider {
if let loaded, loaded.directory == directory { if let loaded, loaded.directory == directory {
model = loaded.container model = loaded.container
} else { } else {
loaded = nil
let url = URL(fileURLWithPath: directory, isDirectory: true) let url = URL(fileURLWithPath: directory, isDirectory: true)
guard FileManager.default.fileExists(atPath: url.appending(path: "config.json").path) else { guard MLXLibrary.isModel(at: url) else {
throw StudioError("Select an MLX model folder containing config.json and model weights.") throw StudioError("Select a complete MLX model folder with a readable config.json and all safetensors weight files.")
} }
if let weightLimit, try MLXRuntimeLimits.weightBytes(in: url) > weightLimit { if let weightLimit, try MLXRuntimeLimits.weightBytes(in: url) > weightLimit {
throw StudioError("The model’s weight files exceed the configured MLX weight limit.") throw StudioError("The model’s weight files exceed the configured MLX weight limit.")
} }
model = try await LLMModelFactory.shared.loadContainer(configuration: .init(directory: url)) loaded = nil
model = try await LLMModelFactory.shared.loadContainer(from: url, using: StudioMLXTokenizerLoader())
try Task.checkCancellation() try Task.checkCancellation()
loaded = (directory, model) loaded = (directory, model)
} }
@@ -92,14 +95,14 @@ actor MLXProvider: InferenceProvider {
} }
let directory = request.model let directory = request.model
let model = try await container(for: directory) let model = try await container(for: directory)
let history: [Chat.Message] = request.messages.map { let history: [Chat.Message] = LocalChatHistory.prepare(request.messages).map {
switch $0.role { switch $0.role {
case .system: .system($0.content) case .system: .system($0.content)
case .user: .user($0.content) case .user: .user($0.content)
case .assistant: .assistant($0.content) case .assistant: .assistant($0.content)
} }
} }
let supportsThinking = MLXThinking.supports(directory) let supportsThinking = ThinkingOutput.supportsMLX(directory)
var context: [String: any Sendable]? var context: [String: any Sendable]?
if supportsThinking { if supportsThinking {
switch request.thinking { switch request.thinking {
@@ -108,15 +111,20 @@ actor MLXProvider: InferenceProvider {
case .automatic, .low, .medium, .high: break case .automatic, .low, .medium, .high: break
} }
} }
var thinkingOutput = MLXThinking() var thinkingOutput = ThinkingOutput()
let input = try await model.prepare(input: UserInput(chat: history, additionalContext: context)) let input: LMInput
do {
input = try await model.prepare(input: UserInput(chat: history, additionalContext: context))
} catch let error where (error as NSError).domain == "Jinja.TemplateException" {
throw StudioError("The MLX model’s chat template rejected this conversation. Try sending the message in a new chat.")
}
let config = request.parameters let config = request.parameters
let parameters = GenerateParameters(maxTokens: config.maxTokens ?? 1024, maxKVSize: config.mlxCache, let parameters = GenerateParameters(maxTokens: config.maxTokens ?? 1024, maxKVSize: config.mlxCache,
temperature: Float(config.temperature ?? 0.6), temperature: Float(config.temperature ?? 0.6),
topP: Float(config.topP ?? 1), topP: Float(config.topP ?? 1),
repetitionPenalty: config.repeatPenalty.map(Float.init), repetitionPenalty: config.repeatPenalty.map(Float.init),
repetitionContextSize: config.repeatLastN ?? 20, repetitionContextSize: config.repeatLastN ?? 20,
prefillStepSize: config.mlxPrefill ?? 512) prefill: .init(stepSize: config.mlxPrefill ?? 512, chunking: .remainder))
let output = try await model.generate(input: input, parameters: parameters) let output = try await model.generate(input: input, parameters: parameters)
var stopMatcher = StopMatcher(sequences: config.stop) var stopMatcher = StopMatcher(sequences: config.stop)
continuation.yield(.backend("MLX · \(URL(fileURLWithPath: directory).lastPathComponent)")) continuation.yield(.backend("MLX · \(URL(fileURLWithPath: directory).lastPathComponent)"))
@@ -138,7 +146,7 @@ actor MLXProvider: InferenceProvider {
case .info(let info): case .info(let info):
finished = true finished = true
continuation.yield(.metrics(ProviderMetrics(tokens: info.generationTokenCount, seconds: info.generateTime))) continuation.yield(.metrics(ProviderMetrics(tokens: info.generationTokenCount, seconds: info.generateTime)))
case .toolCall: case .toolCall, .rejectedToolCall:
continuation.yield(.committed) continuation.yield(.committed)
throw StudioError("The MLX model returned a tool call, but no tools are configured.") throw StudioError("The MLX model returned a tool call, but no tools are configured.")
} }
@@ -176,14 +184,19 @@ enum MLXRuntimeLimits {
} }
} }
struct MLXThinking { struct ThinkingOutput {
private static let start = "<think>" private static let start = "<think>"
private static let end = "</think>" private static let end = "</think>"
private var buffer = "" private var buffer = ""
private var readingThinking = false private var readingThinking = false
private var decided = false private var decided = false
static func supports(_ folder: String) -> Bool { init(prefilled: Bool = false) {
readingThinking = prefilled
decided = prefilled
}
static func supportsMLX(_ folder: String) -> Bool {
guard !folder.isEmpty else { return false } guard !folder.isEmpty else { return false }
let url = URL(fileURLWithPath: folder).appending(path: "tokenizer_config.json") let url = URL(fileURLWithPath: folder).appending(path: "tokenizer_config.json")
guard let size = try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize, guard let size = try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize,
@@ -230,3 +243,38 @@ struct MLXThinking {
return [asThinking ? .thinking(buffer) : .answer(buffer)] return [asThinking ? .thinking(buffer) : .answer(buffer)]
} }
} }
private struct StudioMLXTokenizerLoader: TokenizerLoader {
func load(from directory: URL) async throws -> any MLXLMCommon.Tokenizer {
StudioMLXTokenizer(base: try await AutoTokenizer.from(modelFolder: directory))
}
}
private struct StudioMLXTokenizer: MLXLMCommon.Tokenizer {
let base: any Tokenizers.Tokenizer
var bosToken: String? { base.bosToken }
var eosToken: String? { base.eosToken }
var unknownToken: String? { base.unknownToken }
func encode(text: String, addSpecialTokens: Bool) -> [Int] {
base.encode(text: text, addSpecialTokens: addSpecialTokens)
}
func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String {
base.decode(tokens: tokenIds, skipSpecialTokens: skipSpecialTokens)
}
func convertTokenToId(_ token: String) -> Int? { base.convertTokenToId(token) }
func convertIdToToken(_ id: Int) -> String? { base.convertIdToToken(id) }
func applyChatTemplate(messages: [[String: any Sendable]], tools: [[String: any Sendable]]?,
additionalContext: [String: any Sendable]?) throws -> [Int] {
do {
return try base.applyChatTemplate(messages: messages, tools: tools, additionalContext: additionalContext)
} catch Tokenizers.TokenizerError.missingChatTemplate {
throw MLXLMCommon.TokenizerError.missingChatTemplate
}
}
}
+42 -5
View File
@@ -95,6 +95,8 @@ final class TrainingOperation: ObservableObject {
process.standardInput = FileHandle.nullDevice process.standardInput = FileHandle.nullDevice
var environment = ProcessInfo.processInfo.environment var environment = ProcessInfo.processInfo.environment
environment["PYTHONUNBUFFERED"] = "1" environment["PYTHONUNBUFFERED"] = "1"
environment["NO_COLOR"] = "1"
environment["TERM"] = "dumb"
environment["PATH"] = executable.deletingLastPathComponent().path + ":" + (environment["PATH"] ?? "/usr/bin:/bin") environment["PATH"] = executable.deletingLastPathComponent().path + ":" + (environment["PATH"] ?? "/usr/bin:/bin")
process.environment = environment process.environment = environment
let pipe = Pipe() let pipe = Pipe()
@@ -118,7 +120,7 @@ final class TrainingOperation: ObservableObject {
} }
private func append(_ text: String) { private func append(_ text: String) {
log += text log += text.replacingOccurrences(of: "\u{001B}\\[[0-?]*[ -/]*[@-~]", with: "", options: .regularExpression)
if log.count > 80_000 { log = String(log.suffix(60_000)) } if log.count > 80_000 { log = String(log.suffix(60_000)) }
} }
} }
@@ -133,6 +135,14 @@ struct ModelWorkshop: Identifiable {
struct ModelWorkshopView: View { struct ModelWorkshopView: View {
let workshop: ModelWorkshop let workshop: ModelWorkshop
let register: (URL) -> Void let register: (URL) -> Void
let embedded: Bool
private enum Stage: String, CaseIterable, Identifiable {
case setup = "Tools", convert = "Convert", train = "Train"
var id: Self { self }
}
@State private var stage: Stage = .train
@Environment(\.dismiss) private var dismiss @Environment(\.dismiss) private var dismiss
@AppStorage("trainingInstallerPython") private var installerPython = "" @AppStorage("trainingInstallerPython") private var installerPython = ""
@@ -147,9 +157,10 @@ struct ModelWorkshopView: View {
@State private var iterations = 50 @State private var iterations = 50
@State private var layers = 4 @State private var layers = 4
init(workshop: ModelWorkshop, register: @escaping (URL) -> Void) { init(workshop: ModelWorkshop, embedded: Bool = false, register: @escaping (URL) -> Void) {
self.workshop = workshop self.workshop = workshop
self.register = register self.register = register
self.embedded = embedded
_base = State(initialValue: workshop.base) _base = State(initialValue: workshop.base)
} }
@@ -167,7 +178,22 @@ struct ModelWorkshopView: View {
var body: some View { var body: some View {
VStack(spacing: 0) { VStack(spacing: 0) {
if embedded {
VStack(alignment: .leading, spacing: 10) {
Text("Training").font(.largeTitle.weight(.semibold))
Label(toolsInstalled ? "MLX tools ready" : "MLX tools setup required",
systemImage: toolsInstalled ? "checkmark.circle.fill" : "info.circle")
.foregroundStyle(.secondary)
Picker("Training stage", selection: $stage) {
ForEach(Stage.allCases) { Text($0.rawValue).tag($0) }
}.pickerStyle(.segmented).labelsHidden().frame(maxWidth: 340)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(20)
Divider()
}
Form { Form {
if !embedded || stage == .setup {
Section("MLX Tools") { Section("MLX Tools") {
LabeledContent("Environment", value: toolsInstalled ? "Installed" : "Setup required") LabeledContent("Environment", value: toolsInstalled ? "Installed" : "Setup required")
HStack { HStack {
@@ -179,6 +205,8 @@ struct ModelWorkshopView: View {
Text(installerPython.isEmpty ? "Uses a local Python 3.11 or newer to set up a dedicated environment." : installerPython) Text(installerPython.isEmpty ? "Uses a local Python 3.11 or newer to set up a dedicated environment." : installerPython)
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
} }
}
if !embedded || stage == .convert {
Section("Convert to MLX") { Section("Convert to MLX") {
if let name = workshop.modelName { if let name = workshop.modelName {
Text("For \(name), select its original Hugging Face checkpoint. Ollama GGUF files cannot be converted by MLX LM.") Text("For \(name), select its original Hugging Face checkpoint. Ollama GGUF files cannot be converted by MLX LM.")
@@ -198,6 +226,8 @@ struct ModelWorkshopView: View {
Button("Convert and Register…", action: convert) Button("Convert and Register…", action: convert)
.disabled(!toolsInstalled || (sourceFolder == nil && repository.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)) .disabled(!toolsInstalled || (sourceFolder == nil && repository.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty))
} }
}
if !embedded || stage == .train {
Section("Clone and Train") { Section("Clone and Train") {
LabeledContent("Base checkpoint", value: base?.path ?? "Choose a converted MLX folder") LabeledContent("Base checkpoint", value: base?.path ?? "Choose a converted MLX folder")
HStack { HStack {
@@ -220,15 +250,21 @@ struct ModelWorkshopView: View {
} }
} }
} }
}
.formStyle(.grouped) .formStyle(.grouped)
.disabled(busy) .disabled(busy)
Divider() Divider()
VStack(alignment: .leading, spacing: 8) { VStack(alignment: .leading, spacing: 8) {
if embedded { Text("Run output").font(.headline) }
if !operation.log.isEmpty { if !operation.log.isEmpty {
ScrollViewReader { proxy in
ScrollView { ScrollView {
Text(operation.log).font(.system(.caption, design: .monospaced)) Text(operation.log).font(.system(.caption, design: .monospaced))
.textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) .textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
}.frame(height: 112) .id("run-end")
}
.onChange(of: operation.log) { proxy.scrollTo("run-end", anchor: .bottom) }
}.frame(height: embedded ? 145 : 112)
} }
HStack { HStack {
if let active = operation.active { if let active = operation.active {
@@ -239,13 +275,14 @@ struct ModelWorkshopView: View {
Text(operation.status).textSelection(.enabled) Text(operation.status).textSelection(.enabled)
} }
Spacer() Spacer()
Button("Done") { dismiss() }.disabled(busy) if !embedded { Button("Done") { dismiss() }.disabled(busy) }
} }
} }
.padding(12) .padding(12)
} }
.frame(width: 660, height: 585) .frame(width: embedded ? nil : 660, height: embedded ? nil : 585)
.interactiveDismissDisabled(busy) .interactiveDismissDisabled(busy)
.onAppear { if embedded && !toolsInstalled { stage = .setup } }
} }
private var ready: Bool { toolsInstalled && base != nil && !projectPath.isEmpty } private var ready: Bool { toolsInstalled && base != nil && !projectPath.isEmpty }
+382 -87
View File
@@ -32,7 +32,7 @@ struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
url.host = "huggingface.co" url.host = "huggingface.co"
url.path = "/api/models" url.path = "/api/models"
url.queryItems = [ url.queryItems = [
.init(name: "author", value: "mlx-community"), .init(name: "filter", value: "mlx"),
.init(name: "pipeline_tag", value: "text-generation"), .init(name: "pipeline_tag", value: "text-generation"),
.init(name: "search", value: query), .init(name: "search", value: query),
.init(name: "limit", value: "25"), .init(name: "limit", value: "25"),
@@ -45,46 +45,94 @@ struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
return try decodeSearch(response.data) return try decodeSearch(response.data)
} }
static func decodeSearch(_ data: Data) throws -> [Self] { enum HubGating: Decodable {
struct Entry: Decodable { case open, restricted
init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer()
self = (try? value.decode(Bool.self)) == false ? .open : .restricted
}
}
private struct HubEntry: Decodable {
struct File: Decodable { let rfilename: String } struct File: Decodable { let rfilename: String }
let id: String let id: String
let sha: String? let sha: String?
let siblings: [File]? let siblings: [File]?
let downloads: Int? let downloads: Int?
let likes: Int? let likes: Int?
let library_name: String?
let tags: [String]?
let privateModel: Bool?
let gated: HubGating?
enum CodingKeys: String, CodingKey {
case id, sha, siblings, downloads, likes, library_name, tags, gated
case privateModel = "private"
} }
return try JSONDecoder().decode([Entry].self, from: data).compactMap { entry in
let prefix = "mlx-community/" func catalogModel() -> CatalogModel? {
guard entry.id.hasPrefix(prefix), let revision = entry.sha, revision.count == 40, guard let (owner, name) = CatalogModel.repositoryParts(id),
revision.allSatisfy({ $0.isASCII && $0.isHexDigit }) else { return nil } let revision = sha, revision.count == 40,
let name = String(entry.id.dropFirst(prefix.count)) revision.allSatisfy({ $0.isASCII && $0.isHexDigit }),
let safe = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.") privateModel != true, gated != .restricted else { return nil }
guard !name.isEmpty, name.unicodeScalars.allSatisfy(safe.contains) else { return nil } let declaresMLX = library_name == "mlx" || tags?.contains("mlx") == true
let files = (entry.siblings ?? []).map(\.rfilename).filter { file in guard declaresMLX || (owner == "mlx-community" && library_name == nil) else { return nil }
!file.hasPrefix(".") && file.unicodeScalars.allSatisfy(safe.contains) && let files = Set((siblings ?? []).map(\.rfilename).filter { file in
(file.hasSuffix(".safetensors") || file.hasSuffix(".json") || file.hasSuffix(".txt") || CatalogModel.safeComponent(file) &&
file.hasSuffix(".model") || file.hasSuffix(".jinja") || file.hasSuffix(".tiktoken")) [".safetensors", ".json", ".txt", ".model", ".jinja", ".tiktoken"].contains { file.hasSuffix($0) }
} })
guard files.contains("config.json"), files.contains(where: { $0.hasSuffix(".safetensors") }), guard files.contains("config.json"), files.contains(where: { $0.hasSuffix(".safetensors") }),
!files.contains("adapter_config.json"), !files.contains("adapter_model.safetensors") else { return nil } !files.contains("adapter_config.json"), !files.contains("adapter_model.safetensors") else { return nil }
return Self(id: "hf-" + name, title: name, size: "", repository: entry.id, revision: revision, // Keep the existing installation key for mlx-community models.
files: Array(Set(files)).sorted(), downloads: entry.downloads, likes: entry.likes) let key = owner == "mlx-community" ? "hf-" + name : "hf--" + owner + "/" + name
return CatalogModel(id: key, title: name, size: "", repository: id, revision: revision,
files: files.sorted(), downloads: downloads, likes: likes)
} }
} }
static func safeComponent(_ value: String) -> Bool {
let safe = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.")
return !value.isEmpty && !value.hasPrefix(".") && value.unicodeScalars.allSatisfy(safe.contains)
}
static func repositoryParts(_ id: String) -> (String, String)? {
let parts = id.split(separator: "/", omittingEmptySubsequences: false).map(String.init)
guard parts.count == 2, parts.allSatisfy(safeComponent) else { return nil }
return (parts[0], parts[1])
}
static func decodeSearch(_ data: Data) throws -> [Self] {
try JSONDecoder().decode([HubEntry].self, from: data).compactMap { $0.catalogModel() }
}
static func resolve(_ repository: String) async throws -> Self {
guard repositoryParts(repository) != nil else {
throw StudioError("Enter a Hugging Face model ID in owner/model format.")
}
let endpoint = URL(string: "https://huggingface.co/api/models/")!.appending(path: repository)
let response = try await WebFetch.load(endpoint, types: ["application/json"])
return try decodeRepository(response.data, requested: repository)
}
static func decodeRepository(_ data: Data, requested: String) throws -> Self {
let entry = try JSONDecoder().decode(HubEntry.self, from: data)
guard entry.id.caseInsensitiveCompare(requested) == .orderedSame,
let model = entry.catalogModel() else {
throw StudioError("The repository does not expose a public MLX checkpoint with safetensors weights.")
}
return model
}
var source: URL { URL(string: "https://huggingface.co/" + repository)! } var source: URL { URL(string: "https://huggingface.co/" + repository)! }
var metadataKey: String { "mlx:" + repository + "@" + revision } var metadataKey: String { "mlx:" + repository + "@" + revision }
var localFolder: URL { var localFolder: URL {
URL.applicationSupportDirectory.appending(path: "AIStudio/Models", directoryHint: .isDirectory) URL.applicationSupportDirectory.appending(path: "AIStudio/Models", directoryHint: .isDirectory)
.appending(path: id, directoryHint: .isDirectory) .appending(path: id.contains("/") ? "Custom/" + repository : id, directoryHint: .isDirectory)
} }
func installed(at folder: URL) -> Bool { func installed(at folder: URL) -> Bool {
files.allSatisfy { !files.isEmpty && files.allSatisfy { MLXLibrary.hasFile($0, in: folder) } && MLXLibrary.isModel(at: folder)
let file = folder.appending(path: $0)
return ((try? file.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) > 0
}
} }
func install( func install(
@@ -96,7 +144,9 @@ struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
if manager.fileExists(atPath: destination.path) { if manager.fileExists(atPath: destination.path) {
throw StudioError("Remove the incomplete managed model before reinstalling.") throw StudioError("Remove the incomplete managed model before reinstalling.")
} }
let staging = URL.temporaryDirectory.appending(path: "AIStudio-model-\(UUID())", directoryHint: .isDirectory) let parent = destination.deletingLastPathComponent()
try manager.createDirectory(at: parent, withIntermediateDirectories: true)
let staging = parent.appending(path: ".download-\(UUID())", directoryHint: .isDirectory)
try manager.createDirectory(at: staging, withIntermediateDirectories: false) try manager.createDirectory(at: staging, withIntermediateDirectories: false)
defer { try? manager.removeItem(at: staging) } defer { try? manager.removeItem(at: staging) }
@@ -113,14 +163,15 @@ struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
defer { try? manager.removeItem(at: download) } defer { try? manager.removeItem(at: download) }
guard let http = response as? HTTPURLResponse, http.statusCode == 200, guard let http = response as? HTTPURLResponse, http.statusCode == 200,
http.url?.scheme == "https" else { http.url?.scheme == "https" else {
throw StudioError("Could not download \(file).") let code = (response as? HTTPURLResponse).map { " (HTTP \($0.statusCode))" } ?? ""
throw StudioError("Could not download \(file)\(code).")
} }
try manager.moveItem(at: download, to: staging.appending(path: file)) try manager.moveItem(at: download, to: staging.appending(path: file))
} }
try Task.checkCancellation() try Task.checkCancellation()
guard installed(at: staging) else { throw StudioError("The download was incomplete.") } guard installed(at: staging) else { throw StudioError("The download was incomplete.") }
try manager.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
try manager.moveItem(at: staging, to: destination) try manager.moveItem(at: staging, to: destination)
await progress("Download complete.", 1)
} }
} }
@@ -152,7 +203,7 @@ struct MLXModelConfiguration: Decodable {
struct HubModelMetadata: Decodable { struct HubModelMetadata: Decodable {
struct File: Decodable { struct File: Decodable {
struct LFS: Decodable { let size: Int64 } struct LFS: Decodable { let size: Int64; let sha256: String? }
let rfilename: String let rfilename: String
let size: Int64? let size: Int64?
let lfs: LFS? let lfs: LFS?
@@ -295,15 +346,30 @@ struct ModelLibrarySelection {
let compatible: Bool let compatible: Bool
let mlxPath: String let mlxPath: String
let ollamaModel: String let ollamaModel: String
let ggufPath: String
func isMLX(_ path: String) -> Bool { init(mlxOnly: Bool, compatible: Bool, mlxPath: String, ollamaModel: String, ggufPath: String = "") {
mlxOnly && !mlxPath.isEmpty && self.mlxOnly = mlxOnly
URL(fileURLWithPath: mlxPath).resolvingSymlinksInPath().standardizedFileURL.path == self.compatible = compatible
self.mlxPath = mlxPath
self.ollamaModel = ollamaModel
self.ggufPath = ggufPath
}
func isGGUF(_ path: String) -> Bool {
!ggufPath.isEmpty && canonicalPath(ggufPath) == canonicalPath(path)
}
private func canonicalPath(_ path: String) -> String {
URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL.path URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL.path
} }
func isMLX(_ path: String) -> Bool {
ggufPath.isEmpty && mlxOnly && !mlxPath.isEmpty && canonicalPath(mlxPath) == canonicalPath(path)
}
func isOllama(_ name: String) -> Bool { func isOllama(_ name: String) -> Bool {
guard !mlxOnly, !compatible, !ollamaModel.isEmpty else { return false } guard ggufPath.isEmpty, !mlxOnly, !compatible, !ollamaModel.isEmpty else { return false }
func tag(_ value: String) -> String { func tag(_ value: String) -> String {
let value = value.trimmingCharacters(in: .whitespacesAndNewlines) let value = value.trimmingCharacters(in: .whitespacesAndNewlines)
return value.split(separator: "/").last?.contains(":") == true ? value : value + ":latest" return value.split(separator: "/").last?.contains(":") == true ? value : value + ":latest"
@@ -314,6 +380,8 @@ struct ModelLibrarySelection {
struct ModelCatalogView: View { struct ModelCatalogView: View {
@ObservedObject var studio: StudioModel @ObservedObject var studio: StudioModel
@AppStorage("defaultCoreMLPath") private var defaultCoreMLPath = ""
@AppStorage("defaultGGUFPath") private var defaultGGUFPath = ""
@AppStorage("mlxPath") private var mlxPath = "" @AppStorage("mlxPath") private var mlxPath = ""
@AppStorage("mlxOnly") private var mlxOnly = false @AppStorage("mlxOnly") private var mlxOnly = false
@State private var downloads: [String: Task<Void, Never>] = [:] @State private var downloads: [String: Task<Void, Never>] = [:]
@@ -324,11 +392,15 @@ struct ModelCatalogView: View {
let fraction: Double? let fraction: Double?
} }
@AppStorage("mlxRegisteredPaths") private var registered = Data() @AppStorage("mlxRegisteredPaths") private var registered = Data()
@AppStorage(GGUFModelMetadata.libraryKey) private var ggufLibrary = Data()
@State private var dropTargeted = false
@State private var pickingLibrary = false @State private var pickingLibrary = false
@State private var scanningLibrary = false @State private var scanningLibrary = false
@State private var scanRequested = false
@State private var libraryStatus = "" @State private var libraryStatus = ""
@State private var loadedPath: String?
@State private var cacheScan = 0
private var library: [String] { (try? JSONDecoder().decode([String].self, from: registered)) ?? [] } private var library: [String] { (try? JSONDecoder().decode([String].self, from: registered)) ?? [] }
@State private var removing: CatalogModel? @State private var removing: CatalogModel?
@State private var status = "" @State private var status = ""
@@ -340,12 +412,9 @@ struct ModelCatalogView: View {
@State private var loadingPath: String? @State private var loadingPath: String?
@AppStorage("favoriteModelKeys") private var favoriteData = Data() @AppStorage("favoriteModelKeys") private var favoriteData = Data()
@State private var libraryBackend: String? @State private var libraryBackend = "Local"
@State private var localQuery = ""
private var backend: Binding<String> {
Binding(get: { libraryBackend ?? (selection.mlxOnly ? "MLX" : "Ollama") },
set: { libraryBackend = $0 })
}
@AppStorage("endpoint") private var ollamaEndpoint = "http://127.0.0.1:11434" @AppStorage("endpoint") private var ollamaEndpoint = "http://127.0.0.1:11434"
@AppStorage("ollamaModel") private var ollamaModel = "" @AppStorage("ollamaModel") private var ollamaModel = ""
@AppStorage("compatibleEnabled") private var compatibleEnabled = false @AppStorage("compatibleEnabled") private var compatibleEnabled = false
@@ -368,12 +437,15 @@ struct ModelCatalogView: View {
@State private var catalogBytes: [String: Int64] = [:] @State private var catalogBytes: [String: Int64] = [:]
private func mlxPreview(model: CatalogModel?, folder: URL?) -> ModelPreview { private func mlxPreview(model: CatalogModel?, folder: URL?) -> ModelPreview {
let title = model?.title ?? folder?.lastPathComponent ?? "MLX model" let title = model?.title ?? folder.map(MLXLibrary.displayName(for:)) ?? "MLX model"
let cached = model.flatMap { catalogBytes[$0.metadataKey] } let cached = model.flatMap { catalogBytes[$0.metadataKey] }
let size = folder.map { ModelLibrarySize.mlx($0.path) } ?? cached.map { ModelLibrarySize.label($0) } let size = folder.map { ModelLibrarySize.mlx($0.path) } ?? cached.map { ModelLibrarySize.label($0) }
return ModelPreview(title: title, fields: [ return ModelPreview(title: title, fields: [
("Backend", "MLX"), ("Weights", size), ("Repository", model?.repository), ("Backend", "MLX"), ("Weights", size), ("Repository", model?.repository),
("Revision", model?.revision), ("Local folder", folder?.path) ("Revision", model?.revision), ("Local folder", folder?.path),
("Compatibility", folder.map {
MLXLibrary.isModel(at: $0) ? "Checkpoint files present · runtime checked on load" : "Missing or invalid checkpoint files"
} ?? "MLX checkpoint · runtime checked on load")
], source: model?.source, load: { ], source: model?.source, load: {
if let folder { if let folder {
let data = try Data(contentsOf: folder.appending(path: "config.json")) let data = try Data(contentsOf: folder.appending(path: "config.json"))
@@ -426,11 +498,12 @@ struct ModelCatalogView: View {
return ModelLibrarySelection( return ModelLibrarySelection(
mlxOnly: studio.inferenceBackend.hasPrefix("MLX · "), mlxOnly: studio.inferenceBackend.hasPrefix("MLX · "),
compatible: !studio.inferenceBackend.hasPrefix("Ollama · ") || run.endpoint != ollamaEndpoint, compatible: !studio.inferenceBackend.hasPrefix("Ollama · ") || run.endpoint != ollamaEndpoint,
mlxPath: run.path, ollamaModel: run.tag mlxPath: run.path, ollamaModel: run.tag,
ggufPath: studio.inferenceBackend.hasPrefix("GGUF · ") ? run.tag : ""
) )
} }
return ModelLibrarySelection(mlxOnly: mlxOnly, compatible: compatibleEnabled, return ModelLibrarySelection(mlxOnly: mlxOnly && defaultCoreMLPath.isEmpty, compatible: compatibleEnabled || !defaultCoreMLPath.isEmpty,
mlxPath: mlxPath, ollamaModel: ollamaModel) mlxPath: mlxPath, ollamaModel: ollamaModel, ggufPath: defaultGGUFPath)
} }
private func activeBadge(_ runtime: String) -> some View { private func activeBadge(_ runtime: String) -> some View {
@@ -496,17 +569,17 @@ struct ModelCatalogView: View {
var body: some View { var body: some View {
VStack(spacing: 0) { VStack(spacing: 0) {
Picker("Model runtime", selection: backend) { Picker("Model library", selection: $libraryBackend) {
Text("MLX").tag("MLX") Text("On This Mac").tag("Local")
Text("Ollama").tag("Ollama") Text("Ollama").tag("Ollama")
} }
.pickerStyle(.segmented) .pickerStyle(.segmented)
.frame(width: 260) .frame(width: 260)
.padding() .padding()
if backend.wrappedValue == "Ollama" { if libraryBackend == "Ollama" {
ollamaLibrary ollamaLibrary
} else { } else {
mlxLibrary localLibrary
} }
} }
.sheet(item: $preview) { ModelPreviewSheet(preview: $0) } .sheet(item: $preview) { ModelPreviewSheet(preview: $0) }
@@ -526,30 +599,120 @@ struct ModelCatalogView: View {
} }
} }
private var mlxLibrary: some View { private func matchesLocal(_ name: String) -> Bool {
let query = localQuery.trimmingCharacters(in: .whitespacesAndNewlines)
return query.isEmpty || [name, "MLX"].contains { $0.localizedStandardContains(query) }
}
private func registerLocalModels(_ models: [LocalModelImport]) throws {
let gguf = models.compactMap { if case .gguf(let model) = $0 { return model }; return nil }
let mlx = models.compactMap { if case .mlx(let path) = $0 { return path }; return nil }
if !gguf.isEmpty { ggufLibrary = try GGUFModelMetadata.register(gguf, in: ggufLibrary) }
if !mlx.isEmpty { registered = try JSONEncoder().encode(Array(Set(library + mlx)).sorted()) }
}
private func importLMStudioLibrary() {
scanningLibrary = true
libraryStatus = ""
Task {
defer { scanningLibrary = false }
do {
let models = try await Task.detached(priority: .userInitiated) {
try LocalModelImport.discover(in: LocalModelImport.lmStudioFolder)
}.value
try registerLocalModels(models)
libraryStatus = models.isEmpty ? "No supported models found in the LM Studio library." :
"Found \(models.count) models in the LM Studio library."
} catch { libraryStatus = error.localizedDescription }
}
}
private func acceptModelDrop(_ providers: [NSItemProvider]) -> Bool {
let files = providers.filter { $0.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) }
guard !files.isEmpty, !scanningLibrary, !studio.running else { return false }
scanningLibrary = true
Task {
defer { scanningLibrary = false }
var models: [LocalModelImport] = []
var messages: [String] = []
for provider in files {
do {
let url: URL = try await withCheckedThrowingContinuation { continuation in
_ = provider.loadDataRepresentation(forTypeIdentifier: UTType.fileURL.identifier) { data, error in
if let error { continuation.resume(throwing: error) }
else if let data, let url = URL(dataRepresentation: data, relativeTo: nil), url.isFileURL {
continuation.resume(returning: url)
} else {
continuation.resume(throwing: StudioError("Finder did not provide a local file URL."))
}
}
}
let model = try await Task.detached(priority: .userInitiated) { try LocalModelImport.inspect(url) }.value
models.append(model)
} catch {
messages.append(error.localizedDescription)
}
}
do {
try registerLocalModels(models)
let count = models.count
if count > 0 { messages.insert("Registered \(count) model(s).", at: 0) }
} catch { messages.append(error.localizedDescription) }
libraryStatus = messages.joined(separator: " ")
}
return true
}
private var localLibrary: some View {
Form { Form {
Section {
TextField("Filter installed models", text: $localQuery, prompt: Text("Name, architecture, or format"))
.textFieldStyle(.roundedBorder)
.accessibilityLabel("Filter installed models")
Label(dropTargeted ? "Release to import" : "Drop GGUF files or MLX folders here",
systemImage: "square.and.arrow.down")
.font(.callout)
.foregroundStyle(dropTargeted ? Color.accentColor : Color.secondary)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(10)
.background(dropTargeted ? Color.accentColor.opacity(0.12) : Color.secondary.opacity(0.07),
in: RoundedRectangle(cornerRadius: 8))
.onDrop(of: [.fileURL], isTargeted: $dropTargeted, perform: acceptModelDrop)
Button("Import LM Studio Library", systemImage: "folder.badge.plus", action: importLMStudioLibrary)
.disabled(scanningLibrary || studio.running)
if scanningLibrary { ProgressView("Checking model files…").controlSize(.small) }
if !libraryStatus.isEmpty { Text(libraryStatus).foregroundStyle(.secondary) }
}
GGUFModels(selection: selection.ggufPath, inUse: studio.inferenceBackend.hasPrefix("GGUF · "),
filter: localQuery, selectionDisabled: studio.running) {
studio.selectGGUFModel($0)
}
Section("Installed MLX Models") { Section("Installed MLX Models") {
HStack { HStack {
Button("Register Model Folder…") { scanRequested = false; pickingLibrary = true } Button("Import MLX Models…") { pickingLibrary = true }
Button("Scan Folder for Models…") { scanRequested = true; pickingLibrary = true } Button("Refresh Local Models") { cacheScan += 1 }
Button("MLX Tools…") { workshop = ModelWorkshop(base: nil) } Button("MLX Tools…") { workshop = ModelWorkshop(base: nil) }
if scanningLibrary { ProgressView().controlSize(.small) } if scanningLibrary { ProgressView().controlSize(.small) }
} }
.disabled(studio.running || scanningLibrary) .disabled(studio.running || scanningLibrary)
if library.isEmpty && readyModels.isEmpty && (!selection.mlxOnly || selection.mlxPath.isEmpty) { if library.isEmpty && studio.discoveredMLXPaths.isEmpty && readyModels.isEmpty && (!selection.mlxOnly || selection.mlxPath.isEmpty) {
Text("Register an existing MLX folder, scan a model library, or download a catalog model below.") Text("Register an existing MLX folder, scan a model library, or download a catalog model below.")
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
} }
ForEach(favoriteFirst(readyModels) { "mlx:" + $0.id }) { model in modelRow(model) } ForEach(favoriteFirst(readyModels.filter { matchesLocal($0.id) }) { "mlx:" + $0.id }) { model in modelRow(model) }
let selectedPath = selection.mlxOnly && !selection.mlxPath.isEmpty ? [selection.mlxPath] : [] let selectedPath = selection.mlxOnly && !selection.mlxPath.isEmpty ? [selection.mlxPath] : []
let paths = Array(Set(library + selectedPath)).sorted().filter { path in let managedPaths = Set(readyModels.map { $0.localFolder.resolvingSymlinksInPath().path })
!readyModels.contains { $0.localFolder.standardizedFileURL.path == URL(fileURLWithPath: path).standardizedFileURL.path } let paths = Set((library + studio.discoveredMLXPaths + selectedPath).map {
} URL(fileURLWithPath: $0).resolvingSymlinksInPath().path
ForEach(favoriteFirst(paths) { "folder:" + $0 }, id: \.self) { path in }).subtracting(managedPaths).sorted()
ForEach(favoriteFirst(paths.filter { matchesLocal(MLXLibrary.displayName(for: URL(fileURLWithPath: $0))) }) { "folder:" + $0 }, id: \.self) { path in
HStack { HStack {
let title = URL(fileURLWithPath: path).lastPathComponent let title = MLXLibrary.displayName(for: URL(fileURLWithPath: path))
VStack(alignment: .leading, spacing: 4) { VStack(alignment: .leading, spacing: 4) {
Text(title).help(path) Text(title).help(path)
Text("MLX · Safetensors").font(.caption).foregroundStyle(.secondary)
ModelMemoryWarning(bytes: (try? MLXRuntimeLimits.weightBytes(in: URL(fileURLWithPath: path))).flatMap { Int64(exactly: $0) }, mlx: true)
popularityBadge(title) popularityBadge(title)
} }
favoriteButton("folder:" + path) favoriteButton("folder:" + path)
@@ -557,13 +720,11 @@ struct ModelCatalogView: View {
Text(ModelLibrarySize.mlx(path)) Text(ModelLibrarySize.mlx(path))
.font(.caption).foregroundStyle(.secondary) .font(.caption).foregroundStyle(.secondary)
.help("Size of local model weights") .help("Size of local model weights")
if selection.isMLX(path) { activeBadge("MLX") } mlxStatus(path)
Button("Preview") { Button("Preview") {
preview = mlxPreview(model: nil, folder: URL(fileURLWithPath: path)) preview = mlxPreview(model: nil, folder: URL(fileURLWithPath: path))
} }
Button("Load Model") { load(path) } mlxLoadButton(path)
.disabled(studio.running || loadingPath != nil || selection.isMLX(path) ||
!MLXLibrary.isModel(at: URL(fileURLWithPath: path)))
Menu("Tools") { Menu("Tools") {
Button("Clone & Train…") { workshop = ModelWorkshop(base: URL(fileURLWithPath: path)) } Button("Clone & Train…") { workshop = ModelWorkshop(base: URL(fileURLWithPath: path)) }
Button("Reveal") { Button("Reveal") {
@@ -571,21 +732,24 @@ struct ModelCatalogView: View {
} }
} }
.fixedSize() .fixedSize()
if library.contains(path) {
if library.contains(path) { if library.contains(path) {
Button("Unregister") { Button("Unregister") {
registered = (try? JSONEncoder().encode(library.filter { $0 != path })) ?? Data() registered = (try? JSONEncoder().encode(library.filter { $0 != path })) ?? Data()
}.disabled(studio.running) }.disabled(studio.running)
} }
} }
}
.listRowBackground(selection.isMLX(path) ? Color.accentColor.opacity(0.12) : nil) .listRowBackground(selection.isMLX(path) ? Color.accentColor.opacity(0.12) : nil)
} }
if !libraryStatus.isEmpty { Text(libraryStatus).foregroundStyle(.secondary) }
} }
Section("Hugging Face") { CoreMLModels(selection: defaultCoreMLPath, disabled: studio.running) { studio.selectCoreMLModel($0) }
HubGGUFDownloads()
Section("Hugging Face · MLX") {
HStack { HStack {
TextField("Search MLX models", text: $query, prompt: Text("e.g. Qwen, Gemma")) TextField("Search MLX models", text: $query, prompt: Text("Qwen, Gemma, or owner/model"))
.labelsHidden().textFieldStyle(.roundedBorder).onSubmit(search) .labelsHidden().textFieldStyle(.roundedBorder).onSubmit(search)
Button(query.isEmpty ? "Browse" : "Search", action: search).disabled(searching || hasMLXDownloads) Button(query.isEmpty ? "Browse" : (query.contains("/") ? "Find Model ID" : "Search"), action: search).disabled(searching || hasMLXDownloads)
if searching { ProgressView().controlSize(.small) } if searching { ProgressView().controlSize(.small) }
} }
if !searchStatus.isEmpty { Text(searchStatus).foregroundStyle(.secondary) } if !searchStatus.isEmpty { Text(searchStatus).foregroundStyle(.secondary) }
@@ -605,27 +769,42 @@ struct ModelCatalogView: View {
} }
} }
.formStyle(.grouped) .formStyle(.grouped)
.onAppear { if matches.isEmpty && searchStatus.isEmpty { search() } } .task(id: cacheScan) {
do {
try await studio.refreshLocalMLXModels()
} catch is CancellationError {
return
} catch {
libraryStatus = "Could not scan local models. \(error.localizedDescription)"
}
}
.task {
while !Task.isCancelled {
await refreshLoadedPath()
do { try await Task.sleep(for: .seconds(2)) }
catch { return }
}
}
.fileImporter(isPresented: $pickingLibrary, allowedContentTypes: [.folder]) { result in .fileImporter(isPresented: $pickingLibrary, allowedContentTypes: [.folder]) { result in
do { do {
let url = try result.get() let url = try result.get()
if scanRequested {
scanningLibrary = true scanningLibrary = true
libraryStatus = ""
Task { Task {
defer { scanningLibrary = false } defer { scanningLibrary = false }
do { do {
let found = try await Task.detached { try MLXLibrary.discover(in: url) }.value let found = try await Task.detached(priority: .userInitiated) {
registered = try JSONEncoder().encode(Array(Set(library + found.map(\.path))).sorted()) let scoped = url.startAccessingSecurityScopedResource()
libraryStatus = "Found \(found.count) compatible MLX model folder(s)." defer { if scoped { url.stopAccessingSecurityScopedResource() } }
return try MLXLibrary.discover(in: url.resolvingSymlinksInPath())
}.value
guard !found.isEmpty else {
throw StudioError("No complete MLX checkpoints found in \(url.lastPathComponent).")
}
try registerLocalModels(found.map { .mlx($0.path) })
libraryStatus = "Registered \(found.count) MLX model(s)."
} catch { libraryStatus = error.localizedDescription } } catch { libraryStatus = error.localizedDescription }
} }
} else {
guard MLXLibrary.isModel(at: url) else {
throw StudioError("Choose an MLX folder with config.json and safetensors weights.")
}
registered = try JSONEncoder().encode(Array(Set(library + [url.resolvingSymlinksInPath().path])).sorted())
libraryStatus = "Registered \(url.lastPathComponent)."
}
} catch { libraryStatus = error.localizedDescription } } catch { libraryStatus = error.localizedDescription }
} }
.confirmationDialog("Remove downloaded model?", isPresented: Binding( .confirmationDialog("Remove downloaded model?", isPresented: Binding(
@@ -647,6 +826,9 @@ struct ModelCatalogView: View {
HStack { HStack {
VStack(alignment: .leading, spacing: 4) { VStack(alignment: .leading, spacing: 4) {
Label(model.name, systemImage: "cube") Label(model.name, systemImage: "cube")
if let format = model.details?.format {
Text(format.uppercased()).font(.caption).foregroundStyle(.secondary)
}
popularityBadge(model.name) popularityBadge(model.name)
} }
favoriteButton("ollama:" + model.name) favoriteButton("ollama:" + model.name)
@@ -811,19 +993,22 @@ struct ModelCatalogView: View {
popularityBadge(model.repository) popularityBadge(model.repository)
} }
HStack { HStack {
Text("MLX · Safetensors")
Text(installed ? ModelLibrarySize.mlx(saved.localFolder.path) : ModelLibrarySize.label(catalogBytes[metadataKey])) Text(installed ? ModelLibrarySize.mlx(saved.localFolder.path) : ModelLibrarySize.label(catalogBytes[metadataKey]))
.help(installed ? "Size of local model weights" : "Weight files at the listed Hugging Face revision") .help(installed ? "Size of local model weights" : "Weight files at the listed Hugging Face revision")
ModelMemoryWarning(bytes: installed
? (try? MLXRuntimeLimits.weightBytes(in: saved.localFolder)).flatMap { Int64(exactly: $0) }
: catalogBytes[metadataKey], mlx: true)
if let count = model.downloads { Label(count.formatted(), systemImage: "arrow.down") } if let count = model.downloads { Label(count.formatted(), systemImage: "arrow.down") }
if let count = model.likes { Label(count.formatted(), systemImage: "heart") } if let count = model.likes { Label(count.formatted(), systemImage: "heart") }
if isActive { activeBadge("MLX") } if installed { mlxStatus(saved.localFolder.path) }
}.font(.caption).foregroundStyle(.secondary) }.font(.caption).foregroundStyle(.secondary)
HStack { HStack {
Button("Preview") { preview = mlxPreview(model: model, folder: installed ? saved.localFolder : nil) } Button("Preview") { preview = mlxPreview(model: model, folder: installed ? saved.localFolder : nil) }
Link("Model Card", destination: model.source) Link("Model Card", destination: model.source)
Spacer() Spacer()
if installed { if installed {
Button("Load Model") { load(saved.localFolder.path) } mlxLoadButton(saved.localFolder.path)
.disabled(studio.running || loadingPath != nil || isActive)
Button("Clone & Train…") { workshop = ModelWorkshop(base: saved.localFolder) } Button("Clone & Train…") { workshop = ModelWorkshop(base: saved.localFolder) }
.disabled(studio.running || loadingPath != nil) .disabled(studio.running || loadingPath != nil)
Button("Reveal") { NSWorkspace.shared.activateFileViewerSelecting([saved.localFolder]) } Button("Reveal") { NSWorkspace.shared.activateFileViewerSelecting([saved.localFolder]) }
@@ -843,7 +1028,7 @@ struct ModelCatalogView: View {
} }
.padding(.vertical, 4) .padding(.vertical, 4)
.listRowBackground(isActive ? Color.accentColor.opacity(0.12) : nil) .listRowBackground(isActive ? Color.accentColor.opacity(0.12) : nil)
.task(id: installed) { .task(id: installed ? nil : metadataKey) {
guard !installed, catalogBytes[metadataKey] == nil else { return } guard !installed, catalogBytes[metadataKey] == nil else { return }
if let metadata = try? await HubModelMetadata.load(model), !Task.isCancelled { if let metadata = try? await HubModelMetadata.load(model), !Task.isCancelled {
catalogBytes[metadataKey] = metadata.weightBytes(files: model.files) catalogBytes[metadataKey] = metadata.weightBytes(files: model.files)
@@ -865,27 +1050,75 @@ struct ModelCatalogView: View {
guard !searching, !hasMLXDownloads else { return } guard !searching, !hasMLXDownloads else { return }
searching = true searching = true
searchStatus = "" searchStatus = ""
matches = []
Task { Task {
defer { searching = false } defer { searching = false }
do { do {
if term.contains("/") {
matches = [try await CatalogModel.resolve(term)]
} else {
matches = try await CatalogModel.search(term) matches = try await CatalogModel.search(term)
}
if matches.isEmpty { searchStatus = "No MLX checkpoints matched." } if matches.isEmpty { searchStatus = "No MLX checkpoints matched." }
} catch { searchStatus = error.localizedDescription } } catch { searchStatus = error.localizedDescription }
} }
} }
private func refreshLoadedPath() async {
loadedPath = await studio.mlxLoadedPath().map {
URL(fileURLWithPath: $0).resolvingSymlinksInPath().path
}
}
private func isLoaded(_ path: String) -> Bool {
loadedPath == URL(fileURLWithPath: path).resolvingSymlinksInPath().path
}
@ViewBuilder
private func mlxStatus(_ path: String) -> some View {
if selection.isMLX(path) {
Label("Selected", systemImage: "checkmark.circle.fill")
.font(.caption.weight(.semibold)).foregroundStyle(Color.accentColor)
}
if isLoaded(path) {
let inUse = studio.running && studio.inferenceBackend.hasPrefix("MLX")
Label(inUse ? "In use" : "Loaded", systemImage: "memorychip")
.font(.caption).foregroundStyle(.secondary)
}
}
@ViewBuilder
private func mlxLoadButton(_ path: String) -> some View {
if isLoaded(path) {
Button("Unload") {
Task {
await studio.unloadMLXModel()
await refreshLoadedPath()
}
}
.disabled(studio.running || loadingPath != nil)
if !selection.isMLX(path) {
Button("Use Model") { studio.selectMLXModel(path) }.disabled(studio.running)
}
} else {
Button("Load Model") { load(path) }
.disabled(studio.running || loadingPath != nil || !MLXLibrary.isModel(at: URL(fileURLWithPath: path)))
}
}
private func load(_ path: String) { private func load(_ path: String) {
guard loadingPath == nil, !studio.running else { return } guard loadingPath == nil, !studio.running else { return }
loadingPath = path loadingPath = path
let name = URL(fileURLWithPath: path).lastPathComponent let name = MLXLibrary.displayName(for: URL(fileURLWithPath: path))
status = "Loading \(name)…" status = "Loading \(name)…"
Task { Task {
defer { loadingPath = nil }
do { do {
try await studio.loadMLX(path) try await studio.loadMLX(path)
studio.selectMLXModel(path) studio.selectMLXModel(path)
status = "Loaded \(name)." status = "Loaded \(name)."
} catch { status = error.localizedDescription } } catch { status = "Could not load \(name). \(error.localizedDescription)" }
await refreshLoadedPath()
loadingPath = nil
} }
} }
@@ -913,10 +1146,11 @@ struct ModelCatalogView: View {
guard !studio.running, downloads["mlx:" + model.id] == nil else { return } guard !studio.running, downloads["mlx:" + model.id] == nil else { return }
do { do {
try FileManager.default.removeItem(at: model.localFolder) try FileManager.default.removeItem(at: model.localFolder)
if mlxPath == model.localFolder.path { if isLoaded(model.localFolder.path) { studio.unloadMLX() }
if URL(fileURLWithPath: mlxPath).resolvingSymlinksInPath().path == model.localFolder.resolvingSymlinksInPath().path {
mlxPath = "" mlxPath = ""
studio.unloadMLX()
} }
studio.forgetDiscoveredMLXModel(model.localFolder.resolvingSymlinksInPath().path)
managed = try JSONEncoder().encode(installedModels.filter { $0.id != model.id && !CatalogModel.all.contains($0) }) managed = try JSONEncoder().encode(installedModels.filter { $0.id != model.id && !CatalogModel.all.contains($0) })
status = "Removed \(model.title)." status = "Removed \(model.title)."
} catch { status = error.localizedDescription } } catch { status = error.localizedDescription }
@@ -937,9 +1171,17 @@ enum MLXLibrary {
offset += 1 offset += 1
if isModel(at: folder) { found.append(folder); continue } if isModel(at: folder) { found.append(folder); continue }
guard depth < 4 else { continue } guard depth < 4 else { continue }
let children = try manager.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey], let children: [URL]
do {
children = try manager.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
options: [.skipsHiddenFiles, .skipsPackageDescendants]) options: [.skipsHiddenFiles, .skipsPackageDescendants])
.sorted { $0.lastPathComponent < $1.lastPathComponent }
} catch {
if depth == 0 { throw error }
continue
}
for child in children where queue.count < 2000 { for child in children where queue.count < 2000 {
if folder.lastPathComponent.hasPrefix("models--"), child.lastPathComponent != "snapshots" { continue }
if let values = try? child.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]), if let values = try? child.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]),
values.isDirectory == true, values.isSymbolicLink != true { values.isDirectory == true, values.isSymbolicLink != true {
queue.append((child, depth + 1)) queue.append((child, depth + 1))
@@ -949,9 +1191,62 @@ enum MLXLibrary {
return found.sorted { $0.path < $1.path } return found.sorted { $0.path < $1.path }
} }
static func discoverLocalModels() throws -> [URL] {
let environment = ProcessInfo.processInfo.environment
let home = URL.homeDirectory
let defaultCache = home.appending(path: ".cache/huggingface/hub")
var roots = [
URL.applicationSupportDirectory.appending(path: "AIStudio/Models"),
URL.documentsDirectory.appending(path: "huggingface/models"),
defaultCache, LocalModelImport.lmStudioFolder
]
if let cache = environment["HF_HUB_CACHE"] ?? environment["HUGGINGFACE_HUB_CACHE"], !cache.isEmpty {
roots.append(URL(fileURLWithPath: cache))
}
if let hfHome = environment["HF_HOME"], !hfHome.isEmpty {
roots.append(URL(fileURLWithPath: hfHome).appending(path: "hub"))
}
if let cache = environment["XDG_CACHE_HOME"], !cache.isEmpty {
roots.append(URL(fileURLWithPath: cache).appending(path: "huggingface/hub"))
}
var found: Set<URL> = []
for root in Set(roots.map { $0.resolvingSymlinksInPath() }) where FileManager.default.fileExists(atPath: root.path) {
found.formUnion(try discover(in: root))
}
return found.sorted { $0.path < $1.path }
}
static func displayName(for folder: URL) -> String {
let snapshots = folder.deletingLastPathComponent()
let repository = snapshots.deletingLastPathComponent().lastPathComponent
guard snapshots.lastPathComponent == "snapshots", repository.hasPrefix("models--") else {
return folder.lastPathComponent
}
let name = repository.dropFirst("models--".count).replacingOccurrences(of: "--", with: "/")
return "\(name) · \(folder.lastPathComponent.prefix(8))"
}
static func hasFile(_ name: String, in folder: URL) -> Bool {
let file = folder.appending(path: name).resolvingSymlinksInPath()
guard let values = try? file.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]) else { return false }
return values.isRegularFile == true && (values.fileSize ?? 0) > 0
}
static func isModel(at url: URL) -> Bool { static func isModel(at url: URL) -> Bool {
FileManager.default.fileExists(atPath: url.appending(path: "config.json").path) && let config = url.appending(path: "config.json")
((try? MLXRuntimeLimits.weightBytes(in: url)) ?? 0) > 0 guard hasFile("config.json", in: url),
let data = try? Data(contentsOf: config),
(try? MLXModelConfiguration.decode(data)) != nil,
((try? MLXRuntimeLimits.weightBytes(in: url)) ?? 0) > 0 else { return false }
let index = url.appending(path: "model.safetensors.index.json")
guard FileManager.default.fileExists(atPath: index.path) else { return true }
struct Index: Decodable { let weight_map: [String: String] }
guard let data = try? Data(contentsOf: index),
let map = try? JSONDecoder().decode(Index.self, from: data).weight_map,
!map.isEmpty else { return false }
return Set(map.values).allSatisfy {
CatalogModel.safeComponent($0) && $0.hasSuffix(".safetensors") && hasFile($0, in: url)
}
} }
} }
+65 -3
View File
@@ -86,6 +86,10 @@ final class Store {
private func prepareMessageSources() throws { private func prepareMessageSources() throws {
try execute(""" try execute("""
CREATE TABLE IF NOT EXISTS message_performance (
message TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
measurement TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS message_web_sources ( CREATE TABLE IF NOT EXISTS message_web_sources (
message TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE, message TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
sources TEXT NOT NULL sources TEXT NOT NULL
@@ -245,7 +249,7 @@ final class Store {
[message.id.uuidString, chat.uuidString, message.role.rawValue, message.content, message.thinking, message.backend]) [message.id.uuidString, chat.uuidString, message.role.rawValue, message.content, message.thinking, message.backend])
} }
guard !message.webSources.isEmpty || !message.documentNames.isEmpty || !message.documentCitations.isEmpty else { guard !message.webSources.isEmpty || !message.documentNames.isEmpty || !message.documentCitations.isEmpty || message.performance != nil else {
try insertMessage() try insertMessage()
return return
} }
@@ -268,6 +272,11 @@ final class Store {
try mutate("INSERT INTO message_document_citations(message,citations) VALUES(?,?)", try mutate("INSERT INTO message_document_citations(message,citations) VALUES(?,?)",
[message.id.uuidString, String(decoding: citations, as: UTF8.self)]) [message.id.uuidString, String(decoding: citations, as: UTF8.self)])
} }
if let timing = message.performance {
let data = try encoder.encode(timing)
try mutate("INSERT INTO message_performance(message,measurement) VALUES(?,?)",
[message.id.uuidString, String(decoding: data, as: UTF8.self)])
}
try execute("RELEASE save_message_sources") try execute("RELEASE save_message_sources")
} catch { } catch {
try? execute("ROLLBACK TO save_message_sources") try? execute("ROLLBACK TO save_message_sources")
@@ -278,11 +287,12 @@ final class Store {
func messages(in chat: UUID) throws -> [Message] { func messages(in chat: UUID) throws -> [Message] {
try query(""" try query("""
SELECT m.id,m.role,m.content,m.thinking,m.backend,w.sources,d.names,c.citations SELECT m.id,m.role,m.content,m.thinking,m.backend,w.sources,d.names,c.citations,p.measurement
FROM messages m FROM messages m
LEFT JOIN message_web_sources w ON w.message=m.id LEFT JOIN message_web_sources w ON w.message=m.id
LEFT JOIN message_documents d ON d.message=m.id LEFT JOIN message_documents d ON d.message=m.id
LEFT JOIN message_document_citations c ON c.message=m.id LEFT JOIN message_document_citations c ON c.message=m.id
LEFT JOIN message_performance p ON p.message=m.id
WHERE m.chat=? ORDER BY m.rowid WHERE m.chat=? ORDER BY m.rowid
""", [chat.uuidString]) { row in """, [chat.uuidString]) { row in
guard let role = Role(rawValue: string(row, 1)) else { throw StudioError("Invalid stored message role.") } guard let role = Role(rawValue: string(row, 1)) else { throw StudioError("Invalid stored message role.") }
@@ -291,10 +301,62 @@ final class Store {
let documents = (try? decoder.decode([String].self, from: Data(string(row, 6).utf8))) ?? [] let documents = (try? decoder.decode([String].self, from: Data(string(row, 6).utf8))) ?? []
return Message(id: try uuid(row, 0), role: role, content: string(row, 2), return Message(id: try uuid(row, 0), role: role, content: string(row, 2),
thinking: string(row, 3), backend: string(row, 4), webSources: sources, documentNames: documents, thinking: string(row, 3), backend: string(row, 4), webSources: sources, documentNames: documents,
documentCitations: decodeArray(string(row, 7))) documentCitations: decodeArray(string(row, 7)),
performance: try? decoder.decode(GenerationMeasurement.self, from: Data(string(row, 8).utf8)))
} }
} }
func exportChat(_ chat: UUID, to url: URL) throws {
guard let title = try query("SELECT title FROM chats WHERE id=?", [chat.uuidString], map: {
string($0, 0)
}).first else {
throw StudioError("This conversation is no longer available.")
}
func inline(_ text: String) -> String {
let punctuation: Set<Character> = ["\\", "`", "*", "_", "[", "]", "<", ">", "#", "&", "~"]
return text.components(separatedBy: .newlines).joined(separator: " ").map {
punctuation.contains($0) ? "\\\($0)" : String($0)
}.joined()
}
func quote(_ text: String) -> String {
text.components(separatedBy: "\n").map { "> " + $0 }.joined(separator: "\n")
}
var sections = ["# \(inline(title))"]
for message in try messages(in: chat) {
switch message.role {
case .user: sections.append("## You")
case .assistant: sections.append("## Assistant")
case .system: sections.append("## System")
}
if !message.backend.isEmpty { sections.append("*\(inline(message.backend))*") }
if !message.content.isEmpty { sections.append(message.content) }
if !message.thinking.isEmpty {
sections.append("### Thinking\n\n" + quote(message.thinking))
}
if !message.documentNames.isEmpty {
sections.append("### Attachments\n\n" + message.documentNames.map { "- " + inline($0) }.joined(separator: "\n"))
}
if !message.documentCitations.isEmpty {
sections.append("### Document Sources")
for source in message.documentCitations {
sections.append("**\\[D\(source.number)\\] \(inline(source.title))**\n\n" + quote(source.excerpt))
}
}
let webLinks = message.webSources.compactMap { source -> String? in
guard let url = try? WebClipCapture.url(source.url.absoluteString) else { return nil }
let label = source.title.isEmpty ? url.absoluteString : source.title
return "- [\(inline(label))](<\(url.absoluteString)>)"
}
if !webLinks.isEmpty {
sections.append("### Web Sources\n\n" + webLinks.joined(separator: "\n"))
}
}
try (sections.joined(separator: "\n\n") + "\n").write(to: url, atomically: true, encoding: .utf8)
}
func memory(matching prompt: String, in chat: UUID, excluding: Set<UUID> = []) throws -> [String] { func memory(matching prompt: String, in chat: UUID, excluding: Set<UUID> = []) throws -> [String] {
let terms = Array(Set(prompt.lowercased().split { !$0.isLetter && !$0.isNumber } let terms = Array(Set(prompt.lowercased().split { !$0.isLetter && !$0.isNumber }
.filter { $0.count >= 4 }.prefix(12).map(String.init))).sorted() .filter { $0.count >= 4 }.prefix(12).map(String.init))).sorted()
+155 -37
View File
@@ -65,6 +65,10 @@ final class StudioModel: ObservableObject {
} }
@Published private(set) var measurements: [GenerationMeasurement] = [] @Published private(set) var measurements: [GenerationMeasurement] = []
@Published var performanceModel: ChatModelChoice?
@Published private(set) var benchmarkRunning = false
@Published private(set) var benchmarkStatus = ""
private var benchmarkTask: Task<Void, Never>?
@Published private(set) var knowledgeStacks: [Conversation] = [] @Published private(set) var knowledgeStacks: [Conversation] = []
@Published private(set) var snippets: [WorkspaceSnippet] = [] @Published private(set) var snippets: [WorkspaceSnippet] = []
@Published private(set) var mcpConnections: [MCPConnectionID: MCPConnectionState] = [:] @Published private(set) var mcpConnections: [MCPConnectionID: MCPConnectionState] = [:]
@@ -75,6 +79,18 @@ final class StudioModel: ObservableObject {
mcpConnections.compactMap { id, state in state.toolset.map { (id, $0) } } mcpConnections.compactMap { id, state in state.toolset.map { (id, $0) } }
.sorted { $0.1.name.localizedStandardCompare($1.1.name) == .orderedAscending } .sorted { $0.1.name.localizedStandardCompare($1.1.name) == .orderedAscending }
} }
private var repositoryToolset: ActiveToolset? {
let servers = activeToolsets.filter {
$0.id != .web && $0.toolset.tools.contains { $0.name == "list_repositories" }
}
return (servers.first { entry in
if case .profile(let profile) = entry.id, profile.localizedCaseInsensitiveContains("gitea") {
return true
}
return entry.toolset.name.localizedCaseInsensitiveContains("gitea")
} ?? servers.first)?.toolset
}
@Published var activeStack: UUID? @Published var activeStack: UUID?
@Published var activeRemoteStack: RemoteStackChoice = .automatic @Published var activeRemoteStack: RemoteStackChoice = .automatic
@Published var activeSkill: UUID? @Published var activeSkill: UUID?
@@ -122,6 +138,12 @@ final class StudioModel: ObservableObject {
(try? store?.messages(in: id)) ?? [] (try? store?.messages(in: id)) ?? []
} }
func exportChat(_ id: UUID, to url: URL) throws {
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
try database().exportChat(id, to: url)
}
func searchConversations(_ term: String) -> [Conversation] { func searchConversations(_ term: String) -> [Conversation] {
(try? store?.searchConversations(term)) ?? [] (try? store?.searchConversations(term)) ?? []
} }
@@ -175,12 +197,16 @@ final class StudioModel: ObservableObject {
func send(endpoint: String, model: String, mlxPath: String, thinking: Thinking, failover: Bool, func send(endpoint: String, model: String, mlxPath: String, thinking: Thinking, failover: Bool,
mlxOnly: Bool, compatible: Bool, recall: Bool, useDocuments: Bool, instructions: String, settings: GenerationSettings, agents: [AgentRole] = [], agentTools: Bool = false, mlxOnly: Bool, compatible: Bool, recall: Bool, useDocuments: Bool, instructions: String, settings: GenerationSettings, agents: [AgentRole] = [], agentTools: Bool = false,
ragEnabled: Bool = true, lmStudioPlugins: [String] = []) { ragEnabled: Bool = true, lmStudioPlugins: [String] = [], gguf: Bool = false, coreML: Bool = false) {
let text = prompt.trimmingCharacters(in: .whitespacesAndNewlines) let text = prompt.trimmingCharacters(in: .whitespacesAndNewlines)
let tag = model.trimmingCharacters(in: .whitespacesAndNewlines) let tag = model.trimmingCharacters(in: .whitespacesAndNewlines)
guard !running, !text.isEmpty else { return } guard !running, !benchmarkRunning, !text.isEmpty else { return }
let attachment = toolAttachment let attachment = toolAttachment
let image = attachment?.imagePNG let image = attachment?.imagePNG
if (gguf || coreML) && image != nil {
status = "This local model supports text. Remove the image attachment to continue."
return
}
if image != nil && mlxOnly && attachment?.output.isEmpty == true { if image != nil && mlxOnly && attachment?.output.isEmpty == true {
status = "MLX could not get readable text from this image. Choose a vision-capable model to analyze the image." status = "MLX could not get readable text from this image. Choose a vision-capable model to analyze the image."
return return
@@ -206,7 +232,7 @@ final class StudioModel: ObservableObject {
do { do {
let (name, generate) = try inferenceRoute( let (name, generate) = try inferenceRoute(
endpoint: endpoint, model: tag, mlxPath: mlxPath, mlxOnly: mlxOnly, endpoint: endpoint, model: tag, mlxPath: mlxPath, mlxOnly: mlxOnly,
compatible: compatible, failover: failover) compatible: compatible, failover: failover, gguf: gguf, coreML: coreML)
let pluginClient = compatible && !mlxOnly && !lmStudioPlugins.isEmpty let pluginClient = compatible && !mlxOnly && !lmStudioPlugins.isEmpty
? try compatibleClient(endpoint: endpoint) : nil ? try compatibleClient(endpoint: endpoint) : nil
let parameters = try settings.parameters(mlxOnly: mlxOnly, compatible: compatible) let parameters = try settings.parameters(mlxOnly: mlxOnly, compatible: compatible)
@@ -420,9 +446,7 @@ final class StudioModel: ObservableObject {
if wantsRepositories { if wantsRepositories {
webStatus = "Listing Gitea repositories…" webStatus = "Listing Gitea repositories…"
do { do {
guard let repositoryClient = activeToolsets.first(where: { guard let repositoryClient = repositoryToolset?.client else {
$0.toolset.tools.contains { $0.name == "list_repositories" }
})?.toolset.client else {
throw StudioError("Enable the Gitea server in Toolbox → MCP Servers and check its connection.") throw StudioError("Enable the Gitea server in Toolbox → MCP Servers and check its connection.")
} }
let repositories = try await GiteaRepositoryLookup.references(client: repositoryClient) let repositories = try await GiteaRepositoryLookup.references(client: repositoryClient)
@@ -500,6 +524,7 @@ final class StudioModel: ObservableObject {
do { do {
let data = try await connected.client.callTool(offer.tool.name, argumentsJSON: request.arguments) let data = try await connected.client.callTool(offer.tool.name, argumentsJSON: request.arguments)
try Task.checkCancellation() try Task.checkCancellation()
try MCPToolResponse.check(data, tool: offer.tool.name)
self.agentSteps.append("Tool completed · \(offer.tool.name)") self.agentSteps.append("Tool completed · \(offer.tool.name)")
return String(decoding: data.prefix(48_000), as: UTF8.self) return String(decoding: data.prefix(48_000), as: UTF8.self)
} catch { } catch {
@@ -510,7 +535,9 @@ final class StudioModel: ObservableObject {
}) })
} }
} }
await consume(stream, in: chat, start: start, requested: name) let requestedModel = mlxOnly ? MLXLibrary.displayName(for: URL(fileURLWithPath: mlxPath)) :
(gguf || coreML ? URL(fileURLWithPath: tag).deletingPathExtension().lastPathComponent : tag)
await consume(stream, in: chat, start: start, requested: name, model: requestedModel)
} }
} catch { status = error.localizedDescription } } catch { status = error.localizedDescription }
} }
@@ -543,7 +570,16 @@ final class StudioModel: ObservableObject {
private typealias Generate = @Sendable ([Message], Thinking, GenerationParameters) -> AsyncThrowingStream<Delta, Error> private typealias Generate = @Sendable ([Message], Thinking, GenerationParameters) -> AsyncThrowingStream<Delta, Error>
private func inferenceRoute(endpoint: String, model: String, mlxPath: String, mlxOnly: Bool, private func inferenceRoute(endpoint: String, model: String, mlxPath: String, mlxOnly: Bool,
compatible: Bool, failover: Bool) throws -> (String, Generate) { compatible: Bool, failover: Bool, gguf: Bool = false, coreML: Bool = false) throws -> (String, Generate) {
if gguf || coreML {
let provider: any InferenceProvider = coreML ? CoreMLProvider() : GGUFProvider()
let name = coreML ? "Core ML" : "GGUF"
return (name, { messages, thinking, parameters in
Router.stream(primary: {
provider.generate(.init(model: model, messages: messages, thinking: thinking, parameters: parameters))
}, fallback: nil, primaryName: name)
})
}
let provider: (any InferenceProvider)? let provider: (any InferenceProvider)?
let name: String let name: String
if mlxOnly { if mlxOnly {
@@ -567,11 +603,61 @@ final class StudioModel: ObservableObject {
}) })
} }
static let benchmarkPrompt = "Write a numbered list of 20 practical tips for keeping a small garden healthy. Use one complete sentence per tip."
func benchmark(_ choice: ChatModelChoice, endpoint: String, repetitions: Int) {
guard !running, !benchmarkRunning, !choice.model.isEmpty, (1...5).contains(repetitions) else { return }
benchmarkRunning = true
benchmarkStatus = "Preparing benchmark…"
benchmarkTask = Task {
defer {
benchmarkRunning = false
benchmarkTask = nil
}
do {
let (backend, generate) = try inferenceRoute(endpoint: endpoint, model: choice.model,
mlxPath: choice.model, mlxOnly: choice.backend == .mlx, compatible: choice.backend == .compatible,
failover: false, gguf: choice.backend == .gguf, coreML: choice.backend == .coreML)
var parameters = GenerationParameters()
parameters.temperature = 0
parameters.maxTokens = 128
for run in 1...repetitions {
try Task.checkCancellation()
benchmarkStatus = "Running \(run) of \(repetitions)…"
var capture = GenerationCapture(start: ProcessInfo.processInfo.systemUptime)
do {
for try await delta in generate([.init(role: .user, content: Self.benchmarkPrompt)], .automatic, parameters) {
try Task.checkCancellation()
capture.observe(delta, at: ProcessInfo.processInfo.systemUptime)
}
try Task.checkCancellation()
guard capture.characters > 0 else { throw StudioError("The model returned no text.") }
record(capture.finish(at: ProcessInfo.processInfo.systemUptime, requested: backend,
model: choice.displayName, outcome: "Complete", benchmark: true))
} catch {
record(capture.finish(at: ProcessInfo.processInfo.systemUptime, requested: backend,
model: choice.displayName, outcome: Task.isCancelled ? "Stopped" : "Failed", benchmark: true))
throw error
}
}
benchmarkStatus = repetitions == 1 ? "Benchmark complete." : "\(repetitions) benchmark runs complete."
} catch {
benchmarkStatus = Task.isCancelled ? "Benchmark stopped." : error.localizedDescription
}
}
}
func stopBenchmark() { benchmarkTask?.cancel() }
func evaluatePrompt(_ template: PromptTemplate, input: String) async throws -> String { func evaluatePrompt(_ template: PromptTemplate, input: String) async throws -> String {
let defaults = UserDefaults.standard let defaults = UserDefaults.standard
let mlxOnly = defaults.bool(forKey: "mlxOnly") let ggufPath = defaults.string(forKey: "defaultGGUFPath") ?? ""
let compatible = !mlxOnly && defaults.bool(forKey: "compatibleEnabled") let coreMLPath = defaults.string(forKey: "defaultCoreMLPath") ?? ""
let model = defaults.string(forKey: compatible ? "compatibleModel" : "ollamaModel") ?? "" let coreML = !coreMLPath.isEmpty
let gguf = !coreML && !ggufPath.isEmpty
let mlxOnly = !coreML && !gguf && defaults.bool(forKey: "mlxOnly")
let compatible = !coreML && !gguf && !mlxOnly && defaults.bool(forKey: "compatibleEnabled")
let model = coreML ? coreMLPath : gguf ? ggufPath : defaults.string(forKey: compatible ? "compatibleModel" : "ollamaModel") ?? ""
let mlxPath = defaults.string(forKey: "mlxPath") ?? "" let mlxPath = defaults.string(forKey: "mlxPath") ?? ""
guard mlxOnly ? !mlxPath.isEmpty : !model.isEmpty else { guard mlxOnly ? !mlxPath.isEmpty : !model.isEmpty else {
throw StudioError("Choose a generation model in Settings before evaluating.") throw StudioError("Choose a generation model in Settings before evaluating.")
@@ -581,7 +667,7 @@ final class StudioModel: ObservableObject {
: (defaults.string(forKey: "endpoint") ?? "http://127.0.0.1:11434") : (defaults.string(forKey: "endpoint") ?? "http://127.0.0.1:11434")
let (_, generate) = try inferenceRoute( let (_, generate) = try inferenceRoute(
endpoint: endpoint, model: model, mlxPath: mlxPath, mlxOnly: mlxOnly, endpoint: endpoint, model: model, mlxPath: mlxPath, mlxOnly: mlxOnly,
compatible: compatible, failover: defaults.object(forKey: "failover") as? Bool ?? true) compatible: compatible, failover: defaults.object(forKey: "failover") as? Bool ?? true, gguf: gguf, coreML: coreML)
let settings = GenerationSettings.read(defaults.data(forKey: GenerationSettings.key) ?? Data()) let settings = GenerationSettings.read(defaults.data(forKey: GenerationSettings.key) ?? Data())
let prepared = try StudioPromptRequest.prepare([Message(role: .user, content: input)], template: template, let prepared = try StudioPromptRequest.prepare([Message(role: .user, content: input)], template: template,
options: .init(), parameters: settings.parameters(mlxOnly: mlxOnly, compatible: compatible)) options: .init(), parameters: settings.parameters(mlxOnly: mlxOnly, compatible: compatible))
@@ -848,18 +934,16 @@ final class StudioModel: ObservableObject {
} }
for task in connecting { await task.value } for task in connecting { await task.value }
try Task.checkCancellation() try Task.checkCancellation()
guard let server = activeToolsets.first(where: { guard let server = repositoryToolset else {
$0.toolset.tools.contains { $0.name == "list_repositories" }
}) else {
throw StudioError("Connect your Gitea server in Settings → Toolbox to list repositories.") throw StudioError("Connect your Gitea server in Settings → Toolbox to list repositories.")
} }
let entries = try await GiteaRepositoryLookup.entries(client: server.toolset.client) let entries = try await GiteaRepositoryLookup.entries(client: server.client)
try Task.checkCancellation() try Task.checkCancellation()
let shown = entries.prefix(limit) let shown = entries.prefix(limit)
let summary = shown.isEmpty ? "Gitea returned no repositories for the connected account." : let summary = shown.isEmpty ? "Gitea returned no repositories for the connected account." :
"Showing \(shown.count) of \(entries.count) repositories returned by Gitea.\n\n" + "Showing \(shown.count) of \(entries.count) repositories returned by Gitea.\n\n" +
shown.enumerated().map { "\($0.offset + 1). \($0.element)" }.joined(separator: "\n") shown.enumerated().map { "\($0.offset + 1). \($0.element)" }.joined(separator: "\n")
let reply = Message(role: .assistant, content: summary, backend: "Gitea · " + server.toolset.name) let reply = Message(role: .assistant, content: summary, backend: "Gitea · " + server.name)
try store.save(reply, in: chat) try store.save(reply, in: chat)
if selected == chat { messages.append(reply) } if selected == chat { messages.append(reply) }
} catch { } catch {
@@ -939,8 +1023,37 @@ final class StudioModel: ObservableObject {
} catch { status = error.localizedDescription } } catch { status = error.localizedDescription }
} }
@Published private(set) var discoveredMLXPaths: [String] = []
func refreshLocalMLXModels() async throws {
let scan = Task.detached(priority: .utility) { try MLXLibrary.discoverLocalModels() }
let paths = try await withTaskCancellationHandler {
try await scan.value.map(\.path)
} onCancel: { scan.cancel() }
try Task.checkCancellation()
discoveredMLXPaths = paths
}
func forgetDiscoveredMLXModel(_ path: String) {
discoveredMLXPaths.removeAll { $0 == path }
}
func selectCoreMLModel(_ path: String) {
UserDefaults.standard.removeObject(forKey: "defaultGGUFPath")
UserDefaults.standard.set(path, forKey: "defaultCoreMLPath")
modelSelectionRevision += 1
}
func selectGGUFModel(_ path: String) {
UserDefaults.standard.removeObject(forKey: "defaultCoreMLPath")
UserDefaults.standard.set(path, forKey: "defaultGGUFPath")
modelSelectionRevision += 1
}
func selectMLXModel(_ path: String) { func selectMLXModel(_ path: String) {
let defaults = UserDefaults.standard let defaults = UserDefaults.standard
defaults.removeObject(forKey: "defaultGGUFPath")
defaults.removeObject(forKey: "defaultCoreMLPath")
defaults.set(path, forKey: "mlxPath") defaults.set(path, forKey: "mlxPath")
defaults.set(true, forKey: "mlxOnly") defaults.set(true, forKey: "mlxOnly")
modelSelectionRevision += 1 modelSelectionRevision += 1
@@ -948,6 +1061,8 @@ final class StudioModel: ObservableObject {
func selectOllamaModel(_ name: String) { func selectOllamaModel(_ name: String) {
let defaults = UserDefaults.standard let defaults = UserDefaults.standard
defaults.removeObject(forKey: "defaultGGUFPath")
defaults.removeObject(forKey: "defaultCoreMLPath")
defaults.set(name, forKey: "ollamaModel") defaults.set(name, forKey: "ollamaModel")
defaults.set(false, forKey: "compatibleEnabled") defaults.set(false, forKey: "compatibleEnabled")
defaults.set(false, forKey: "mlxOnly") defaults.set(false, forKey: "mlxOnly")
@@ -959,7 +1074,11 @@ final class StudioModel: ObservableObject {
try await mlx.load(path) try await mlx.load(path)
} }
func unloadMLX() { Task { await mlx.unload() } } func unloadMLX() { Task { await unloadMLXModel() } }
func unloadMLXModel() async { await mlx.unload() }
func mlxLoadedPath() async -> String? { await mlx.modelDirectory() }
func mlxModelName() async -> String? { await mlx.modelName() } func mlxModelName() async -> String? { await mlx.modelName() }
@@ -992,25 +1111,22 @@ final class StudioModel: ObservableObject {
} }
private func consume(_ stream: AsyncThrowingStream<Delta, Error>, in chat: UUID, private func consume(_ stream: AsyncThrowingStream<Delta, Error>, in chat: UUID,
start: Double, requested: String) async { start: Double, requested: String, model: String) async {
var firstOutput: Double? var capture = GenerationCapture(start: start)
var provider: ProviderMetrics?
defer { partial = nil; running = false; generation = nil } defer { partial = nil; running = false; generation = nil }
do { do {
for try await delta in stream { for try await delta in stream {
try Task.checkCancellation() try Task.checkCancellation()
capture.observe(delta, at: ProcessInfo.processInfo.systemUptime)
switch delta { switch delta {
case .answer(let text): case .answer(let text):
if firstOutput == nil, !text.isEmpty { firstOutput = ProcessInfo.processInfo.systemUptime - start }
partial?.content += text partial?.content += text
case .thinking(let text): case .thinking(let text):
if firstOutput == nil, !text.isEmpty { firstOutput = ProcessInfo.processInfo.systemUptime - start }
partial?.thinking += text partial?.thinking += text
case .backend(let name): case .backend(let name):
inferenceBackend = name inferenceBackend = name
partial?.backend = name partial?.backend = name
case .metrics(let metrics): provider = metrics case .metrics, .committed: break
case .committed: break
} }
} }
try Task.checkCancellation() try Task.checkCancellation()
@@ -1020,19 +1136,11 @@ final class StudioModel: ObservableObject {
} catch { } catch {
status = Task.isCancelled ? "Generation stopped." : error.localizedDescription status = Task.isCancelled ? "Generation stopped." : error.localizedDescription
} }
let backend = partial?.backend ?? "" let measurement = capture.finish(at: ProcessInfo.processInfo.systemUptime, requested: requested,
measurements.insert(GenerationMeasurement( model: model, outcome: Task.isCancelled ? "Stopped" : (status.isEmpty ? "Complete" : "Failed"))
backend: backend.isEmpty ? requested : backend, record(measurement)
firstOutput: firstOutput,
seconds: ProcessInfo.processInfo.systemUptime - start,
characters: (partial?.content.count ?? 0) + (partial?.thinking.count ?? 0),
provider: provider, outcome: Task.isCancelled ? "Stopped" : (status.isEmpty ? "Complete" : "Failed")
), at: 0)
if measurements.count > 50 { measurements.removeLast() }
if let history = try? JSONEncoder().encode(measurements) {
UserDefaults.standard.set(history, forKey: GenerationMeasurement.key)
}
if var reply = partial, !reply.content.isEmpty || !reply.thinking.isEmpty { if var reply = partial, !reply.content.isEmpty || !reply.thinking.isEmpty {
reply.performance = measurement
if !status.isEmpty { reply.backend += " · Interrupted" } if !status.isEmpty { reply.backend += " · Interrupted" }
do { do {
try database().save(reply, in: chat) try database().save(reply, in: chat)
@@ -1044,6 +1152,15 @@ final class StudioModel: ObservableObject {
} }
} }
private func record(_ measurement: GenerationMeasurement) {
let defaults = UserDefaults.standard
let previous = GenerationMeasurement.history(defaults.data(forKey: GenerationMeasurement.key) ?? Data())
measurements = Array(([measurement] + previous).prefix(50))
if let data = try? JSONEncoder().encode(measurements) {
defaults.set(data, forKey: GenerationMeasurement.key)
}
}
private func database() throws -> Store { private func database() throws -> Store {
guard let store else { throw StudioError("The chat database is unavailable.") } guard let store else { throw StudioError("The chat database is unavailable.") }
return store return store
@@ -1129,6 +1246,7 @@ extension StudioModel {
runMCP(id, progress: "Running \(tool)…") { runMCP(id, progress: "Running \(tool)…") {
let client: any MCPToolClient = id == .web ? BuiltInWebTools(searchEndpoint: searchEndpoint) : connected.client let client: any MCPToolClient = id == .web ? BuiltInWebTools(searchEndpoint: searchEndpoint) : connected.client
let response = try await client.callTool(tool, argumentsJSON: arguments) let response = try await client.callTool(tool, argumentsJSON: arguments)
try MCPToolResponse.check(response, tool: tool)
return MCPConnectionState(toolset: connected, output: String(decoding: response, as: UTF8.self), return MCPConnectionState(toolset: connected, output: String(decoding: response, as: UTF8.self),
completedTool: tool) completedTool: tool)
} }
+542 -5
View File
@@ -6,6 +6,412 @@ import SQLite3
@testable import AIStudio @testable import AIStudio
final class StudioTests: XCTestCase { final class StudioTests: XCTestCase {
func testGGUFHeaderRecognizesSupportedVersionsAndRejectsInvalidFiles() throws {
for version: UInt8 in [2, 3] {
XCTAssertEqual(try GGUFHeader.version(in: Data([71, 71, 85, 70, version, 0, 0, 0])), UInt32(version))
}
for bytes: [UInt8] in [[], [71, 71, 85, 70], [71, 71, 85, 70, 4, 0, 0, 0], [0, 71, 85, 70, 3, 0, 0, 0]] {
XCTAssertThrowsError(try GGUFHeader.version(in: Data(bytes)))
}
}
func testGGUFModelChoiceRoundTripsWithExistingBackends() throws {
let records = Dictionary(uniqueKeysWithValues: [
ChatModelChoice(backend: .gguf, model: "/Models/Example-Q4_K_M.gguf"),
ChatModelChoice(backend: .mlx, model: "/Models/MLX"),
ChatModelChoice(backend: .ollama, model: "test:latest"),
ChatModelChoice(backend: .compatible, model: "api-model")
].map { (UUID(), $0) })
XCTAssertEqual(ChatModelChoice.read(try JSONEncoder().encode(records)), records)
XCTAssertEqual(records.values.first(where: { $0.backend == .gguf })?.displayName, "Example-Q4_K_M")
}
func testGGUFProviderRejectsImagesBeforeLoadingAFile() async throws {
let request = InferenceRequest(model: "/missing.gguf", messages: [
Message(role: .user, content: "Describe this", imagePNG: Data([1]))
], thinking: .automatic)
do {
for try await _ in GGUFProvider().generate(request) {
XCTFail("Unexpected output for an image request")
}
XCTFail("Expected a text-only error")
} catch {
XCTAssertEqual(error.localizedDescription, "This GGUF backend supports text input.")
}
}
func testGGUFMetalStreamingWithLocalFixture() async throws {
guard let path = ProcessInfo.processInfo.environment["AISTUDIO_TEST_GGUF_PATH"] else {
throw XCTSkip("Set TEST_RUNNER_AISTUDIO_TEST_GGUF_PATH to a local GGUF chat fixture.")
}
var parameters = GenerationParameters()
parameters.temperature = 0
parameters.maxTokens = 8
var answer = ""
var backend = ""
var metrics: ProviderMetrics?
let request = InferenceRequest(model: path, messages: [.init(role: .user, content: "Once upon a time")],
thinking: .automatic, parameters: parameters)
for try await delta in GGUFProvider().generate(request) {
switch delta {
case .answer(let text): answer += text
case .backend(let value): backend = value
case .metrics(let value): metrics = value
case .thinking, .committed: break
}
}
XCTAssertFalse(answer.isEmpty)
XCTAssertEqual(backend, "GGUF · Metal")
XCTAssertTrue((1...8).contains(try XCTUnwrap(metrics).tokens))
}
func testLocalModelImportDetectsMLXAndRejectsIncompleteOrUnsupportedItems() throws {
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
XCTAssertThrowsError(try LocalModelImport.inspect(root))
let unsupported = root.appending(path: "weights.bin")
try Data([1]).write(to: unsupported)
XCTAssertThrowsError(try LocalModelImport.inspect(unsupported))
try Data("{}".utf8).write(to: root.appending(path: "config.json"))
try Data([1]).write(to: root.appending(path: "model.safetensors"))
XCTAssertEqual(try LocalModelImport.inspect(root), .mlx(root.resolvingSymlinksInPath().path))
}
func testLocalModelImportRecognizesGGUFByContentsAndRejectsTruncation() throws {
guard let path = ProcessInfo.processInfo.environment["AISTUDIO_TEST_GGUF_PATH"] else {
throw XCTSkip("Set TEST_RUNNER_AISTUDIO_TEST_GGUF_PATH to a local GGUF chat fixture.")
}
let source = URL(fileURLWithPath: path)
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
let renamed = root.appending(path: "renamed.weights")
let contents = try Data(contentsOf: source)
try contents.write(to: renamed)
guard case .gguf(let metadata) = try LocalModelImport.inspect(renamed) else {
return XCTFail("Expected GGUF metadata")
}
XCTAssertEqual(metadata.architectureName, "Llama")
let truncated = root.appending(path: "truncated.gguf")
try contents.prefix(contents.count / 2).write(to: truncated)
XCTAssertThrowsError(try LocalModelImport.inspect(truncated))
}
func testHubGGUFMetadataPinsRevisionAndFiltersUnsupportedFiles() throws {
let revision = String(repeating: "a", count: 40)
let digest = String(repeating: "b", count: 64)
let data = Data("""
{"id":"owner/model","sha":"\(revision)","private":false,"gated":false,"siblings":[
{"rfilename":"model-Q4_K.gguf","size":100,"lfs":{"size":100,"sha256":"\(digest)"}},
{"rfilename":"../bad.gguf","size":100},
{"rfilename":"split-00001-of-00002.gguf","size":100},
{"rfilename":"weights.safetensors","size":100}
]}
""".utf8)
let assets = try HubGGUFAsset.decodeRepository(data, requested: "owner/model")
let model = try XCTUnwrap(assets.first)
XCTAssertEqual(assets.count, 1)
XCTAssertEqual(model.bytes, 100)
XCTAssertEqual(model.sha256, digest)
XCTAssertEqual(model.url.absoluteString, "https://huggingface.co/owner/model/resolve/\(revision)/model-Q4_K.gguf")
XCTAssertThrowsError(try HubGGUFAsset.decodeRepository(data, requested: "owner/other"))
let gated = Data(String(decoding: data, as: UTF8.self).replacingOccurrences(of: "\"gated\":false", with: "\"gated\":\"auto\"").utf8)
XCTAssertThrowsError(try HubGGUFAsset.decodeRepository(gated, requested: "owner/model"))
}
func testHubGGUFInstallVerifiesDigestBeforePublishingFile() async throws {
guard let path = ProcessInfo.processInfo.environment["AISTUDIO_TEST_GGUF_PATH"] else {
throw XCTSkip("Set TEST_RUNNER_AISTUDIO_TEST_GGUF_PATH to a local GGUF chat fixture.")
}
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
let contents = try Data(contentsOf: URL(fileURLWithPath: path))
let asset = HubGGUFAsset(repository: "owner/model", revision: String(repeating: "a", count: 40),
filename: "model.gguf", bytes: Int64(contents.count), sha256: nil)
let destination = root.appending(path: "install/model.gguf")
let imported = try await asset.install(to: destination, progress: { _, _ in }, transfer: { _, target, _ in
try contents.write(to: target)
})
XCTAssertEqual(imported.architectureName, "Llama")
XCTAssertEqual(try Data(contentsOf: destination), contents)
let corrupt = HubGGUFAsset(repository: asset.repository, revision: asset.revision, filename: asset.filename,
bytes: asset.bytes, sha256: String(repeating: "0", count: 64))
let rejected = root.appending(path: "invalid/model.gguf")
do {
_ = try await corrupt.install(to: rejected, progress: { _, _ in }, transfer: { _, target, _ in
try contents.write(to: target)
})
XCTFail("The checksum mismatch should reject the download")
} catch {
XCTAssertTrue(error.localizedDescription.contains("checksum"))
}
XCTAssertFalse(FileManager.default.fileExists(atPath: rejected.path))
XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath: rejected.deletingLastPathComponent().path).isEmpty)
}
func testLiveHubGGUFDownloadInstallsAndStreams() async throws {
let env = ProcessInfo.processInfo.environment
guard let repository = env["AISTUDIO_TEST_GGUF_HUB_REPO"], let filename = env["AISTUDIO_TEST_GGUF_HUB_FILE"] else {
throw XCTSkip("Set the TEST_RUNNER_AISTUDIO_TEST_GGUF_HUB_REPO and TEST_RUNNER_AISTUDIO_TEST_GGUF_HUB_FILE variables.")
}
let assets = try await HubGGUFAsset.resolve(repository)
let asset = try XCTUnwrap(assets.first { $0.filename == filename })
XCTAssertNotNil(asset.sha256)
let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
defer { try? FileManager.default.removeItem(at: folder) }
let updates = AsyncStream<Int64>.makeStream(bufferingPolicy: .bufferingNewest(1))
let model = try await asset.install(to: folder.appending(path: filename), progress: { written, _ in
updates.continuation.yield(written)
})
updates.continuation.finish()
var reportedBytes: Int64?
for await written in updates.stream { reportedBytes = written }
XCTAssertEqual(reportedBytes, asset.bytes)
var settings = GenerationParameters()
settings.temperature = 0
settings.maxTokens = 8
let request = InferenceRequest(model: model.path, messages: [.init(role: .user, content: "What is 2 + 2?")],
thinking: .automatic, parameters: settings)
var reply = ""
for try await delta in GGUFProvider().generate(request) {
if case .answer(let text) = delta { reply += text }
}
XCTAssertFalse(reply.isEmpty)
}
func testGGUFCatalogFiltersRestrictedAndDuplicateRepositories() throws {
let json = Data("""
[{"id":"owner/open","downloads":73,"gated":false},
{"id":"Owner/Open"},{"id":"owner/gated","gated":"auto"},
{"id":"owner/private","private":true},{"id":"../unsafe"}]
""".utf8)
let models = try HubGGUFAsset.decodeSearch(json)
XCTAssertEqual(models.map(\.id), ["owner/open"])
XCTAssertEqual(models.first?.downloads, 73)
}
@MainActor
func testInstalledLMStudioModelsAndHuggingFaceDiscovery() async throws {
guard ProcessInfo.processInfo.environment["AISTUDIO_TEST_LM_STUDIO"] == "1" else {
throw XCTSkip("Enable the installed LM Studio library and live Hugging Face smoke test.")
}
let library = try LocalModelImport.discover(in: LocalModelImport.lmStudioFolder)
let folders = try MLXLibrary.discover(in: LocalModelImport.lmStudioFolder)
for name in ["Qwen3.5-9B-MLX-4bit", "Mistral-Nemo-Instruct-2407-4bit"] {
let folder = try XCTUnwrap(folders.first { $0.lastPathComponent == name })
XCTAssertTrue(library.contains(.mlx(folder.path)))
}
let gguf = library.compactMap { entry -> GGUFModelMetadata? in
guard case .gguf(let model) = entry else { return nil }
return model
}
XCTAssertFalse(gguf.contains { URL(fileURLWithPath: $0.path).lastPathComponent.hasPrefix("mmproj") })
let model = try XCTUnwrap(gguf.first { $0.architecture == "qwen35" })
let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
defer { try? FileManager.default.removeItem(at: folder) }
let studio = StudioModel()
studio.open(databaseURL: folder.appending(path: "studio.sqlite"))
studio.prompt = "Hello"
var settings = GenerationSettings()
settings.temperature = "0"
settings.maxTokens = "24"
settings.context = "1024"
studio.send(endpoint: "unused", model: model.path, mlxPath: "", thinking: .off,
failover: false, mlxOnly: false, compatible: false, recall: false,
useDocuments: false, instructions: "", settings: settings, gguf: true)
let deadline = ContinuousClock.now + .seconds(30)
while studio.running && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(50)) }
XCTAssertFalse(studio.running)
let reply = try XCTUnwrap(studio.messages.last(where: { $0.role == .assistant }), studio.status)
XCTAssertFalse(reply.content.isEmpty)
XCTAssertEqual(reply.backend, "GGUF · Metal")
XCTAssertTrue(model.supportsThinking)
var parameters = GenerationParameters()
parameters.temperature = 0
parameters.maxTokens = 24
parameters.context = 1024
let thinkingRequest = InferenceRequest(model: model.path,
messages: [.init(role: .user, content: "What is 2 + 2?")],
thinking: .on, parameters: parameters)
var reasoning = ""
for try await delta in GGUFProvider().generate(thinkingRequest) {
if case .thinking(let text) = delta { reasoning += text }
}
XCTAssertFalse(reasoning.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
let candidates = try await HubGGUFAsset.search("Qwen3.5")
XCTAssertFalse(candidates.isEmpty)
let mlx = try await CatalogModel.search("Qwen")
XCTAssertFalse(mlx.isEmpty)
}
func testLocalHistoryCoalescesAdjacentTurnsAndKeepsTheirText() {
let messages: [Message] = [
.init(role: .assistant, content: "Earlier reply"),
.init(role: .system, content: "Be concise"),
.init(role: .user, content: "Stopped turn"),
.init(role: .user, content: "Next question"),
.init(role: .assistant, content: "Reply"),
.init(role: .user, content: "Follow-up")
]
let result = LocalChatHistory.prepare(messages)
XCTAssertEqual(result.map(\.role), [.system, .user, .assistant, .user])
XCTAssertEqual(result[0].content, "Be concise")
XCTAssertTrue(result[1].content.contains("Earlier reply"))
XCTAssertTrue(result[1].content.hasSuffix("Stopped turn\n\nNext question"))
XCTAssertEqual(result.last?.content, "Follow-up")
XCTAssertEqual(messages.count, 6)
}
func testGGUFThinkingSetsSupportedPromptAndSeparatesReasoning() {
let prompt = "<|im_start|>assistant\n"
let template = "enable_thinking <|im_start|>assistant <think> </think>"
let enabled = GGUFThinking.prepare(prompt, template: template, mode: .on)
XCTAssertEqual(enabled.prompt, prompt + "<think>\n")
var output = ThinkingOutput(prefilled: enabled.prefilled)
XCTAssertEqual(output.append("Reason</think>Answer"), [.thinking("Reason"), .answer("Answer")])
let disabled = GGUFThinking.prepare(prompt, template: template, mode: .off)
XCTAssertEqual(disabled.prompt, prompt + "<think>\n\n</think>\n\n")
XCTAssertEqual(GGUFThinking.prepare(prompt, template: "plain", mode: .on).prompt, prompt)
}
func testMemoryBudgetFlagsWeightSizesAboveTheLimit() {
XCTAssertTrue(ModelMemoryBudget.exceeds(bytes: 101, budget: 100))
XCTAssertFalse(ModelMemoryBudget.exceeds(bytes: 100, budget: 100))
XCTAssertFalse(ModelMemoryBudget.exceeds(bytes: nil, budget: 100))
XCTAssertFalse(ModelMemoryBudget.exceeds(bytes: 100, budget: nil))
}
func testCoreMLImportedModelChoiceAndCausalMask() throws {
let choice = ChatModelChoice(backend: .coreML, model: "/Models/Chat.mlpackage")
let id = UUID()
XCTAssertEqual(ChatModelChoice.read(try JSONEncoder().encode([id: choice]))[id], choice)
XCTAssertEqual(choice.displayName, "Chat")
XCTAssertEqual(CoreMLInputs.mask(queryCount: 2, pastCount: 1), [0, 0, -65504, 0, 0, 0])
}
@MainActor
func testLiveAppleCoreMLChat() async throws {
guard let path = ProcessInfo.processInfo.environment["AISTUDIO_TEST_COREML_PATH"] else {
throw XCTSkip("Set TEST_RUNNER_AISTUDIO_TEST_COREML_PATH to the compatible Core ML package.")
}
let model = try CoreMLLibrary.inspect(URL(fileURLWithPath: path))
XCTAssertGreaterThan(model.bytes, 0)
let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
defer { try? FileManager.default.removeItem(at: folder) }
let studio = StudioModel()
studio.open(databaseURL: folder.appending(path: "studio.sqlite"))
studio.prompt = "What is two plus two?"
var config = GenerationSettings()
config.maxTokens = "32"
config.temperature = "0"
studio.send(endpoint: "unused", model: model.path, mlxPath: "", thinking: .off,
failover: false, mlxOnly: false, compatible: false, recall: false,
useDocuments: false, instructions: "", settings: config, ragEnabled: false, coreML: true)
let deadline = ContinuousClock.now + .seconds(180)
while studio.running && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(50)) }
XCTAssertFalse(studio.running)
let reply = try XCTUnwrap(studio.messages.last(where: { $0.role == .assistant }), studio.status)
XCTAssertEqual(reply.backend, "Core ML")
XCTAssertTrue(reply.content.localizedCaseInsensitiveContains("four") || reply.content.contains("4"), reply.content)
let results = try await HubGGUFAsset.search("mistral", format: "coreml")
XCTAssertFalse(results.isEmpty)
}
func testThinkingControlKeepsDefaultForUnsupportedBackends() {
XCTAssertEqual(ChatThinkingControl.options(backend: .coreML, supportsLocalThinking: false), [.automatic])
XCTAssertEqual(ChatThinkingControl.options(backend: .gguf, supportsLocalThinking: true), [.automatic, .off, .on])
XCTAssertEqual(ChatThinkingControl.options(backend: .mlx, supportsLocalThinking: false), [.automatic])
XCTAssertEqual(ChatThinkingControl.options(backend: .ollama, supportsLocalThinking: false), Thinking.allCases)
}
func testImagePreviewScalesAndEncodesPNG() throws {
let bitmap = try XCTUnwrap(NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 80, pixelsHigh: 40,
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB,
bytesPerRow: 0, bitsPerPixel: 0))
let source = try XCTUnwrap(bitmap.representation(using: .png, properties: [:]))
let preview = try StudioImagePreview(data: source, name: "Test", maxDimension: 20)
XCTAssertEqual(preview.width, 80)
XCTAssertEqual(preview.height, 40)
let thumbnail = try XCTUnwrap(NSBitmapImageRep(data: preview.png))
XCTAssertEqual(thumbnail.pixelsWide, 20)
XCTAssertEqual(thumbnail.pixelsHigh, 10)
XCTAssertThrowsError(try StudioImagePreview(data: Data([1]), name: "Invalid"))
}
func testGenerationTimingCapturesReasoningAndProviderThroughput() {
var capture = GenerationCapture(start: 10)
capture.observe(.backend("GGUF · Metal"), at: 10.1)
capture.observe(.answer(""), at: 10.2)
capture.observe(.thinking("Plan"), at: 11)
capture.observe(.answer("Reply"), at: 12)
capture.observe(.metrics(.init(tokens: 10, seconds: 2)), at: 12)
let result = capture.finish(at: 14, requested: "GGUF", model: "Test", outcome: "Complete", benchmark: true)
XCTAssertEqual(result.backend, "GGUF · Metal")
XCTAssertEqual(result.firstOutput, 1)
XCTAssertEqual(result.seconds, 4)
XCTAssertEqual(result.charactersPerSecond, 3)
XCTAssertEqual(result.provider?.tokensPerSecond, 5)
XCTAssertEqual(result.benchmark, true)
}
func testChatPersistsTimingAndReadsExistingMeasurements() throws {
let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: directory) }
let url = directory.appending(path: "studio.sqlite")
let store = try Store(url: url)
let conversation = try store.create(title: "Performance")
let legacy = Data("""
[{"id":"00000000-0000-0000-0000-000000000001","backend":"MLX","firstOutput":1,"seconds":2,"characters":10,"outcome":"Complete"}]
""".utf8)
let timing = try XCTUnwrap(JSONDecoder().decode([GenerationMeasurement].self, from: legacy).first)
XCTAssertNil(timing.model)
try store.save(Message(role: .user, content: "Hello"), in: conversation.id)
try store.save(Message(role: .assistant, content: "Hello", performance: timing), in: conversation.id)
let messages = try Store(url: url).messages(in: conversation.id)
XCTAssertNil(messages.first?.performance)
XCTAssertEqual(messages.last?.performance, timing)
}
func testMarkdownExportIncludesEntireStoredConversationInOrder() throws {
let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: directory) }
let store = try Store(url: directory.appending(path: "workspace.sqlite"))
let chat = try store.create(title: "Café [notes]")
let other = try store.create(title: "Another chat")
try store.save(Message(role: .user, content: "Separate conversation"), in: other.id)
for index in 0..<40 {
try store.save(Message(role: .user, content: "Saved message \(index)",
documentNames: index == 0 ? ["report.pdf"] : []), in: chat.id)
}
let url = try XCTUnwrap(URL(string: "https://example.com/page"))
let answer = "Sample code\n\n```swift\nprint(42)\n```"
try store.save(Message(role: .assistant, content: answer, thinking: "First line\nSecond line",
backend: "Ollama · example", webSources: [
WebReplySource(url: url, title: "Source [one]", kind: .page)
], documentCitations: [
DocumentCitation(number: 1, title: "report.pdf", excerpt: "Page 1\nFull excerpt",
documentID: nil, chunkID: nil)
]), in: chat.id)
let destination = directory.appending(path: "export.md")
try store.exportChat(chat.id, to: destination)
let markdown = try String(contentsOf: destination, encoding: .utf8)
XCTAssertTrue(markdown.hasPrefix("# Café \\[notes\\]\n\n## You\n\nSaved message 0\n"))
let messagesInOrder = (0..<40).map { "Saved message \($0)" }
XCTAssertEqual(markdown.components(separatedBy: .newlines).filter { $0.hasPrefix("Saved message ") },
messagesInOrder)
XCTAssertTrue(markdown.contains("## Assistant\n\n*Ollama · example*\n\n" + answer))
XCTAssertTrue(markdown.contains("> First line\n> Second line"))
XCTAssertTrue(markdown.contains("- report.pdf"))
XCTAssertTrue(markdown.contains("**\\[D1\\] report.pdf**\n\n> Page 1\n> Full excerpt"))
XCTAssertTrue(markdown.contains("- [Source \\[one\\]](<https://example.com/page>)"))
XCTAssertFalse(markdown.contains("Separate conversation"))
}
func testHybridSearchPromotesAgreementBetweenRankings() throws { func testHybridSearchPromotesAgreementBetweenRankings() throws {
let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
@@ -108,6 +514,13 @@ final class StudioTests: XCTestCase {
XCTAssertEqual(output, [.answer("fallback")]) XCTAssertEqual(output, [.answer("fallback")])
} }
func testEmptySuccessfulStreamFallsBack() async throws {
let output = try await collect(Router.stream(
primary: { AsyncThrowingStream { $0.finish() } }, fallback: { success() }
))
XCTAssertEqual(output, [.answer("fallback")])
}
func testThinkingCommitsRoute() async throws { func testThinkingCommitsRoute() async throws {
var received: [Delta] = [] var received: [Delta] = []
do { do {
@@ -247,7 +660,9 @@ final class LiveInferenceTests: XCTestCase {
examples: [PromptExample(input: "Repeat this word: goodbye.", output: "goodbye")]), examples: [PromptExample(input: "Repeat this word: goodbye.", output: "goodbye")]),
options: AgentPromptSettings(contextBudget: "512", outputTokens: "64"), options: AgentPromptSettings(contextBudget: "512", outputTokens: "64"),
parameters: GenerationParameters(temperature: 0)) parameters: GenerationParameters(temperature: 0))
let request = InferenceRequest(model: directory, messages: prepared.messages, var history = prepared.messages
history.insert(Message(role: .user, content: "An earlier message whose generation was stopped."), at: history.count - 1)
let request = InferenceRequest(model: directory, messages: history,
thinking: .off, parameters: prepared.parameters) thinking: .off, parameters: prepared.parameters)
do { do {
_ = try await collect(mlx.generate(request)) _ = try await collect(mlx.generate(request))
@@ -302,7 +717,7 @@ final class ExpandedStudioTests: XCTestCase {
} }
func testReasoningMarkersCanCrossStreamChunks() { func testReasoningMarkersCanCrossStreamChunks() {
var stream = MLXThinking() var stream = ThinkingOutput()
XCTAssertEqual(stream.append(" <thi"), []) XCTAssertEqual(stream.append(" <thi"), [])
XCTAssertEqual(stream.append("nk>reason</th"), [.thinking("reason")]) XCTAssertEqual(stream.append("nk>reason</th"), [.thinking("reason")])
XCTAssertEqual(stream.append("ink>hello"), [.answer("hello")]) XCTAssertEqual(stream.append("ink>hello"), [.answer("hello")])
@@ -310,7 +725,7 @@ final class ExpandedStudioTests: XCTestCase {
} }
func testMLXThinkingDoesNotConsumeOrdinaryAnswer() { func testMLXThinkingDoesNotConsumeOrdinaryAnswer() {
var stream = MLXThinking() var stream = ThinkingOutput()
XCTAssertEqual(stream.append("Hello"), [.answer("Hello")]) XCTAssertEqual(stream.append("Hello"), [.answer("Hello")])
XCTAssertEqual(stream.append(" <think>inside answer"), [.answer(" <think>inside answer")]) XCTAssertEqual(stream.append(" <think>inside answer"), [.answer(" <think>inside answer")])
} }
@@ -328,6 +743,8 @@ final class ExpandedStudioTests: XCTestCase {
throw XCTSkip("Enable live catalog checks explicitly.") throw XCTSkip("Enable live catalog checks explicitly.")
} }
let mlx = try await CatalogModel.search("") let mlx = try await CatalogModel.search("")
let custom = try await CatalogModel.resolve("mlx-community/Qwen3-0.6B-4bit")
XCTAssertEqual(custom.repository, "mlx-community/Qwen3-0.6B-4bit")
let ollama = try await OllamaCatalog.search("") let ollama = try await OllamaCatalog.search("")
let qwen = try await OllamaCatalog.search("qwen") let qwen = try await OllamaCatalog.search("qwen")
XCTAssertFalse(mlx.isEmpty) XCTAssertFalse(mlx.isEmpty)
@@ -351,6 +768,32 @@ final class ExpandedStudioTests: XCTestCase {
XCTAssertEqual(models.first?.likes, 3) XCTAssertEqual(models.first?.likes, 3)
} }
func testCatalogRejectsDotRepositoryAndAnotherRuntime() throws {
let sha = String(repeating: "a", count: 40)
let data = Data("""
[{"id":"mlx-community/..","sha":"\(sha)",
"siblings":[{"rfilename":"config.json"},{"rfilename":"model.safetensors"}]},
{"id":"mlx-community/GPTQ","sha":"\(sha)","library_name":"transformers",
"siblings":[{"rfilename":"config.json"},{"rfilename":"model.safetensors"}]}]
""".utf8)
XCTAssertTrue(try CatalogModel.decodeSearch(data).isEmpty)
}
func testCustomMLXRepositoryKeepsOwnerInInstallationIdentity() throws {
let sha = String(repeating: "a", count: 40)
func entry(_ owner: String) -> Data {
Data("""
{"id":"\(owner)/Shared-4bit","sha":"\(sha)","library_name":"mlx","gated":false,
"siblings":[{"rfilename":"config.json"},{"rfilename":"model.safetensors"}]}
""".utf8)
}
let first = try CatalogModel.decodeRepository(entry("team-a"), requested: "team-a/Shared-4bit")
let second = try CatalogModel.decodeRepository(entry("team-b"), requested: "team-b/Shared-4bit")
XCTAssertNotEqual(first.localFolder, second.localFolder)
XCTAssertEqual(first.source.absoluteString, "https://huggingface.co/team-a/Shared-4bit")
XCTAssertThrowsError(try CatalogModel.decodeRepository(entry("team-a"), requested: "team-b/Shared-4bit"))
}
func testDownloadedCatalogModelAndRuntime() async throws { func testDownloadedCatalogModelAndRuntime() async throws {
guard let id = ProcessInfo.processInfo.environment["AISTUDIO_TEST_MODEL_DOWNLOAD"], guard let id = ProcessInfo.processInfo.environment["AISTUDIO_TEST_MODEL_DOWNLOAD"],
let model = CatalogModel.all.first(where: { $0.id == id }) else { let model = CatalogModel.all.first(where: { $0.id == id }) else {
@@ -369,7 +812,7 @@ final class ExpandedStudioTests: XCTestCase {
XCTAssertTrue(events.contains { if case .answer(let text) = $0 { return !text.isEmpty }; return false }) XCTAssertTrue(events.contains { if case .answer(let text) = $0 { return !text.isEmpty }; return false })
XCTAssertFalse(events.contains { if case .thinking = $0 { return true }; return false }) XCTAssertFalse(events.contains { if case .thinking = $0 { return true }; return false })
if id == "qwen3-0.6b-4bit" { if id == "qwen3-0.6b-4bit" {
XCTAssertTrue(MLXThinking.supports(folder.path)) XCTAssertTrue(ThinkingOutput.supportsMLX(folder.path))
let reasoning = try await collect(provider.generate(.init(model: folder.path, messages: messages, thinking: .on))) let reasoning = try await collect(provider.generate(.init(model: folder.path, messages: messages, thinking: .on)))
XCTAssertTrue(reasoning.contains { if case .thinking(let text) = $0 { return !text.isEmpty }; return false }) XCTAssertTrue(reasoning.contains { if case .thinking(let text) = $0 { return !text.isEmpty }; return false })
} }
@@ -674,6 +1117,31 @@ final class StdioMCPTests: XCTestCase {
} }
final class DesktopRuntimeTests: XCTestCase { final class DesktopRuntimeTests: XCTestCase {
@MainActor
func testClipboardDistinguishesFilesFromOrdinaryText() throws {
let clipboard = NSPasteboard.withUniqueName()
defer { clipboard.releaseGlobally() }
let url = FileManager.default.temporaryDirectory.appending(path: "\(UUID()).txt")
defer { try? FileManager.default.removeItem(at: url) }
try Data("Pasted file contents".utf8).write(to: url)
let file = NSPasteboardItem()
XCTAssertTrue(file.setString(url.absoluteString, forType: .fileURL))
XCTAssertTrue(file.setData(Data([0]), forType: .tiff))
clipboard.clearContents()
XCTAssertTrue(clipboard.writeObjects([file]))
XCTAssertTrue(ComposerPaste.isAvailable(on: clipboard))
let paste = try XCTUnwrap(ComposerPaste.read(clipboard))
XCTAssertEqual(paste, .files([url]))
XCTAssertEqual(try paste.preview().text, "Pasted file contents")
XCTAssertThrowsError(try ComposerPaste.files([url, url]).preview())
clipboard.clearContents()
XCTAssertTrue(clipboard.setString("Ordinary draft text", forType: .string))
XCTAssertFalse(ComposerPaste.isAvailable(on: clipboard))
XCTAssertNil(ComposerPaste.read(clipboard))
}
@MainActor
func testScreenshotPreviewAndImageRequests() throws { func testScreenshotPreviewAndImageRequests() throws {
let file = FileManager.default.temporaryDirectory.appending(path: "\(UUID()).png") let file = FileManager.default.temporaryDirectory.appending(path: "\(UUID()).png")
defer { try? FileManager.default.removeItem(at: file) } defer { try? FileManager.default.removeItem(at: file) }
@@ -691,6 +1159,17 @@ final class DesktopRuntimeTests: XCTestCase {
try original.write(to: file) try original.write(to: file)
let preview = try ChatFilePreview.read(file) let preview = try ChatFilePreview.read(file)
let clipboard = NSPasteboard.withUniqueName()
defer { clipboard.releaseGlobally() }
clipboard.clearContents()
XCTAssertTrue(clipboard.setData(original, forType: .png))
XCTAssertTrue(ComposerPaste.isAvailable(on: clipboard))
let paste = try XCTUnwrap(ComposerPaste.read(clipboard))
XCTAssertEqual(paste, .image(original))
let pasted = try paste.preview()
XCTAssertEqual(pasted.name, "Pasted Image.png")
XCTAssertEqual(pasted.text, preview.text)
XCTAssertEqual(pasted.imagePNG, preview.imagePNG)
let png = try XCTUnwrap(preview.imagePNG) let png = try XCTUnwrap(preview.imagePNG)
let previewImage = try XCTUnwrap(NSBitmapImageRep(data: png)) let previewImage = try XCTUnwrap(NSBitmapImageRep(data: png))
XCTAssertEqual(previewImage.pixelsWide, 640) XCTAssertEqual(previewImage.pixelsWide, 640)
@@ -1024,6 +1503,23 @@ final class ToolboxRepairTests: XCTestCase {
XCTAssertEqual(found.map(\.lastPathComponent), ["example"]) XCTAssertEqual(found.map(\.lastPathComponent), ["example"])
} }
func testMLXScanSkipsIncompleteSnapshotsAndKeepsUsableOnes() throws {
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let snapshots = root.appending(path: "models--team--test/snapshots")
let ready = snapshots.appending(path: "ready")
let partial = snapshots.appending(path: "partial")
for folder in [ready, partial] {
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
try Data(#"{"model_type":"llama"}"#.utf8).write(to: folder.appending(path: "config.json"))
try Data([1]).write(to: folder.appending(path: "model-00001.safetensors"))
try Data(#"{"weight_map":{"a":"model-00001.safetensors","b":"model-00002.safetensors"}}"#.utf8)
.write(to: folder.appending(path: "model.safetensors.index.json"))
}
try Data([2]).write(to: ready.appending(path: "model-00002.safetensors"))
XCTAssertEqual(try MLXLibrary.discover(in: root).map(\.lastPathComponent), ["ready"])
}
func testExternalVectorQueryReferencesSources() async throws { func testExternalVectorQueryReferencesSources() async throws {
struct Knowledge: MCPToolClient { struct Knowledge: MCPToolClient {
func listTools() async throws -> [MCPTool] { [] } func listTools() async throws -> [MCPTool] { [] }
@@ -1092,6 +1588,21 @@ final class MultipleToolsetsTests: XCTestCase {
XCTAssertNil(afterDisable.mcpConnections[.web]) XCTAssertNil(afterDisable.mcpConnections[.web])
} }
@MainActor
func testMCPToolFailureIsNotAttachable() async throws {
let studio = StudioModel()
let id = MCPConnectionID.profile("Failure")
studio.connectMCP(id, name: "Failure") {
MockClient(identifier: #"{"isError":true,"content":[{"type":"text","text":"Access denied"}]}"#)
}
try await waitUntil { studio.mcpConnections[id]?.toolset != nil }
studio.invokeMCP(id, tool: "echo", arguments: Data("{}".utf8), searchEndpoint: "")
try await waitUntil { studio.mcpConnections[id]?.progress == nil }
XCTAssertEqual(studio.mcpConnections[id]?.failed, true)
XCTAssertNil(studio.mcpConnections[id]?.completedTool)
XCTAssertTrue(studio.mcpConnections[id]?.output.contains("Access denied") == true)
}
@MainActor @MainActor
func testSeparateConnectionsRunCallsAndRetainResultsIndependently() async throws { func testSeparateConnectionsRunCallsAndRetainResultsIndependently() async throws {
let studio = StudioModel() let studio = StudioModel()
@@ -1485,6 +1996,23 @@ final class AgentWorkflowTests: XCTestCase {
XCTAssertNotEqual(ModelLibrarySize.label(6_600_000_000), "Size unknown") XCTAssertNotEqual(ModelLibrarySize.label(6_600_000_000), "Size unknown")
} }
func testGGUFSelectionSuppressesStaleDefaultsAndNormalizesPaths() {
let gguf = ModelLibrarySelection(mlxOnly: true, compatible: false, mlxPath: "/tmp/models/MLX",
ollamaModel: "legacy", ggufPath: "/tmp/models/./chat.gguf")
XCTAssertTrue(gguf.isGGUF("/tmp/models/chat.gguf"))
XCTAssertFalse(gguf.isGGUF("/tmp/models/other.gguf"))
XCTAssertFalse(gguf.isMLX("/tmp/models/MLX"))
XCTAssertFalse(gguf.isOllama("legacy"))
}
func testGGUFLibraryDisplaysRecognizableArchitectureNames() {
for (architecture, label) in [("llama", "Llama"), ("mpt", "MPT"), ("openelm", "OpenELM"), ("future", "future")] {
let model = GGUFModelMetadata(path: "/tmp/chat.gguf", version: 3, tensorFormat: "Q4_K",
architecture: architecture)
XCTAssertEqual(model.architectureName, label)
}
}
func testSelectionIncludesBackendAndNormalizesMLXFolders() { func testSelectionIncludesBackendAndNormalizesMLXFolders() {
let mlx = ModelLibrarySelection(mlxOnly: true, compatible: true, mlxPath: "/tmp/models/A/", ollamaModel: "a") let mlx = ModelLibrarySelection(mlxOnly: true, compatible: true, mlxPath: "/tmp/models/A/", ollamaModel: "a")
XCTAssertTrue(mlx.isMLX("/tmp/models/A")) XCTAssertTrue(mlx.isMLX("/tmp/models/A"))
@@ -1688,7 +2216,7 @@ extension NativeTrainingTests {
func testTrainingOperationCapturesOutputAndCancelsRunningProcess() async throws { func testTrainingOperationCapturesOutputAndCancelsRunningProcess() async throws {
let operation = TrainingOperation() let operation = TrainingOperation()
operation.run("Read output") { operation.run("Read output") {
try await operation.execute(URL(fileURLWithPath: "/usr/bin/printf"), ["ready"]) try await operation.execute(URL(fileURLWithPath: "/usr/bin/printf"), ["\u{001B}[1mready\u{001B}[0m"])
} }
let deadline = ContinuousClock.now + .seconds(5) let deadline = ContinuousClock.now + .seconds(5)
while operation.active != nil && ContinuousClock.now < deadline { while operation.active != nil && ContinuousClock.now < deadline {
@@ -1979,3 +2507,12 @@ extension RemoteStackSelectionTests {
XCTAssertFalse(reply.content.contains("github.com")) XCTAssertFalse(reply.content.contains("github.com"))
} }
} }
extension RemoteStackSelectionTests {
func testGiteaRepositoryEnvelopeUnderData() async throws {
let payload = #"{"structuredContent":{"data":{"repositories":[{"full_name":"team/project"}]}}}"#
let client = ConnectedChatTests.Server(name: "list_repositories", result: Data(payload.utf8))
let entries = try await GiteaRepositoryLookup.entries(client: client)
XCTAssertEqual(entries, ["team/project"])
}
}