Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
Fix: correct sampler defaults, fix sheet layout under window controls, and harden backend installs (#8327)
Akarshan Biswasef4d219a53dc
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex 62312964f..c4131920e 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -41,6 +41,7 @@ import {verifyBackendInstallation,getBackendExePath,getBackendDir,+ getLocalInstalledBackends,} from './backend'import { invoke } from '@tauri-apps/api/core'import {@@ -2176,12 +2177,9 @@ export default class llamacpp_extension extends AIEngine {const expectedBinDir = await joinPath([backendDir, 'build', 'bin'])const expectedBinPath = await joinPath([expectedBinDir, serverName])- // Archive layouts vary: Jan-published tarballs expand to- // `<backendDir>/build/bin/llama-server`, while upstream llama.cpp- // GitHub release tarballs (e.g. `llama-b9193-bin-...`) expand to- // a flat `<backendDir>/llama-bXXXX/llama-server`. If the binary is- // not at the expected path, scan the extracted tree for it and- // relocate its containing directory into `build/bin/`.+ // Normalize varying archive layouts to `build/bin/`: Jan tarballs already+ // ship it; upstream Linux tarballs nest under `llama-bXXXX/`; upstream+ // Windows zips are flat with the binary + DLLs at the root.if (!(await fs.existsSync(expectedBinPath))) {const foundDir = await findLlamaServerDir(backendDir, serverName)if (!foundDir) {@@ -2191,19 +2189,23 @@ export default class llamacpp_extension extends AIEngine {)}if (foundDir !== expectedBinDir) {+ const staging = `${backendDir}.staging`try {- // Rename the whole directory in one shot — moving entries- // individually breaks relative symlinks (libggml.so →- // libggml.so.0 → libggml.so.0.10.0) as soon as the first- // target is renamed.- const buildDir = await joinPath([backendDir, 'build'])- await fs.mkdir(buildDir)- await fs.mv(foundDir, expectedBinDir)+ // Move the binary's dir into build/bin in one rename to keep relative+ // symlinks intact (libggml.so → .so.0 → .so.0.10.0). A flat-root+ // archive can't rename into its own subtree, so stage to a sibling.+ if (foundDir === backendDir) {+ await fs.mv(backendDir, staging)+ await fs.mkdir(await joinPath([backendDir, 'build']))+ await fs.mv(staging, expectedBinDir)+ } else {+ await fs.mkdir(await joinPath([backendDir, 'build']))+ await fs.mv(foundDir, expectedBinDir)+ }} catch (e) {- await fs.rm(backendDir)- throw new Error(- `Failed to normalize backend layout: ${String(e)}`- )+ if (await fs.existsSync(staging)) await fs.rm(staging)+ if (await fs.existsSync(backendDir)) await fs.rm(backendDir)+ throw new Error(`Failed to normalize backend layout: ${String(e)}`)}}}@@ -2228,6 +2230,58 @@ export default class llamacpp_extension extends AIEngine {}}+ /**+ * Install the supplementary CUDA runtime DLLs that upstream ships separately+ * (`cudart-llama-bin-<backend>.zip`) into every installed backend of that+ * type, so llama-server can resolve cublas/cudart at launch.+ */+ async installCudaRuntime(path: string): Promise<void> {+ if (+ !(await fs.existsSync(path)) ||+ (!path.endsWith('tar.gz') && !path.endsWith('zip'))+ ) {+ throw new Error(`Invalid path or file ${path}`)+ }++ const archiveName = await basename(path)+ const match = /^cudart-llama-bin-(.+?)\.(?:tar\.gz|zip)$/.exec(archiveName)+ if (!match || !match[1]) {+ throw new Error(+ `Not a CUDA runtime archive: ${archiveName}. Expected cudart-llama-bin-<backend>.(zip|tar.gz)`+ )+ }+ const backendType = match[1]++ const targets = (await getLocalInstalledBackends()).filter(+ (b) => b.backend === backendType+ )+ if (targets.length === 0) {+ throw new Error(+ `No installed "${backendType}" backend found. Install that backend first, then add the CUDA runtime.`+ )+ }++ let installed = 0+ for (const t of targets) {+ const binDir = await joinPath([+ await getBackendDir(t.backend, t.version),+ 'build',+ 'bin',+ ])+ if (!(await fs.existsSync(binDir))) continue+ await invoke('decompress', { path, outputDir: binDir })+ installed+++ }+ if (installed === 0) {+ throw new Error(+ `Found ${backendType} backend(s) but none had a build/bin directory to install into.`+ )+ }+ logger.info(+ `CUDA runtime installed into ${installed} ${backendType} backend(s)`+ )+ }+/*** Update a model with new information.* @param modelIddiff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.tsindex c6f1a05be..be68c4f71 100644--- a/extensions/llamacpp-extension/src/test/index.test.ts+++ b/extensions/llamacpp-extension/src/test/index.test.ts@@ -13,6 +13,7 @@ vi.mock('../backend', () => ({downloadBackend: vi.fn(),listSupportedBackends: vi.fn(),getBackendDir: vi.fn(),+ getLocalInstalledBackends: vi.fn(),}))// Mock tauri-plugin-llamacpp-api (partial mock)@@ -673,6 +674,124 @@ describe('llamacpp_extension', () => {})})})++ describe('installCudaRuntime', () => {+ it('should reject a path that does not exist', async () => {+ const { fs } = await import('@janhq/core')+ vi.mocked(fs.existsSync).mockResolvedValue(false)++ await expect(+ extension.installCudaRuntime('/tmp/cudart-llama-bin-win-cuda.zip')+ ).rejects.toThrow('Invalid path or file')+ })++ it('should reject a file with an unsupported extension', async () => {+ const { fs } = await import('@janhq/core')+ vi.mocked(fs.existsSync).mockResolvedValue(true)++ await expect(+ extension.installCudaRuntime('/tmp/cudart-llama-bin-win-cuda.rar')+ ).rejects.toThrow('Invalid path or file')+ })++ it('should reject an archive that is not a CUDA runtime archive', async () => {+ const { fs } = await import('@janhq/core')+ const { basename } = await import('@tauri-apps/api/path')+ vi.mocked(fs.existsSync).mockResolvedValue(true)+ vi.mocked(basename).mockResolvedValue('llama-b9193-bin-win-cuda.zip')++ await expect(+ extension.installCudaRuntime('/tmp/llama-b9193-bin-win-cuda.zip')+ ).rejects.toThrow('Not a CUDA runtime archive')+ })++ it('should throw when no matching backend is installed', async () => {+ const { fs } = await import('@janhq/core')+ const { basename } = await import('@tauri-apps/api/path')+ const backendModule = await import('../backend')+ vi.mocked(fs.existsSync).mockResolvedValue(true)+ vi.mocked(basename).mockResolvedValue('cudart-llama-bin-win-cuda-12.4.zip')+ vi.mocked(backendModule.getLocalInstalledBackends).mockResolvedValue([+ { backend: 'win-cpu-x64', version: 'v1.0.0' },+ ])++ await expect(+ extension.installCudaRuntime('/tmp/cudart-llama-bin-win-cuda-12.4.zip')+ ).rejects.toThrow('No installed "win-cuda-12.4" backend found')+ })++ it('should throw when matching backends lack a build/bin directory', async () => {+ const { fs, joinPath } = await import('@janhq/core')+ const { basename } = await import('@tauri-apps/api/path')+ const { invoke } = await import('@tauri-apps/api/core')+ const backendModule = await import('../backend')++ vi.mocked(basename).mockResolvedValue('cudart-llama-bin-win-cuda-12.4.zip')+ vi.mocked(backendModule.getLocalInstalledBackends).mockResolvedValue([+ { backend: 'win-cuda-12.4', version: 'v1.0.0' },+ ])+ vi.mocked(backendModule.getBackendDir).mockResolvedValue(+ '/path/to/jan/llamacpp/backends/v1.0.0/win-cuda-12.4'+ )+ vi.mocked(joinPath).mockImplementation((paths) =>+ Promise.resolve(paths.join('/'))+ )+ // archive path exists, build/bin dir does not+ vi.mocked(fs.existsSync)+ .mockResolvedValueOnce(true)+ .mockResolvedValue(false)++ await expect(+ extension.installCudaRuntime('/tmp/cudart-llama-bin-win-cuda-12.4.zip')+ ).rejects.toThrow('none had a build/bin directory')+ expect(invoke).not.toHaveBeenCalledWith('decompress', expect.anything())+ })++ it('should decompress into every matching backend build/bin', async () => {+ const { fs, joinPath } = await import('@janhq/core')+ const { basename } = await import('@tauri-apps/api/path')+ const { invoke } = await import('@tauri-apps/api/core')+ const backendModule = await import('../backend')++ vi.mocked(basename).mockResolvedValue('cudart-llama-bin-win-cuda-12.4.zip')+ vi.mocked(backendModule.getLocalInstalledBackends).mockResolvedValue([+ { backend: 'win-cuda-12.4', version: 'v1.0.0' },+ { backend: 'win-cuda-12.4', version: 'v2.0.0' },+ { backend: 'win-cpu-x64', version: 'v1.0.0' },+ ])+ vi.mocked(backendModule.getBackendDir).mockImplementation(+ (backend, version) =>+ Promise.resolve(+ `/path/to/jan/llamacpp/backends/${version}/${backend}`+ )+ )+ vi.mocked(joinPath).mockImplementation((paths) =>+ Promise.resolve(paths.join('/'))+ )+ vi.mocked(fs.existsSync).mockResolvedValue(true)+ vi.mocked(invoke).mockResolvedValue(undefined)++ await extension.installCudaRuntime(+ '/tmp/cudart-llama-bin-win-cuda-12.4.zip'+ )++ // Only the two win-cuda-12.4 backends, not the cpu one.+ const decompressCalls = vi+ .mocked(invoke)+ .mock.calls.filter(([cmd]) => cmd === 'decompress')+ expect(decompressCalls).toHaveLength(2)+ expect(invoke).toHaveBeenCalledWith('decompress', {+ path: '/tmp/cudart-llama-bin-win-cuda-12.4.zip',+ outputDir:+ '/path/to/jan/llamacpp/backends/v1.0.0/win-cuda-12.4/build/bin',+ })+ expect(invoke).toHaveBeenCalledWith('decompress', {+ path: '/tmp/cudart-llama-bin-win-cuda-12.4.zip',+ outputDir:+ '/path/to/jan/llamacpp/backends/v2.0.0/win-cuda-12.4/build/bin',+ })+ })+ })})describe('normalizeLlamacppConfig', () => {diff --git a/web-app/index.html b/web-app/index.htmlindex dd7b2bc5e..1b10efa43 100644--- a/web-app/index.html+++ b/web-app/index.html@@ -127,9 +127,9 @@</script></head><body>- <div id="initial-loader">- <img src="/images/jan-logo.png" alt="Jan Logo" />- <p id="initial-loader-caption">Booting up Jan…</p>+ <div id="initial-loader" data-tauri-drag-region>+ <img src="/images/jan-logo.png" alt="Jan Logo" data-tauri-drag-region />+ <p id="initial-loader-caption" data-tauri-drag-region>Booting up Jan…</p></div><div id="root"></div><script type="module" src="/src/main.tsx"></script>diff --git a/web-app/src/components/ui/sheet.tsx b/web-app/src/components/ui/sheet.tsxindex 0821524c6..97f751061 100644--- a/web-app/src/components/ui/sheet.tsx+++ b/web-app/src/components/ui/sheet.tsx@@ -5,6 +5,7 @@ import * as SheetPrimitive from "@radix-ui/react-dialog"import { XIcon } from "lucide-react"import { cn } from "@/lib/utils"+import { useTitlebarLayout } from "@/stores/titlebar-layout-store"function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {return <SheetPrimitive.Root data-slot="sheet" {...props} />@@ -54,6 +55,12 @@ function SheetContent({side?: "top" | "right" | "bottom" | "left"showCloseButton?: boolean}) {+ // On Windows/Linux the native window controls are an in-app overlay pinned to+ // the top-right (z-[60]); a right-side sheet only collides when the DE places+ // any control on the right (GNOME's left-side layout needs no offset).+ const controlsOnRight = useTitlebarLayout((s) => s.layout.right.length > 0)+ const offsetForTitlebar =+ side === "right" && (IS_WINDOWS || IS_LINUX) && controlsOnRightreturn (<SheetPortal><SheetOverlay />@@ -69,13 +76,17 @@ function SheetContent({"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",side === "bottom" &&"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",+ offsetForTitlebar && "pt-15",className)}{...props}>{children}{showCloseButton && (- <SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">+ <SheetPrimitive.Close className={cn(+ "ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none",+ offsetForTitlebar && "top-15"+ )}><XIcon className="size-4" /><span className="sr-only">Close</span></SheetPrimitive.Close>diff --git a/web-app/src/containers/ModelSetting.tsx b/web-app/src/containers/ModelSetting.tsxindex 1a1add235..63f418761 100644--- a/web-app/src/containers/ModelSetting.tsx+++ b/web-app/src/containers/ModelSetting.tsx@@ -14,29 +14,16 @@ import { Button } from '@/components/ui/button'import { Input } from '@/components/ui/input'import { Switch } from '@/components/ui/switch'import { DynamicControllerSetting } from '@/containers/dynamicControllerSetting'+import { SamplerDefaults } from '@/containers/SamplerDefaults'import { useModelProvider } from '@/hooks/useModelProvider'import { useServiceHub } from '@/hooks/useServiceHub'import { cn, getModelDisplayName } from '@/lib/utils'import { useTranslation } from '@/i18n/react-i18next-compat'import { useAppState } from '@/hooks/useAppState'-import { paramsSettings } from '@/lib/predefinedParams'+import { paramsSettings, samplerKeysForProvider } from '@/lib/predefinedParams'const MTP_MIN_BUILD = 9193-// Sampling defaults shown in the model settings sheet. These persist to the-// model (model.yml → router preset for llamacpp) and act as server-side-// defaults for the local API server; per-request values still override.-// `repeat_last_n` is intentionally omitted — it has no paramsSettings entry.-const SAMPLER_DEFAULT_KEYS = [- 'temperature',- 'top_p',- 'top_k',- 'min_p',- 'repeat_penalty',- 'presence_penalty',- 'frequency_penalty',-] as const-function parseBuildNumber(version: unknown): number | null {if (typeof version !== 'string') return nullconst m = version.match(/^b(\d+)$/)@@ -244,7 +231,7 @@ export function ModelSetting({<IconSettings size={18} className="text-muted-foreground" /></Button></SheetTrigger>- <SheetContent className="overflow-y-auto">+ <SheetContent><SheetHeader><SheetTitle>{t('common:modelSettings.title', {@@ -256,49 +243,18 @@ export function ModelSetting({</SheetDescription></SheetHeader>- <div className="px-4 space-y-8 pb-4">+ <div className="px-4 space-y-8 pb-4 flex-1 min-h-0 overflow-y-auto">{provider.provider === 'llamacpp' && (<MtpPanel modelId={model.id} provider={provider} />)}- {(provider.provider === 'llamacpp' || provider.provider === 'mlx') && (- <div className="space-y-4">- <div>- <span className="font-medium">- {t('common:modelSettings.samplingDefaults.title')}- </span>- <p className="text-muted-foreground leading-normal text-xs">- {t('common:modelSettings.samplingDefaults.description')}- </p>- </div>- {SAMPLER_DEFAULT_KEYS.map((key) => {- const def = paramsSettings[key]- if (!def) return null- const stored = model.settings?.[key]?.controller_props?.value- const value = stored ?? def.value- return (- <div key={key} className="space-y-2">- <div className="flex items-start justify-between gap-8">- <div className="mb-1 truncate">- <span title={def.title} className="font-medium">- {def.title}- </span>- </div>- <DynamicControllerSetting- title={def.title}- description={def.description}- controllerType={def.controllerType}- controllerProps={{ ...(def.controllerProps ?? {}), value }}- onChange={(newValue) => handleSettingChange(key, newValue)}- />- </div>- <p className="text-muted-foreground leading-normal text-xs">- {def.description}- </p>- </div>- )- })}- </div>- )}+ {(provider.provider === 'llamacpp' || provider.provider === 'mlx') &&+ model.embedding !== true && (+ <SamplerDefaults+ model={model}+ keys={samplerKeysForProvider(provider.provider)}+ onChange={handleSettingChange}+ />+ )}{fitEnabled && fitCtxSetting && (<div key="fit_ctx" className="space-y-2"><div className="flex items-start justify-between gap-8">diff --git a/web-app/src/containers/SamplerDefaults.tsx b/web-app/src/containers/SamplerDefaults.tsxnew file mode 100644index 000000000..7d44a670c--- /dev/null+++ b/web-app/src/containers/SamplerDefaults.tsx@@ -0,0 +1,69 @@+import { DynamicControllerSetting } from '@/containers/dynamicControllerSetting'+import { useTranslation } from '@/i18n/react-i18next-compat'+import {+ paramsSettings,+ resolveSamplerValue,+ SAMPLER_DEFAULT_KEYS,+} from '@/lib/predefinedParams'++type SamplerDefaultsProps = {+ model: Model+ /** Sampler keys to render; defaults to the full set. */+ keys?: readonly string[]+ /** Draft overrides (dialogs that persist on save); falls back to model.settings. */+ pendingValues?: Record<string, string | number | boolean>+ onChange: (key: string, value: string | number | boolean) => void+}++export function SamplerDefaults({+ model,+ keys = SAMPLER_DEFAULT_KEYS,+ pendingValues,+ onChange,+}: SamplerDefaultsProps) {+ const { t } = useTranslation()+ return (+ <div className="space-y-4">+ <div>+ <span className="font-medium">+ {t('common:modelSettings.samplingDefaults.title')}+ </span>+ <p className="text-muted-foreground leading-normal text-xs">+ {t('common:modelSettings.samplingDefaults.description')}+ </p>+ </div>+ {keys.map((key) => {+ const def = paramsSettings[key]+ if (!def) return null+ const value =+ pendingValues && key in pendingValues+ ? pendingValues[key]+ : resolveSamplerValue(+ model.settings?.[key]?.controller_props?.value,+ def.value+ )+ return (+ <div key={key} className="space-y-2">+ <div className="flex items-start justify-between gap-8">+ <div className="mb-1 truncate">+ <span title={def.title} className="font-medium">+ {def.title}+ </span>+ </div>+ <DynamicControllerSetting+ title={def.title}+ description={def.description}+ controllerType={def.controllerType}+ controllerProps={{ ...(def.controllerProps ?? {}), value }}+ onChange={(newValue) => onChange(key, newValue)}+ />+ </div>+ <p className="text-muted-foreground leading-normal text-xs">+ {def.description}+ </p>+ </div>+ )+ })}+ </div>+ )+}diff --git a/web-app/src/hooks/useBackendUpdater.ts b/web-app/src/hooks/useBackendUpdater.tsindex c19c82e41..ec523e023 100644--- a/web-app/src/hooks/useBackendUpdater.ts+++ b/web-app/src/hooks/useBackendUpdater.ts@@ -55,6 +55,7 @@ interface LlamacppExtension {targetBackend: string): Promise<{ wasUpdated: boolean; newBackend: string }>installBackend?(filePath: string): Promise<void>+ installCudaRuntime?(filePath: string): Promise<void>configureBackends?(): Promise<void>refreshBackendOptions?(): Promise<void>}@@ -446,11 +447,22 @@ export const useBackendUpdater = () => {}}, [])+ const installCudaRuntime = useCallback(async (filePath: string) => {+ const extension = ExtensionManager.getInstance().getByName(+ 'llamacpp-extension'+ ) as LlamacppExtension | undefined+ if (!extension || !('installCudaRuntime' in extension)) {+ throw new Error('Extension does not support CUDA runtime installation')+ }+ await extension.installCudaRuntime?.(filePath)+ }, [])+return {updateState,checkForUpdate,updateBackend,setRemindMeLater,installBackend,+ installCudaRuntime,}}diff --git a/web-app/src/lib/__tests__/predefinedParams.test.ts b/web-app/src/lib/__tests__/predefinedParams.test.tsindex 2b538609a..3eb6cfa51 100644--- a/web-app/src/lib/__tests__/predefinedParams.test.ts+++ b/web-app/src/lib/__tests__/predefinedParams.test.ts@@ -1,5 +1,11 @@import { describe, it, expect } from 'vitest'-import { paramsSettings } from '../predefinedParams'+import {+ paramsSettings,+ resolveSamplerValue,+ samplerKeysForProvider,+ SAMPLER_DEFAULT_KEYS,+ MLX_SAMPLER_KEYS,+} from '../predefinedParams'describe('predefinedParams', () => {it('exports paramsSettings object', () => {@@ -33,8 +39,8 @@ describe('predefinedParams', () => {expect(paramsSettings.stream.value).toBe(true)})- it('temperature defaults to 0.7', () => {- expect(paramsSettings.temperature.value).toBe(0.7)+ it('temperature defaults to llama.cpp default (0.8)', () => {+ expect(paramsSettings.temperature.value).toBe(0.8)})it('max_output_tokens defaults to 2048', () => {@@ -48,4 +54,22 @@ describe('predefinedParams', () => {it('top_p has controllerType slider', () => {expect((paramsSettings.top_p as any).controllerType).toBe('slider')})++ it('MLX exposes only the samplers its server forwards', () => {+ expect([...MLX_SAMPLER_KEYS]).toEqual([+ 'temperature',+ 'top_p',+ 'repeat_penalty',+ ])+ expect(samplerKeysForProvider('mlx')).toBe(MLX_SAMPLER_KEYS)+ expect(samplerKeysForProvider('llamacpp')).toBe(SAMPLER_DEFAULT_KEYS)+ })++ it('resolveSamplerValue treats empty string as unset', () => {+ expect(resolveSamplerValue('', 0.8)).toBe(0.8)+ expect(resolveSamplerValue(undefined, 0.8)).toBe(0.8)+ expect(resolveSamplerValue(null, 0.8)).toBe(0.8)+ expect(resolveSamplerValue(0, 0.8)).toBe(0)+ expect(resolveSamplerValue(0.5, 0.8)).toBe(0.5)+ })})diff --git a/web-app/src/lib/predefinedParams.ts b/web-app/src/lib/predefinedParams.tsindex ab82ea803..15993a329 100644--- a/web-app/src/lib/predefinedParams.ts+++ b/web-app/src/lib/predefinedParams.ts@@ -106,7 +106,7 @@ export const paramsSettings: Record<string, ParamDef> = {key: 'temperature',title: 'Temperature',description: 'Controls response randomness.',- value: 0.7,+ value: 0.8,controllerType: 'slider',controllerProps: { min: 0, max: 2, step: 0.05, warnAbove: 1.5 },capability: 'core',@@ -177,7 +177,7 @@ export const paramsSettings: Record<string, ParamDef> = {title: 'Repeat Penalty',description:'llama.cpp-style multiplicative penalty for repeated tokens. 1.0 = disabled.',- value: 1.1,+ value: 1.0,controllerType: 'slider',controllerProps: { min: 1, max: 2, step: 0.01, warnAbove: 1.3 },capability: 'repetition',@@ -350,6 +350,50 @@ export const paramsSettings: Record<string, ParamDef> = {},}+/**+ * Sampler keys exposed as per-model defaults in the model edit dialog. Persist+ * to the model (model.yml → router preset for llamacpp) and act as defaults the+ * local API server uses; per-assistant and per-request values override them.+ * `repeat_last_n` is intentionally omitted — it has no paramsSettings entry.+ */+export const SAMPLER_DEFAULT_KEYS = [+ 'temperature',+ 'top_p',+ 'top_k',+ 'min_p',+ 'repeat_penalty',+ 'presence_penalty',+ 'frequency_penalty',+] as const++// The MLX server only forwards these to GenerateParameters (top_k/min_p/+// presence/frequency are silently dropped); see mlx-server Server.swift.+export const MLX_SAMPLER_KEYS = [+ 'temperature',+ 'top_p',+ 'repeat_penalty',+] as const++/** Sampler keys a provider actually honors. */+export function samplerKeysForProvider(+ providerId: string+): readonly string[] {+ return providerId === 'mlx' ? MLX_SAMPLER_KEYS : SAMPLER_DEFAULT_KEYS+}++/**+ * Model settings seed sampler keys with '' (predefined.ts); `??` wouldn't catch+ * the empty string, so resolve ''/null/undefined to the param's default.+ */+export function resolveSamplerValue(+ stored: unknown,+ fallback: string | number | boolean+): string | number | boolean {+ return stored === undefined || stored === null || stored === ''+ ? fallback+ : (stored as string | number | boolean)+}+/*** Outbound strip list for non-llamacpp providers. Kept explicit to preserve* existing wire-level behavior. resolveProviderCaps owns the richer UI gating.diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex 1a401a28e..8c6b73895 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -248,7 +248,7 @@"description": "Configure model settings to optimize performance and behavior.","samplingDefaults": {"title": "Default sampling parameters",- "description": "Used by the local API server (and new chats) when a request doesn't set them. Per-request values always override these."+ "description": "Default sampler settings for this model. Used unless overridden by per-assistant or per-request values."},"mtp": {"section": "Multi-Token Prediction (MTP)",diff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.jsonindex a1b3b00ba..4bb4abc22 100644--- a/web-app/src/locales/en/settings.json+++ b/web-app/src/locales/en/settings.json@@ -341,5 +341,10 @@"updateError": "Failed to update Llamacpp"},"backendInstallSuccess": "Backend installed successfully!",- "backendInstallError": "Failed to install backend"+ "backendInstallError": "Failed to install backend",+ "installBackendFromFile": "Install Backend from File",+ "installingBackend": "Installing Backend...",+ "installCudaRuntime": "Install CUDA Runtime",+ "installingCudaRuntime": "Installing CUDA Runtime...",+ "cudaRuntimeInstalled": "CUDA runtime installed"}diff --git a/web-app/src/routes/settings/providers/$providerName.tsx b/web-app/src/routes/settings/providers/$providerName.tsxindex 00a64d1f3..ff6ff1d18 100644--- a/web-app/src/routes/settings/providers/$providerName.tsx+++ b/web-app/src/routes/settings/providers/$providerName.tsx@@ -75,6 +75,7 @@ function ProviderDetail() {const [refreshingModels, setRefreshingModels] = useState(false)const [isCheckingBackendUpdate, setIsCheckingBackendUpdate] = useState(false)const [isInstallingBackend, setIsInstallingBackend] = useState(false)+ const [isInstallingCuda, setIsInstallingCuda] = useState(false)const [importingModel, setImportingModel] = useState<string | null>(null)const [apiKeysDraft, setApiKeysDraft] = useState('')const [baseUrlDraft, setBaseUrlDraft] = useState('')@@ -83,8 +84,11 @@ function ProviderDetail() {const [keyCheckResults, setKeyCheckResults] = useState<{ index: number; masked: string; status: string; detail: string }[]>([])- const { checkForUpdate: checkForBackendUpdate, installBackend } =- useBackendUpdater()+ const {+ checkForUpdate: checkForBackendUpdate,+ installBackend,+ installCudaRuntime,+ } = useBackendUpdater()const { providerName } = useParams({ from: Route.id })const { getProviderByName, setProviders, updateProvider, addDeletedModels } =useModelProvider()@@ -726,6 +730,34 @@ function ProviderDetail() {}}, [provider, serviceHub, refreshSettings, t, installBackend])+ const handleInstallCudaRuntime = useCallback(async () => {+ if (provider?.provider !== 'llamacpp') return++ setIsInstallingCuda(true)+ try {+ const selectedFile = await serviceHub.dialog().open({+ multiple: false,+ directory: false,+ filters: [{ name: 'CUDA Runtime Archive', extensions: ['zip', 'gz'] }],+ })++ if (selectedFile && typeof selectedFile === 'string') {+ await installCudaRuntime(selectedFile)+ toast.success(t('settings:backendInstallSuccess'), {+ description: t('settings:cudaRuntimeInstalled'),+ })+ }+ } catch (error) {+ console.error('Failed to install CUDA runtime:', error)+ toast.error(t('settings:backendInstallError'), {+ description:+ error instanceof Error ? error.message : 'Unknown error occurred',+ })+ } finally {+ setIsInstallingCuda(false)+ }+ }, [provider, serviceHub, t, installCudaRuntime])+return (<div className="flex flex-col h-svh w-full"><HeaderPage>@@ -983,10 +1015,32 @@ function ProviderDetail() {/><span>{isInstallingBackend- ? 'Installing Backend...'- : 'Install Backend from File'}+ ? t('settings:installingBackend')+ : t('settings:installBackendFromFile')}</span></Button>+ {provider?.provider === 'llamacpp' &&+ IS_WINDOWS && (+ <Button+ variant="outline"+ size="sm"+ onClick={handleInstallCudaRuntime}+ disabled={isInstallingCuda}+ >+ <IconUpload+ size={12}+ className={cn(+ 'text-muted-foreground',+ isInstallingCuda && 'animate-pulse'+ )}+ />+ <span>+ {isInstallingCuda+ ? t('settings:installingCudaRuntime')+ : t('settings:installCudaRuntime')}+ </span>+ </Button>+ )}</div>)}</>diff --git a/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx b/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsxindex 293faccfa..d2dfeac02 100644--- a/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx+++ b/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx@@ -454,7 +454,7 @@ describe('ProviderDetail route', () => {renderComponent()expect(screen.getByTestId('import-vision')).toBeInTheDocument()expect(screen.getByText('settings:checkForBackendUpdates')).toBeInTheDocument()- expect(screen.getByText('Install Backend from File')).toBeInTheDocument()+ expect(screen.getByText('settings:installBackendFromFile')).toBeInTheDocument()})})@@ -721,7 +721,7 @@ describe('ProviderDetail route', () => {it('install-from-file no-ops cleanly when dialog returns null', async () => {renderComponent()await act(async () => {- fireEvent.click(screen.getByText('Install Backend from File'))+ fireEvent.click(screen.getByText('settings:installBackendFromFile'))})// no toast fired because file selection was cancelledexpect(h.toastSuccess).not.toHaveBeenCalled()@@ -732,7 +732,7 @@ describe('ProviderDetail route', () => {h.dialogSvc.open = vi.fn().mockResolvedValue('/some/path/My Backend.tar.gz')renderComponent()await act(async () => {- fireEvent.click(screen.getByText('Install Backend from File'))+ fireEvent.click(screen.getByText('settings:installBackendFromFile'))})await waitFor(() => {expect(h.backendUpdater.installBackend).toHaveBeenCalledWith(@@ -747,7 +747,7 @@ describe('ProviderDetail route', () => {h.backendUpdater.installBackend = vi.fn().mockRejectedValue(new Error('install fail'))renderComponent()await act(async () => {- fireEvent.click(screen.getByText('Install Backend from File'))+ fireEvent.click(screen.getByText('settings:installBackendFromFile'))})await waitFor(() => {expect(h.toastError).toHaveBeenCalled()