Skip to content

armgit / jan

Public Imported from GitHub
0

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

fix(llamacpp): every surface shares slot 0, and Jan reserves none

Akarshan Biswasa79b34ae16b2
diff --git a/extensions/llamacpp-extension/settings.json b/extensions/llamacpp-extension/settings.json
index d5a326ce3..8d0762455 100644
--- a/extensions/llamacpp-extension/settings.json
+++ b/extensions/llamacpp-extension/settings.json
@@ -254,11 +254,11 @@
{
"key": "parallel",
"title": "Parallel Sequences",
- "description": "Number of parallel sequences to decode for your own chat requests (0 = llama.cpp default of 4). Jan reserves one additional internal slot beyond this for background requests (e.g. thread auto-titling), so they don't evict your chat's KV cache.",
+ "description": "Number of parallel sequences to decode (0 = llama.cpp default). Jan reserves no slot of its own: chat, Cowork and background requests all share slot 0 and their KV caches are parked and restored per conversation.",
"controllerType": "input",
"controllerProps": {
- "value": 1,
- "placeholder": "1",
+ "value": 0,
+ "placeholder": "0",
"type": "number",
"textAlign": "right",
"min": 0
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.ts
index 7a7fe353e..e2b6312bb 100644
--- a/extensions/llamacpp-extension/src/index.ts
+++ b/extensions/llamacpp-extension/src/index.ts
@@ -468,6 +468,8 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng
await this.migrateAutoUnloadToModelsMax()
+ await this.migrateParallelToDefault()
+
this.timeout = asI32(this.config.timeout, DEFAULT_TIMEOUT) || DEFAULT_TIMEOUT
this.llamacpp_env = this.config.llamacpp_env
@@ -1088,6 +1090,36 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng
await setBackendSetting(MIGRATION_KEY, '1')
}
+ // The old default was 1 plus two slots Jan reserved for background work and
+ // Cowork; both now share slot 0, so the reservation is gone and a persisted
+ // 1 would pin the engine to a single slot rather than letting it resolve its
+ // own count. Only the old default value is moved.
+ private async migrateParallelToDefault(): Promise<void> {
+ const MIGRATION_KEY = 'llamacpp_parallel_default_v1'
+ if (await getBackendSetting(MIGRATION_KEY)) return
+
+ try {
+ if (asI32(this.config.parallel, 0) === 1) {
+ const settings = await this.getSettings()
+ await this.updateSettings(
+ settings.map((item) => {
+ if (item.key === 'parallel') {
+ item.controllerProps.value = 0
+ }
+ return item
+ })
+ )
+ this.config.parallel = 0
+ logger.info('Migrated parallel: 1 -> 0 (llama.cpp default)')
+ }
+ } catch (e) {
+ logger.warn('migrateParallelToDefault failed:', e)
+ return
+ }
+
+ await setBackendSetting(MIGRATION_KEY, '1')
+ }
+
private async migrateFitOff(): Promise<void> {
const MIGRATION_KEY = 'llamacpp_fit_off_v1'
if (await getBackendSetting(MIGRATION_KEY)) return
diff --git a/extensions/llamacpp-extension/src/preset.test.ts b/extensions/llamacpp-extension/src/preset.test.ts
index 9cb106e15..3178b3d23 100644
--- a/extensions/llamacpp-extension/src/preset.test.ts
+++ b/extensions/llamacpp-extension/src/preset.test.ts
@@ -166,20 +166,19 @@ describe('generatePreset MTP emission', () => {
})
})
-describe('generatePreset parallel reservation', () => {
- it('adds the reserved background slots on top of the global parallel value', async () => {
+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, {
- })
+ await generatePreset('/p', '/jan', { parallel: 1 } as any)
const ini = writtenFiles['/p/router.preset.ini']
- expect(ini).toContain('parallel = 3')
+ expect(ini).toContain('parallel = 1')
})
- it('adds the reserved background slots on top of a per-model parallel override', async () => {
+ 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 = 5')
+ expect(ini).toContain('parallel = 3')
})
it('omits parallel when unset, leaving llama.cpp auto-default untouched', async () => {
@@ -189,9 +188,8 @@ describe('generatePreset parallel reservation', () => {
expect(ini).not.toContain('parallel =')
})
- // 0 is the setting's "let llama.cpp decide": omitting the key is what the
- // engine resolves to its own auto default (4 slots, unified KV), so a
- // reserved background slot must not be added on top of nothing.
+ // 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)
@@ -200,53 +198,30 @@ describe('generatePreset parallel reservation', () => {
expect(ini).not.toContain('kv-unified')
})
- it('reserves no extra slot when reservedBackgroundSlots is 0 (global)', async () => {
- setupModel('llama', {})
- await generatePreset('/p', '/jan', { parallel: 1 } as any, {
- reservedBackgroundSlots: 0,
- })
- const ini = writtenFiles['/p/router.preset.ini']
- expect(ini).toContain('parallel = 1')
- })
-
- it('reserves no extra slot when reservedBackgroundSlots is 0 (per-model)', async () => {
- setupModel('llama', { parallel: 3 })
- await generatePreset('/p', '/jan', {} as any, {
- reservedBackgroundSlots: 0,
- })
- const ini = writtenFiles['/p/router.preset.ini']
- expect(ini).toContain('parallel = 3')
- })
-
- // The frontend pins background work to a fixed slot index 1
- // (BACKGROUND_SLOT_ID), and upstream wraps an out-of-range id_slot modulo the
- // slot count rather than rejecting it. So the reservation has to be
- // unconditional: every emitted `parallel` must be at least 2, or the pin
- // silently lands back on the chat slot 0.
- it('reserves the background slots by default, so slots 1 and 2 always exist', async () => {
+ // 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 = 3')
+ expect(writtenFiles['/p/router.preset.ini']).toContain('parallel = 1')
})
- it('reserves it in the per-model section too, which overrides [*]', async () => {
+ 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']
- // The provider-level value is what the old pin was computed from; the
- // section's own value is what llama.cpp actually applies.
- expect(ini).toContain('parallel = 6')
- expect(ini).toContain('parallel = 3')
+ expect(ini).toContain('parallel = 4')
+ expect(ini).toContain('parallel = 1')
})
})
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, {
- })
+ await generatePreset('/p', '/jan', { parallel: 1 } as any)
const ini = writtenFiles['/p/router.preset.ini']
- expect(ini).toContain('parallel = 3')
+ expect(ini).toContain('parallel = 1')
expect(ini).toContain('kv-unified = true')
})
@@ -266,16 +241,17 @@ describe('generatePreset 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, {
- })
+ 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, {
- })
+ await generatePreset('/p', '/jan', { kv_unified: 'on' } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('kv-unified = true')
})
@@ -284,8 +260,7 @@ describe('generatePreset kv-unified', () => {
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, {
- })
+ await generatePreset('/p', '/jan', { fit: false } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).toContain('ctx-size = 8192')
})
@@ -294,24 +269,21 @@ describe('generatePreset ctx-size default', () => {
// 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, {
- })
+ 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, {
- })
+ 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, {
- })
+ 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')
@@ -323,23 +295,20 @@ 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, {
- })
+ 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, {
- })
+ 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, {
- })
+ await generatePreset('/p', '/jan', { fit: true } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).not.toContain('n-gpu-layers')
})
@@ -348,16 +317,14 @@ describe('generatePreset n-gpu-layers under fit', () => {
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, {
- })
+ 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, {
- })
+ await generatePreset('/p', '/jan', { ctx_shift: false } as any)
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).not.toContain('context-shift')
})
@@ -366,8 +333,7 @@ describe('generatePreset 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, {
- })
+ 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.
@@ -377,8 +343,7 @@ describe('generatePreset embedding ctx-size', () => {
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, {
- })
+ 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')
@@ -410,8 +375,7 @@ describe('generatePreset global engine options', () => {
})
it('emits batch-size when it differs from the 2048 default', async () => {
- await generatePreset('/p', '/jan', { batch_size: 4096 } as any, {
- })
+ await generatePreset('/p', '/jan', { batch_size: 4096 } as any)
expect(globalSection()).toContain('batch-size = 4096')
})
@@ -428,22 +392,19 @@ describe('generatePreset global engine options', () => {
})
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, {
- })
+ 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, {
- })
+ 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, {
- })
+ await generatePreset('/p', '/jan', { no_kv_offload: true } as any)
expect(globalSection()).toContain('no-kv-offload = true')
})
})
@@ -535,8 +496,7 @@ describe('generatePreset upstream-default skipping', () => {
[true, true, 'load-mode = mlock'],
]
for (const [mlock, no_mmap, expected] of cases) {
- await generatePreset('/p', '/jan', { mlock, no_mmap } as any, {
- })
+ await generatePreset('/p', '/jan', { mlock, no_mmap } as any)
const g = globalSection()
expect(g, `mlock=${mlock} no_mmap=${no_mmap}`).not.toMatch(/^mlock = /m)
expect(g).not.toMatch(/^no-mmap = /m)
@@ -548,33 +508,27 @@ describe('generatePreset upstream-default skipping', () => {
// 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, {
- })
+ await generatePreset('/p', '/jan', { rope_scaling: 'none' } as any)
expect(globalSection()).toContain('rope-scaling = none')
- await generatePreset('/p', '/jan', { rope_scaling: 'auto' } as any, {
- })
+ 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, {
- })
+ 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, {
- })
+ 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, {
- })
+ await generatePreset('/p', '/jan', { cache_ram: 8192 } as any)
expect(globalSection()).not.toContain('cache-ram')
- await generatePreset('/p', '/jan', { cache_ram: -1 } as any, {
- })
+ await generatePreset('/p', '/jan', { cache_ram: -1 } as any)
expect(globalSection()).toContain('cache-ram = -1')
})
@@ -589,8 +543,7 @@ describe('generatePreset upstream-default skipping', () => {
// 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, {
- })
+ await generatePreset('/p', '/jan', { persist_thread_cache: false } as any)
expect(globalSection()).toContain(
`slot-save-path = ${threadCacheDir('/p')}`
)
@@ -603,12 +556,10 @@ describe('generatePreset upstream-default skipping', () => {
})
it('omits cont-batching when enabled and emits it only when turned off', async () => {
- await generatePreset('/p', '/jan', { cont_batching: true } as any, {
- })
+ await generatePreset('/p', '/jan', { cont_batching: true } as any)
expect(globalSection()).not.toContain('cont-batching')
- await generatePreset('/p', '/jan', { cont_batching: false } as any, {
- })
+ await generatePreset('/p', '/jan', { cont_batching: false } as any)
expect(globalSection()).toContain('cont-batching = false')
})
diff --git a/extensions/llamacpp-extension/src/preset.ts b/extensions/llamacpp-extension/src/preset.ts
index 142471894..7eecbb2a2 100644
--- a/extensions/llamacpp-extension/src/preset.ts
+++ b/extensions/llamacpp-extension/src/preset.ts
@@ -54,20 +54,6 @@ type ModelYaml = ModelConfig & {
mmproj_offload?: boolean
}
-// One extra llama-server slot beyond the user-visible "Parallel Sequences"
-// count, reserved for background requests (e.g. thread auto-titling) that
-// must never be able to evict the user's own chat KV cache from its slot.
-// Hidden from the setting's UI value.
-//
-// Added unconditionally, and that is load-bearing. The emitted `parallel` is
-// therefore always 3 or more, which is what lets the frontend pin background
-// work and Cowork to fixed slot ids (web-app/src/constants/models.ts) instead
-// of computing an index here that the two sides then have to keep in sync.
-// Upstream wraps an out-of-range id_slot modulo the slot count rather than
-// rejecting it, so any such desync is silent: the background request lands back
-// on the chat slot and overwrites the cache it was meant to protect.
-export const RESERVED_BACKGROUND_SLOTS = 2
-
/**
* The ubatch every embedding model's preset section is pinned to.
*
@@ -164,17 +150,8 @@ function escapeIniValue(v: string): string {
export async function generatePreset(
providerPath: string,
janDataFolderPath: string,
- config: LlamacppConfig,
- opts: { reservedBackgroundSlots?: number } = {}
+ config: LlamacppConfig
): Promise<{ path: string; embeddingCount: number }> {
- // Overridable for tests only. Production callers take the default: gating it
- // on the auto-title setting made the reservation appear and disappear behind
- // a toggle that regenerates no preset, so the frontend's pin outlived the
- // slot it named.
- const reservedBackgroundSlots =
- typeof opts.reservedBackgroundSlots === 'number'
- ? opts.reservedBackgroundSlots
- : RESERVED_BACKGROUND_SLOTS
const modelsDir = await joinPath([providerPath, 'models'])
// Ensure the directory exists; an empty install is fine — we still emit a
@@ -281,10 +258,12 @@ export async function generatePreset(
) {
lines.push(`cache-type-v = ${escapeIniValue(config.cache_type_v)}`)
}
- // parallel default = -1 (auto); positive user value is intent. The reserved
- // slot is added on top and never exposed in the setting's own value.
+ // parallel default = 0 (llama.cpp's own auto resolution); a positive user
+ // value is intent and is emitted verbatim. Jan adds no hidden slot of its
+ // own: every pinned surface shares slot 0 and is told apart by `thread_id`
+ // (web-app/src/constants/models.ts), so no slot has to be reserved for one.
if (typeof config.parallel === 'number' && config.parallel > 0) {
- lines.push(`parallel = ${config.parallel + reservedBackgroundSlots}`)
+ lines.push(`parallel = ${config.parallel}`)
// llama.cpp only turns on unified KV as part of resolving parallel = -1;
// passing parallel explicitly leaves it off, which splits ctx-size into
// ctx-size/parallel per slot. Restore the auto behaviour so the configured
@@ -598,7 +577,7 @@ export async function generatePreset(
lines.push(`cache-type-v = ${escapeIniValue(mc.cache_type_v)}`)
}
if (typeof mc.parallel === 'number' && mc.parallel > 0) {
- lines.push(`parallel = ${mc.parallel + reservedBackgroundSlots}`)
+ lines.push(`parallel = ${mc.parallel}`)
if (kvUnifiedIsAuto) lines.push('kv-unified = true')
}
if (mc.cont_batching === false) {
diff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.ts
index e7439e83e..ba399debe 100644
--- a/extensions/llamacpp-extension/src/test/index.test.ts
+++ b/extensions/llamacpp-extension/src/test/index.test.ts
@@ -551,6 +551,71 @@ describe('llamacpp_extension', () => {
})
})
+ describe('migrateParallelToDefault', () => {
+ beforeEach(() => {
+ vi.mocked(getBackendSetting).mockResolvedValue(null)
+ })
+
+ it('should skip migration if already migrated', async () => {
+ vi.mocked(getBackendSetting).mockResolvedValue('1')
+ extension['config'] = { parallel: 1 } as any
+ extension['getSettings'] = vi.fn()
+
+ await extension['migrateParallelToDefault']()
+
+ expect(extension['getSettings']).not.toHaveBeenCalled()
+ })
+
+ it('should move the old default of 1 to 0', async () => {
+ extension['config'] = { parallel: 1 } as any
+ extension['getSettings'] = vi.fn().mockResolvedValue([
+ { key: 'parallel', controllerProps: { value: 1 } },
+ { key: 'ctx_size', controllerProps: { value: 2048 } },
+ ])
+ extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)
+
+ await extension['migrateParallelToDefault']()
+
+ const updated = vi.mocked(extension['updateSettings']).mock.calls[0][0]
+ expect(
+ updated.find((s: any) => s.key === 'parallel').controllerProps.value
+ ).toBe(0)
+ expect(
+ updated.find((s: any) => s.key === 'ctx_size').controllerProps.value
+ ).toBe(2048)
+ expect(extension['config'].parallel).toBe(0)
+ expect(setBackendSetting).toHaveBeenCalledWith(
+ 'llamacpp_parallel_default_v1',
+ '1'
+ )
+ })
+
+ it('should leave a deliberately raised value alone', async () => {
+ extension['config'] = { parallel: 4 } as any
+ extension['getSettings'] = vi.fn()
+ extension['updateSettings'] = vi.fn()
+
+ await extension['migrateParallelToDefault']()
+
+ expect(extension['updateSettings']).not.toHaveBeenCalled()
+ expect(extension['config'].parallel).toBe(4)
+ expect(setBackendSetting).toHaveBeenCalledWith(
+ 'llamacpp_parallel_default_v1',
+ '1'
+ )
+ })
+
+ it('should leave an already-default 0 alone', async () => {
+ extension['config'] = { parallel: 0 } as any
+ extension['updateSettings'] = vi.fn()
+
+ await extension['migrateParallelToDefault']()
+
+ expect(extension['updateSettings']).not.toHaveBeenCalled()
+ expect(extension['config'].parallel).toBe(0)
+ })
+ })
+
describe('getLoadedModels', () => {
it('should return list of loaded models', async () => {
const { invoke } = await import('@tauri-apps/api/core')
diff --git a/web-app/src/constants/__tests__/slots.test.ts b/web-app/src/constants/__tests__/slots.test.ts
index 481a2f43a..f5fe9aa86 100644
--- a/web-app/src/constants/__tests__/slots.test.ts
+++ b/web-app/src/constants/__tests__/slots.test.ts
@@ -1,33 +1,32 @@
import { describe, it, expect } from 'vitest'
import {
+ BACKGROUND_THREAD_ID,
CHAT_SLOT_ID,
- BACKGROUND_SLOT_ID,
- COWORK_SLOT_ID,
+ coworkThreadId,
} from '@/constants/models'
-import { RESERVED_BACKGROUND_SLOTS } from '../../../../extensions/llamacpp-extension/src/preset'
// llama.cpp wraps an out-of-range id_slot modulo the slot count instead of
-// rejecting it, so a pin naming a slot that does not exist silently lands back
-// on slot 0 and overwrites the chat cache it was meant to avoid. These two
-// files are the only things keeping that from happening, and they live in
-// separate packages — so the invariant is asserted rather than commented.
+// rejecting it, so any pin above 0 silently lands back on slot 0 whenever the
+// resolved count disagrees. Jan therefore reserves no slot and pins every
+// surface to 0, separating them by thread_id instead -- which only works while
+// those identities stay distinct.
describe('llama.cpp slot allocation', () => {
- it('gives every pinned surface a distinct slot', () => {
- const pins = [CHAT_SLOT_ID, BACKGROUND_SLOT_ID, COWORK_SLOT_ID]
- expect(new Set(pins).size).toBe(pins.length)
+ it('keeps every surface on slot 0', () => {
+ expect(CHAT_SLOT_ID).toBe(0)
})
- it('reserves enough slots for every non-chat pin to exist', () => {
- const nonChatPins = [BACKGROUND_SLOT_ID, COWORK_SLOT_ID]
- expect(RESERVED_BACKGROUND_SLOTS).toBeGreaterThanOrEqual(
- nonChatPins.length
- )
- // Contiguous from 1: the reservation adds N slots above the user's
- // configured parallel value, so pin ids must fill 1..N with no gap.
- expect([...nonChatPins].sort()).toEqual([1, 2])
+ it('gives every surface sharing the slot a distinct thread identity', () => {
+ const chatThread = 'thread-abc'
+ const identities = [
+ chatThread,
+ BACKGROUND_THREAD_ID,
+ coworkThreadId(chatThread),
+ ]
+ expect(new Set(identities).size).toBe(identities.length)
})
- it('keeps chat on slot 0', () => {
- expect(CHAT_SLOT_ID).toBe(0)
+ it('namespaces a cowork identity even when it names no thread', () => {
+ expect(coworkThreadId(undefined)).not.toBe('')
+ expect(coworkThreadId(undefined)).not.toBe(BACKGROUND_THREAD_ID)
})
})
diff --git a/web-app/src/constants/models.ts b/web-app/src/constants/models.ts
index 525b2711e..f064d0693 100644
--- a/web-app/src/constants/models.ts
+++ b/web-app/src/constants/models.ts
@@ -147,29 +147,30 @@ export const providerModels = {
} as const
/**
- * llama.cpp slot pins. Jan sends every chat turn to slot 0 so a thread reuses
- * its cached KV prefix across turns, every background task (title generation,
- * subagents) to slot 1 so it can never overwrite that cache, and every Cowork
- * turn to slot 2.
+ * The one llama.cpp slot Jan pins, and the thread identities that share it.
*
- * Cowork needs its own slot because one agent turn re-prefills a growing prompt
- * dozens of times; sharing slot 0 would evict the viewed thread's prefix on
- * every step, and vice versa. Subagents deliberately reuse the background slot
- * rather than taking a fourth: their prefixes are worth nothing to preserve
- * (each has a different system prompt, so concurrent subagents evict each other
- * regardless), and all that matters is that a dispatch cannot evict the
- * *parent's* prefix on slot 2. Reserving one slot instead of two keeps the KV
- * cache split three ways rather than four.
+ * Every surface -- chat, Cowork, background tasks -- sends `id_slot: 0` plus a
+ * `thread_id`. Jan reserves no slot of its own, so the emitted "Parallel
+ * Sequences" count is exactly what the user configured (llama.cpp's own default
+ * when unset). What keeps the surfaces from destroying each other's KV cache is
+ * not a slot each but the engine's per-`thread_id` slot-cache park/restore
+ * (`engine/http.rs`'s `SlotHint`): a claim by a different identity saves the
+ * outgoing thread's prefix before overwriting it, and restores it on return.
*
- * Both are fixed indices rather than values derived from the "Parallel
- * Sequences" setting, because upstream *wraps* an out-of-range `id_slot`
- * instead of rejecting it (`get_slot_by_id`: `id_slot = id_slot % slots.size()`)
- * -- so a pin computed from a stale or differently-resolved slot count silently
- * lands back on slot 0. The extension's RESERVED_BACKGROUND_SLOTS keeps the
- * emitted `parallel` at 2 or more unconditionally, which is what guarantees
- * slot 1 exists; nothing else pins to it, so it is free even when the user
- * raised the sequence count.
+ * Slot 0 specifically, and a fixed index rather than one derived from the
+ * sequence count, because upstream *wraps* an out-of-range `id_slot` instead of
+ * rejecting it (`get_slot_by_id`: `id_slot = id_slot % slots.size()`) -- so any
+ * pin above 0 silently lands back here whenever the resolved count disagrees.
+ * Slot 0 is the only index guaranteed to exist.
+ *
+ * A `thread_id` is required for the park to happen at all: a request without one
+ * yields no `SlotHint`, so it overwrites whatever the slot held with no save.
+ * That is why background work has an identity of its own instead of no field.
*/
export const CHAT_SLOT_ID = 0
-export const BACKGROUND_SLOT_ID = 1
-export const COWORK_SLOT_ID = 2
+
+/** Thread identity for background work (title generation) sharing slot 0. */
+export const BACKGROUND_THREAD_ID = 'background'
+
+/** Thread identity for a Cowork session sharing slot 0 with the chat it names. */
+export const coworkThreadId = (threadId?: string) => `cowork:${threadId ?? ''}`
diff --git a/web-app/src/lib/__tests__/coworkTransport.test.ts b/web-app/src/lib/__tests__/coworkTransport.test.ts
index 4d52831cb..c5d78b0f3 100644
--- a/web-app/src/lib/__tests__/coworkTransport.test.ts
+++ b/web-app/src/lib/__tests__/coworkTransport.test.ts
@@ -14,7 +14,7 @@ vi.mock('@/lib/coworkTools', async (orig) => ({
}))
import { CoworkChatTransport } from '../coworkTransport'
-import { CHAT_SLOT_ID, COWORK_SLOT_ID } from '@/constants/models'
+import { CHAT_SLOT_ID } from '@/constants/models'
const config = (over = {}) => ({
planMode: false,
@@ -40,15 +40,16 @@ describe('CoworkChatTransport', () => {
sandboxEnforces.mockReturnValue(true)
})
- // Sharing slot 0 would have each of an agent turn's many prefills evict the
- // viewed chat thread's KV cache, and vice versa. Nothing surfaces that but a
- // slowdown, so it is asserted.
- it('pins to the Cowork slot, not the chat slot', () => {
+ // Cowork reserves no slot of its own: it shares the chat slot and is told
+ // apart by thread_id, which is what makes the engine park the outgoing
+ // thread's KV cache instead of overwriting it. Nothing surfaces a regression
+ // here but a slowdown, so it is asserted.
+ it('shares the chat slot, under its own thread identity', () => {
const t = new CoworkChatTransport('s1', config())
const params = slotParamsOf(t, 's1')
- expect(params.id_slot).toBe(COWORK_SLOT_ID)
- expect(params.id_slot).not.toBe(CHAT_SLOT_ID)
+ expect(params.id_slot).toBe(CHAT_SLOT_ID)
expect(params.thread_id).toBe('cowork:s1')
+ expect(params.thread_id).not.toBe('s1')
})
it('namespaces thread_id so a session cannot collide with a chat thread', () => {
diff --git a/web-app/src/lib/__tests__/thread-title-summarizer.test.ts b/web-app/src/lib/__tests__/thread-title-summarizer.test.ts
index c9108c0d1..e6adc6662 100644
--- a/web-app/src/lib/__tests__/thread-title-summarizer.test.ts
+++ b/web-app/src/lib/__tests__/thread-title-summarizer.test.ts
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { cleanTitle, generateThreadTitle } from '../thread-title-summarizer'
-import { BACKGROUND_SLOT_ID } from '@/constants/models'
+import { BACKGROUND_THREAD_ID, CHAT_SLOT_ID } from '@/constants/models'
// Mock AI SDK generateText
const mockGenerateText = vi.fn()
@@ -151,9 +151,11 @@ describe('generateThreadTitle', () => {
expect(mockCreateModel).toHaveBeenCalledWith(
'test-model',
expect.anything(),
- expect.objectContaining({ id_slot: BACKGROUND_SLOT_ID })
+ expect.objectContaining({
+ id_slot: CHAT_SLOT_ID,
+ thread_id: BACKGROUND_THREAD_ID,
+ })
)
- expect(BACKGROUND_SLOT_ID).toBe(1)
})
it('returns null when aborted', async () => {
diff --git a/web-app/src/lib/coworkSubagent.ts b/web-app/src/lib/coworkSubagent.ts
index 1aa0c90e5..a978ca15d 100644
--- a/web-app/src/lib/coworkSubagent.ts
+++ b/web-app/src/lib/coworkSubagent.ts
@@ -39,9 +39,11 @@ import type { StreamEvent } from '@/hooks/useCoworkRun'
* instance, so a child costs no second llama-server load.
*
* The cost of that reuse: llama.cpp slot params are baked in at model creation,
- * so a child prefills on the parent's slot and evicts its KV prefix, which the
- * parent then re-prefills on its next step. Fixing it means a dedicated
- * subagent slot, which is part of the still-open slot-reservation decision.
+ * so a child inherits the parent's `thread_id` and prefills over its KV prefix,
+ * which the parent then re-prefills on its next step. Giving a child its own
+ * identity would park and restore instead, at the price of a state file per
+ * dispatch; concurrent children would still evict each other, since they share
+ * the slot and each has a different system prompt.
*
* `task` is non-blocking, as `dispatch_subagent` is in Rust: it returns the file
* its child's answer will be written to, and the child runs on. Blocking held
diff --git a/web-app/src/lib/coworkTransport.ts b/web-app/src/lib/coworkTransport.ts
index 3521cd4b1..814928ab5 100644
--- a/web-app/src/lib/coworkTransport.ts
+++ b/web-app/src/lib/coworkTransport.ts
@@ -1,6 +1,6 @@
import type { Tool } from 'ai'
import { CustomChatTransport } from '@/lib/custom-chat-transport'
-import { COWORK_SLOT_ID } from '@/constants/models'
+import { CHAT_SLOT_ID, coworkThreadId } from '@/constants/models'
import {
getMemoryCatalog,
sandboxEnforces,
@@ -79,10 +79,11 @@ export class CoworkChatTransport extends CustomChatTransport {
return this.frozenTools ?? this.tools
}
- /** Cowork gets its own llama.cpp slot: sharing chat's would evict the viewed
- * thread's prefix on every one of this turn's many prefills, and vice versa. */
+ /** Cowork shares slot 0 with the main chat, under a thread identity of its
+ * own: the engine parks the outgoing thread's KV prefix when the identity on
+ * the slot changes, so neither surface loses its cache to the other. */
protected override slotParams(threadId?: string): Record<string, unknown> {
- return { id_slot: COWORK_SLOT_ID, thread_id: `cowork:${threadId ?? ''}` }
+ return { id_slot: CHAT_SLOT_ID, thread_id: coworkThreadId(threadId) }
}
/**
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index 59fa93f46..bcecf5ec5 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -889,9 +889,9 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
* @private
*/
/**
- * llama.cpp slot pin for this surface. Chat reuses one slot per thread so its
- * KV prefix survives across turns; other surfaces override to claim their own
- * and avoid evicting it. See CHAT_SLOT_ID.
+ * llama.cpp slot pin for this surface. Every surface shares slot 0 -- the one
+ * index guaranteed to exist -- and overrides only `thread_id`, which is what
+ * the engine parks and restores the slot's KV cache by. See CHAT_SLOT_ID.
*/
protected slotParams(threadId?: string): Record<string, unknown> {
return { id_slot: CHAT_SLOT_ID, thread_id: threadId }
@@ -1318,9 +1318,9 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
if (isPredefinedRemoteProvider(effectiveProviderName)) {
for (const key of Object.keys(paramsSettings)) delete mergedParams[key]
}
- // Pin chat to the chat slot so llama-server reuses this thread's cached
- // KV prefix across turns; background tasks use BACKGROUND_SLOT_ID and
- // can't evict it.
+ // Pin chat to slot 0 so llama-server reuses this thread's cached KV
+ // prefix across turns. Cowork and background tasks share the same slot;
+ // what keeps them from destroying this prefix is thread_id below.
//
// thread_id names whose cache that is, which is what lets the engine
// park it when another thread takes the slot and pick it back up later,
diff --git a/web-app/src/lib/thread-title-summarizer.ts b/web-app/src/lib/thread-title-summarizer.ts
index af4c9a281..66a7f104e 100644
--- a/web-app/src/lib/thread-title-summarizer.ts
+++ b/web-app/src/lib/thread-title-summarizer.ts
@@ -1,7 +1,7 @@
import { generateText } from 'ai'
import { ModelFactory } from './model-factory'
import { useModelProvider } from '@/hooks/useModelProvider'
-import { BACKGROUND_SLOT_ID } from '@/constants/models'
+import { BACKGROUND_THREAD_ID, CHAT_SLOT_ID } from '@/constants/models'
const MAX_TITLE_WORDS = 10
const MAX_PROMPT_LENGTH = 1500
@@ -81,16 +81,17 @@ export async function generateThreadTitle(
}
console.log('[ThreadTitle] Creating model:', selectedModel.id, 'provider:', selectedProvider)
- // Pin to the reserved background slot so this call can never evict a chat
- // request's KV cache. It is a fixed index, not one derived from the
- // "Parallel Sequences" setting: upstream wraps an out-of-range id_slot
- // modulo the slot count instead of rejecting it, so a pin computed from the
- // provider-level value silently landed back on slot 0 whenever the emitted
- // count disagreed -- which a per-model `parallel` override does.
+ // Slot 0 like every other surface, but under its own thread identity: the
+ // engine parks the chat's KV prefix before this call takes the slot and
+ // restores it on the next chat turn. Sending no thread_id would overwrite
+ // that prefix with nothing saved, and pinning a higher slot is unsafe --
+ // upstream wraps an out-of-range id_slot modulo the slot count instead of
+ // rejecting it, so it would land back on slot 0 anyway.
const params: Record<string, unknown> = {}
if (selectedProvider === 'llamacpp') {
params.chat_template_kwargs = { enable_thinking: false }
- params.id_slot = BACKGROUND_SLOT_ID
+ params.id_slot = CHAT_SLOT_ID
+ params.thread_id = BACKGROUND_THREAD_ID
}
const model = await ModelFactory.createModel(
selectedModel.id,