Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
import { describe, it, expect, vi, beforeEach } from 'vitest'
const writtenFiles: Record<string, string> = {}
const modelYamls: Record<string, unknown> = {}
const existingPaths = new Set<string>()
vi.mock('@janhq/core', () => ({
logger: {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
fs: {
existsSync: vi.fn(
async (p: string) =>
p === '/p/models' || p in modelYamls || existingPaths.has(p)
),
mkdir: vi.fn(async () => undefined),
readdirSync: vi.fn(async (dir: string) => {
if (dir === '/p/models') {
const ids = new Set(
Object.keys(modelYamls).map((k) =>
k.slice('/p/models/'.length).split('/')[0]
)
)
return Array.from(ids).map((id) => `/p/models/${id}`)
}
return []
}),
fileStat: vi.fn(async (p: string) => ({
isDirectory: !p.endsWith('model.yml'),
})),
writeFileSync: vi.fn(async (p: string, body: string) => {
writtenFiles[p] = body
}),
mv: vi.fn(async (from: string, to: string) => {
writtenFiles[to] = writtenFiles[from]
delete writtenFiles[from]
}),
rm: vi.fn(async () => undefined),
readYaml: vi.fn(async (p: string) => modelYamls[p]),
},
joinPath: vi.fn(async (parts: string[]) => parts.join('/')),
}))
import { generatePreset, threadCacheDir } from './preset'
const CONFIG = {} as any
beforeEach(() => {
for (const k of Object.keys(writtenFiles)) delete writtenFiles[k]
for (const k of Object.keys(modelYamls)) delete modelYamls[k]
existingPaths.clear()
})
function setupModel(id: string, yaml: Record<string, unknown>) {
modelYamls[`/p/models/${id}/model.yml`] = {
model_path: `models/${id}/model.gguf`,
...yaml,
}
}
describe('generatePreset MTP emission', () => {
it('emits spec-type = draft-mtp when mtp is on, layers > 0, and backend supports it', async () => {
setupModel('glm', {
mtp: true,
mtp_layers: 1,
spec_draft_n_max: 8,
spec_draft_n_min: 0,
spec_draft_p_min: 0.8,
})
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('spec-type = draft-mtp')
expect(ini).toContain('spec-draft-n-max = 8')
expect(ini).toContain('spec-draft-n-min = 0')
expect(ini).toContain('spec-draft-p-min = 0.8')
})
it('omits MTP lines when model has no MTP heads (mtp_layers = 0)', async () => {
setupModel('llama', { mtp: true, mtp_layers: 0 })
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).not.toContain('spec-type')
})
it('omits MTP lines when mtp flag is off even if heads exist', async () => {
setupModel('glm', { mtp: false, mtp_layers: 1 })
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).not.toContain('spec-type')
})
it('emits spec-draft-model for a separate MTP gguf even when main reports 0 heads', async () => {
setupModel('gemma', {
mtp: true,
mtp_layers: 0,
mtp_model_path: 'models/gemma/mtp.gguf',
})
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('spec-type = draft-mtp')
expect(ini).toContain('spec-draft-model = /jan/models/gemma/mtp.gguf')
})
it('does not emit spec-draft-model for embedded MTP (no draft path)', async () => {
setupModel('glm', { mtp: true, mtp_layers: 1 })
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('spec-type = draft-mtp')
expect(ini).not.toContain('spec-draft-model')
})
// Values are chosen to differ from llama.cpp's defaults: an equal value is
// deliberately skipped now, since emitting one suppresses the GGUF's own
// sampling recommendations. The two penalties set no such bit and are always
// emitted, so their defaults are fine here.
it('emits per-model sampling values with CLI-style INI keys', async () => {
setupModel('s', {
temperature: 0,
top_k: 20,
top_p: 0.9,
min_p: 0.1,
repeat_last_n: 128,
repeat_penalty: 1.1,
presence_penalty: 0.5,
frequency_penalty: 0.25,
})
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('temperature = 0')
expect(ini).toContain('top-k = 20')
expect(ini).toContain('top-p = 0.9')
expect(ini).toContain('min-p = 0.1')
expect(ini).toContain('repeat-last-n = 128')
expect(ini).toContain('repeat-penalty = 1.1')
expect(ini).toContain('presence-penalty = 0.5')
expect(ini).toContain('frequency-penalty = 0.25')
})
it('omits sampling keys that are absent or non-numeric', async () => {
setupModel('s', { temperature: 0.7 })
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('temperature = 0.7')
expect(ini).not.toContain('top-p')
expect(ini).not.toContain('min-p')
})
it('skips out-of-range spec tunables', async () => {
setupModel('glm', {
mtp: true,
mtp_layers: 1,
spec_draft_n_max: -5,
spec_draft_p_min: 1.5,
})
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('spec-type = draft-mtp')
expect(ini).not.toContain('spec-draft-n-max')
expect(ini).not.toContain('spec-draft-p-min')
})
})
describe('generatePreset parallel', () => {
it('emits the global parallel value verbatim, with no slot reserved on top', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', { parallel: 1 } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('parallel = 1')
})
it('emits a per-model parallel override verbatim too', async () => {
setupModel('llama', { parallel: 3 })
await generatePreset('/p', '/jan', {} as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('parallel = 3')
})
it('omits parallel when unset, leaving llama.cpp auto-default untouched', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', {} as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).not.toContain('parallel =')
})
// 0 is both the setting's default and its "let llama.cpp decide": omitting
// the key is what the engine resolves to its own auto default.
it('omits parallel when the setting is an explicit 0', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', { parallel: 0 } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).not.toContain('parallel =')
expect(ini).not.toContain('kv-unified')
})
// Every surface shares slot 0 and is told apart by `thread_id`, so nothing
// pins an index that a low slot count would have to keep alive. A single
// configured slot must therefore emit exactly one.
it('emits parallel = 1 for a single configured slot', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', { parallel: 1 } as any)
expect(writtenFiles['/p/router.preset.ini']).toContain('parallel = 1')
})
it('lets the per-model section override [*] with its own value', async () => {
setupModel('llama', { parallel: 1 })
await generatePreset('/p', '/jan', { parallel: 4 } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('parallel = 4')
expect(ini).toContain('parallel = 1')
})
})
describe('generatePreset 0.4.0 keys', () => {
it('emits n-cpu-ffn when set, and omits it at 0', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', { n_cpu_ffn: 12 } as any)
expect(writtenFiles['/p/router.preset.ini']).toContain('n-cpu-ffn = 12')
await generatePreset('/p', '/jan', { n_cpu_ffn: 0 } as any)
expect(writtenFiles['/p/router.preset.ini']).not.toContain('n-cpu-ffn')
})
it('emits a per-model n-cpu-ffn override', async () => {
setupModel('llama', { n_cpu_ffn: 4 })
await generatePreset('/p', '/jan', {} as any)
expect(writtenFiles['/p/router.preset.ini']).toContain('n-cpu-ffn = 4')
})
// auto is upstream's own default, so naming it would pin a value that is
// meant to track the engine.
it('emits lazy-mode only when it is not auto', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', { lazy_mode: 'auto' } as any)
expect(writtenFiles['/p/router.preset.ini']).not.toContain('lazy-mode')
await generatePreset('/p', '/jan', { lazy_mode: 'off' } as any)
expect(writtenFiles['/p/router.preset.ini']).toContain('lazy-mode = off')
await generatePreset('/p', '/jan', { lazy_mode: 'on' } as any)
expect(writtenFiles['/p/router.preset.ini']).toContain('lazy-mode = on')
})
it('emits kv-unified-per-slot when set, and omits it at 0', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', { kv_unified_per_slot: 4096 } as any)
expect(writtenFiles['/p/router.preset.ini']).toContain(
'kv-unified-per-slot = 4096'
)
await generatePreset('/p', '/jan', { kv_unified_per_slot: 0 } as any)
expect(writtenFiles['/p/router.preset.ini']).not.toContain(
'kv-unified-per-slot'
)
})
// Enabled is the engine's default since 0.4.0, so only the off case is
// written; emitting `true` would be a no-op line that outlives the default.
it('emits reasoning-preserve only to turn it off', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', { reasoning_preserve: true } as any)
expect(writtenFiles['/p/router.preset.ini']).not.toContain(
'reasoning-preserve'
)
await generatePreset('/p', '/jan', { reasoning_preserve: false } as any)
expect(writtenFiles['/p/router.preset.ini']).toContain(
'reasoning-preserve = false'
)
})
})
describe('generatePreset 0.7.0 keys', () => {
// b11669 throws "MoE cache requires a MoE model" for any model without
// experts, so an engine-wide key would break every dense and embedding model
// the moment it was set. It is per-model only.
it('never emits moe-cache-mib engine-wide', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', { moe_cache_mib: 4096 } as any)
expect(writtenFiles['/p/router.preset.ini']).not.toContain('moe-cache-mib')
})
it('emits moe-cache-mib only in the section of the model that set it', async () => {
setupModel('dense', {})
setupModel('moe', { moe_cache_mib: 4096, expert_count: 128 })
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
const section = (id: string) =>
ini.split(`[${id}]`)[1].split('load-on-startup')[0]
expect(section('moe')).toContain('moe-cache-mib = 4096')
expect(section('dense')).not.toContain('moe-cache-mib')
})
// The other two load-time throws in llama-moe-cache.cpp depend on engine-wide
// settings the preset can see: tensor split mode, and no GPU at all.
it('drops moe-cache-mib under configurations llama.cpp refuses it in', async () => {
setupModel('moe', { moe_cache_mib: 4096, expert_count: 128 })
await generatePreset('/p', '/jan', { split_mode: 'tensor' } as any)
expect(writtenFiles['/p/router.preset.ini']).not.toContain('moe-cache-mib')
await generatePreset('/p', '/jan', { device: 'none' } as any)
expect(writtenFiles['/p/router.preset.ini']).not.toContain('moe-cache-mib')
await generatePreset('/p', '/jan', { split_mode: 'row', device: 'CUDA0' } as any)
expect(writtenFiles['/p/router.preset.ini']).toContain('moe-cache-mib = 4096')
})
// A per-model value can still be set on a dense model by mistake, and
// llama.cpp then refuses to load it. Only a model whose GGUF declares
// experts gets the key; an unknown count (not yet detected) is treated as
// dense, since a false negative only loses the cache.
it('omits moe-cache-mib for a model without experts, or with an unknown count', async () => {
setupModel('dense', { moe_cache_mib: 4096, expert_count: 0 })
setupModel('unknown', { moe_cache_mib: 4096 })
await generatePreset('/p', '/jan', CONFIG)
expect(writtenFiles['/p/router.preset.ini']).not.toContain('moe-cache-mib')
})
it('omits a per-model moe-cache-mib of 0 or below', async () => {
setupModel('moe', { moe_cache_mib: 0, expert_count: 128 })
setupModel('moe2', { moe_cache_mib: -5, expert_count: 128 })
await generatePreset('/p', '/jan', CONFIG)
expect(writtenFiles['/p/router.preset.ini']).not.toContain('moe-cache-mib')
})
it('emits the draft sampling mode and ubatch with speculative decoding', async () => {
setupModel('glm', {
mtp: true,
mtp_layers: 1,
spec_draft_sampling: 'probabilistic',
spec_draft_n_ubatch: 128,
})
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('spec-draft-sampling = probabilistic')
expect(ini).toContain('spec-draft-n-ubatch = 128')
})
// greedy and 0 (follow ubatch-size) are upstream's defaults.
it('omits the draft keys at their defaults or when an unknown mode is recorded', async () => {
setupModel('glm', {
mtp: true,
mtp_layers: 1,
spec_draft_sampling: 'greedy',
spec_draft_n_ubatch: 0,
})
await generatePreset('/p', '/jan', CONFIG)
let ini = writtenFiles['/p/router.preset.ini']
expect(ini).not.toContain('spec-draft-sampling')
expect(ini).not.toContain('spec-draft-n-ubatch')
setupModel('glm', { mtp: true, mtp_layers: 1, spec_draft_sampling: 'bogus' })
await generatePreset('/p', '/jan', CONFIG)
ini = writtenFiles['/p/router.preset.ini']
expect(ini).not.toContain('spec-draft-sampling')
})
it('omits the draft keys when speculative decoding is off', async () => {
setupModel('glm', {
mtp: false,
mtp_layers: 1,
spec_draft_sampling: 'probabilistic',
spec_draft_n_ubatch: 128,
})
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).not.toContain('spec-draft-sampling')
expect(ini).not.toContain('spec-draft-n-ubatch')
})
})
describe('generatePreset 1.0.0 keys', () => {
// llama.cpp reads the share only while building the MoE cache, so it rides
// on the same gates as moe-cache-mib and means nothing without it.
it('emits moe-cache-cpu-share beside moe-cache-mib', async () => {
setupModel('moe', { moe_cache_mib: 4096, moe_cache_cpu_share: 0.25, expert_count: 128 })
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
const section = ini.split('[moe]')[1].split('load-on-startup')[0]
expect(section).toContain('moe-cache-mib = 4096')
expect(section).toContain('moe-cache-cpu-share = 0.25')
})
it('omits moe-cache-cpu-share when no MoE cache is emitted', async () => {
setupModel('nocache', { moe_cache_cpu_share: 0.5, expert_count: 128 })
setupModel('dense', { moe_cache_mib: 4096, moe_cache_cpu_share: 0.5, expert_count: 0 })
await generatePreset('/p', '/jan', CONFIG)
expect(writtenFiles['/p/router.preset.ini']).not.toContain('moe-cache-cpu-share')
setupModel('moe', { moe_cache_mib: 4096, moe_cache_cpu_share: 0.5, expert_count: 128 })
await generatePreset('/p', '/jan', { split_mode: 'tensor' } as any)
expect(writtenFiles['/p/router.preset.ini']).not.toContain('moe-cache-cpu-share')
})
// The arg parser throws outside [0, 1], which aborts the load; 0 is the
// upstream default.
it.each([0, -0.1, 1.5, Number.NaN])(
'omits a moe-cache-cpu-share of %s',
async (share) => {
setupModel('moe', { moe_cache_mib: 4096, moe_cache_cpu_share: share, expert_count: 128 })
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('moe-cache-mib = 4096')
expect(ini).not.toContain('moe-cache-cpu-share')
}
)
it('passes the f8_e4m3 KV cache type through, engine-wide and per model', async () => {
setupModel('m', { cache_type_k: 'f8_e4m3', cache_type_v: 'f8_e4m3' })
await generatePreset('/p', '/jan', { cache_type_k: 'f8_e4m3', cache_type_v: 'f8_e4m3' } as any)
const ini = writtenFiles['/p/router.preset.ini']
const [shared, model] = ini.split('[m]')
for (const section of [shared, model]) {
expect(section).toContain('cache-type-k = f8_e4m3')
expect(section).toContain('cache-type-v = f8_e4m3')
}
})
it('emits a moe-cache-cpu-share of 1', async () => {
setupModel('moe', { moe_cache_mib: 4096, moe_cache_cpu_share: 1, expert_count: 128 })
await generatePreset('/p', '/jan', CONFIG)
expect(writtenFiles['/p/router.preset.ini']).toContain('moe-cache-cpu-share = 1')
})
})
// A slot of a hybrid model with speculative decoding holds (1 + n_max) rows
// of recurrent state, so auto's 4 slots overflowed a 12 GB card in 0.8.5.
describe('generatePreset parallel with speculative decoding', () => {
const section = (ini: string, id: string) =>
ini.split(`[${id}]`)[1].split('load-on-startup')[0]
it('pins an embedded-MTP model to one slot when parallel is auto', async () => {
setupModel('qwen', { mtp: true, mtp_layers: 1 })
await generatePreset('/p', '/jan', { parallel: 0 } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(section(ini, 'qwen')).toContain('parallel = 1')
expect(section(ini, 'qwen')).toContain('kv-unified = true')
expect(ini.split('[qwen]')[0]).not.toContain('parallel =')
})
it('pins a draft-companion model to one slot when parallel is unset', async () => {
setupModel('qwen', {
mtp: true,
mtp_layers: 0,
mtp_model_path: 'models/qwen/mtp.gguf',
})
await generatePreset('/p', '/jan', {} as any)
expect(section(writtenFiles['/p/router.preset.ini'], 'qwen')).toContain(
'parallel = 1'
)
})
it('leaves models without speculative decoding on auto', async () => {
setupModel('off', { mtp: false, mtp_layers: 1 })
setupModel('plain', {})
await generatePreset('/p', '/jan', { parallel: 0 } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).not.toContain('parallel =')
expect(ini).not.toContain('kv-unified')
})
it('keeps an explicit global parallel for an MTP model', async () => {
setupModel('qwen', { mtp: true, mtp_layers: 1 })
await generatePreset('/p', '/jan', { parallel: 2 } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini.split('[qwen]')[0]).toContain('parallel = 2')
expect(section(ini, 'qwen')).not.toContain('parallel =')
})
// The gate and the [*] emission must read the string the same way: if only
// the gate accepted it, nothing would be emitted and auto's 4 slots return.
it('emits a legacy string parallel and does not pin the MTP model', async () => {
setupModel('qwen', { mtp: true, mtp_layers: 1 })
await generatePreset('/p', '/jan', { parallel: '2' } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini.split('[qwen]')[0]).toContain('parallel = 2')
expect(section(ini, 'qwen')).not.toContain('parallel =')
})
it('treats a zero or non-numeric string parallel as auto and pins', async () => {
for (const parallel of ['0', '', 'auto']) {
setupModel('qwen', { mtp: true, mtp_layers: 1 })
await generatePreset('/p', '/jan', { parallel } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini.split('[qwen]')[0]).not.toContain('parallel =')
expect(section(ini, 'qwen')).toContain('parallel = 1')
}
})
it('keeps a legacy string per-model parallel for an MTP model', async () => {
setupModel('qwen', { mtp: true, mtp_layers: 1, parallel: '2' })
await generatePreset('/p', '/jan', {} as any)
const qwen = section(writtenFiles['/p/router.preset.ini'], 'qwen')
expect(qwen).toContain('parallel = 2')
expect(qwen).not.toContain('parallel = 1')
})
it('keeps an explicit per-model parallel for an MTP model', async () => {
setupModel('qwen', { mtp: true, mtp_layers: 1, parallel: 2 })
await generatePreset('/p', '/jan', {} as any)
const qwen = section(writtenFiles['/p/router.preset.ini'], 'qwen')
expect(qwen).toContain('parallel = 2')
expect(qwen).not.toContain('parallel = 1')
})
it('respects an explicit kv-unified off', async () => {
setupModel('qwen', { mtp: true, mtp_layers: 1 })
await generatePreset('/p', '/jan', { kv_unified: 'off' } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(section(ini, 'qwen')).toContain('parallel = 1')
expect(section(ini, 'qwen')).not.toContain('kv-unified')
})
})
describe('generatePreset kv-unified', () => {
it('enables unified KV on auto when an explicit parallel is emitted', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', { parallel: 1 } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('parallel = 1')
expect(ini).toContain('kv-unified = true')
})
it('enables unified KV on auto when only a per-model parallel is emitted', async () => {
setupModel('llama', { parallel: 3 })
await generatePreset('/p', '/jan', {} as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('kv-unified = true')
})
it('omits kv-unified on auto when no explicit parallel is emitted', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', {} as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).not.toContain('kv-unified')
})
it('respects an explicit off even when parallel is emitted', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', {
parallel: 1,
kv_unified: 'off',
} as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('kv-unified = false')
})
it('respects an explicit on when no parallel is emitted', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', { kv_unified: 'on' } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('kv-unified = true')
})
})
describe('generatePreset ctx-size default', () => {
it('emits ctx-size = 8192 in [*] when fit is off and no ctx_size is set', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', { fit: false } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('ctx-size = 8192')
})
// There is no engine-level ctx_size setting: the [*] value is purely an OOM
// guard, and a user's choice belongs to the per-model ctx_len.
it('uses the per-model ctx_size over the [*] guard', async () => {
setupModel('llama', { ctx_size: 16384 })
await generatePreset('/p', '/jan', { fit: false } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('ctx-size = 16384')
})
it('omits ctx-size when auto-fit is enabled', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', { fit: true } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).not.toContain('ctx-size = 8192')
})
it('honors a per-model ctx_size = 0 override as native', async () => {
setupModel('llama', { ctx_size: 0 })
await generatePreset('/p', '/jan', { fit: false } as any)
const ini = writtenFiles['/p/router.preset.ini']
// [*] keeps the guard, but the per-model section overrides it to native.
expect(ini).toContain('ctx-size = 8192')
expect(ini).toContain('ctx-size = 0')
})
})
describe('generatePreset n-gpu-layers under fit', () => {
// There is no engine-level n_gpu_layers setting either; offload is per-model.
it('never emits an engine-level n-gpu-layers', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', { fit: false } as any)
expect(writtenFiles['/p/router.preset.ini']).not.toContain('n-gpu-layers')
})
it('emits per-model n-gpu-layers when fit is off', async () => {
setupModel('llama', { n_gpu_layers: 33 })
await generatePreset('/p', '/jan', { fit: false } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('n-gpu-layers = 33')
})
it('omits per-model n-gpu-layers when auto-fit is enabled', async () => {
setupModel('llama', { n_gpu_layers: 33 })
await generatePreset('/p', '/jan', { fit: true } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).not.toContain('n-gpu-layers')
})
})
describe('generatePreset context-shift', () => {
it('emits context-shift = true when ctx_shift is enabled', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', { ctx_shift: true } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('context-shift = true')
})
it('omits context-shift when disabled, matching llama.cpp own default', async () => {
setupModel('llama', {})
await generatePreset('/p', '/jan', { ctx_shift: false } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).not.toContain('context-shift')
})
})
describe('generatePreset embedding ctx-size', () => {
it('pins embedders to native ctx-size = 0 so they do not inherit the global 8192', async () => {
setupModel('minilm', { embedding: true })
await generatePreset('/p', '/jan', { fit: false } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('embeddings = true')
// global [*] still emits 8192, but the embedder section overrides to native.
expect(ini).toContain('ctx-size = 8192')
expect(ini).toContain('ctx-size = 0')
})
it('keeps a positive per-model embedder ctx-size instead of forcing native', async () => {
setupModel('minilm', { embedding: true, ctx_size: 2048 })
await generatePreset('/p', '/jan', { fit: false } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('embeddings = true')
expect(ini).toContain('ctx-size = 2048')
// the embedder section must not additionally emit native 0.
const embedderSection = ini.slice(ini.indexOf('[minilm]'))
expect(embedderSection).not.toContain('ctx-size = 0')
})
})
describe('generatePreset global engine options', () => {
const globalSection = () => {
const ini = writtenFiles['/p/router.preset.ini']
const end = ini.indexOf('\n[', ini.indexOf('[*]') + 1)
return end === -1 ? ini : ini.slice(0, end)
}
// Only non-defaults are emitted, so the preset stays intent-revealing.
it('omits every option left at its llama.cpp default', async () => {
await generatePreset('/p', '/jan', {
batch_size: 2048,
ubatch_size: 512,
n_cpu_moe: 0,
no_kv_offload: false,
} as any)
const g = globalSection()
expect(g).not.toContain('batch-size')
expect(g).not.toContain('n-cpu-moe')
expect(g).not.toContain('kv-offload')
})
it('emits batch-size when it differs from the 2048 default', async () => {
await generatePreset('/p', '/jan', { batch_size: 4096 } as any)
expect(globalSection()).toContain('batch-size = 4096')
})
// ubatch-size was exposed without its logical counterpart, so a user could
// set the physical batch but not the logical one it must not exceed.
it('emits batch-size and ubatch-size independently', async () => {
await generatePreset('/p', '/jan', {
batch_size: 1024,
ubatch_size: 256,
} as any)
const g = globalSection()
expect(g).toContain('batch-size = 1024')
expect(g).toContain('ubatch-size = 256')
})
it('emits n-cpu-moe only when at least one layer is pinned to the host', async () => {
await generatePreset('/p', '/jan', { n_cpu_moe: 12 } as any)
expect(globalSection()).toContain('n-cpu-moe = 12')
})
it('floors a fractional n-cpu-moe rather than emitting a non-integer', async () => {
await generatePreset('/p', '/jan', { n_cpu_moe: 3.7 } as any)
expect(globalSection()).toContain('n-cpu-moe = 3')
})
// Spelled as the negated half of llama.cpp's kv-offload pair; common_preset
// inverts it, so `true` here really does disable offloading.
it('emits no-kv-offload only when offloading is disabled', async () => {
await generatePreset('/p', '/jan', { no_kv_offload: true } as any)
expect(globalSection()).toContain('no-kv-offload = true')
})
})
describe('generatePreset upstream-default skipping', () => {
const globalSection = () => {
const ini = writtenFiles['/p/router.preset.ini']
const end = ini.indexOf('\n[', ini.indexOf('[*]') + 1)
return end === -1 ? ini : ini.slice(0, end)
}
const modelSection = (id: string) => {
const ini = writtenFiles['/p/router.preset.ini']
const start = ini.indexOf(`[${id}]`)
const end = ini.indexOf('\n[', start + 1)
return end === -1 ? ini.slice(start) : ini.slice(start, end)
}
// Passing any of these sets a bit that suppresses the GGUF's own
// general.sampling.* recommendations, so an identical-looking default
// silently overrode what the model asked for.
it('omits sampling values equal to llama.cpp defaults', async () => {
setupModel('m', {
temperature: 0.8,
top_k: 40,
top_p: 0.95,
min_p: 0.05,
repeat_last_n: 64,
repeat_penalty: 1.0,
})
await generatePreset('/p', '/jan', {} as any)
const sec = modelSection('m')
for (const k of ['temperature', 'top-k', 'top-p', 'min-p', 'repeat-last-n', 'repeat-penalty']) {
expect(sec, k).not.toContain(`${k} = `)
}
})
it('still emits a sampling value that differs from the default', async () => {
setupModel('m', { temperature: 0.6, top_k: 20 })
await generatePreset('/p', '/jan', {} as any)
const sec = modelSection('m')
expect(sec).toContain('temperature = 0.6')
expect(sec).toContain('top-k = 20')
})
// temperature 0 is greedy decoding, an explicit choice, not a default.
it('emits temperature = 0', async () => {
setupModel('m', { temperature: 0 })
await generatePreset('/p', '/jan', {} as any)
expect(modelSection('m')).toContain('temperature = 0')
})
// Upstream throws on a negative window rather than clamping, which aborts
// the load; the old UI documented -1 as "full context".
it('omits a negative repeat-last-n', async () => {
setupModel('m', { repeat_last_n: -1 })
await generatePreset('/p', '/jan', {} as any)
expect(modelSection('m')).not.toContain('repeat-last-n')
})
// Upstream's fit leaves a user-set context alone, so gating this on fit was
// why "Increase Context Size" did nothing while Fit was on.
it('emits per-model ctx-size even when fit is enabled', async () => {
setupModel('m', { ctx_size: 16384 })
await generatePreset('/p', '/jan', { fit: true } as any)
expect(modelSection('m')).toContain('ctx-size = 16384')
})
// No ctx_size in model.yml (the seeded 8192 is gone) means nothing pins n_ctx,
// so fit is free to shrink the context down to fit_ctx.
it('emits no ctx-size anywhere when fit is on and the model sets none', async () => {
setupModel('m', {})
await generatePreset('/p', '/jan', { fit: true } as any)
expect(modelSection('m')).not.toContain('ctx-size')
expect(globalSection()).not.toContain('ctx-size')
})
it('emits n-gpu-layers for auto (-1) and all (-2) but not below', async () => {
setupModel('a', { n_gpu_layers: -1 })
await generatePreset('/p', '/jan', { fit: false } as any)
expect(modelSection('a')).toContain('n-gpu-layers = -1')
setupModel('b', { n_gpu_layers: -2 })
await generatePreset('/p', '/jan', { fit: false } as any)
expect(modelSection('b')).toContain('n-gpu-layers = -2')
setupModel('c', { n_gpu_layers: -3 })
await generatePreset('/p', '/jan', { fit: false } as any)
expect(modelSection('c')).not.toContain('n-gpu-layers')
})
// mlock and no_mmap were aliases for the one upstream load-mode field and are
// gone as of 0.4.1; load-mode is the only key llama.cpp still accepts. `auto`
// is upstream's own default, so naming it would pin a value meant to track the
// engine.
it('emits the global load-mode for every value but auto', async () => {
for (const mode of ['none', 'mmap', 'mlock', 'mmap+mlock', 'dio']) {
await generatePreset('/p', '/jan', { load_mode: mode } as any)
expect(globalSection(), mode).toContain(`load-mode = ${mode}`)
}
await generatePreset('/p', '/jan', { load_mode: 'auto' } as any)
expect(globalSection()).not.toContain('load-mode')
})
it('ignores the removed mlock and no_mmap booleans', async () => {
await generatePreset('/p', '/jan', { mlock: true, no_mmap: true } as any)
const g = globalSection()
expect(g).not.toMatch(/^mlock = /m)
expect(g).not.toMatch(/^no-mmap = /m)
expect(g).not.toContain('load-mode')
})
it('drops an unknown global load-mode instead of emitting it', async () => {
for (const bad of ['bogus', '', 'MMAP', 7, null, true]) {
await generatePreset('/p', '/jan', { load_mode: bad } as any)
expect(globalSection(), String(bad)).not.toContain('load-mode')
}
})
// A model value must override the global one, and `auto` is a real override
// when the global is not auto, so unlike [*] it is emitted.
it('emits an explicit per-model load-mode, including auto', async () => {
for (const mode of ['auto', 'none', 'mmap', 'mlock', 'mmap+mlock', 'dio']) {
setupModel('m', { load_mode: mode })
await generatePreset('/p', '/jan', { load_mode: 'mlock' } as any)
expect(modelSection('m'), mode).toContain(`load-mode = ${mode}`)
}
})
it('emits nothing per model when load_mode is unset so the global applies', async () => {
setupModel('m', {})
await generatePreset('/p', '/jan', { load_mode: 'mlock' } as any)
expect(globalSection()).toContain('load-mode = mlock')
expect(modelSection('m')).not.toContain('load-mode')
})
it('drops an invalid per-model load-mode', async () => {
for (const bad of ['bogus', '', 'MMAP', 7, true]) {
setupModel('m', { load_mode: bad })
await generatePreset('/p', '/jan', {} as any)
expect(modelSection('m'), String(bad)).not.toContain('load-mode')
}
})
// Upstream's default is UNSPECIFIED, so treating 'none' as the default made
// an explicit "disable scaling" impossible to express.
it('emits rope-scaling for none but not for auto', async () => {
await generatePreset('/p', '/jan', { rope_scaling: 'none' } as any)
expect(globalSection()).toContain('rope-scaling = none')
await generatePreset('/p', '/jan', { rope_scaling: 'auto' } as any)
expect(globalSection()).not.toContain('rope-scaling')
})
// 1.0 is an explicit "force no scaling", not the default (which is 0).
it('emits rope-freq-scale = 1 and omits it at 0', async () => {
await generatePreset('/p', '/jan', { rope_freq_scale: 1 } as any)
expect(globalSection()).toContain('rope-freq-scale = 1')
await generatePreset('/p', '/jan', { rope_freq_scale: 0 } as any)
expect(globalSection()).not.toContain('rope-freq-scale')
})
it('omits cache-ram at the upstream default and emits an explicit -1', async () => {
await generatePreset('/p', '/jan', { cache_ram: 8192 } as any)
expect(globalSection()).not.toContain('cache-ram')
await generatePreset('/p', '/jan', { cache_ram: -1 } as any)
expect(globalSection()).toContain('cache-ram = -1')
})
it('names a slot-save-path even when conversation persistence is off', async () => {
// Absent by default in llama.cpp, and naming it is what enables the slot
// save/restore routes at all -- so the default (unset) must still emit it.
await generatePreset('/p', '/jan', {} as any)
expect(globalSection()).toContain(
`slot-save-path = ${threadCacheDir('/p')}`
)
// Off, the worker still needs the directory: it prunes what an earlier
// session left there and erases a deleted thread's state out of it. The
// zero budget is what stops it writing.
await generatePreset('/p', '/jan', { persist_thread_cache: false } as any)
expect(globalSection()).toContain(
`slot-save-path = ${threadCacheDir('/p')}`
)
})
it('puts the thread cache under the provider directory, not a temp dir', async () => {
// A cache the user paid prefill time for has to survive a reboot, which is
// the entire point of persisting it.
expect(threadCacheDir('/p')).toBe('/p/thread-cache')
})
it('omits cont-batching when enabled and emits it only when turned off', async () => {
await generatePreset('/p', '/jan', { cont_batching: true } as any)
expect(globalSection()).not.toContain('cont-batching')
await generatePreset('/p', '/jan', { cont_batching: false } as any)
expect(globalSection()).toContain('cont-batching = false')
})
it('emits the newly exposed offload and checkpoint options only when set', async () => {
await generatePreset('/p', '/jan', {} as any)
let g = globalSection()
expect(g).not.toContain('tensor-split')
expect(g).not.toContain('no-op-offload')
expect(g).not.toContain('ctx-checkpoints')
expect(g).not.toContain('checkpoint-min-step')
await generatePreset(
'/p',
'/jan',
{
tensor_split: ' 3,1 ',
no_op_offload: true,
ctx_checkpoints: 8,
checkpoint_min_step: 4096,
} as any,
)
g = globalSection()
expect(g).toContain('tensor-split = 3,1')
expect(g).toContain('no-op-offload = true')
expect(g).toContain('ctx-checkpoints = 8')
expect(g).toContain('checkpoint-min-step = 4096')
})
it('omits the checkpoint options at their upstream defaults', async () => {
await generatePreset(
'/p',
'/jan',
{ ctx_checkpoints: 32, checkpoint_min_step: 8192 } as any,
)
const g = globalSection()
expect(g).not.toContain('ctx-checkpoints')
expect(g).not.toContain('checkpoint-min-step')
})
// Upstream documents 0 as "no minimum" and only rejects negatives
// (common/arg.cpp), and settings.json puts no `min` on the field, so 0 is
// reachable from the UI and has to reach the preset.
it('emits an explicit checkpoint-min-step of 0, which means no minimum', async () => {
await generatePreset(
'/p',
'/jan',
{ ctx_checkpoints: 0, checkpoint_min_step: 0 } as any,
)
const g = globalSection()
expect(g).toContain('checkpoint-min-step = 0')
expect(g).toContain('ctx-checkpoints = 0')
})
})
// The ini value grammar ends a value at `#` or `;` and has no line
// continuation, so an inline template is truncated or flattened. Anything that
// is not a plain built-in name goes to a file instead.
describe('generatePreset chat template', () => {
it('writes a multi-line template to a file and points the preset at it', async () => {
const template = "{%- if x %}\n<|im_start|>\n{%- endif %}"
setupModel('glm', { chat_template: template })
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain(
'chat-template-file = /p/models/glm/chat_template.jinja'
)
expect(ini).not.toContain('chat-template =')
expect(writtenFiles['/p/models/glm/chat_template.jinja']).toBe(template)
})
it('preserves a template containing a comment marker verbatim', async () => {
const template = "{# a comment #}{{ '#1' }}; done"
setupModel('glm', { chat_template: template })
await generatePreset('/p', '/jan', CONFIG)
expect(writtenFiles['/p/models/glm/chat_template.jinja']).toBe(template)
expect(writtenFiles['/p/router.preset.ini']).toContain(
'chat-template-file = /p/models/glm/chat_template.jinja'
)
})
// A built-in name is not a template body, and --chat-template-file would
// try to read it as a path.
it('keeps a built-in template name inline', async () => {
setupModel('glm', { chat_template: 'chatml' })
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('chat-template = chatml')
expect(ini).not.toContain('chat-template-file')
expect(writtenFiles['/p/models/glm/chat_template.jinja']).toBeUndefined()
})
it('emits nothing for a blank template', async () => {
setupModel('glm', { chat_template: ' ' })
await generatePreset('/p', '/jan', CONFIG)
expect(writtenFiles['/p/router.preset.ini']).not.toContain('chat-template')
})
it('passes an absolute path to an existing file straight through', async () => {
existingPaths.add('/home/u/templates/custom.jinja')
setupModel('glm', { chat_template: '/home/u/templates/custom.jinja' })
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('chat-template-file = /home/u/templates/custom.jinja')
expect(writtenFiles['/p/models/glm/chat_template.jinja']).toBeUndefined()
})
// A path that resolves to nothing is not silently trusted; it falls back to
// the inline-body path so the value still reaches llama.cpp somehow.
it('treats an absolute path to a missing file as an inline body', async () => {
setupModel('glm', { chat_template: '/nope/custom.jinja' })
await generatePreset('/p', '/jan', CONFIG)
expect(writtenFiles['/p/models/glm/chat_template.jinja']).toBe(
'/nope/custom.jinja'
)
expect(writtenFiles['/p/router.preset.ini']).toContain(
'chat-template-file = /p/models/glm/chat_template.jinja'
)
})
})
// GBNF uses `#` for comments, so an inline grammar can never survive the ini;
// it always reaches llama.cpp as a file.
describe('generatePreset grammar', () => {
it('writes an inline grammar to a file and points the preset at it', async () => {
const grammar = '# yes/no only\nroot ::= "yes" | "no"'
setupModel('glm', { grammar })
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('grammar-file = /p/models/glm/grammar.gbnf')
expect(writtenFiles['/p/models/glm/grammar.gbnf']).toBe(grammar)
})
it('passes an absolute path to an existing file straight through', async () => {
existingPaths.add('/home/u/grammars/json.gbnf')
setupModel('glm', { grammar: '/home/u/grammars/json.gbnf' })
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('grammar-file = /home/u/grammars/json.gbnf')
expect(writtenFiles['/p/models/glm/grammar.gbnf']).toBeUndefined()
})
it('emits nothing for a blank grammar', async () => {
setupModel('glm', { grammar: ' ' })
await generatePreset('/p', '/jan', CONFIG)
expect(writtenFiles['/p/router.preset.ini']).not.toContain('grammar')
})
})
// The four draft flavours differ only in the `spec-type` value; a draft that
// cannot implement the type it is given fails the load with an unrelated
// message, so the type recorded at import is what must be emitted.
describe('generatePreset spec type', () => {
it('emits the recorded spec type for a dflash draft', async () => {
setupModel('dsv4', {
mtp: true,
mtp_layers: 1,
mtp_model_path: 'models/dsv4/mtp.gguf',
spec_type: 'draft-dflash',
})
await generatePreset('/p', '/jan', CONFIG)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('spec-type = draft-dflash')
expect(ini).toContain('spec-draft-model = /jan/models/dsv4/mtp.gguf')
expect(ini).not.toContain('draft-mtp')
})
it('emits draft-dspark when that is what was detected', async () => {
setupModel('dsv4', {
mtp: true,
mtp_layers: 1,
mtp_model_path: 'models/dsv4/mtp.gguf',
spec_type: 'draft-dspark',
})
await generatePreset('/p', '/jan', CONFIG)
expect(writtenFiles['/p/router.preset.ini']).toContain(
'spec-type = draft-dspark'
)
})
// Models imported before the type was recorded, and every embedded-MTP
// model, carry no spec_type.
it('falls back to draft-mtp when no type was recorded', async () => {
setupModel('glm', { mtp: true, mtp_layers: 1 })
await generatePreset('/p', '/jan', CONFIG)
expect(writtenFiles['/p/router.preset.ini']).toContain(
'spec-type = draft-mtp'
)
})
it('ignores a spec type that is not one llama.cpp accepts', async () => {
setupModel('glm', {
mtp: true,
mtp_layers: 1,
spec_type: 'draft-nonsense',
})
await generatePreset('/p', '/jan', CONFIG)
expect(writtenFiles['/p/router.preset.ini']).toContain(
'spec-type = draft-mtp'
)
})
})
describe('threadCacheDir separator handling', () => {
const WIN_EXT = '\\\\?\\C:\\Users\\u\\AppData\\Roaming\\Jan-nightly\\data\\llamacpp'
it('joins a POSIX path with a forward slash', () => {
expect(threadCacheDir('/p')).toBe('/p/thread-cache')
expect(threadCacheDir('/home/u/.local/share/Jan/data/llamacpp')).toBe(
'/home/u/.local/share/Jan/data/llamacpp/thread-cache'
)
})
it('joins a Windows extended path with a backslash', () => {
// Win32 normalizes `/` to `\` for ordinary paths but not for `\\?\` ones,
// where a `/` is a literal name character -- so create_dir_all fails with
// ERROR_INVALID_NAME (os error 123) and the worker exits 7 before serving.
expect(threadCacheDir(WIN_EXT)).toBe(`${WIN_EXT}\\thread-cache`)
expect(threadCacheDir(WIN_EXT)).not.toContain('/')
})
it('joins a plain Windows path with a backslash', () => {
expect(threadCacheDir('C:\\Users\\u\\llamacpp')).toBe(
'C:\\Users\\u\\llamacpp\\thread-cache'
)
})
it('does not read a backslash in a POSIX name as a Windows separator', () => {
// `\` is a legal filename character on Linux, so the separator follows the
// path's root rather than whether a backslash appears anywhere in it.
expect(threadCacheDir('/home/u/od\\d/llamacpp')).toBe(
'/home/u/od\\d/llamacpp/thread-cache'
)
})
it('does not double an existing trailing separator', () => {
expect(threadCacheDir('/p/')).toBe('/p/thread-cache')
expect(threadCacheDir('C:\\p\\')).toBe('C:\\p\\thread-cache')
})
it('is the one definition the preset and the erase path both use', async () => {
// index.ts's forgetThreadCache passes threadCacheDir(providerPath) as
// cacheDir, and llama.cpp joins state file names onto slot-save-path, so a
// preset that derived the directory differently would erase from a
// directory the worker never wrote to.
await generatePreset(WIN_EXT, 'C:\\jan', CONFIG)
const ini = Object.entries(writtenFiles).find(([p]) =>
p.endsWith('router.preset.ini')
)?.[1] as string
expect(ini).toContain(`slot-save-path = ${threadCacheDir(WIN_EXT)}`)
})
})