The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(engine): P2 — wire built-in engine as managed frontend backend
purplec0ac27f0652c
diff --git a/src/api/__tests__/builtin-default-provider.test.ts b/src/api/__tests__/builtin-default-provider.test.tsnew file mode 100644index 00000000..b5d45244--- /dev/null+++ b/src/api/__tests__/builtin-default-provider.test.ts@@ -0,0 +1,60 @@+/**+ * Built-in engine as the default backend (2.5.7) — P2.+ *+ * A fresh provider store must default to the app-managed built-in engine (in the+ * `openai` slot) instead of Ollama, so a clean install can chat with zero+ * external install. Also pins `isManagedBuiltinActive()`, which routes the+ * model list to `list_bundled_models`.+ *+ * Run: npx vitest run src/api/__tests__/builtin-default-provider.test.ts+ */+import { describe, it, expect, beforeEach } from 'vitest'+import { useProviderStore } from '../../stores/providerStore'+import { isManagedBuiltinActive } from '../engine'++// Snapshot the pristine defaults before any test mutates the store.+const DEFAULTS = structuredClone(useProviderStore.getState().providers)++beforeEach(() => {+ useProviderStore.setState({ providers: structuredClone(DEFAULTS) })+})++describe('default provider = built-in engine', () => {+ it('enables the managed built-in engine in the openai slot', () => {+ const openai = useProviderStore.getState().providers.openai+ expect(openai.enabled).toBe(true)+ expect(openai.managed).toBe(true)+ expect(openai.isLocal).toBe(true)+ expect(openai.name).toBe('Built-in Engine')+ expect(openai.baseUrl).toBe('http://127.0.0.1:8127/v1')+ expect(openai.apiKey).toBe('')+ })++ it('disables Ollama by default (available as Advanced)', () => {+ expect(useProviderStore.getState().providers.ollama.enabled).toBe(false)+ })++ it('exposes the built-in engine as the only enabled provider', () => {+ const enabled = useProviderStore.getState().getEnabledProviders()+ expect(enabled.map(p => p.id)).toEqual(['openai'])+ expect(enabled[0].managed).toBe(true)+ })+})++describe('isManagedBuiltinActive', () => {+ it('is true for the default managed engine', () => {+ expect(isManagedBuiltinActive()).toBe(true)+ })++ it('is false once the openai slot is repointed at a user backend (LM Studio)', () => {+ useProviderStore.getState().setProviderConfig('openai', {+ name: 'LM Studio', baseUrl: 'http://localhost:1234/v1', managed: false,+ })+ expect(isManagedBuiltinActive()).toBe(false)+ })++ it('is false when the openai slot is disabled', () => {+ useProviderStore.getState().setProviderConfig('openai', { enabled: false })+ expect(isManagedBuiltinActive()).toBe(false)+ })+})diff --git a/src/api/__tests__/engine.test.ts b/src/api/__tests__/engine.test.tsnew file mode 100644index 00000000..fcdda227--- /dev/null+++ b/src/api/__tests__/engine.test.ts@@ -0,0 +1,136 @@+/**+ * Built-in Engine client (2.5.7) — P2.+ *+ * Pins the Tauri-command wrappers, the GGUF→AIModel mapper, and the+ * activate→swap path against the P1 command surface in+ * `src-tauri/src/commands/engine.rs`.+ *+ * Run: npx vitest run src/api/__tests__/engine.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++vi.mock('../backend', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../backend')>()+ return { ...actual, backendCall: vi.fn() }+})++import {+ startBundledEngine,+ stopBundledEngine,+ bundledEngineStatus,+ swapBundledModel,+ listBundledModels,+ bundledToAIModels,+ activateBuiltinModel,+ type BundledModel,+} from '../engine'+import { backendCall } from '../backend'++beforeEach(() => {+ vi.mocked(backendCall).mockReset()+})++describe('engine command wrappers', () => {+ it('starts the engine with camelCase args (Tauri maps → snake_case)', async () => {+ vi.mocked(backendCall).mockResolvedValue({ port: 8127 } as never)+ await startBundledEngine('/models/qwen.gguf', 4096)+ expect(backendCall).toHaveBeenCalledWith('start_bundled_engine', {+ modelPath: '/models/qwen.gguf',+ ctx: 4096,+ })+ })++ it('swaps the loaded model by path', async () => {+ vi.mocked(backendCall).mockResolvedValue({ port: 8127 } as never)+ await swapBundledModel('/models/other.gguf')+ expect(backendCall).toHaveBeenCalledWith('swap_bundled_model', {+ modelPath: '/models/other.gguf',+ ctx: undefined,+ })+ })++ it('stops the engine and reads status', async () => {+ vi.mocked(backendCall).mockResolvedValue({} as never)+ await stopBundledEngine()+ expect(backendCall).toHaveBeenCalledWith('stop_bundled_engine')++ vi.mocked(backendCall).mockResolvedValue({+ running: true, healthy: true, port: 8127, model_path: '/models/qwen.gguf',+ } as never)+ const status = await bundledEngineStatus()+ expect(status.port).toBe(8127)+ expect(backendCall).toHaveBeenCalledWith('bundled_engine_status')+ })++ it('unwraps the models array from list_bundled_models', async () => {+ vi.mocked(backendCall).mockResolvedValue({+ dir: '/data/models',+ models: [{ name: 'qwen', path: '/data/models/qwen.gguf', size: 400, loaded: true }],+ } as never)+ const models = await listBundledModels()+ expect(backendCall).toHaveBeenCalledWith('list_bundled_models')+ expect(models).toHaveLength(1)+ expect(models[0].name).toBe('qwen')+ })++ it('tolerates a missing models field', async () => {+ vi.mocked(backendCall).mockResolvedValue({ dir: '/data/models' } as never)+ expect(await listBundledModels()).toEqual([])+ })+})++describe('bundledToAIModels', () => {+ it('maps GGUFs to openai::-prefixed text models', () => {+ const bundled: BundledModel[] = [+ { name: 'qwen2.5-0.5b', path: '/m/qwen.gguf', size: 400, loaded: true },+ { name: 'llama3', path: '/m/llama3.gguf', size: 8000, loaded: false },+ ]+ const models = bundledToAIModels(bundled)+ expect(models).toHaveLength(2)+ expect(models[0]).toMatchObject({+ name: 'openai::qwen2.5-0.5b',+ model: 'qwen2.5-0.5b',+ type: 'text',+ provider: 'openai',+ providerName: 'Built-in Engine',+ })+ expect(models[1].name).toBe('openai::llama3')+ })+})++describe('activateBuiltinModel', () => {+ it('resolves the path from the last list and calls swap', async () => {+ vi.mocked(backendCall).mockResolvedValue({+ dir: '/m',+ models: [{ name: 'qwen', path: '/m/qwen.gguf', size: 400, loaded: false }],+ } as never)+ await listBundledModels() // populates name→path map++ vi.mocked(backendCall).mockClear()+ const ok = await activateBuiltinModel('openai::qwen')+ expect(ok).toBe(true)+ expect(backendCall).toHaveBeenCalledWith('swap_bundled_model', {+ modelPath: '/m/qwen.gguf',+ ctx: undefined,+ })+ })++ it('accepts a bare (unprefixed) model id', async () => {+ vi.mocked(backendCall).mockResolvedValue({+ dir: '/m',+ models: [{ name: 'qwen', path: '/m/qwen.gguf', size: 400, loaded: false }],+ } as never)+ await listBundledModels()+ vi.mocked(backendCall).mockClear()+ expect(await activateBuiltinModel('qwen')).toBe(true)+ })++ it('no-ops when the path is unknown', async () => {+ vi.mocked(backendCall).mockResolvedValue({ dir: '/m', models: [] } as never)+ await listBundledModels()+ vi.mocked(backendCall).mockClear()+ const ok = await activateBuiltinModel('openai::ghost')+ expect(ok).toBe(false)+ expect(backendCall).not.toHaveBeenCalled()+ })+})diff --git a/src/api/engine.ts b/src/api/engine.tsnew file mode 100644index 00000000..dfd04e3c--- /dev/null+++ b/src/api/engine.ts@@ -0,0 +1,107 @@+/**+ * Built-in Engine client (2.5.7)+ *+ * Thin typed wrappers over the P1 Rust sidecar commands (see+ * `src-tauri/src/commands/engine.rs`). The built-in engine is a bundled+ * `llama.cpp` `llama-server` — OpenAI-compatible on `127.0.0.1:8127`, whose+ * lifecycle the app owns. Chat itself flows through the existing+ * `OpenAIProvider` + Rust proxy; this module only manages start/stop/swap and+ * sources the model list (the downloaded GGUFs, not just the loaded one).+ *+ * `backendCall` maps camelCase args → snake_case Rust params (Tauri).+ */++import { backendCall } from './backend'+import { prefixModelName } from './providers'+import { useProviderStore } from '../stores/providerStore'+import type { CloudModel } from '../types/models'++export interface BundledModel {+ /** File name without the `.gguf` extension. The id shown in the picker. */+ name: string+ /** Absolute path to the GGUF file — passed back to `swapBundledModel`. */+ path: string+ /** File size in bytes (0 if unknown). */+ size: number+ /** Whether this model is the one currently loaded by the engine. */+ loaded: boolean+}++export interface EngineStatus {+ running: boolean+ healthy: boolean+ port: number+ model_path: string | null+}++// name → absolute GGUF path, populated by listBundledModels(). Lets callers+// activate a model by its picker id (which is what the model store carries)+// without threading the path through AIModel, which has no path field.+const pathByName = new Map<string, string>()++/**+ * True when the active OpenAI-compat backend is the app-managed built-in engine+ * (occupies the `openai` slot with `managed: true`). Drives the model-list+ * source: bundled GGUFs via `list_bundled_models`, not `/v1/models`.+ */+export function isManagedBuiltinActive(): boolean {+ const cfg = useProviderStore.getState().providers.openai+ return cfg.enabled && cfg.managed === true+}++/** Start the built-in engine with a specific GGUF. Idempotent for the same model. */+export function startBundledEngine(modelPath: string, ctx?: number) {+ return backendCall('start_bundled_engine', { modelPath, ctx })+}++/** Stop the managed engine child if one is running. */+export function stopBundledEngine() {+ return backendCall('stop_bundled_engine')+}++/** Engine health + which model is loaded on which port. */+export function bundledEngineStatus() {+ return backendCall<EngineStatus>('bundled_engine_status')+}++/** Swap the loaded model (stop → start on the same port). */+export function swapBundledModel(modelPath: string, ctx?: number) {+ return backendCall('swap_bundled_model', { modelPath, ctx })+}++/** List downloaded GGUFs in the app models dir. Refreshes the name→path map. */+export async function listBundledModels(): Promise<BundledModel[]> {+ const res = await backendCall<{ dir: string; models: BundledModel[] }>('list_bundled_models')+ const models = res?.models ?? []+ pathByName.clear()+ for (const m of models) pathByName.set(m.name, m.path)+ return models+}++/**+ * Map bundled GGUFs to the app's model list shape. Built-in models live in the+ * `openai` slot, so they are prefixed `openai::<name>` for provider routing.+ */+export function bundledToAIModels(models: BundledModel[]): CloudModel[] {+ return models.map((m) => ({+ name: prefixModelName('openai', m.name),+ model: m.name,+ size: m.size,+ type: 'text' as const,+ provider: 'openai' as const,+ providerName: 'Built-in Engine',+ }))+}++/**+ * Activate a built-in model by its picker id (`openai::<name>` or bare `<name>`).+ * Resolves the GGUF path from the last listBundledModels() and swaps the engine.+ * No-op if the path is unknown (list not yet fetched).+ */+export async function activateBuiltinModel(nameOrPrefixed: string, ctx?: number): Promise<boolean> {+ const name = nameOrPrefixed.includes('::') ? nameOrPrefixed.split('::')[1] : nameOrPrefixed+ const path = pathByName.get(name)+ if (!path) return false+ await swapBundledModel(path, ctx)+ return true+}diff --git a/src/api/providers/types.ts b/src/api/providers/types.tsindex c8e87257..b7d1aa26 100644--- a/src/api/providers/types.ts+++ b/src/api/providers/types.ts@@ -16,6 +16,12 @@ export interface ProviderConfig {baseUrl: string // e.g. "http://localhost:11434", "https://openrouter.ai/api/v1"apiKey: string // Encrypted in store. Empty string for local providers.isLocal: boolean // true for Ollama, LM Studio, vLLM — no API key needed+ // Built-in engine (2.5.7): the app manages this OpenAI-compatible backend's+ // lifecycle itself (bundled llama-server on 127.0.0.1:8127). When true the UI+ // hides the URL/key inputs and the model list comes from `list_bundled_models`+ // (the Tauri command), not `/v1/models`. Undefined = a normal user-configured+ // backend, unchanged behavior.+ managed?: boolean}// ── Provider Presets (auto-fill URL) ───────────────────────────@@ -27,9 +33,14 @@ export interface ProviderPreset {baseUrl: stringisLocal: booleanplaceholder?: string // API key placeholder hint+ managed?: boolean // App-managed lifecycle (built-in engine). See ProviderConfig.managed.}export const PROVIDER_PRESETS: ProviderPreset[] = [+ // Built-in engine (2.5.7) — bundled llama.cpp llama-server, OpenAI-compatible,+ // lifecycle owned by the app. Zero external install. Default backend.+ { id: 'builtin', name: 'Built-in Engine', providerId: 'openai', baseUrl: 'http://127.0.0.1:8127/v1', isLocal: true, managed: true },+// Ollama (dedicated provider){ id: 'ollama', name: 'Ollama', providerId: 'ollama', baseUrl: 'http://localhost:11434', isLocal: true },diff --git a/src/components/settings/ProviderConfig.tsx b/src/components/settings/ProviderConfig.tsxindex 2f014caf..a749be86 100644--- a/src/components/settings/ProviderConfig.tsx+++ b/src/components/settings/ProviderConfig.tsx@@ -94,7 +94,9 @@ export function ProviderSettings() {} else if (preset.providerId === 'anthropic') {setProviderConfig('anthropic', { enabled: true, name: preset.name, baseUrl: preset.baseUrl, isLocal: false })} else {- setProviderConfig('openai', { enabled: true, name: preset.name, baseUrl: preset.baseUrl, isLocal: preset.isLocal })+ // `managed` must be set explicitly so switching to LM Studio/vLLM clears+ // the built-in flag, and re-selecting Built-in restores it.+ setProviderConfig('openai', { enabled: true, name: preset.name, baseUrl: preset.baseUrl, isLocal: preset.isLocal, managed: !!preset.managed })}setDropdownOpen(false)@@ -201,16 +203,23 @@ export function ProviderSettings() {{/* Expanded config */}{isExpanded && (<div className="px-2 pb-2 space-y-1.5 border-t border-white/[0.04]">- {/* Endpoint */}- <div className="pt-1.5">- <label className="text-[0.6rem] text-gray-500 mb-0.5 block">Endpoint</label>- <input- value={config.baseUrl}- onChange={(e) => setProviderConfig(id, { baseUrl: e.target.value })}- placeholder="http://localhost:..."- className="w-full px-2 py-1 rounded bg-white/5 border border-white/8 text-[0.65rem] text-gray-300 font-mono focus:outline-none focus:border-white/20"- />- </div>+ {/* Endpoint — hidden for the app-managed built-in engine, whose+ URL is fixed and lifecycle is owned by the app. */}+ {config.managed ? (+ <p className="pt-1.5 text-[0.6rem] text-gray-500 leading-tight">+ Built-in engine — runs locally, nothing to configure.+ </p>+ ) : (+ <div className="pt-1.5">+ <label className="text-[0.6rem] text-gray-500 mb-0.5 block">Endpoint</label>+ <input+ value={config.baseUrl}+ onChange={(e) => setProviderConfig(id, { baseUrl: e.target.value })}+ placeholder="http://localhost:..."+ className="w-full px-2 py-1 rounded bg-white/5 border border-white/8 text-[0.65rem] text-gray-300 font-mono focus:outline-none focus:border-white/20"+ />+ </div>+ )}{/* API Key (cloud only) */}{needsKey && (diff --git a/src/hooks/useModels.ts b/src/hooks/useModels.tsindex 0cad9eb0..23a9cdab 100644--- a/src/hooks/useModels.ts+++ b/src/hooks/useModels.ts@@ -5,7 +5,8 @@ import { getCheckpoints as getComfyCheckpoints, getDiffusionModels as getComfyDiimport { parseNDJSONStream } from '../api/stream'import { useModelStore } from '../stores/modelStore'import { useProviderStore } from '../stores/providerStore'-import { getEnabledProviders, prefixModelName } from '../api/providers'+import { getEnabledProviders, prefixModelName, getProviderIdFromModel } from '../api/providers'+import { listBundledModels, bundledToAIModels, activateBuiltinModel, isManagedBuiltinActive } from '../api/engine'import type { PullProgress, AIModel, ModelCategory, ImageModel, VideoModel, CloudModel } from '../types/models'const VIDEO_PATTERNS = [/wan/, /svd/, /animatediff/, /animate/, /video/, /cogvideo/, /ltx/i, /framepack/, /mochi/, /cosmos/, /hunyuan/, /pyramidflow/, /allegro/]@@ -60,7 +61,14 @@ export function useModels() {const fetchModels = useCallback(async () => {try {const allModels: AIModel[] = []- const providers = getEnabledProviders()+ // Built-in engine (2.5.7): when the managed OpenAI-compat backend is the+ // active provider, its model list is the downloaded GGUFs (via the Tauri+ // `list_bundled_models` command), NOT `/v1/models` (which reports only the+ // single loaded model). Skip the openai client's listModels for it.+ const managedBuiltin = isManagedBuiltinActive()+ const providers = getEnabledProviders().filter(+ (p) => !(managedBuiltin && p.id === 'openai'),+ )const providerResults = await Promise.allSettled(providers.map(async (provider) => {const providerModels = await provider.listModels()@@ -87,6 +95,14 @@ export function useModels() {allModels.push(...result.value.filter(m => !isEmbeddingModel(m.name)))}}+ // Built-in engine model list (downloaded GGUFs). Guarded: a missing/older+ // backend or non-Tauri dev context just yields no built-in models.+ if (managedBuiltin) {+ try {+ const bundled = bundledToAIModels(await listBundledModels())+ allModels.push(...bundled.filter(m => !isEmbeddingModel(m.name)))+ } catch { /* engine command unavailable — non-critical */ }+ }const ollamaEnabled = useProviderStore.getState().providers.ollama.enabledconst hasOllamaModels = allModels.some(m => m.provider === 'ollama')if (ollamaEnabled && !hasOllamaModels) {@@ -216,9 +232,20 @@ export function useModels() {return models.filter((m: AIModel) => m.type === filter)}+ // Selecting a built-in model must also swap the loaded GGUF: the managed+ // engine serves one model per process, so activation → swap_bundled_model.+ // Other providers just set the active model as before.+ const activateModel = useCallback((name: string) => {+ setActiveModel(name)+ const cfg = useProviderStore.getState().providers.openai+ if (cfg.enabled && cfg.managed && getProviderIdFromModel(name) === 'openai') {+ void activateBuiltinModel(name).catch(() => { /* engine unavailable — non-critical */ })+ }+ }, [setActiveModel])+return {models, activeModel, activePulls, isPulling, categoryFilter,fetchModels, pullModel, pausePull, dismissPull,- removeModel, setActiveModel, setCategoryFilter, getFilteredModels, isPullingModel,+ removeModel, setActiveModel: activateModel, setCategoryFilter, getFilteredModels, isPullingModel,}}diff --git a/src/stores/providerStore.ts b/src/stores/providerStore.tsindex dc2ce656..c94dcb44 100644--- a/src/stores/providerStore.ts+++ b/src/stores/providerStore.ts@@ -52,22 +52,29 @@ const _keychainFailed = new Set<ProviderId>()// ── Default provider configs ───────────────────────────────────+// 2.5.7 — the default backend is now the app's built-in engine (bundled+// llama-server, managed lifecycle) so a fresh install can chat without+// installing Ollama/LM Studio. It occupies the `openai` slot (OpenAI-compatible)+// with `managed: true`. Ollama/LM Studio stay available as "Advanced" — the user+// can re-enable them from Settings → Providers. This default only applies to a+// FRESH store; existing `lu-providers` persistence is untouched.const DEFAULT_PROVIDERS: Record<ProviderId, ProviderConfig> = {ollama: {id: 'ollama',name: 'Ollama',- enabled: true,+ enabled: false,baseUrl: 'http://localhost:11434',apiKey: '',isLocal: true,},openai: {id: 'openai',- name: 'LM Studio',- enabled: false,- baseUrl: 'http://localhost:1234/v1',+ name: 'Built-in Engine',+ enabled: true,+ baseUrl: 'http://127.0.0.1:8127/v1',apiKey: '',isLocal: true,+ managed: true,},anthropic: {id: 'anthropic',