Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

chore: remove Apple Foundation Models integration (#8120)

Akarshan Biswasd642ff7e3f3d
diff --git a/extensions/foundation-models-extension/package.json b/extensions/foundation-models-extension/package.json
deleted file mode 100644
index 03a022879..000000000
--- a/extensions/foundation-models-extension/package.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "name": "@janhq/foundation-models-extension",
- "productName": "Apple Foundation Models",
- "version": "1.0.0",
- "description": "Run Apple on-device Foundation Models (macOS 26+ with Apple Intelligence)",
- "main": "dist/index.js",
- "module": "dist/module.js",
- "engine": "foundation-models",
- "author": "Jan <[email protected]>",
- "license": "AGPL-3.0",
- "scripts": {
- "build": "rolldown -c rolldown.config.mjs",
- "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install"
- },
- "devDependencies": {
- "cpx": "1.5.0",
- "rimraf": "3.0.2",
- "rolldown": "1.0.0-beta.1",
- "typescript": "5.9.2"
- },
- "dependencies": {
- "@janhq/core": "../../core/package.tgz",
- "@janhq/tauri-plugin-foundation-models-api": "link:../../src-tauri/plugins/tauri-plugin-foundation-models",
- "@tauri-apps/api": "2.8.0",
- "@tauri-apps/plugin-log": "^2.6.0"
- },
- "engines": {
- "node": ">=18.0.0"
- },
- "files": [
- "dist/*",
- "package.json"
- ],
- "installConfig": {
- "hoistingLimits": "workspaces"
- },
- "packageManager": "[email protected]"
-}
diff --git a/extensions/foundation-models-extension/rolldown.config.mjs b/extensions/foundation-models-extension/rolldown.config.mjs
deleted file mode 100644
index cc6abbcf4..000000000
--- a/extensions/foundation-models-extension/rolldown.config.mjs
+++ /dev/null
@@ -1,19 +0,0 @@
-import { defineConfig } from 'rolldown'
-import pkgJson from './package.json' with { type: 'json' }
-import settingJson from './settings.json' with { type: 'json' }
-
-export default defineConfig({
- input: 'src/index.ts',
- output: {
- format: 'esm',
- file: 'dist/index.js',
- },
- platform: 'browser',
- define: {
- SETTINGS: JSON.stringify(settingJson),
- ENGINE: JSON.stringify(pkgJson.engine),
- },
- inject: process.env.IS_DEV ? {} : {
- fetch: ['@tauri-apps/plugin-http', 'fetch'],
- },
-})
diff --git a/extensions/foundation-models-extension/settings.json b/extensions/foundation-models-extension/settings.json
deleted file mode 100644
index fe51488c7..000000000
--- a/extensions/foundation-models-extension/settings.json
+++ /dev/null
@@ -1 +0,0 @@
-[]
diff --git a/extensions/foundation-models-extension/src/env.d.ts b/extensions/foundation-models-extension/src/env.d.ts
deleted file mode 100644
index 9a78d6680..000000000
--- a/extensions/foundation-models-extension/src/env.d.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-/// <reference types="vite/client" />
-
-declare const SETTINGS: any[]
-declare const ENGINE: string
diff --git a/extensions/foundation-models-extension/src/index.ts b/extensions/foundation-models-extension/src/index.ts
deleted file mode 100644
index 04f295b00..000000000
--- a/extensions/foundation-models-extension/src/index.ts
+++ /dev/null
@@ -1,303 +0,0 @@
-/**
- * Apple Foundation Models Extension
- *
- * Provides access to Apple's on-device Foundation Models (macOS 26+ with Apple
- * Intelligence) as a Jan AI engine. The model runs fully locally — no internet
- * connection or external API key is required.
- *
- * Architecture:
- * Jan extension (TypeScript) → Tauri plugin (Rust / fm-rs) → FoundationModels.framework
- *
- * The Tauri plugin calls Apple's FoundationModels framework directly via Rust
- * FFI bindings (fm-rs), eliminating the need for a separate HTTP server process.
- */
-
-import {
- AIEngine,
- EngineManager,
- modelInfo,
- SessionInfo,
- UnloadResult,
- chatCompletion,
- chatCompletionChunk,
- ImportOptions,
- chatCompletionRequest,
-} from '@janhq/core'
-
-import { info, warn, error as logError } from '@tauri-apps/plugin-log'
-import { listen, type UnlistenFn } from '@tauri-apps/api/event'
-import {
- loadFoundationModels,
- unloadFoundationModels,
- isFoundationModelsLoaded,
- foundationModelsChatCompletion,
- foundationModelsChatCompletionStream,
- abortFoundationModelsStream,
- checkFoundationModelsAvailability,
-} from '@janhq/tauri-plugin-foundation-models-api'
-
-// ─── Constants ───────────────────────────────────────────────────────────────
-
-const APPLE_MODEL_ID = 'apple/on-device'
-const APPLE_MODEL_NAME = 'Apple On-Device Model'
-
-// ─── Logger ──────────────────────────────────────────────────────────────────
-
-const logger = {
- info: (...args: any[]) => {
- console.log(...args)
- info(args.map(String).join(' '))
- },
- warn: (...args: any[]) => {
- console.warn(...args)
- warn(args.map(String).join(' '))
- },
- error: (...args: any[]) => {
- console.error(...args)
- logError(args.map(String).join(' '))
- },
-}
-
-// ─── Extension ───────────────────────────────────────────────────────────────
-
-export default class FoundationModelsExtension extends AIEngine {
- readonly provider: string = 'foundation-models'
- readonly providerId: string = 'foundation-models'
-
- timeout: number = 300
-
- // ── Lifecycle ──────────────────────────────────────────────────────────────
-
- override async onLoad(): Promise<void> {
- super.onLoad()
-
- try {
- const availability = await checkFoundationModelsAvailability()
- if (availability !== 'available') {
- logger.warn(
- `Foundation Models not available on this device (status: ${availability}). ` +
- 'Hiding provider.'
- )
- EngineManager.instance().engines.delete(this.provider)
- }
- } catch (err) {
- logger.warn('Could not determine Foundation Models availability — hiding provider.', err)
- EngineManager.instance().engines.delete(this.provider)
- }
- }
-
- override async onUnload(): Promise<void> {
- // Cleanup handled by the Tauri plugin on app exit.
- }
-
- // ── Model catalogue ────────────────────────────────────────────────────────
-
- override async list(): Promise<modelInfo[]> {
- return [this.buildModelInfo()]
- }
-
- override async get(modelId: string): Promise<modelInfo | undefined> {
- if (modelId !== APPLE_MODEL_ID) return undefined
- return this.buildModelInfo()
- }
-
- private buildModelInfo(): modelInfo {
- return {
- id: APPLE_MODEL_ID,
- name: APPLE_MODEL_NAME,
- providerId: this.provider,
- port: 0,
- sizeBytes: 0,
- tags: ['on-device', 'apple-intelligence'],
- capabilities: ['tools'],
- }
- }
-
- // ── Session management ─────────────────────────────────────────────────────
-
- override async load(
- modelId: string,
- _overrideSettings?: any,
- _isEmbedding: boolean = false,
- _bypassAutoUnload: boolean = false
- ): Promise<SessionInfo> {
- if (modelId !== APPLE_MODEL_ID) {
- throw new Error(
- `Foundation Models extension only supports model '${APPLE_MODEL_ID}', got '${modelId}'`
- )
- }
-
- const alreadyLoaded = await isFoundationModelsLoaded()
- if (alreadyLoaded) {
- logger.info('Foundation Models already loaded')
- return this.toSessionInfo(modelId)
- }
-
- logger.info('Loading Foundation Models...')
-
- try {
- await loadFoundationModels(modelId)
- logger.info('Foundation Models loaded successfully')
- return this.toSessionInfo(modelId)
- } catch (err) {
- logger.error('Failed to load Foundation Models:', err)
- throw err
- }
- }
-
- override async unload(_modelId: string): Promise<UnloadResult> {
- try {
- await unloadFoundationModels()
- logger.info('Foundation Models unloaded successfully')
- return { success: true }
- } catch (err) {
- logger.error('Error unloading Foundation Models:', err)
- return { success: false, error: String(err) }
- }
- }
-
- // ── Inference ──────────────────────────────────────────────────────────────
-
- override async chat(
- opts: chatCompletionRequest,
- abortController?: AbortController
- ): Promise<chatCompletion | AsyncIterable<chatCompletionChunk>> {
- const loaded = await isFoundationModelsLoaded()
- if (!loaded) {
- throw new Error(
- 'Apple Foundation Model is not loaded. Please load the model first.'
- )
- }
-
- const body = JSON.stringify(opts)
-
- if (opts.stream) {
- return this.handleStreamingChat(body, abortController)
- }
-
- const result = await foundationModelsChatCompletion(body)
- return JSON.parse(result) as chatCompletion
- }
-
- private async *handleStreamingChat(
- body: string,
- abortController?: AbortController
- ): AsyncIterable<chatCompletionChunk> {
- const requestId = crypto.randomUUID()
- const chunks: chatCompletionChunk[] = []
- let done = false
- let streamError: Error | null = null
- let resolver: (() => void) | null = null
-
- const unlisten: UnlistenFn = await listen(
- `foundation-models-stream-${requestId}`,
- (event) => {
- const payload = event.payload as {
- data?: string
- done?: boolean
- error?: string
- }
- if (payload.done) {
- done = true
- resolver?.()
- } else if (payload.error) {
- streamError = new Error(payload.error)
- resolver?.()
- } else if (payload.data) {
- try {
- chunks.push(JSON.parse(payload.data) as chatCompletionChunk)
- } catch (e) {
- logger.error('Error parsing Foundation Models stream JSON:', e)
- }
- resolver?.()
- }
- }
- )
-
- foundationModelsChatCompletionStream(body, requestId).catch((err) => {
- streamError =
- err instanceof Error ? err : new Error(String(err))
- resolver?.()
- })
-
- if (abortController?.signal) {
- const onAbort = () => {
- abortFoundationModelsStream(requestId).catch(() => {})
- }
- if (abortController.signal.aborted) {
- onAbort()
- } else {
- abortController.signal.addEventListener('abort', onAbort, { once: true })
- }
- }
-
- try {
- while (!done) {
- if (streamError) throw streamError
-
- while (chunks.length > 0) {
- yield chunks.shift()!
- }
-
- if (done) break
- if (streamError) throw streamError
-
- await new Promise<void>((r) => {
- resolver = r
- })
- }
-
- while (chunks.length > 0) {
- yield chunks.shift()!
- }
- } finally {
- unlisten()
- }
- }
-
- // ── Unsupported operations ─────────────────────────────────────────────────
-
- override async delete(_modelId: string): Promise<void> {
- throw new Error(
- 'Apple Foundation Models are part of the operating system and cannot be deleted from Jan.'
- )
- }
-
- override async update(_modelId: string, _model: Partial<modelInfo>): Promise<void> {
- throw new Error(
- 'Apple Foundation Models are managed by the OS and cannot be updated from Jan.'
- )
- }
-
- override async import(_modelId: string, _opts: ImportOptions): Promise<void> {
- throw new Error(
- 'Apple Foundation Models are built into the OS — there is nothing to import.'
- )
- }
-
- override async abortImport(_modelId: string): Promise<void> {
- // No download to abort — the model is managed by the OS.
- }
-
- override async getLoadedModels(): Promise<string[]> {
- const loaded = await isFoundationModelsLoaded()
- return loaded ? [APPLE_MODEL_ID] : []
- }
-
- override async isToolSupported(_modelId: string): Promise<boolean> {
- return true
- }
-
- // ── Helpers ────────────────────────────────────────────────────────────────
-
- private toSessionInfo(modelId: string): SessionInfo {
- return {
- pid: 0,
- port: 0,
- model_id: modelId,
- model_path: '',
- is_embedding: false,
- api_key: '',
- }
- }
-}
diff --git a/extensions/foundation-models-extension/tsconfig.json b/extensions/foundation-models-extension/tsconfig.json
deleted file mode 100644
index 34d31fe4a..000000000
--- a/extensions/foundation-models-extension/tsconfig.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "compilerOptions": {
- "target": "es2018",
- "module": "ES6",
- "moduleResolution": "node",
- "outDir": "./dist",
- "esModuleInterop": true,
- "forceConsistentCasingInFileNames": true,
- "strict": false,
- "skipLibCheck": true,
- "rootDir": "./src"
- },
- "include": ["./src"],
- "exclude": ["**/*.test.ts"]
-}
diff --git a/package.json b/package.json
index 27fe3d18e..e6d44a736 100644
--- a/package.json
+++ b/package.json
@@ -45,8 +45,8 @@
"build:web": "yarn workspace @janhq/web-app build",
"build:extensions": "rimraf ./pre-install/*.tgz || true && yarn workspace @janhq/core build && cd extensions && yarn install && cd .. && run-script-os",
"build:extensions:darwin": "cd extensions && yarn workspaces foreach -Apt run build:publish",
- "build:extensions:win32": "cd extensions && yarn workspaces foreach -Apt --exclude @janhq/mlx-extension --exclude @janhq/foundation-models-extension run build:publish",
- "build:extensions:linux": "cd extensions && yarn workspaces foreach -Apt --exclude @janhq/mlx-extension --exclude @janhq/foundation-models-extension run build:publish",
+ "build:extensions:win32": "cd extensions && yarn workspaces foreach -Apt --exclude @janhq/mlx-extension run build:publish",
+ "build:extensions:linux": "cd extensions && yarn workspaces foreach -Apt --exclude @janhq/mlx-extension run build:publish",
"prepare": "husky"
},
"devDependencies": {
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index c3fd9b89f..2026180e6 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -46,7 +46,6 @@ dependencies = [
"tauri-build",
"tauri-plugin-deep-link",
"tauri-plugin-dialog",
- "tauri-plugin-foundation-models",
"tauri-plugin-hardware",
"tauri-plugin-http",
"tauri-plugin-llamacpp",
@@ -1819,16 +1818,6 @@ dependencies = [
"spin",
]
-[[package]]
-name = "fm-rs"
-version = "0.1.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "76ba96ac90cf1955a708bc53f2a2730a042609fe0836c5989b1d4424f471e868"
-dependencies = [
- "serde",
- "serde_json",
-]
-
[[package]]
name = "fnv"
version = "1.0.7"
@@ -1892,6 +1881,15 @@ dependencies = [
"percent-encoding",
]
+[[package]]
+name = "fs-err"
+version = "3.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73fde052dbfc920003cfd2c8e2c6e6d4cc7c1091538c3a24226cec0665ab08c0"
+dependencies = [
+ "autocfg",
+]
+
[[package]]
name = "funty"
version = "2.0.0"
@@ -2289,6 +2287,17 @@ dependencies = [
"system-deps",
]
+[[package]]
+name = "goblin"
+version = "0.10.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "983a6aafb3b12d4c41ea78d39e189af4298ce747353945ff5105b54a056e5cd9"
+dependencies = [
+ "log",
+ "plain",
+ "scroll",
+]
+
[[package]]
name = "gtk"
version = "0.18.2"
@@ -3164,6 +3173,18 @@ dependencies = [
"spin",
]
+[[package]]
+name = "lddtree"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39f71c5bd42adf4ee8e6b24da58c1f00a2817d27f618b169399f5adbf9e74492"
+dependencies = [
+ "fs-err",
+ "glob",
+ "goblin",
+ "memmap2",
+]
+
[[package]]
name = "libappindicator"
version = "0.9.0"
@@ -3378,6 +3399,15 @@ version = "2.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"
+[[package]]
+name = "memmap2"
+version = "0.9.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "714098028fe011992e1c3962653c96b2d578c4b4bce9036e15ff220319b1e0e3"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "memoffset"
version = "0.9.1"
@@ -4398,6 +4428,12 @@ version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
+[[package]]
+name = "plain"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
+
[[package]]
name = "plist"
version = "1.8.0"
@@ -5399,6 +5435,26 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "scroll"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1257cd4248b4132760d6524d6dda4e053bc648c9070b960929bf50cfb1e7add"
+dependencies = [
+ "scroll_derive",
+]
+
+[[package]]
+name = "scroll_derive"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed76efe62313ab6610570951494bdaa81568026e0318eaa55f167de70eeea67d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.106",
+]
+
[[package]]
name = "sct"
version = "0.7.1"
@@ -5521,15 +5577,15 @@ dependencies = [
[[package]]
name = "serde_json"
-version = "1.0.145"
+version = "1.0.149"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c"
+checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
dependencies = [
"itoa",
"memchr",
- "ryu",
"serde",
"serde_core",
+ "zmij",
]
[[package]]
@@ -6511,21 +6567,6 @@ dependencies = [
"url",
]
-[[package]]
-name = "tauri-plugin-foundation-models"
-version = "0.6.599"
-dependencies = [
- "fm-rs",
- "log",
- "serde",
- "serde_json",
- "tauri",
- "tauri-plugin",
- "thiserror 2.0.17",
- "tokio",
- "uuid",
-]
-
[[package]]
name = "tauri-plugin-fs"
version = "2.4.2"
@@ -6597,11 +6638,13 @@ dependencies = [
"byteorder",
"hmac",
"jan-utils",
+ "lddtree",
"log",
"nix",
"rand 0.8.5",
"reqwest 0.11.27",
"serde",
+ "serde_json",
"sha2",
"sysinfo",
"tauri",
@@ -6609,6 +6652,7 @@ dependencies = [
"tauri-plugin-hardware",
"thiserror 2.0.17",
"tokio",
+ "walkdir",
]
[[package]]
@@ -8893,6 +8937,12 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "zmij"
+version = "1.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
+
[[package]]
name = "zstd"
version = "0.11.2+zstd.1.5.2"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 69da78a65..d7b7fb406 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -34,12 +34,10 @@ default = [
hardware = ["dep:tauri-plugin-hardware"]
deep-link = ["dep:tauri-plugin-deep-link"]
mlx = ["dep:tauri-plugin-mlx"]
-foundation-models = ["dep:tauri-plugin-foundation-models"]
desktop = [
"deep-link",
"hardware",
"mlx",
- "foundation-models"
]
mobile = [
"tauri/protocol-asset",
@@ -47,7 +45,6 @@ mobile = [
"tauri/wry",
"dep:sqlx",
]
-# foundation-models excluded from test-tauri - framework not available in CI
test-tauri = [
"tauri/wry",
"tauri/x11",
@@ -99,7 +96,6 @@ tauri-plugin-deep-link = { version = "2", optional = true }
tauri-plugin-hardware = { path = "./plugins/tauri-plugin-hardware", optional = true }
tauri-plugin-llamacpp = { path = "./plugins/tauri-plugin-llamacpp" }
tauri-plugin-mlx = { path = "./plugins/tauri-plugin-mlx", optional = true }
-tauri-plugin-foundation-models = { path = "./plugins/tauri-plugin-foundation-models", optional = true }
tauri-plugin-vector-db = { path = "./plugins/tauri-plugin-vector-db" }
tauri-plugin-rag = { path = "./plugins/tauri-plugin-rag" }
tauri-plugin-http = { version = "2", features = ["unsafe-headers"] }
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/.gitignore b/src-tauri/plugins/tauri-plugin-foundation-models/.gitignore
deleted file mode 100644
index 5d3934a86..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/.gitignore
+++ /dev/null
@@ -1,12 +0,0 @@
-/.vs
-.DS_Store
-package-lock.json
-yarn.lock
-
-/.tauri
-/target
-Cargo.lock
-node_modules/
-
-dist-js
-dist
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/Cargo.toml b/src-tauri/plugins/tauri-plugin-foundation-models/Cargo.toml
deleted file mode 100644
index a50bc8996..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/Cargo.toml
+++ /dev/null
@@ -1,26 +0,0 @@
-[package]
-name = "tauri-plugin-foundation-models"
-version = "0.6.599"
-authors = ["Jan <[email protected]>"]
-description = "Tauri plugin for Apple Foundation Models inference via fm-rs on macOS 26+"
-license = "MIT"
-repository = "https://github.com/janhq/jan"
-edition = "2021"
-rust-version = "1.77.2"
-exclude = ["/examples", "/dist-js", "/guest-js", "/node_modules"]
-links = "tauri-plugin-foundation-models"
-
-[dependencies]
-log = "0.4"
-serde = { version = "1.0", features = ["derive"] }
-serde_json = "1.0"
-tauri = { version = "2.5.0", default-features = false, features = [] }
-thiserror = "2.0.12"
-tokio = { version = "1", features = ["full"] }
-uuid = { version = "1", features = ["v4"] }
-
-[target.'cfg(all(target_os = "macos", target_arch = "aarch64"))'.dependencies]
-fm-rs = "0.1"
-
-[build-dependencies]
-tauri-plugin = { version = "2.3.1", features = ["build"] }
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/build.rs b/src-tauri/plugins/tauri-plugin-foundation-models/build.rs
deleted file mode 100644
index 1ed06b1e9..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/build.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-const COMMANDS: &[&str] = &[
- "cleanup_foundation_models_processes",
- "check_foundation_models_availability",
- "load_foundation_models",
- "unload_foundation_models",
- "is_foundation_models_loaded",
- "foundation_models_chat_completion",
- "foundation_models_chat_completion_stream",
- "abort_foundation_models_stream",
-];
-
-fn main() {
- tauri_plugin::Builder::new(COMMANDS).build();
-}
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-foundation-models/guest-js/index.ts
deleted file mode 100644
index badd47224..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/guest-js/index.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { invoke } from '@tauri-apps/api/core'
-
-export { StreamEvent } from './types'
-
-export async function checkFoundationModelsAvailability(): Promise<string> {
- return await invoke('plugin:foundation-models|check_foundation_models_availability')
-}
-
-export async function loadFoundationModels(modelId: string): Promise<void> {
- return await invoke('plugin:foundation-models|load_foundation_models', { modelId })
-}
-
-export async function unloadFoundationModels(): Promise<void> {
- return await invoke('plugin:foundation-models|unload_foundation_models')
-}
-
-export async function isFoundationModelsLoaded(): Promise<boolean> {
- return await invoke('plugin:foundation-models|is_foundation_models_loaded')
-}
-
-export async function foundationModelsChatCompletion(body: string): Promise<string> {
- return await invoke('plugin:foundation-models|foundation_models_chat_completion', { body })
-}
-
-export async function foundationModelsChatCompletionStream(
- body: string,
- requestId: string
-): Promise<void> {
- return await invoke('plugin:foundation-models|foundation_models_chat_completion_stream', {
- body,
- requestId,
- })
-}
-
-export async function abortFoundationModelsStream(requestId: string): Promise<void> {
- return await invoke('plugin:foundation-models|abort_foundation_models_stream', { requestId })
-}
-
-export async function cleanupFoundationModelsProcesses(): Promise<void> {
- return await invoke('plugin:foundation-models|cleanup_foundation_models_processes')
-}
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-foundation-models/guest-js/types.ts
deleted file mode 100644
index d150c29e3..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/guest-js/types.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export interface StreamEvent {
- data?: string
- done?: boolean
- error?: string
-}
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/package.json b/src-tauri/plugins/tauri-plugin-foundation-models/package.json
deleted file mode 100644
index 0fe5e7fc6..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/package.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "name": "@janhq/tauri-plugin-foundation-models-api",
- "version": "0.6.599",
- "private": true,
- "description": "Tauri plugin API for Apple Foundation Models inference on macOS 26+",
- "type": "module",
- "types": "./dist-js/index.d.ts",
- "main": "./dist-js/index.cjs",
- "module": "./dist-js/index.js",
- "exports": {
- "types": "./dist-js/index.d.ts",
- "import": "./dist-js/index.js",
- "require": "./dist-js/index.cjs"
- },
- "files": [
- "dist-js",
- "README.md"
- ],
- "scripts": {
- "build": "rollup -c",
- "prepublishOnly": "yarn build",
- "pretest": "yarn build"
- },
- "dependencies": {
- "@tauri-apps/api": ">=2.0.0-beta.6"
- },
- "devDependencies": {
- "@rollup/plugin-typescript": "^12.0.0",
- "rollup": "^4.9.6",
- "tslib": "^2.6.2",
- "typescript": "^5.3.3"
- }
-}
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/permissions/default.toml b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/default.toml
deleted file mode 100644
index f2cd967d0..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/permissions/default.toml
+++ /dev/null
@@ -1,12 +0,0 @@
-[default]
-description = "Default permissions for the Foundation Models plugin"
-permissions = [
- "allow-cleanup-foundation-models-processes",
- "allow-check-foundation-models-availability",
- "allow-load-foundation-models",
- "allow-unload-foundation-models",
- "allow-is-foundation-models-loaded",
- "allow-foundation-models-chat-completion",
- "allow-foundation-models-chat-completion-stream",
- "allow-abort-foundation-models-stream",
-]
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-foundation-models/permissions/schemas/schema.json
deleted file mode 100644
index f0bcf4093..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/permissions/schemas/schema.json
+++ /dev/null
@@ -1,402 +0,0 @@
-{
- "$schema": "http://json-schema.org/draft-07/schema#",
- "title": "PermissionFile",
- "description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
- "type": "object",
- "properties": {
- "default": {
- "description": "The default permission set for the plugin",
- "anyOf": [
- {
- "$ref": "#/definitions/DefaultPermission"
- },
- {
- "type": "null"
- }
- ]
- },
- "set": {
- "description": "A list of permissions sets defined",
- "type": "array",
- "items": {
- "$ref": "#/definitions/PermissionSet"
- }
- },
- "permission": {
- "description": "A list of inlined permissions",
- "default": [],
- "type": "array",
- "items": {
- "$ref": "#/definitions/Permission"
- }
- }
- },
- "definitions": {
- "DefaultPermission": {
- "description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
- "type": "object",
- "required": [
- "permissions"
- ],
- "properties": {
- "version": {
- "description": "The version of the permission.",
- "type": [
- "integer",
- "null"
- ],
- "format": "uint64",
- "minimum": 1.0
- },
- "description": {
- "description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
- "type": [
- "string",
- "null"
- ]
- },
- "permissions": {
- "description": "All permissions this set contains.",
- "type": "array",
- "items": {
- "type": "string"
- }
- }
- }
- },
- "PermissionSet": {
- "description": "A set of direct permissions grouped together under a new name.",
- "type": "object",
- "required": [
- "description",
- "identifier",
- "permissions"
- ],
- "properties": {
- "identifier": {
- "description": "A unique identifier for the permission.",
- "type": "string"
- },
- "description": {
- "description": "Human-readable description of what the permission does.",
- "type": "string"
- },
- "permissions": {
- "description": "All permissions this set contains.",
- "type": "array",
- "items": {
- "$ref": "#/definitions/PermissionKind"
- }
- }
- }
- },
- "Permission": {
- "description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
- "type": "object",
- "required": [
- "identifier"
- ],
- "properties": {
- "version": {
- "description": "The version of the permission.",
- "type": [
- "integer",
- "null"
- ],
- "format": "uint64",
- "minimum": 1.0
- },
- "identifier": {
- "description": "A unique identifier for the permission.",
- "type": "string"
- },
- "description": {
- "description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
- "type": [
- "string",
- "null"
- ]
- },
- "commands": {
- "description": "Allowed or denied commands when using this permission.",
- "default": {
- "allow": [],
- "deny": []
- },
- "allOf": [
- {
- "$ref": "#/definitions/Commands"
- }
- ]
- },
- "scope": {
- "description": "Allowed or denied scoped when using this permission.",
- "allOf": [
- {
- "$ref": "#/definitions/Scopes"
- }
- ]
- },
- "platforms": {
- "description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
- "type": [
- "array",
- "null"
- ],
- "items": {
- "$ref": "#/definitions/Target"
- }
- }
- }
- },
- "Commands": {
- "description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
- "type": "object",
- "properties": {
- "allow": {
- "description": "Allowed command.",
- "default": [],
- "type": "array",
- "items": {
- "type": "string"
- }
- },
- "deny": {
- "description": "Denied command, which takes priority.",
- "default": [],
- "type": "array",
- "items": {
- "type": "string"
- }
- }
- }
- },
- "Scopes": {
- "description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
- "type": "object",
- "properties": {
- "allow": {
- "description": "Data that defines what is allowed by the scope.",
- "type": [
- "array",
- "null"
- ],
- "items": {
- "$ref": "#/definitions/Value"
- }
- },
- "deny": {
- "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
- "type": [
- "array",
- "null"
- ],
- "items": {
- "$ref": "#/definitions/Value"
- }
- }
- }
- },
- "Value": {
- "description": "All supported ACL values.",
- "anyOf": [
- {
- "description": "Represents a null JSON value.",
- "type": "null"
- },
- {
- "description": "Represents a [`bool`].",
- "type": "boolean"
- },
- {
- "description": "Represents a valid ACL [`Number`].",
- "allOf": [
- {
- "$ref": "#/definitions/Number"
- }
- ]
- },
- {
- "description": "Represents a [`String`].",
- "type": "string"
- },
- {
- "description": "Represents a list of other [`Value`]s.",
- "type": "array",
- "items": {
- "$ref": "#/definitions/Value"
- }
- },
- {
- "description": "Represents a map of [`String`] keys to [`Value`]s.",
- "type": "object",
- "additionalProperties": {
- "$ref": "#/definitions/Value"
- }
- }
- ]
- },
- "Number": {
- "description": "A valid ACL number.",
- "anyOf": [
- {
- "description": "Represents an [`i64`].",
- "type": "integer",
- "format": "int64"
- },
- {
- "description": "Represents a [`f64`].",
- "type": "number",
- "format": "double"
- }
- ]
- },
- "Target": {
- "description": "Platform target.",
- "oneOf": [
- {
- "description": "MacOS.",
- "type": "string",
- "enum": [
- "macOS"
- ]
- },
- {
- "description": "Windows.",
- "type": "string",
- "enum": [
- "windows"
- ]
- },
- {
- "description": "Linux.",
- "type": "string",
- "enum": [
- "linux"
- ]
- },
- {
- "description": "Android.",
- "type": "string",
- "enum": [
- "android"
- ]
- },
- {
- "description": "iOS.",
- "type": "string",
- "enum": [
- "iOS"
- ]
- }
- ]
- },
- "PermissionKind": {
- "type": "string",
- "oneOf": [
- {
- "description": "Enables the abort_foundation_models_stream command without any pre-configured scope.",
- "type": "string",
- "const": "allow-abort-foundation-models-stream",
- "markdownDescription": "Enables the abort_foundation_models_stream command without any pre-configured scope."
- },
- {
- "description": "Denies the abort_foundation_models_stream command without any pre-configured scope.",
- "type": "string",
- "const": "deny-abort-foundation-models-stream",
- "markdownDescription": "Denies the abort_foundation_models_stream command without any pre-configured scope."
- },
- {
- "description": "Enables the check_foundation_models_availability command without any pre-configured scope.",
- "type": "string",
- "const": "allow-check-foundation-models-availability",
- "markdownDescription": "Enables the check_foundation_models_availability command without any pre-configured scope."
- },
- {
- "description": "Denies the check_foundation_models_availability command without any pre-configured scope.",
- "type": "string",
- "const": "deny-check-foundation-models-availability",
- "markdownDescription": "Denies the check_foundation_models_availability command without any pre-configured scope."
- },
- {
- "description": "Enables the cleanup_foundation_models_processes command without any pre-configured scope.",
- "type": "string",
- "const": "allow-cleanup-foundation-models-processes",
- "markdownDescription": "Enables the cleanup_foundation_models_processes command without any pre-configured scope."
- },
- {
- "description": "Denies the cleanup_foundation_models_processes command without any pre-configured scope.",
- "type": "string",
- "const": "deny-cleanup-foundation-models-processes",
- "markdownDescription": "Denies the cleanup_foundation_models_processes command without any pre-configured scope."
- },
- {
- "description": "Enables the foundation_models_chat_completion command without any pre-configured scope.",
- "type": "string",
- "const": "allow-foundation-models-chat-completion",
- "markdownDescription": "Enables the foundation_models_chat_completion command without any pre-configured scope."
- },
- {
- "description": "Denies the foundation_models_chat_completion command without any pre-configured scope.",
- "type": "string",
- "const": "deny-foundation-models-chat-completion",
- "markdownDescription": "Denies the foundation_models_chat_completion command without any pre-configured scope."
- },
- {
- "description": "Enables the foundation_models_chat_completion_stream command without any pre-configured scope.",
- "type": "string",
- "const": "allow-foundation-models-chat-completion-stream",
- "markdownDescription": "Enables the foundation_models_chat_completion_stream command without any pre-configured scope."
- },
- {
- "description": "Denies the foundation_models_chat_completion_stream command without any pre-configured scope.",
- "type": "string",
- "const": "deny-foundation-models-chat-completion-stream",
- "markdownDescription": "Denies the foundation_models_chat_completion_stream command without any pre-configured scope."
- },
- {
- "description": "Enables the is_foundation_models_loaded command without any pre-configured scope.",
- "type": "string",
- "const": "allow-is-foundation-models-loaded",
- "markdownDescription": "Enables the is_foundation_models_loaded command without any pre-configured scope."
- },
- {
- "description": "Denies the is_foundation_models_loaded command without any pre-configured scope.",
- "type": "string",
- "const": "deny-is-foundation-models-loaded",
- "markdownDescription": "Denies the is_foundation_models_loaded command without any pre-configured scope."
- },
- {
- "description": "Enables the load_foundation_models command without any pre-configured scope.",
- "type": "string",
- "const": "allow-load-foundation-models",
- "markdownDescription": "Enables the load_foundation_models command without any pre-configured scope."
- },
- {
- "description": "Denies the load_foundation_models command without any pre-configured scope.",
- "type": "string",
- "const": "deny-load-foundation-models",
- "markdownDescription": "Denies the load_foundation_models command without any pre-configured scope."
- },
- {
- "description": "Enables the unload_foundation_models command without any pre-configured scope.",
- "type": "string",
- "const": "allow-unload-foundation-models",
- "markdownDescription": "Enables the unload_foundation_models command without any pre-configured scope."
- },
- {
- "description": "Denies the unload_foundation_models command without any pre-configured scope.",
- "type": "string",
- "const": "deny-unload-foundation-models",
- "markdownDescription": "Denies the unload_foundation_models command without any pre-configured scope."
- },
- {
- "description": "Default permissions for the Foundation Models plugin\n#### This default permission set includes:\n\n- `allow-cleanup-foundation-models-processes`\n- `allow-check-foundation-models-availability`\n- `allow-load-foundation-models`\n- `allow-unload-foundation-models`\n- `allow-is-foundation-models-loaded`\n- `allow-foundation-models-chat-completion`\n- `allow-foundation-models-chat-completion-stream`\n- `allow-abort-foundation-models-stream`",
- "type": "string",
- "const": "default",
- "markdownDescription": "Default permissions for the Foundation Models plugin\n#### This default permission set includes:\n\n- `allow-cleanup-foundation-models-processes`\n- `allow-check-foundation-models-availability`\n- `allow-load-foundation-models`\n- `allow-unload-foundation-models`\n- `allow-is-foundation-models-loaded`\n- `allow-foundation-models-chat-completion`\n- `allow-foundation-models-chat-completion-stream`\n- `allow-abort-foundation-models-stream`"
- }
- ]
- }
- }
-}
\ No newline at end of file
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/rollup.config.js b/src-tauri/plugins/tauri-plugin-foundation-models/rollup.config.js
deleted file mode 100644
index 8b4768ff6..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/rollup.config.js
+++ /dev/null
@@ -1,31 +0,0 @@
-import { readFileSync } from 'node:fs'
-import { dirname, join } from 'node:path'
-import { cwd } from 'node:process'
-import typescript from '@rollup/plugin-typescript'
-
-const pkg = JSON.parse(readFileSync(join(cwd(), 'package.json'), 'utf8'))
-
-export default {
- input: 'guest-js/index.ts',
- output: [
- {
- file: pkg.exports.import,
- format: 'esm'
- },
- {
- file: pkg.exports.require,
- format: 'cjs'
- }
- ],
- plugins: [
- typescript({
- declaration: true,
- declarationDir: dirname(pkg.exports.import)
- })
- ],
- external: [
- /^@tauri-apps\/api/,
- ...Object.keys(pkg.dependencies || {}),
- ...Object.keys(pkg.peerDependencies || {})
- ]
-}
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/src/cleanup.rs b/src-tauri/plugins/tauri-plugin-foundation-models/src/cleanup.rs
deleted file mode 100644
index 9f844b5e9..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/src/cleanup.rs
+++ /dev/null
@@ -1,25 +0,0 @@
-use tauri::{Manager, Runtime};
-
-pub async fn cleanup_processes<R: Runtime>(app_handle: &tauri::AppHandle<R>) {
- let app_state = match app_handle.try_state::<crate::state::FoundationModelsState>() {
- Some(state) => state,
- None => {
- log::warn!("FoundationModelsState not found in app_handle");
- return;
- }
- };
-
- *app_state.loaded.lock().await = false;
- if let Ok(mut tokens) = app_state.cancel_tokens.lock() {
- tokens.clear();
- }
- log::info!("Foundation Models state cleaned up");
-}
-
-#[tauri::command]
-pub async fn cleanup_foundation_models_processes<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
-) -> Result<(), String> {
- cleanup_processes(&app_handle).await;
- Ok(())
-}
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/src/commands.rs b/src-tauri/plugins/tauri-plugin-foundation-models/src/commands.rs
deleted file mode 100644
index 68983eae2..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/src/commands.rs
+++ /dev/null
@@ -1,508 +0,0 @@
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-use serde::{Deserialize, Serialize};
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-use std::sync::atomic::{AtomicBool, Ordering};
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-use std::sync::Arc;
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-use tauri::{Emitter, Manager, Runtime, State};
-#[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
-use tauri::{Manager, Runtime, State};
-
-use crate::error::FoundationModelsError;
-use crate::state::FoundationModelsState;
-
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-const MODEL_ID: &str = "apple/on-device";
-
-// ─── OpenAI-compatible types (macOS only) ──────────────────────────────────
-
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-#[derive(Debug, Deserialize)]
-struct ChatCompletionRequest {
- #[allow(dead_code)]
- model: Option<String>,
- messages: Vec<ChatMessage>,
- temperature: Option<f64>,
- #[allow(dead_code)]
- top_p: Option<f64>,
- max_tokens: Option<u32>,
- #[allow(dead_code)]
- stream: Option<bool>,
- #[allow(dead_code)]
- stop: Option<Vec<String>>,
-}
-
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-#[derive(Debug, Deserialize)]
-struct ChatMessage {
- role: String,
- content: Option<String>,
-}
-
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-#[derive(Debug, Serialize)]
-struct ChatCompletionResponse {
- id: String,
- object: String,
- created: u64,
- model: String,
- choices: Vec<ChatCompletionChoice>,
- usage: UsageInfo,
-}
-
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-#[derive(Debug, Serialize)]
-struct ChatCompletionChoice {
- index: u32,
- message: ChatResponseMessage,
- finish_reason: String,
-}
-
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-#[derive(Debug, Serialize)]
-struct ChatResponseMessage {
- role: String,
- content: String,
-}
-
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-#[derive(Debug, Serialize)]
-struct UsageInfo {
- prompt_tokens: u32,
- completion_tokens: u32,
- total_tokens: u32,
-}
-
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-#[derive(Debug, Serialize)]
-struct ChatCompletionChunk {
- id: String,
- object: String,
- created: u64,
- model: String,
- choices: Vec<ChunkChoice>,
-}
-
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-#[derive(Debug, Serialize)]
-struct ChunkChoice {
- index: u32,
- delta: DeltaContent,
- finish_reason: Option<String>,
-}
-
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-#[derive(Debug, Serialize)]
-struct DeltaContent {
- role: Option<String>,
- content: Option<String>,
-}
-
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-fn current_timestamp() -> u64 {
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs()
-}
-
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-/// Build session instructions from the OpenAI message list.
-///
-/// System messages become the instruction text. Prior user/assistant turns
-/// are serialised into the instructions block so the model has full
-/// conversation context (matching the previous Swift server behaviour).
-fn build_instructions(messages: &[ChatMessage]) -> String {
- let system_content = messages
- .iter()
- .find(|m| m.role == "system")
- .and_then(|m| m.content.as_deref())
- .unwrap_or("");
-
- let non_system: Vec<&ChatMessage> = messages.iter().filter(|m| m.role != "system").collect();
- let history = if non_system.len() > 1 {
- &non_system[..non_system.len() - 1]
- } else {
- &[]
- };
-
- let mut instructions = if system_content.is_empty() {
- "You are a helpful assistant.".to_string()
- } else {
- system_content.to_string()
- };
-
- if !history.is_empty() {
- instructions.push_str("\n\n[Previous conversation]\n");
- for msg in history {
- let label = if msg.role == "assistant" {
- "Assistant"
- } else {
- "User"
- };
- instructions.push_str(&format!(
- "{}: {}\n",
- label,
- msg.content.as_deref().unwrap_or("")
- ));
- }
- instructions.push_str("[End of previous conversation]");
- }
-
- instructions
-}
-
-#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
-fn extract_last_user_message(messages: &[ChatMessage]) -> String {
- messages
- .iter()
- .filter(|m| m.role != "system")
- .last()
- .and_then(|m| m.content.clone())
- .unwrap_or_default()
-}
-
-// ─── Commands ───────────────────────────────────────────────────────────────
-
-#[tauri::command]
-pub async fn check_foundation_models_availability<R: Runtime>(
- _app_handle: tauri::AppHandle<R>,
-) -> Result<String, String> {
- #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
- {
- let result = tokio::task::spawn_blocking(|| {
- let model = match fm_rs::SystemLanguageModel::new() {
- Ok(m) => m,
- Err(_) => return "unavailable".to_string(),
- };
-
- if model.is_available() {
- return "available".to_string();
- }
-
- match model.ensure_available() {
- Ok(()) => "available".to_string(),
- Err(e) => {
- let msg = e.to_string().to_lowercase();
- if msg.contains("not eligible") || msg.contains("eligible") {
- "notEligible".to_string()
- } else if msg.contains("not enabled") || msg.contains("intelligence") {
- "appleIntelligenceNotEnabled".to_string()
- } else if msg.contains("not ready") || msg.contains("ready") {
- "modelNotReady".to_string()
- } else {
- "unavailable".to_string()
- }
- }
- }
- })
- .await
- .map_err(|e| e.to_string())?;
- Ok(result)
- }
-
- #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
- {
- Ok("unavailable".to_string())
- }
-}
-
-#[tauri::command]
-pub async fn load_foundation_models<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
- _model_id: String,
-) -> Result<(), FoundationModelsError> {
- #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
- {
- tokio::task::spawn_blocking(|| {
- let model = fm_rs::SystemLanguageModel::new()
- .map_err(|e| FoundationModelsError::unavailable(e.to_string()))?;
- model
- .ensure_available()
- .map_err(|e| FoundationModelsError::unavailable(e.to_string()))?;
- Ok::<(), FoundationModelsError>(())
- })
- .await
- .map_err(|e| FoundationModelsError::internal_error(e.to_string()))??;
-
- let state: State<FoundationModelsState> = app_handle.state();
- *state.loaded.lock().await = true;
- log::info!("Foundation Models loaded successfully");
- Ok(())
- }
-
- #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
- {
- let _ = app_handle;
- Err(FoundationModelsError::unavailable(
- "Foundation Models are only available on macOS 26+ with Apple Silicon".into(),
- ))
- }
-}
-
-#[tauri::command]
-pub async fn unload_foundation_models<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
-) -> Result<(), String> {
- let state: State<FoundationModelsState> = app_handle.state();
- *state.loaded.lock().await = false;
- state
- .cancel_tokens
- .lock()
- .unwrap_or_else(|e| e.into_inner())
- .clear();
- log::info!("Foundation Models unloaded");
- Ok(())
-}
-
-#[tauri::command]
-pub async fn is_foundation_models_loaded<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
-) -> Result<bool, String> {
- let state: State<FoundationModelsState> = app_handle.state();
- let loaded = *state.loaded.lock().await;
- Ok(loaded)
-}
-
-#[tauri::command]
-pub async fn foundation_models_chat_completion<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
- body: String,
-) -> Result<String, FoundationModelsError> {
- {
- let state: State<FoundationModelsState> = app_handle.state();
- if !*state.loaded.lock().await {
- return Err(FoundationModelsError::not_loaded());
- }
- }
-
- #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
- {
- let result = tokio::task::spawn_blocking(move || {
- let request: ChatCompletionRequest = serde_json::from_str(&body)
- .map_err(|e| FoundationModelsError::invalid_request(e.to_string()))?;
-
- let model = fm_rs::SystemLanguageModel::new()
- .map_err(|e| FoundationModelsError::inference_error(e.to_string()))?;
-
- let instructions = build_instructions(&request.messages);
- let last_message = extract_last_user_message(&request.messages);
-
- let session = fm_rs::Session::with_instructions(&model, &instructions)
- .map_err(|e| FoundationModelsError::inference_error(e.to_string()))?;
-
- let mut opts = fm_rs::GenerationOptions::builder();
- if let Some(temp) = request.temperature {
- opts = opts.temperature(temp);
- }
- if let Some(max) = request.max_tokens {
- opts = opts.max_response_tokens(max);
- }
- let opts = opts.build();
-
- let response = session
- .respond(&last_message, &opts)
- .map_err(|e| FoundationModelsError::inference_error(e.to_string()))?;
-
- let completion = ChatCompletionResponse {
- id: format!("chatcmpl-{}", uuid::Uuid::new_v4()),
- object: "chat.completion".to_string(),
- created: current_timestamp(),
- model: MODEL_ID.to_string(),
- choices: vec![ChatCompletionChoice {
- index: 0,
- message: ChatResponseMessage {
- role: "assistant".to_string(),
- content: response.content().to_string(),
- },
- finish_reason: "stop".to_string(),
- }],
- usage: UsageInfo {
- prompt_tokens: 0,
- completion_tokens: 0,
- total_tokens: 0,
- },
- };
-
- serde_json::to_string(&completion)
- .map_err(|e| FoundationModelsError::internal_error(e.to_string()))
- })
- .await
- .map_err(|e| FoundationModelsError::internal_error(e.to_string()))??;
-
- Ok(result)
- }
-
- #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
- {
- let _ = &body;
- Err(FoundationModelsError::unavailable(
- "Foundation Models are only available on macOS 26+ with Apple Silicon".into(),
- ))
- }
-}
-
-#[tauri::command]
-pub async fn foundation_models_chat_completion_stream<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
- body: String,
- request_id: String,
-) -> Result<(), FoundationModelsError> {
- {
- let state: State<FoundationModelsState> = app_handle.state();
- if !*state.loaded.lock().await {
- return Err(FoundationModelsError::not_loaded());
- }
- }
-
- #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
- {
- let state: State<FoundationModelsState> = app_handle.state();
- let cancel_tokens = state.cancel_tokens.clone();
- let event_name = format!("foundation-models-stream-{}", request_id);
- let handle = app_handle.clone();
-
- tokio::task::spawn_blocking(move || -> Result<(), FoundationModelsError> {
- let request: ChatCompletionRequest = serde_json::from_str(&body)
- .map_err(|e| FoundationModelsError::invalid_request(e.to_string()))?;
-
- let model = fm_rs::SystemLanguageModel::new()
- .map_err(|e| FoundationModelsError::inference_error(e.to_string()))?;
-
- let instructions = build_instructions(&request.messages);
- let last_message = extract_last_user_message(&request.messages);
-
- let session = fm_rs::Session::with_instructions(&model, &instructions)
- .map_err(|e| FoundationModelsError::inference_error(e.to_string()))?;
-
- let mut opts = fm_rs::GenerationOptions::builder();
- if let Some(temp) = request.temperature {
- opts = opts.temperature(temp);
- }
- if let Some(max) = request.max_tokens {
- opts = opts.max_response_tokens(max);
- }
- let opts = opts.build();
-
- let chunk_id = format!("chatcmpl-{}", uuid::Uuid::new_v4());
- let created = current_timestamp();
- let model_id = MODEL_ID.to_string();
-
- // Emit role chunk
- let role_chunk = ChatCompletionChunk {
- id: chunk_id.clone(),
- object: "chat.completion.chunk".to_string(),
- created,
- model: model_id.clone(),
- choices: vec![ChunkChoice {
- index: 0,
- delta: DeltaContent {
- role: Some("assistant".to_string()),
- content: None,
- },
- finish_reason: None,
- }],
- };
- if let Ok(json) = serde_json::to_string(&role_chunk) {
- let _ = handle.emit(&event_name, serde_json::json!({ "data": json }));
- }
-
- let cancelled = Arc::new(AtomicBool::new(false));
- let cancelled_ref = cancelled.clone();
- let cancel_tokens_ref = cancel_tokens.clone();
- let request_id_ref = request_id.clone();
- let event_name_ref = event_name.clone();
- let handle_ref = handle.clone();
- let chunk_id_ref = chunk_id.clone();
- let model_id_ref = model_id.clone();
-
- let stream_result =
- session.stream_response(&last_message, &opts, move |chunk_text: &str| {
- if cancelled_ref.load(Ordering::Relaxed) {
- return;
- }
-
- if let Ok(tokens) = cancel_tokens_ref.lock() {
- if tokens.contains(&request_id_ref) {
- cancelled_ref.store(true, Ordering::Relaxed);
- return;
- }
- }
-
- let chunk = ChatCompletionChunk {
- id: chunk_id_ref.clone(),
- object: "chat.completion.chunk".to_string(),
- created,
- model: model_id_ref.clone(),
- choices: vec![ChunkChoice {
- index: 0,
- delta: DeltaContent {
- role: None,
- content: Some(chunk_text.to_string()),
- },
- finish_reason: None,
- }],
- };
- if let Ok(json) = serde_json::to_string(&chunk) {
- let _ = handle_ref.emit(&event_name_ref, serde_json::json!({ "data": json }));
- }
- });
-
- // Emit stop chunk
- let stop_chunk = ChatCompletionChunk {
- id: chunk_id,
- object: "chat.completion.chunk".to_string(),
- created,
- model: model_id,
- choices: vec![ChunkChoice {
- index: 0,
- delta: DeltaContent {
- role: None,
- content: None,
- },
- finish_reason: Some("stop".to_string()),
- }],
- };
- if let Ok(json) = serde_json::to_string(&stop_chunk) {
- let _ = handle.emit(&event_name, serde_json::json!({ "data": json }));
- }
-
- // Signal completion
- let _ = handle.emit(&event_name, serde_json::json!({ "done": true }));
-
- // Clean up cancel token
- if let Ok(mut tokens) = cancel_tokens.lock() {
- tokens.remove(&request_id);
- }
-
- stream_result
- .map(|_| ())
- .map_err(|e| FoundationModelsError::inference_error(e.to_string()))
- })
- .await
- .map_err(|e| FoundationModelsError::internal_error(e.to_string()))??;
-
- Ok(())
- }
-
- #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
- {
- let _ = (body, request_id);
- Err(FoundationModelsError::unavailable(
- "Foundation Models are only available on macOS 26+ with Apple Silicon".into(),
- ))
- }
-}
-
-#[tauri::command]
-pub async fn abort_foundation_models_stream<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
- request_id: String,
-) -> Result<(), String> {
- let state: State<FoundationModelsState> = app_handle.state();
- if let Ok(mut tokens) = state.cancel_tokens.lock() {
- tokens.insert(request_id);
- }
- Ok(())
-}
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/src/error.rs b/src-tauri/plugins/tauri-plugin-foundation-models/src/error.rs
deleted file mode 100644
index 9436eb47f..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/src/error.rs
+++ /dev/null
@@ -1,65 +0,0 @@
-use serde::{Deserialize, Serialize};
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
-pub enum ErrorCode {
- NotLoaded,
- Unavailable,
- InvalidRequest,
- InferenceError,
- InternalError,
-}
-
-#[derive(Debug, Clone, Serialize, thiserror::Error)]
-#[error("FoundationModelsError {{ code: {code:?}, message: \"{message}\" }}")]
-pub struct FoundationModelsError {
- pub code: ErrorCode,
- pub message: String,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub details: Option<String>,
-}
-
-impl FoundationModelsError {
- pub fn not_loaded() -> Self {
- Self {
- code: ErrorCode::NotLoaded,
- message: "Foundation Models are not loaded. Please load the model first.".into(),
- details: None,
- }
- }
-
- pub fn unavailable(details: String) -> Self {
- Self {
- code: ErrorCode::Unavailable,
- message: "Foundation Models are not available on this device.".into(),
- details: Some(details),
- }
- }
-
- #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
- pub fn invalid_request(details: String) -> Self {
- Self {
- code: ErrorCode::InvalidRequest,
- message: "Invalid request.".into(),
- details: Some(details),
- }
- }
-
- #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
- pub fn inference_error(details: String) -> Self {
- Self {
- code: ErrorCode::InferenceError,
- message: "An error occurred during inference.".into(),
- details: Some(details),
- }
- }
-
- #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
- pub fn internal_error(details: String) -> Self {
- Self {
- code: ErrorCode::InternalError,
- message: "An internal error occurred.".into(),
- details: Some(details),
- }
- }
-}
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/src/lib.rs b/src-tauri/plugins/tauri-plugin-foundation-models/src/lib.rs
deleted file mode 100644
index a42976bb1..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/src/lib.rs
+++ /dev/null
@@ -1,31 +0,0 @@
-use tauri::{
- plugin::{Builder, TauriPlugin},
- Manager, Runtime,
-};
-
-pub mod cleanup;
-mod commands;
-mod error;
-pub mod state;
-
-pub use cleanup::cleanup_processes;
-pub use state::FoundationModelsState;
-
-pub fn init<R: Runtime>() -> TauriPlugin<R> {
- Builder::new("foundation-models")
- .invoke_handler(tauri::generate_handler![
- cleanup::cleanup_foundation_models_processes,
- commands::check_foundation_models_availability,
- commands::load_foundation_models,
- commands::unload_foundation_models,
- commands::is_foundation_models_loaded,
- commands::foundation_models_chat_completion,
- commands::foundation_models_chat_completion_stream,
- commands::abort_foundation_models_stream,
- ])
- .setup(|app, _api| {
- app.manage(state::FoundationModelsState::new());
- Ok(())
- })
- .build()
-}
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/src/state.rs b/src-tauri/plugins/tauri-plugin-foundation-models/src/state.rs
deleted file mode 100644
index 1f952f2ff..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/src/state.rs
+++ /dev/null
@@ -1,25 +0,0 @@
-use std::collections::HashSet;
-use std::sync::Arc;
-use tokio::sync::Mutex;
-
-pub struct FoundationModelsState {
- pub loaded: Arc<Mutex<bool>>,
- /// Request IDs that have been signalled for cancellation.
- /// Checked by the streaming callback to stop emitting events.
- pub cancel_tokens: Arc<std::sync::Mutex<HashSet<String>>>,
-}
-
-impl Default for FoundationModelsState {
- fn default() -> Self {
- Self {
- loaded: Arc::new(Mutex::new(false)),
- cancel_tokens: Arc::new(std::sync::Mutex::new(HashSet::new())),
- }
- }
-}
-
-impl FoundationModelsState {
- pub fn new() -> Self {
- Self::default()
- }
-}
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/Package.swift b/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/Package.swift
deleted file mode 100644
index d899a6925..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/Package.swift
+++ /dev/null
@@ -1,30 +0,0 @@
-// swift-tools-version: 6.2
-
-import PackageDescription
-
-let package = Package(
- name: "foundation-models-server",
- platforms: [
- .macOS(.v26)
- ],
- products: [
- .executable(name: "foundation-models-server", targets: ["FoundationModelsServer"])
- ],
- dependencies: [
- .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"),
- .package(url: "https://github.com/hummingbird-project/hummingbird", from: "2.19.0"),
- ],
- targets: [
- .executableTarget(
- name: "FoundationModelsServer",
- dependencies: [
- .product(name: "ArgumentParser", package: "swift-argument-parser"),
- .product(name: "Hummingbird", package: "hummingbird"),
- ],
- path: "Sources/FoundationModelsServer",
- swiftSettings: [
- .swiftLanguageMode(.v6)
- ]
- )
- ]
-)
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/README.md b/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/README.md
deleted file mode 100644
index 3d840b72c..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/README.md
+++ /dev/null
@@ -1,40 +0,0 @@
-# foundation-models-server
-
-A lightweight OpenAI-compatible HTTP server that wraps Apple's Foundation Models framework, enabling Jan to use on-device Apple Intelligence models on macOS 26+.
-
-## Requirements
-
-- macOS 26 (Tahoe) or later
-- Apple Silicon Mac with Apple Intelligence enabled
-- Xcode 26 or later
-
-## Building
-
-```bash
-swift build -c release
-```
-
-The binary will be at `.build/release/foundation-models-server`.
-
-## Usage
-
-```bash
-# Check availability
-foundation-models-server --check
-
-# Start server on default port
-foundation-models-server --port 8080
-
-# Start server with API key
-foundation-models-server --port 8080 --api-key <key>
-```
-
-## API
-
-The server exposes an OpenAI-compatible API:
-
-- `GET /health` — health check
-- `GET /v1/models` — lists the `apple/on-device` model
-- `POST /v1/chat/completions` — chat completions (streaming and non-streaming)
-
-The model ID is always `apple/on-device`.
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/Sources/FoundationModelsServer/FoundationModelsServerCommand.swift b/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/Sources/FoundationModelsServer/FoundationModelsServerCommand.swift
deleted file mode 100644
index 36d2d5ec8..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/Sources/FoundationModelsServer/FoundationModelsServerCommand.swift
+++ /dev/null
@@ -1,78 +0,0 @@
-import ArgumentParser
-import Foundation
-import Hummingbird
-import FoundationModels
-
-@main
-struct FoundationModelsServerCommand: AsyncParsableCommand {
- static let configuration = CommandConfiguration(
- commandName: "foundation-models-server",
- abstract: "Apple Foundation Models inference server with OpenAI-compatible API"
- )
-
- @Option(name: .long, help: "Port to listen on")
- var port: Int = 8080
-
- @Option(name: .long, help: "API key for authentication (optional)")
- var apiKey: String = ""
-
- @Flag(name: .long, help: "Check availability and exit with status 0 if available")
- var check: Bool = false
-
- func run() async throws {
- let availability = SystemLanguageModel.default.availability
-
- // In --check mode, always print a machine-readable status token and exit 0.
- // Callers (e.g. the Tauri plugin) parse this string to decide visibility.
- if check {
- switch availability {
- case .available:
- print("available")
- case .unavailable(.deviceNotEligible):
- print("notEligible")
- case .unavailable(.appleIntelligenceNotEnabled):
- print("appleIntelligenceNotEnabled")
- case .unavailable(.modelNotReady):
- print("modelNotReady")
- default:
- print("unavailable")
- }
- return
- }
-
- guard case .available = availability else {
- let reason: String
- switch availability {
- case .unavailable(.deviceNotEligible):
- reason = "Device is not eligible for Apple Intelligence"
- case .unavailable(.appleIntelligenceNotEnabled):
- reason = "Apple Intelligence is not enabled in System Settings"
- case .unavailable(.modelNotReady):
- reason = "Foundation model is downloading or not yet ready"
- default:
- reason = "Foundation model is unavailable on this system"
- }
- fputs("[foundation-models] ERROR: \(reason)\n", stderr)
- throw ExitCode(1)
- }
-
- log("[foundation-models] Foundation Models Server starting...")
- log("[foundation-models] Port: \(port)")
-
- let server = FoundationModelsHTTPServer(
- modelId: "apple/on-device",
- apiKey: apiKey
- )
-
- let router = server.buildRouter()
- let app = Application(
- router: router,
- configuration: .init(address: .hostname("127.0.0.1", port: port))
- )
-
- log("[foundation-models] http server listening on http://127.0.0.1:\(port)")
- log("[foundation-models] server is listening on 127.0.0.1:\(port)")
-
- try await app.run()
- }
-}
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/Sources/FoundationModelsServer/Logger.swift b/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/Sources/FoundationModelsServer/Logger.swift
deleted file mode 100644
index 34bb17517..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/Sources/FoundationModelsServer/Logger.swift
+++ /dev/null
@@ -1,6 +0,0 @@
-import Foundation
-
-func log(_ message: String) {
- print(message)
- fflush(stdout)
-}
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/Sources/FoundationModelsServer/Server.swift b/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/Sources/FoundationModelsServer/Server.swift
deleted file mode 100644
index b14eb3574..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/Sources/FoundationModelsServer/Server.swift
+++ /dev/null
@@ -1,299 +0,0 @@
-import Foundation
-import Hummingbird
-import FoundationModels
-
-/// HTTP server exposing an OpenAI-compatible API backed by Apple Foundation Models
-struct FoundationModelsHTTPServer: Sendable {
- let modelId: String
- let apiKey: String
-
- func buildRouter() -> Router<BasicRequestContext> {
- let router = Router()
-
- // Health check
- router.get("/health") { _, _ in
- let response = HealthResponse(status: "ok")
- return try encodeJSONResponse(response)
- }
-
- // List available models
- router.get("/v1/models") { _, _ in
- let response = ModelsListResponse(
- object: "list",
- data: [
- ModelData(
- id: self.modelId,
- object: "model",
- created: currentTimestamp(),
- owned_by: "apple"
- )
- ]
- )
- return try encodeJSONResponse(response)
- }
-
- // Chat completions (OpenAI-compatible)
- router.post("/v1/chat/completions") { request, _ in
- // Validate API key when configured
- if !self.apiKey.isEmpty {
- let authHeader = request.headers[.authorization]
- guard authHeader == "Bearer \(self.apiKey)" else {
- let errorResp = ErrorResponse(
- error: ErrorDetail(
- message: "Unauthorized: invalid or missing API key",
- type: "authentication_error",
- code: "unauthorized"
- )
- )
- return try Response(
- status: .unauthorized,
- headers: [.contentType: "application/json"],
- body: .init(byteBuffer: encodeJSONBuffer(errorResp))
- )
- }
- }
-
- let body = try await request.body.collect(upTo: 10 * 1024 * 1024)
- let chatRequest: ChatCompletionRequest
- do {
- chatRequest = try JSONDecoder().decode(ChatCompletionRequest.self, from: body)
- } catch {
- let errorResp = ErrorResponse(
- error: ErrorDetail(
- message: "Invalid request body: \(error.localizedDescription)",
- type: "invalid_request_error",
- code: nil
- )
- )
- return try Response(
- status: .badRequest,
- headers: [.contentType: "application/json"],
- body: .init(byteBuffer: encodeJSONBuffer(errorResp))
- )
- }
- let isStreaming = chatRequest.stream ?? false
-
- log("[foundation-models] Request: messages=\(chatRequest.messages.count), stream=\(isStreaming)")
-
- if isStreaming {
- return try await self.handleStreamingRequest(chatRequest)
- } else {
- return try await self.handleNonStreamingRequest(chatRequest)
- }
- }
-
- return router
- }
-
- // MARK: - Non-streaming
-
- private func handleNonStreamingRequest(_ chatRequest: ChatCompletionRequest) async throws -> Response {
- let session = buildSession(from: chatRequest.messages)
- let lastUserMessage = extractLastUserMessage(from: chatRequest.messages)
-
- let response = try await session.respond(to: lastUserMessage)
- let content = response.content
-
- let completionResponse = ChatCompletionResponse(
- id: "chatcmpl-\(UUID().uuidString)",
- object: "chat.completion",
- created: currentTimestamp(),
- model: modelId,
- choices: [
- ChatCompletionChoice(
- index: 0,
- message: ChatResponseMessage(role: "assistant", content: content),
- finish_reason: "stop"
- )
- ],
- usage: UsageInfo(
- prompt_tokens: 0,
- completion_tokens: 0,
- total_tokens: 0
- )
- )
-
- return try encodeJSONResponse(completionResponse)
- }
-
- // MARK: - Streaming
-
- private func handleStreamingRequest(_ chatRequest: ChatCompletionRequest) async throws -> Response {
- let requestId = "chatcmpl-\(UUID().uuidString)"
- let created = currentTimestamp()
- let modelId = self.modelId
- let messages = chatRequest.messages
-
- let (stream, continuation) = AsyncStream<ByteBuffer>.makeStream()
-
- let task = Task { [self] in
- do {
- let session = self.buildSession(from: messages)
- let lastUserMessage = self.extractLastUserMessage(from: messages)
-
- let roleDelta = ChatCompletionChunk(
- id: requestId,
- object: "chat.completion.chunk",
- created: created,
- model: modelId,
- choices: [
- ChunkChoice(
- index: 0,
- delta: DeltaContent(role: "assistant", content: nil),
- finish_reason: nil
- )
- ]
- )
- if let buffer = encodeSSEBuffer(roleDelta) {
- continuation.yield(buffer)
- }
-
- var previousText = ""
- for try await snapshot in session.streamResponse(to: lastUserMessage) {
- let currentText = snapshot.content
- let delta = String(currentText.dropFirst(previousText.count))
- previousText = currentText
-
- if delta.isEmpty { continue }
-
- let chunk = ChatCompletionChunk(
- id: requestId,
- object: "chat.completion.chunk",
- created: created,
- model: modelId,
- choices: [
- ChunkChoice(
- index: 0,
- delta: DeltaContent(role: nil, content: delta),
- finish_reason: nil
- )
- ]
- )
- if let buffer = encodeSSEBuffer(chunk) {
- continuation.yield(buffer)
- }
- }
-
- // Send stop chunk
- let stopChunk = ChatCompletionChunk(
- id: requestId,
- object: "chat.completion.chunk",
- created: created,
- model: modelId,
- choices: [
- ChunkChoice(
- index: 0,
- delta: DeltaContent(role: nil, content: nil),
- finish_reason: "stop"
- )
- ]
- )
- if let buffer = encodeSSEBuffer(stopChunk) {
- continuation.yield(buffer)
- }
-
- // SSE terminator
- var doneBuffer = ByteBufferAllocator().buffer(capacity: 16)
- doneBuffer.writeString("data: [DONE]\n\n")
- continuation.yield(doneBuffer)
- } catch {
- log("[foundation-models] Streaming error: \(error.localizedDescription)")
- var errBuffer = ByteBufferAllocator().buffer(capacity: 256)
- errBuffer.writeString("error: {\"message\":\"\(error.localizedDescription)\"}\n\n")
- continuation.yield(errBuffer)
- }
- continuation.finish()
- }
-
- // Cancel the generation task when the client disconnects
- continuation.onTermination = { @Sendable _ in
- log("[foundation-models] SSE continuation terminated by client disconnect")
- task.cancel()
- }
-
- return Response(
- status: .ok,
- headers: [
- .contentType: "text/event-stream",
- .cacheControl: "no-cache",
- .init("X-Accel-Buffering")!: "no"
- ],
- body: .init(asyncSequence: stream)
- )
- }
-
- // MARK: - Session Construction
-
- /// Build a `LanguageModelSession` from the OpenAI message list.
- ///
- /// System messages become the session instructions.
- /// Prior user/assistant turns are serialised into the instructions block so
- /// the model has full conversation context without re-running inference.
- /// (The Foundation Models `Transcript` API is not used for history injection
- /// because it is designed for observing an already-live session's state, not
- /// for priming a fresh one with arbitrary history.)
- private func buildSession(from messages: [ChatMessage]) -> LanguageModelSession {
- let systemContent = messages.first(where: { $0.role == "system" })?.content ?? ""
- let nonSystem = messages.filter { $0.role != "system" }
- let history = nonSystem.dropLast() // all turns except the last user message
-
- var instructionsText: String
- if systemContent.isEmpty {
- instructionsText = "You are a helpful assistant."
- } else {
- instructionsText = systemContent
- }
-
- // Append prior turns so the model understands conversation context
- if !history.isEmpty {
- instructionsText += "\n\n[Previous conversation]\n"
- for msg in history {
- let label = msg.role == "assistant" ? "Assistant" : "User"
- instructionsText += "\(label): \(msg.content ?? "")\n"
- }
- instructionsText += "[End of previous conversation]"
- }
-
- return LanguageModelSession(instructions: instructionsText)
- }
-
- private func extractLastUserMessage(from messages: [ChatMessage]) -> String {
- let nonSystem = messages.filter { $0.role != "system" }
- return nonSystem.last?.content ?? ""
- }
-}
-
-// MARK: - Helpers
-
-private func currentTimestamp() -> Int {
- Int(Date().timeIntervalSince1970)
-}
-
-private func encodeJSONResponse<T: Encodable>(_ value: T) throws -> Response {
- let data = try JSONEncoder().encode(value)
- var buffer = ByteBufferAllocator().buffer(capacity: data.count)
- buffer.writeBytes(data)
- return Response(
- status: .ok,
- headers: [.contentType: "application/json"],
- body: .init(byteBuffer: buffer)
- )
-}
-
-private func encodeJSONBuffer<T: Encodable>(_ value: T) -> ByteBuffer {
- let data = (try? JSONEncoder().encode(value)) ?? Data()
- var buffer = ByteBufferAllocator().buffer(capacity: data.count)
- buffer.writeBytes(data)
- return buffer
-}
-
-private func encodeSSEBuffer<T: Encodable>(_ value: T) -> ByteBuffer? {
- guard let json = try? JSONEncoder().encode(value),
- let jsonString = String(data: json, encoding: .utf8) else {
- return nil
- }
- let line = "data: \(jsonString)\n\n"
- var buffer = ByteBufferAllocator().buffer(capacity: line.utf8.count)
- buffer.writeString(line)
- return buffer
-}
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/Sources/FoundationModelsServer/Types.swift b/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/Sources/FoundationModelsServer/Types.swift
deleted file mode 100644
index 86dc656f7..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/swift-server/Sources/FoundationModelsServer/Types.swift
+++ /dev/null
@@ -1,98 +0,0 @@
-import Foundation
-
-// MARK: - OpenAI Request Types
-
-struct ChatCompletionRequest: Codable, Sendable {
- let model: String
- let messages: [ChatMessage]
- var temperature: Double?
- var top_p: Double?
- var max_tokens: Int?
- var n_predict: Int?
- var stream: Bool?
- var stop: [String]?
-}
-
-struct ChatMessage: Codable, Sendable {
- let role: String
- let content: String?
-}
-
-// MARK: - OpenAI Response Types
-
-struct ChatCompletionResponse: Codable, Sendable {
- let id: String
- let object: String
- let created: Int
- let model: String
- let choices: [ChatCompletionChoice]
- let usage: UsageInfo
-}
-
-struct ChatCompletionChoice: Codable, Sendable {
- let index: Int
- let message: ChatResponseMessage
- let finish_reason: String
-}
-
-struct ChatResponseMessage: Codable, Sendable {
- let role: String
- let content: String
-}
-
-struct UsageInfo: Codable, Sendable {
- let prompt_tokens: Int
- let completion_tokens: Int
- let total_tokens: Int
-}
-
-// MARK: - Streaming Types
-
-struct ChatCompletionChunk: Codable, Sendable {
- let id: String
- let object: String
- let created: Int
- let model: String
- let choices: [ChunkChoice]
-}
-
-struct ChunkChoice: Codable, Sendable {
- let index: Int
- let delta: DeltaContent
- let finish_reason: String?
-}
-
-struct DeltaContent: Codable, Sendable {
- let role: String?
- let content: String?
-}
-
-// MARK: - Model List Types
-
-struct ModelsListResponse: Codable, Sendable {
- let object: String
- let data: [ModelData]
-}
-
-struct ModelData: Codable, Sendable {
- let id: String
- let object: String
- let created: Int
- let owned_by: String
-}
-
-// MARK: - Health / Error Types
-
-struct HealthResponse: Codable, Sendable {
- let status: String
-}
-
-struct ErrorDetail: Codable, Sendable {
- let message: String
- let type: String
- let code: String?
-}
-
-struct ErrorResponse: Codable, Sendable {
- let error: ErrorDetail
-}
diff --git a/src-tauri/plugins/tauri-plugin-foundation-models/tsconfig.json b/src-tauri/plugins/tauri-plugin-foundation-models/tsconfig.json
deleted file mode 100644
index 059112270..000000000
--- a/src-tauri/plugins/tauri-plugin-foundation-models/tsconfig.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "compilerOptions": {
- "target": "es2021",
- "module": "esnext",
- "moduleResolution": "bundler",
- "skipLibCheck": true,
- "strict": true,
- "noUnusedLocals": true,
- "noImplicitAny": true,
- "noEmit": true
- },
- "include": ["guest-js/*.ts"],
- "exclude": ["dist-js", "node_modules"]
-}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index fe7110e69..c97cda5d8 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -143,11 +143,6 @@ pub fn run() {
app_builder = app_builder.plugin(tauri_plugin_mlx::init());
}
- #[cfg(feature = "foundation-models")]
- {
- app_builder = app_builder.plugin(tauri_plugin_foundation_models::init());
- }
-
#[cfg(not(any(target_os = "android", target_os = "ios")))]
{
app_builder = app_builder.plugin(tauri_plugin_hardware::init());
@@ -323,13 +318,6 @@ pub fn run() {
}
- #[cfg(feature = "foundation-models")]
- {
- use tauri_plugin_foundation_models::cleanup_processes;
- cleanup_processes(&app_handle).await;
- log::info!("Foundation Models state cleaned up successfully");
- }
-
log::info!("App cleanup completed");
});
});
diff --git a/web-app/public/images/model-provider/apple-intelligence.svg b/web-app/public/images/model-provider/apple-intelligence.svg
deleted file mode 100644
index 35f0cd9f4..000000000
--- a/web-app/public/images/model-provider/apple-intelligence.svg
+++ /dev/null
@@ -1,14 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none">
- <defs>
- <linearGradient id="bg" x1="0" y1="0" x2="64" y2="64" gradientUnits="userSpaceOnUse">
- <stop offset="0%" stop-color="#5AC8FA"/>
- <stop offset="33%" stop-color="#AF52DE"/>
- <stop offset="66%" stop-color="#FF6482"/>
- <stop offset="100%" stop-color="#FFD60A"/>
- </linearGradient>
- </defs>
- <rect width="64" height="64" rx="14" fill="url(#bg)"/>
- <g transform="translate(16, 10)" fill="white">
- <path d="M26.2 11.6c-1.5 1.7-3.9 3-6.3 2.8-.3-2.4.9-5 2.3-6.6C23.7 6 26.3 4.8 28.4 4.7c.3 2.5-.7 5-2.2 6.9zM28.3 14.7c-3.5-.2-6.5 2-8.2 2s-4.3-1.9-7.1-1.8c-3.6.1-7 2.1-8.8 5.4-3.8 6.6-1 16.3 2.7 21.6 1.8 2.6 3.9 5.5 6.7 5.4 2.7-.1 3.7-1.7 7-1.7 3.2 0 4.1 1.7 6.9 1.6 2.9-.1 4.7-2.6 6.5-5.3 2-2.9 2.8-5.8 2.9-5.9-.1 0-5.5-2.1-5.6-8.4-.1-5.3 4.3-7.8 4.5-8-2.5-3.6-6.3-4-7.5-4z"/>
- </g>
-</svg>
diff --git a/web-app/src/containers/DropdownModelProvider.tsx b/web-app/src/containers/DropdownModelProvider.tsx
index 825ae61b8..660bb9425 100644
--- a/web-app/src/containers/DropdownModelProvider.tsx
+++ b/web-app/src/containers/DropdownModelProvider.tsx
@@ -263,7 +263,6 @@ const DropdownModelProvider = memo(function DropdownModelProvider({
providers.forEach((provider) => {
if (!provider.active) return
- if (provider.provider === 'foundation-models') return
provider.models.forEach((modelItem) => {
// Skip embedding models - they can't be used for chat
@@ -345,7 +344,7 @@ const DropdownModelProvider = memo(function DropdownModelProvider({
// When not searching, show all active providers (even without models)
// Sort: local first, then providers with API keys or custom with models, then others, alphabetically
const activeProviders = providers
- .filter((p) => p.active && p.provider !== 'foundation-models')
+ .filter((p) => p.active)
.sort((a, b) => {
const aIsLocal = a.provider === 'llamacpp' || a.provider === 'mlx'
const bIsLocal = b.provider === 'llamacpp' || b.provider === 'mlx'
diff --git a/web-app/src/containers/SettingsMenu.tsx b/web-app/src/containers/SettingsMenu.tsx
index ebbc781c3..375c071cf 100644
--- a/web-app/src/containers/SettingsMenu.tsx
+++ b/web-app/src/containers/SettingsMenu.tsx
@@ -66,14 +66,12 @@ const SettingsMenu = () => {
const activeProviders = providers.filter((provider) => {
if (!provider.active) return false
if (!IS_MACOS && provider.provider === 'mlx') return false
- if (provider.provider === 'foundation-models') return false
return true
})
const hiddenProviders = providers.filter((provider) => {
if (provider.active) return false
if (!IS_MACOS && provider.provider === 'mlx') return false
- if (provider.provider === 'foundation-models') return false
return true
})
diff --git a/web-app/src/lib/__tests__/model-factory.coverage.test.ts b/web-app/src/lib/__tests__/model-factory.coverage.test.ts
index 0aa1e182d..35ceaa5a9 100644
--- a/web-app/src/lib/__tests__/model-factory.coverage.test.ts
+++ b/web-app/src/lib/__tests__/model-factory.coverage.test.ts
@@ -234,45 +234,4 @@ describe('ModelFactory - coverage', () => {
).rejects.toThrow('No running MLX session found')
})
- it('creates foundation-models model', async () => {
- const { invoke } = await import('@tauri-apps/api/core')
- vi.mocked(invoke)
- .mockResolvedValueOnce('available') // availability check
- .mockResolvedValueOnce(true) // is_loaded check
- const model = await ModelFactory.createModel('apple/on-device', mkProvider('foundation-models'), {})
- expect(model).toBeDefined()
- })
-
- it('throws when foundation-models not available', async () => {
- const { invoke } = await import('@tauri-apps/api/core')
- vi.mocked(invoke).mockResolvedValueOnce('notEligible')
- await expect(
- ModelFactory.createModel('apple/on-device', mkProvider('foundation-models'), {})
- ).rejects.toThrow('Apple Intelligence is not supported')
- })
-
- it('throws when foundation-models not loaded', async () => {
- const { invoke } = await import('@tauri-apps/api/core')
- vi.mocked(invoke)
- .mockResolvedValueOnce('available')
- .mockResolvedValueOnce(false)
- await expect(
- ModelFactory.createModel('apple/on-device', mkProvider('foundation-models'), {})
- ).rejects.toThrow('No running Foundation Models session')
- })
-
- it('throws specific messages for each unavailability reason', async () => {
- const { invoke } = await import('@tauri-apps/api/core')
-
- for (const [reason, snippet] of [
- ['appleIntelligenceNotEnabled', 'not enabled'],
- ['modelNotReady', 'still preparing'],
- ['unavailable', 'currently unavailable'],
- ] as const) {
- vi.mocked(invoke).mockResolvedValueOnce(reason)
- await expect(
- ModelFactory.createModel('apple/on-device', mkProvider('foundation-models'), {})
- ).rejects.toThrow(snippet)
- }
- })
})
diff --git a/web-app/src/lib/__tests__/model-factory.deep.test.ts b/web-app/src/lib/__tests__/model-factory.deep.test.ts
index 5afa76db3..18c431eab 100644
--- a/web-app/src/lib/__tests__/model-factory.deep.test.ts
+++ b/web-app/src/lib/__tests__/model-factory.deep.test.ts
@@ -231,96 +231,6 @@ describe('model-factory deep coverage', () => {
})
})
- /* foundation-models */
- describe('foundation-models fetch', () => {
- it('non-streaming returns Response', async () => {
- vi.mocked(invoke)
- .mockResolvedValueOnce('available')
- .mockResolvedValueOnce(true)
- await ModelFactory.createModel('fm', mkProvider('foundation-models'), {})
- const opts = getOpts()
- vi.mocked(invoke).mockResolvedValueOnce('{"choices":[]}')
- const resp = await opts.fetch('fm://x', { method: 'POST', body: JSON.stringify({ messages: [], stream: false }) })
- expect(resp.status).toBe(200)
- expect(await resp.text()).toBe('{"choices":[]}')
- })
-
- it('streaming creates ReadableStream', async () => {
- vi.mocked(invoke)
- .mockResolvedValueOnce('available')
- .mockResolvedValueOnce(true)
- await ModelFactory.createModel('fm', mkProvider('foundation-models'), {})
- const opts = getOpts()
-
- const { listen } = await import('@tauri-apps/api/event')
- let cb: any = null
- vi.mocked(listen).mockImplementation(async (_ev: string, fn: any) => {
- cb = fn
- return () => {}
- })
- vi.mocked(invoke).mockResolvedValueOnce(undefined)
-
- const resp = await opts.fetch('fm://x', { method: 'POST', body: JSON.stringify({ messages: [], stream: true }) })
- expect(resp.headers.get('Content-Type')).toBe('text/event-stream')
-
- const reader = resp.body!.getReader()
- const dec = new TextDecoder()
-
- cb({ payload: { data: '{"c":1}' } })
- const c1 = await reader.read()
- expect(dec.decode(c1.value)).toContain('{"c":1}')
-
- cb({ payload: { done: true } })
- const c2 = await reader.read()
- expect(dec.decode(c2.value)).toContain('[DONE]')
- })
-
- it('streaming handles error payload', async () => {
- vi.mocked(invoke)
- .mockResolvedValueOnce('available')
- .mockResolvedValueOnce(true)
- await ModelFactory.createModel('fm', mkProvider('foundation-models'), {})
- const opts = getOpts()
-
- const { listen } = await import('@tauri-apps/api/event')
- let cb: any = null
- vi.mocked(listen).mockImplementation(async (_ev: string, fn: any) => {
- cb = fn
- return () => {}
- })
- vi.mocked(invoke).mockResolvedValueOnce(undefined)
-
- const resp = await opts.fetch('fm://x', { method: 'POST', body: JSON.stringify({ messages: [], stream: true }) })
- const reader = resp.body!.getReader()
- cb({ payload: { error: 'boom' } })
- await expect(reader.read()).rejects.toThrow('boom')
- })
-
- it('streaming handles invoke error', async () => {
- vi.mocked(invoke)
- .mockResolvedValueOnce('available')
- .mockResolvedValueOnce(true)
- await ModelFactory.createModel('fm', mkProvider('foundation-models'), {})
- const opts = getOpts()
-
- const { listen } = await import('@tauri-apps/api/event')
- vi.mocked(listen).mockImplementation(async (_ev: string, _fn: any) => {
- return () => {}
- })
- vi.mocked(invoke).mockRejectedValueOnce(new Error('invoke fail'))
-
- const resp = await opts.fetch('fm://x', { method: 'POST', body: JSON.stringify({ messages: [], stream: true }) })
- const reader = resp.body!.getReader()
- await expect(reader.read()).rejects.toThrow('invoke fail')
- })
-
- it('startModel error is wrapped', async () => {
- vi.mocked(invoke).mockResolvedValueOnce('available')
- mockStartModel.mockRejectedValueOnce(new Error('FM fail'))
- await expect(ModelFactory.createModel('fm', mkProvider('foundation-models'), {})).rejects.toThrow('Failed to start model: FM fail')
- })
- })
-
/* custom headers on google, openai, xai */
describe('custom headers', () => {
it('google passes custom headers', async () => {
diff --git a/web-app/src/lib/__tests__/model-factory.test.ts b/web-app/src/lib/__tests__/model-factory.test.ts
index fdbcbc840..552bed370 100644
--- a/web-app/src/lib/__tests__/model-factory.test.ts
+++ b/web-app/src/lib/__tests__/model-factory.test.ts
@@ -20,7 +20,7 @@ vi.mock('@tauri-apps/plugin-http', () => ({
// Mock the AI SDK providers
vi.mock('@ai-sdk/openai-compatible', () => {
const MockChatModel = vi.fn().mockImplementation(() => ({
- type: 'foundation-models',
+ type: 'openai-compatible-chat',
modelId: 'apple/on-device',
}))
return {
@@ -232,117 +232,4 @@ describe('ModelFactory', () => {
})
})
- describe('foundation-models provider', () => {
- const foundationModelsProvider: ProviderObject = {
- provider: 'foundation-models',
- models: [],
- settings: [],
- active: true,
- }
-
- it('should throw with notEligible message when device is not eligible', async () => {
- mockedInvoke.mockResolvedValueOnce('notEligible')
-
- await expect(
- ModelFactory.createModel('apple/on-device', foundationModelsProvider)
- ).rejects.toThrow(
- 'Apple Intelligence is not supported on this device. An Apple Silicon Mac (M1 or later) with macOS 26+ is required.'
- )
-
- expect(mockedInvoke).toHaveBeenCalledWith(
- 'plugin:foundation-models|check_foundation_models_availability',
- {}
- )
- })
-
- it('should throw when Apple Intelligence is not enabled', async () => {
- mockedInvoke.mockResolvedValueOnce('appleIntelligenceNotEnabled')
-
- await expect(
- ModelFactory.createModel('apple/on-device', foundationModelsProvider)
- ).rejects.toThrow(
- 'Apple Intelligence is not enabled. Please enable it in System Settings > Apple Intelligence & Siri.'
- )
- })
-
- it('should throw when the model is not ready', async () => {
- mockedInvoke.mockResolvedValueOnce('modelNotReady')
-
- await expect(
- ModelFactory.createModel('apple/on-device', foundationModelsProvider)
- ).rejects.toThrow(
- 'The Apple on-device model is still preparing. Please wait and try again shortly.'
- )
- })
-
- it('should throw when the server binary is missing', async () => {
- mockedInvoke.mockResolvedValueOnce('binaryNotFound')
-
- await expect(
- ModelFactory.createModel('apple/on-device', foundationModelsProvider)
- ).rejects.toThrow(
- 'Apple Foundation Models are currently unavailable on this device.'
- )
- })
-
- it('should throw with generic unavailable message for unknown status', async () => {
- mockedInvoke.mockResolvedValueOnce('unavailable')
-
- await expect(
- ModelFactory.createModel('apple/on-device', foundationModelsProvider)
- ).rejects.toThrow(
- 'Apple Foundation Models are currently unavailable on this device.'
- )
- })
-
- it('should throw when available but model is not loaded after start', async () => {
- mockedInvoke
- .mockResolvedValueOnce('available') // check_foundation_models_availability
- .mockResolvedValueOnce(false) // is_foundation_models_loaded
-
- await expect(
- ModelFactory.createModel('apple/on-device', foundationModelsProvider)
- ).rejects.toThrow(
- 'No running Foundation Models session. The model may have failed to load — please check the logs.'
- )
-
- expect(mockStartModel).toHaveBeenCalledWith(
- foundationModelsProvider,
- 'apple/on-device'
- )
- expect(mockedInvoke).toHaveBeenCalledWith(
- 'plugin:foundation-models|check_foundation_models_availability',
- {}
- )
- expect(mockedInvoke).toHaveBeenCalledWith(
- 'plugin:foundation-models|is_foundation_models_loaded',
- {}
- )
- })
-
- it('should create a model when available and model is loaded', async () => {
- mockedInvoke
- .mockResolvedValueOnce('available') // check_foundation_models_availability
- .mockResolvedValueOnce(true) // is_foundation_models_loaded
-
- const model = await ModelFactory.createModel(
- 'apple/on-device',
- foundationModelsProvider
- )
-
- expect(model).toBeDefined()
- expect(mockStartModel).toHaveBeenCalledWith(
- foundationModelsProvider,
- 'apple/on-device'
- )
- expect(mockedInvoke).toHaveBeenCalledWith(
- 'plugin:foundation-models|check_foundation_models_availability',
- {}
- )
- expect(mockedInvoke).toHaveBeenCalledWith(
- 'plugin:foundation-models|is_foundation_models_loaded',
- {}
- )
- })
- })
})
diff --git a/web-app/src/lib/__tests__/utils.test.ts b/web-app/src/lib/__tests__/utils.test.ts
index 28640d36c..8c9aaebdd 100644
--- a/web-app/src/lib/__tests__/utils.test.ts
+++ b/web-app/src/lib/__tests__/utils.test.ts
@@ -21,9 +21,6 @@ describe('getProviderLogo', () => {
expect(getProviderLogo('openai')).toBe('/images/model-provider/openai.svg')
expect(getProviderLogo('gemini')).toBe('/images/model-provider/gemini.svg')
expect(getProviderLogo('nvidia')).toBe('/images/model-provider/nvidia.svg')
- expect(getProviderLogo('foundation-models')).toBe(
- '/images/model-provider/apple-intelligence.svg'
- )
})
it('returns undefined for unknown providers', () => {
@@ -39,7 +36,6 @@ describe('getProviderTitle', () => {
expect(getProviderTitle('openrouter')).toBe('OpenRouter')
expect(getProviderTitle('gemini')).toBe('Gemini')
expect(getProviderTitle('nvidia')).toBe('NVIDIA NIM')
- expect(getProviderTitle('foundation-models')).toBe('Apple Intelligence')
})
it('capitalizes first letter for unknown providers', () => {
diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.ts
index b8c668dd5..00e8db251 100644
--- a/web-app/src/lib/model-factory.ts
+++ b/web-app/src/lib/model-factory.ts
@@ -228,95 +228,6 @@ function getRuntimeFetch(): typeof globalThis.fetch {
: globalThis.fetch
}
-/**
- * Custom fetch for Foundation Models that routes through Tauri IPC
- * instead of HTTP, emulating an OpenAI-compatible fetch interface.
- */
-function createFoundationModelsFetch(
- parameters: Record<string, unknown>
-): typeof globalThis.fetch {
- return async (
- _input: RequestInfo | URL,
- init?: RequestInit
- ): Promise<Response> => {
- const rawBody = init?.body ? JSON.parse(init.body as string) : {}
- const body = { ...rawBody, ...parameters }
- const isStreaming = body.stream === true
-
- if (!isStreaming) {
- const result = await invoke<string>(
- 'plugin:foundation-models|foundation_models_chat_completion',
- { body: JSON.stringify(body) }
- )
- return new Response(result, {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- })
- }
-
- const requestId = crypto.randomUUID()
- const { listen } = await import('@tauri-apps/api/event')
-
- let unlistenFn: (() => void) | null = null
- const stream = new ReadableStream<Uint8Array>({
- async start(controller) {
- const encoder = new TextEncoder()
-
- unlistenFn = await listen(
- `foundation-models-stream-${requestId}`,
- (event: { payload: { data?: string; done?: boolean; error?: string } }) => {
- const payload = event.payload
- if (payload.done) {
- controller.enqueue(encoder.encode('data: [DONE]\n\n'))
- try {
- controller.close()
- } catch {
- /* already closed */
- }
- unlistenFn?.()
- } else if (payload.error) {
- try {
- controller.error(new Error(payload.error))
- } catch {
- /* already errored */
- }
- unlistenFn?.()
- } else if (payload.data) {
- controller.enqueue(
- encoder.encode(`data: ${payload.data}\n\n`)
- )
- }
- }
- )
-
- invoke(
- 'plugin:foundation-models|foundation_models_chat_completion_stream',
- { body: JSON.stringify(body), requestId }
- ).catch((err) => {
- try {
- controller.error(err)
- } catch {
- /* already errored */
- }
- unlistenFn?.()
- })
- },
- cancel() {
- unlistenFn?.()
- invoke(
- 'plugin:foundation-models|abort_foundation_models_stream',
- { requestId }
- ).catch(() => {})
- },
- })
-
- return new Response(stream, {
- status: 200,
- headers: { 'Content-Type': 'text/event-stream' },
- })
- }
-}
-
/**
* Map of model keywords to their respective reasoning tags.
* Used for models that use tags other than the default 'think'.
@@ -366,9 +277,6 @@ export class ModelFactory {
case 'mlx':
return this.createMlxModel(modelId, provider, parameters)
- case 'foundation-models':
- return this.createFoundationModelsModel(modelId, provider, parameters)
-
case 'anthropic':
return this.createAnthropicModel(modelId, provider, parameters)
@@ -549,81 +457,6 @@ export class ModelFactory {
})
}
- /**
- * Create a Foundation Models model (Apple on-device) via direct Tauri IPC
- * to the fm-rs Rust bindings — no HTTP server involved.
- */
- private static async createFoundationModelsModel(
- modelId: string,
- provider?: ProviderObject,
- parameters: Record<string, unknown> = {}
- ): Promise<LanguageModel> {
- parameters = filterParameters(parameters, false)
- const availability = await invoke<string>(
- 'plugin:foundation-models|check_foundation_models_availability',
- {}
- )
-
- if (availability !== 'available') {
- const messages: Record<string, string> = {
- notEligible:
- 'Apple Intelligence is not supported on this device. An Apple Silicon Mac (M1 or later) with macOS 26+ is required.',
- appleIntelligenceNotEnabled:
- 'Apple Intelligence is not enabled. Please enable it in System Settings > Apple Intelligence & Siri.',
- modelNotReady:
- 'The Apple on-device model is still preparing. Please wait and try again shortly.',
- unavailable:
- 'Apple Foundation Models are currently unavailable on this device.',
- }
- throw new Error(messages[availability] ?? messages.unavailable)
- }
-
- if (provider) {
- try {
- const { useServiceStore } = await import('@/hooks/useServiceHub')
- const serviceHub = useServiceStore.getState().serviceHub
-
- if (serviceHub) {
- await serviceHub.models().startModel(provider, modelId)
- }
- } catch (error) {
- console.error('Failed to start Foundation Models:', error)
- throw new Error(
- `Failed to start model: ${error instanceof Error ? error.message : JSON.stringify(error)}`
- )
- }
- }
-
- const loaded = await invoke<boolean>(
- 'plugin:foundation-models|is_foundation_models_loaded',
- {}
- )
-
- if (!loaded) {
- throw new Error(
- 'No running Foundation Models session. The model may have failed to load — please check the logs.'
- )
- }
-
- const customFetch = createFoundationModelsFetch(parameters)
-
- const model = new OpenAICompatibleChatLanguageModel(modelId, {
- provider: 'foundation-models',
- headers: () => ({}),
- url: ({ path }) => `foundation-models://local/v1${path}`,
- fetch: customFetch as typeof httpFetch,
- metadataExtractor: providerMetadataExtractor,
- })
-
- return wrapLanguageModel({
- model,
- middleware: extractReasoningMiddleware({
- tagName: getReasoningTagName(modelId),
- separator: '\n',
- }),
- })
- }
-
/**
* Create an Anthropic model using the official AI SDK
*/
diff --git a/web-app/src/lib/utils.ts b/web-app/src/lib/utils.ts
index 60accfd07..0e85e8070 100644
--- a/web-app/src/lib/utils.ts
+++ b/web-app/src/lib/utils.ts
@@ -72,8 +72,6 @@ export function getProviderLogo(provider: string) {
return '/images/model-provider/llamacpp.svg'
case 'mlx':
return '/images/model-provider/mlx.png'
- case 'foundation-models':
- return '/images/model-provider/apple-intelligence.svg'
case 'anthropic':
return '/images/model-provider/anthropic.svg'
case 'huggingface':
@@ -111,8 +109,6 @@ export const getProviderTitle = (provider: string) => {
return 'Llama.cpp'
case 'mlx':
return 'MLX'
- case 'foundation-models':
- return 'Apple Intelligence'
case 'openai':
return 'OpenAI'
case 'openrouter':
diff --git a/web-app/src/services/providers/__tests__/tauri.test.ts b/web-app/src/services/providers/__tests__/tauri.test.ts
index 4de855545..8c7562766 100644
--- a/web-app/src/services/providers/__tests__/tauri.test.ts
+++ b/web-app/src/services/providers/__tests__/tauri.test.ts
@@ -107,18 +107,6 @@ describe('TauriProvidersService', () => {
expect(llama!.models).toHaveLength(1)
})
- it('skips hidden providers (foundation-models)', async () => {
- const hiddenEngine = { list: vi.fn(), getSettings: vi.fn() }
- vi.mocked(EngineManager.instance).mockReturnValue({
- engines: new Map([['foundation-models', hiddenEngine]]),
- } as any)
-
- const result = await svc.getProviders()
- expect(hiddenEngine.list).not.toHaveBeenCalled()
- // Only builtins
- expect(result.every((p: any) => p.provider !== 'foundation-models')).toBe(true)
- })
-
it('adds TOOLS capability when isToolSupported returns true', async () => {
const mockEngine = {
list: vi.fn().mockResolvedValue([{ id: 'm1', name: 'M1', description: '' }]),
diff --git a/web-app/src/services/providers/tauri.ts b/web-app/src/services/providers/tauri.ts
index 73340db7c..1d5b663a0 100644
--- a/web-app/src/services/providers/tauri.ts
+++ b/web-app/src/services/providers/tauri.ts
@@ -46,12 +46,9 @@ export class TauriProvidersService extends DefaultProvidersService {
}
}).filter(Boolean)
- // TODO: Re-enable foundation-models once migrated to apple-foundation-models crate
- const hiddenProviders = new Set(['foundation-models'])
const runtimeProviders: ModelProvider[] = []
for (const [providerName, value] of EngineManager.instance().engines) {
- if (hiddenProviders.has(providerName)) continue
- const models = await value.list() ?? []
+ const models = await value.list() ?? []
const provider: ModelProvider = {
active: false,
persist: true,