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): preserve KV-cache reuse across chat turns

Akarshan Biswas1a5d3703402c
diff --git a/extensions/llamacpp-extension/settings.json b/extensions/llamacpp-extension/settings.json
index 06e14df2b..b818175bd 100644
--- a/extensions/llamacpp-extension/settings.json
+++ b/extensions/llamacpp-extension/settings.json
@@ -222,7 +222,7 @@
{
"key": "parallel",
"title": "Parallel Sequences",
- "description": "Number of parallel sequences to decode (0 = llama.cpp default of 1). Set to 1 to also enable -kvu for optimized single-request serving.",
+ "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.",
"controllerType": "input",
"controllerProps": {
"value": 1,
@@ -259,6 +259,15 @@
"value": false
}
},
+ {
+ "key": "strip_reasoning_from_context",
+ "title": "Strip reasoning from context",
+ "description": "Remove prior turns' thinking/reasoning content before resending history. Improves KV-cache reuse across turns, but some models (e.g. newer Qwen releases) recommend keeping it for better multi-turn reasoning.",
+ "controllerType": "checkbox",
+ "controllerProps": {
+ "value": true
+ }
+ },
{
"key": "cache_type_k",
"title": "KV Cache K Type",
@@ -381,7 +390,7 @@
{
"key": "swa_full",
"title": "Full SWA Cache",
- "description": "Use full-size SWA cache. May improve quality at the cost of memory.",
+ "description": "Use full-size KV cache for sliding-window-attention models (e.g. Gemma). Enable this if such a model reprocesses the entire prompt every turn instead of reusing cache; costs more memory.",
"controllerType": "checkbox",
"controllerProps": {
"value": false
diff --git a/extensions/llamacpp-extension/src/preset.test.ts b/extensions/llamacpp-extension/src/preset.test.ts
index 50fa07a2f..46f559c9c 100644
--- a/extensions/llamacpp-extension/src/preset.test.ts
+++ b/extensions/llamacpp-extension/src/preset.test.ts
@@ -159,6 +159,31 @@ describe('generatePreset MTP emission', () => {
})
})
+describe('generatePreset parallel reservation', () => {
+ it('adds one reserved background slot on top of the global parallel value', async () => {
+ setupModel('llama', {})
+ await generatePreset('/p', '/jan', { parallel: 1 } as any, {
+ supportsMtp: false,
+ })
+ const ini = writtenFiles['/p/router.preset.ini']
+ expect(ini).toContain('parallel = 2')
+ })
+
+ it('adds one reserved background slot on top of a per-model parallel override', async () => {
+ setupModel('llama', { parallel: 3 })
+ await generatePreset('/p', '/jan', {} as any, { supportsMtp: false })
+ const ini = writtenFiles['/p/router.preset.ini']
+ expect(ini).toContain('parallel = 4')
+ })
+
+ it('omits parallel when unset, leaving llama.cpp auto-default untouched', async () => {
+ setupModel('llama', {})
+ await generatePreset('/p', '/jan', {} as any, { supportsMtp: false })
+ const ini = writtenFiles['/p/router.preset.ini']
+ expect(ini).not.toContain('parallel =')
+ })
+})
+
describe('generatePreset ctx-size default', () => {
it('emits ctx-size = 8192 in [*] when fit is off and no ctx_size is set', async () => {
setupModel('llama', {})
diff --git a/extensions/llamacpp-extension/src/preset.ts b/extensions/llamacpp-extension/src/preset.ts
index 043125013..7376fd002 100644
--- a/extensions/llamacpp-extension/src/preset.ts
+++ b/extensions/llamacpp-extension/src/preset.ts
@@ -47,6 +47,12 @@ 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; see reservedSlotId in thread-title-summarizer.ts.
+export const RESERVED_BACKGROUND_SLOTS = 1
+
export const MTP_MIN_BUILD = 9193
const DEFAULT_EMBEDDING_UBATCH = 2048
@@ -182,9 +188,10 @@ export async function generatePreset(
) {
lines.push(`cache-type-v = ${escapeIniValue(config.cache_type_v)}`)
}
- // parallel default = -1 (auto); positive user value is intent.
+ // 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.
if (typeof config.parallel === 'number' && config.parallel > 0) {
- lines.push(`parallel = ${config.parallel}`)
+ lines.push(`parallel = ${config.parallel + RESERVED_BACKGROUND_SLOTS}`)
}
// cont-batching default = true; emit only the explicit-off case.
if (config.cont_batching === false) {
@@ -387,7 +394,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}`)
+ lines.push(`parallel = ${mc.parallel + RESERVED_BACKGROUND_SLOTS}`)
}
if (mc.cont_batching === false) {
lines.push('cont-batching = false')
diff --git a/extensions/mlx-extension/settings.json b/extensions/mlx-extension/settings.json
index b330668a3..6b9c5d05b 100644
--- a/extensions/mlx-extension/settings.json
+++ b/extensions/mlx-extension/settings.json
@@ -5,5 +5,12 @@
"description": "Automatically unload other models when loading a new one",
"controllerType": "checkbox",
"controllerProps": { "value": true }
+ },
+ {
+ "key": "strip_reasoning_from_context",
+ "title": "Strip reasoning from context",
+ "description": "Remove prior turns' thinking/reasoning content before resending history. Improves KV-cache reuse across turns, but some models (e.g. newer Qwen releases) recommend keeping it for better multi-turn reasoning.",
+ "controllerType": "checkbox",
+ "controllerProps": { "value": true }
}
]
diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rs
index 5640e86e5..d36443769 100644
--- a/src-tauri/src/core/mcp/commands.rs
+++ b/src-tauri/src/core/mcp/commands.rs
@@ -25,10 +25,17 @@ async fn tool_call_timeout(state: &AppState) -> Duration {
/// Shared implementation for listing MCP tools.
///
-/// - `server_filter: None` — every connected server (same behavior as `get_tools`).
-/// - `server_filter: Some(names)` — only connected servers in that set; unknown or
-/// disconnected names are skipped (logged). Transport / list failures use the same
-/// cleanup as `get_tools` (remove stale entry, emit `mcp-update` when needed).
+/// - `server_filter: None` — every enabled server (same behavior as `get_tools`).
+/// - `server_filter: Some(names)` — only enabled servers in that set; unknown names
+/// are skipped (logged).
+///
+/// A server counts as "enabled" if it's in `mcp_active_servers`, regardless of
+/// whether it's currently connected — a transiently disconnected server still
+/// contributes its last successfully listed tools (`mcp_last_known_tools`), so
+/// the tool schema Jan sends stays present and stable across reconnects instead
+/// of shrinking/growing and invalidating the downstream KV-cache prefix.
+/// `mcp_last_known_tools` is only cleared by explicit user deactivation
+/// (`deactivate_mcp_server`), never by a transient list-tools failure here.
async fn collect_mcp_tools<R: Runtime>(
app: &AppHandle<R>,
state: &AppState,
@@ -39,20 +46,20 @@ async fn collect_mcp_tools<R: Runtime>(
let mut removed_any = false;
let server_names: Vec<String> = {
- let servers = state.mcp_servers.lock().await;
+ let active_servers = state.mcp_active_servers.lock().await;
match &server_filter {
- None => servers.keys().cloned().collect(),
+ None => active_servers.keys().cloned().collect(),
Some(filter) => {
for name in filter {
- if !servers.contains_key(name) {
+ if !active_servers.contains_key(name) {
log::debug!(
- "collect_mcp_tools: requested server {name:?} is not connected (removed or never started); skipping"
+ "collect_mcp_tools: requested server {name:?} is not enabled; skipping"
);
}
}
filter
.iter()
- .filter(|n| servers.contains_key(*n))
+ .filter(|n| active_servers.contains_key(*n))
.cloned()
.collect()
}
@@ -60,30 +67,33 @@ async fn collect_mcp_tools<R: Runtime>(
};
for server_name in server_names {
- let list_result = {
+ // Snapshot the live service's list_all_tools() future while holding the
+ // lock, but resolve it after dropping the guard so a slow/hanging
+ // server doesn't hold `mcp_servers` locked for other callers.
+ let maybe_list_result = {
let servers = state.mcp_servers.lock().await;
- if let Some(service) = servers.get(&server_name) {
- timeout(timeout_duration, service.list_all_tools()).await
- } else {
- log::debug!(
- "collect_mcp_tools: server {server_name:?} disappeared before list_tools; skipping"
- );
- continue;
+ match servers.get(&server_name) {
+ Some(service) => Some(timeout(timeout_duration, service.list_all_tools()).await),
+ None => None,
}
};
- match list_result {
- Ok(Ok(tools)) => {
- for tool in tools {
- all_tools.push(ToolWithServer {
+ let fresh_tools = match maybe_list_result {
+ Some(Ok(Ok(tools))) => {
+ let mapped: Vec<ToolWithServer> = tools
+ .into_iter()
+ .map(|tool| ToolWithServer {
name: tool.name.to_string(),
description: tool.description.as_ref().map(|d| d.to_string()),
input_schema: serde_json::Value::Object((*tool.input_schema).clone()),
server: server_name.clone(),
- });
- }
+ })
+ .collect();
+ let mut last_known = state.mcp_last_known_tools.lock().await;
+ last_known.insert(server_name.clone(), mapped.clone());
+ Some(mapped)
}
- Ok(Err(e)) => {
+ Some(Ok(Err(e))) => {
let err_str = e.to_string();
log::warn!("MCP server {server_name} failed to list tools: {err_str}");
if is_transport_error(&err_str) {
@@ -92,14 +102,31 @@ async fn collect_mcp_tools<R: Runtime>(
if remove_mcp_server_entry(&state.mcp_servers, &server_name).await {
removed_any = true;
}
+ None
}
- Err(_) => {
+ Some(Err(_)) => {
log::warn!(
"MCP server {server_name}: listing tools timed out after {} seconds",
timeout_duration.as_secs()
);
+ None
}
- }
+ None => {
+ log::debug!(
+ "collect_mcp_tools: server {server_name:?} not connected; using last-known tools if any"
+ );
+ None
+ }
+ };
+
+ let tools = match fresh_tools {
+ Some(tools) => tools,
+ None => {
+ let last_known = state.mcp_last_known_tools.lock().await;
+ last_known.get(&server_name).cloned().unwrap_or_default()
+ }
+ };
+ all_tools.extend(tools);
}
if removed_any {
@@ -173,6 +200,14 @@ pub async fn deactivate_mcp_server<R: Runtime>(
log::info!("Removed MCP server {name} from active servers list");
}
+ // Explicit deactivation is the only thing that should drop the last-known
+ // tool schema — a transient disconnect must not (collect_mcp_tools keeps
+ // serving it until the server is actually turned off).
+ {
+ let mut last_known = state.mcp_last_known_tools.lock().await;
+ last_known.remove(&name);
+ }
+
// Now remove and stop the server
let servers = state.mcp_servers.clone();
let mut servers_map = servers.lock().await;
@@ -324,20 +359,16 @@ pub async fn get_tools_for_servers<R: Runtime>(
collect_mcp_tools(&app, &state, Some(filter)).await
}
-/// Returns name, capability tags, and description for all connected MCP servers
+/// Returns name, capability tags, and description for all enabled MCP servers
+/// (regardless of live connection state — see `collect_mcp_tools`).
#[tauri::command]
pub async fn get_server_summaries(
state: State<'_, AppState>,
) -> Result<Vec<ServerSummary>, String> {
- let connected_servers: Vec<String> = {
- let servers = state.mcp_servers.lock().await;
- servers.keys().cloned().collect()
- };
-
let active_servers = state.mcp_active_servers.lock().await;
let mut summaries = Vec::new();
- for name in &connected_servers {
+ for name in active_servers.keys() {
let config = active_servers.get(name);
let capabilities: Vec<String> = config
diff --git a/src-tauri/src/core/mcp/tests.rs b/src-tauri/src/core/mcp/tests.rs
index 7731f3264..61f31c607 100644
--- a/src-tauri/src/core/mcp/tests.rs
+++ b/src-tauri/src/core/mcp/tests.rs
@@ -288,12 +288,16 @@ async fn test_get_server_summaries_with_capabilities_in_active_config() {
);
}
- // Summaries are derived from the intersection of connected servers and active config.
- // With no entries in mcp_servers the result should still be empty.
+ // Summaries are derived from enabled (active_servers) config, independent of
+ // live connection state, so a transiently disconnected server still appears
+ // and keeps contributing a stable tool schema.
let result = get_server_summaries(state).await;
assert!(result.is_ok());
let summaries = result.unwrap();
- assert!(summaries.is_empty(), "No connected servers → no summaries");
+ assert_eq!(summaries.len(), 1, "enabled server appears even when disconnected");
+ assert_eq!(summaries[0].name, "filesystem");
+ assert_eq!(summaries[0].capabilities, vec!["filesystem", "files"]);
+ assert_eq!(summaries[0].description, "Read and write local files");
}
#[tokio::test]
@@ -318,10 +322,93 @@ async fn test_get_server_summaries_missing_metadata_defaults() {
);
}
- // No entries in mcp_servers → summaries list is empty
+ // Enabled server with no metadata still appears, with defaulted fields.
let result = get_server_summaries(state).await;
assert!(result.is_ok());
- assert!(result.unwrap().is_empty());
+ let summaries = result.unwrap();
+ assert_eq!(summaries.len(), 1);
+ assert_eq!(summaries[0].name, "minimal_server");
+ assert!(summaries[0].capabilities.is_empty());
+ assert_eq!(summaries[0].description, "");
+}
+
+// ============================================================================
+// get_tools last-known-tools fallback tests
+// ============================================================================
+
+#[tokio::test]
+async fn test_get_tools_falls_back_to_last_known_when_server_enabled_but_disconnected() {
+ use super::commands::get_tools;
+ use super::models::ToolWithServer;
+
+ let app = mock_app();
+ let servers_state: SharedMcpServers = Arc::new(Mutex::new(HashMap::new()));
+ app.manage(AppState {
+ mcp_servers: servers_state.clone(),
+ ..Default::default()
+ });
+
+ let state = app.state::<AppState>();
+
+ // Enabled (in active_servers) but not present in mcp_servers — simulates a
+ // transient disconnect of a remote MCP server.
+ {
+ let mut active = state.mcp_active_servers.lock().await;
+ active.insert("exa".to_string(), serde_json::json!({ "type": "http" }));
+ }
+ {
+ let mut last_known = state.mcp_last_known_tools.lock().await;
+ last_known.insert(
+ "exa".to_string(),
+ vec![ToolWithServer {
+ name: "web_search_exa".to_string(),
+ description: Some("search the web".to_string()),
+ input_schema: serde_json::json!({}),
+ server: "exa".to_string(),
+ }],
+ );
+ }
+
+ let result = get_tools(app.handle().clone(), state).await;
+ assert!(result.is_ok());
+ let tools = result.unwrap();
+ assert_eq!(tools.len(), 1, "disconnected-but-enabled server's last-known tools still present");
+ assert_eq!(tools[0].name, "web_search_exa");
+ assert_eq!(tools[0].server, "exa");
+}
+
+#[tokio::test]
+async fn test_get_tools_omits_disabled_server_even_with_stale_last_known_entry() {
+ use super::commands::get_tools;
+ use super::models::ToolWithServer;
+
+ let app = mock_app();
+ let servers_state: SharedMcpServers = Arc::new(Mutex::new(HashMap::new()));
+ app.manage(AppState {
+ mcp_servers: servers_state.clone(),
+ ..Default::default()
+ });
+
+ let state = app.state::<AppState>();
+
+ // Not in active_servers (disabled/never enabled this session) but a stale
+ // last-known entry lingers — must not leak into the tool list.
+ {
+ let mut last_known = state.mcp_last_known_tools.lock().await;
+ last_known.insert(
+ "old_server".to_string(),
+ vec![ToolWithServer {
+ name: "stale_tool".to_string(),
+ description: None,
+ input_schema: serde_json::json!({}),
+ server: "old_server".to_string(),
+ }],
+ );
+ }
+
+ let result = get_tools(app.handle().clone(), state).await;
+ assert!(result.is_ok());
+ assert!(result.unwrap().is_empty(), "disabled server must not contribute stale tools");
}
// ============================================================================
diff --git a/src-tauri/src/core/state.rs b/src-tauri/src/core/state.rs
index 79f517b58..a2633b01a 100644
--- a/src-tauri/src/core/state.rs
+++ b/src-tauri/src/core/state.rs
@@ -1,6 +1,9 @@
use std::{collections::HashMap, sync::Arc};
-use crate::core::{downloads::models::DownloadManagerState, mcp::models::McpSettings};
+use crate::core::{
+ downloads::models::DownloadManagerState,
+ mcp::models::{McpSettings, ToolWithServer},
+};
use rmcp::{
model::{CallToolRequestParam, CallToolResult, InitializeRequestParam, Tool},
service::RunningService,
@@ -67,6 +70,12 @@ pub struct AppState {
pub model_param_defaults: Arc<Mutex<HashMap<String, serde_json::Value>>>,
/// Wakes up MCP monitors to trigger an immediate health check + reconnect
pub mcp_reconnect_notify: Arc<Notify>,
+ /// Last successful tool listing per enabled server, served when a server
+ /// is transiently disconnected so its schema stays present and stable in
+ /// the prompt instead of disappearing/reappearing across reconnects.
+ /// Cleared only on explicit user deactivation, never on a transient
+ /// list-tools failure.
+ pub mcp_last_known_tools: Arc<Mutex<HashMap<String, Vec<ToolWithServer>>>>,
}
impl Default for AppState {
@@ -86,6 +95,7 @@ impl Default for AppState {
provider_configs: Default::default(),
model_param_defaults: Default::default(),
mcp_reconnect_notify: Arc::new(Notify::new()),
+ mcp_last_known_tools: Default::default(),
}
}
}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 084eb25d5..14c7f04fa 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -277,6 +277,7 @@ pub fn run() {
provider_configs: Arc::new(Mutex::new(HashMap::new())),
model_param_defaults: Arc::new(Mutex::new(HashMap::new())),
mcp_reconnect_notify: Arc::new(tokio::sync::Notify::new()),
+ mcp_last_known_tools: Arc::new(Mutex::new(HashMap::new())),
})
.setup(|app| {
app.handle().plugin(
diff --git a/web-app/src/hooks/__tests__/useTools.test.ts b/web-app/src/hooks/__tests__/useTools.test.ts
index b78982630..8864ecbe8 100644
--- a/web-app/src/hooks/__tests__/useTools.test.ts
+++ b/web-app/src/hooks/__tests__/useTools.test.ts
@@ -7,6 +7,11 @@ const mockGetTools = vi.fn()
const mockUpdateTools = vi.fn()
const mockListen = vi.fn()
const mockUnsubscribe = vi.fn()
+const mockInvalidateCache = vi.fn()
+
+vi.mock('@/lib/mcp-orchestrator/mcp-orchestrator', () => ({
+ mcpOrchestrator: { invalidateCache: mockInvalidateCache },
+}))
// Mock useAppState
vi.mock('../useAppState', () => ({
@@ -108,6 +113,31 @@ describe('useTools', () => {
expect(mockUpdateTools).toHaveBeenCalledWith(mockTools)
})
+ it('invalidates the MCP orchestrator tool cache on mount and on MCP_UPDATE, so a server connect/disconnect cannot serve stale tools to the next chat request', async () => {
+ const { useTools } = await import('../useTools')
+
+ let eventCallback: () => void
+ mockListen.mockImplementation((_event, callback) => {
+ eventCallback = callback
+ return Promise.resolve(mockUnsubscribe)
+ })
+
+ renderHook(() => useTools())
+
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+
+ expect(mockInvalidateCache).toHaveBeenCalledTimes(1)
+
+ await act(async () => {
+ eventCallback()
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+
+ expect(mockInvalidateCache).toHaveBeenCalledTimes(2)
+ })
+
it('should return unsubscribe function for cleanup', async () => {
const { useTools } = await import('../useTools')
diff --git a/web-app/src/hooks/useTools.ts b/web-app/src/hooks/useTools.ts
index 85e8e866c..9148076c6 100644
--- a/web-app/src/hooks/useTools.ts
+++ b/web-app/src/hooks/useTools.ts
@@ -5,6 +5,7 @@ import { useAppState } from './useAppState'
import { useToolAvailable } from './useToolAvailable'
import { ExtensionManager } from '@/lib/extension'
import { ExtensionTypeEnum, MCPExtension } from '@janhq/core'
+import { mcpOrchestrator } from '@/lib/mcp-orchestrator/mcp-orchestrator'
export const useTools = () => {
const updateTools = useAppState((state) => state.updateTools)
@@ -15,6 +16,12 @@ export const useTools = () => {
useEffect(() => {
async function setTools() {
try {
+ // A server connect/disconnect/tools-refresh fired this (mcp-update);
+ // the orchestrator's per-request tool cache would otherwise only
+ // notice via its own TTL, serving stale/reordered tools in the
+ // meantime and destabilizing the KV-cache prefix Jan sends.
+ mcpOrchestrator.invalidateCache()
+
// Get MCP extension first
const mcpExtension = ExtensionManager.getInstance().get<MCPExtension>(
ExtensionTypeEnum.MCP
diff --git a/web-app/src/lib/mcp-orchestrator/__tests__/mcp-orchestrator.test.ts b/web-app/src/lib/mcp-orchestrator/__tests__/mcp-orchestrator.test.ts
index 8ca1fff89..1ac6a9444 100644
--- a/web-app/src/lib/mcp-orchestrator/__tests__/mcp-orchestrator.test.ts
+++ b/web-app/src/lib/mcp-orchestrator/__tests__/mcp-orchestrator.test.ts
@@ -75,6 +75,26 @@ describe('MCPOrchestrator', () => {
expect(tools).toHaveLength(1)
expect(tools[0].name).toBe('read_file')
})
+
+ it('returns tools sorted by (server, name) regardless of fetch order, to keep the serialized tool list stable across turns for KV-cache reuse', async () => {
+ const shuffledTools = [
+ { name: 'browse', description: '', inputSchema: {}, server: 'web' },
+ { name: 'write_file', description: '', inputSchema: {}, server: 'fs' },
+ { name: 'read_file', description: '', inputSchema: {}, server: 'fs' },
+ ]
+ const service = makeService({
+ getServerSummaries: vi.fn().mockResolvedValue(fewSummaries),
+ getTools: vi.fn().mockResolvedValue(shuffledTools),
+ })
+
+ const tools = await orchestrator.getRelevantTools('do something', service, [])
+
+ expect(tools.map((t) => `${(t as { server?: string }).server}::${t.name}`)).toEqual([
+ 'fs::read_file',
+ 'fs::write_file',
+ 'web::browse',
+ ])
+ })
})
// ─── above threshold — uses getToolsForServers() ─────────────────────────
diff --git a/web-app/src/lib/mcp-orchestrator/mcp-orchestrator.ts b/web-app/src/lib/mcp-orchestrator/mcp-orchestrator.ts
index 5baa2352d..beb5130b6 100644
--- a/web-app/src/lib/mcp-orchestrator/mcp-orchestrator.ts
+++ b/web-app/src/lib/mcp-orchestrator/mcp-orchestrator.ts
@@ -275,10 +275,22 @@ export class MCPOrchestrator {
}
private filterDisabled(tools: MCPTool[], disabledKeys: string[]): MCPTool[] {
- if (disabledKeys.length === 0) return tools
- return tools.filter((tool) => {
- const key = `${(tool as { server?: string }).server ?? 'unknown'}::${tool.name}`
- return !disabledKeys.includes(key)
+ const filtered =
+ disabledKeys.length === 0
+ ? tools
+ : tools.filter((tool) => {
+ const key = `${(tool as { server?: string }).server ?? 'unknown'}::${tool.name}`
+ return !disabledKeys.includes(key)
+ })
+ // Sort by (server, name) so transient fetch-order/count fluctuations from
+ // MCP servers (reconnects, TTL-driven re-fetches) can't reorder the
+ // serialized tool list and invalidate the llama-server KV-cache prefix
+ // when the underlying tool set is otherwise unchanged.
+ return [...filtered].sort((a, b) => {
+ const serverA = (a as { server?: string }).server ?? 'unknown'
+ const serverB = (b as { server?: string }).server ?? 'unknown'
+ if (serverA !== serverB) return serverA < serverB ? -1 : 1
+ return a.name < b.name ? -1 : a.name > b.name ? 1 : 0
})
}
}
diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.ts
index f47db4811..e5112054f 100644
--- a/web-app/src/lib/model-factory.ts
+++ b/web-app/src/lib/model-factory.ts
@@ -585,6 +585,15 @@ export function stripAssistantReasoningInBody(
}
}
+/** Reads the per-provider "Strip reasoning from context" checkbox; defaults to true. */
+function shouldStripReasoningFromContext(provider?: ProviderObject): boolean {
+ const setting = provider?.settings?.find(
+ (s) => s.key === 'strip_reasoning_from_context'
+ )
+ const value = setting?.controller_props?.value
+ return typeof value === 'boolean' ? value : true
+}
+
/** Wraps `inner` to strip reasoning fields from assistant messages before send. */
function withAssistantReasoningStripped(
inner: typeof globalThis.fetch
@@ -875,12 +884,19 @@ export class ModelFactory {
})()
}
: undefined
- const customFetch = createCustomFetch(
+ // Reasoning content re-shapes assistant turns (content + sibling
+ // reasoning_content) relative to what llama-server originally streamed
+ // and cached, so stripping it (default on) preserves KV-cache prefix
+ // reuse across turns; some models recommend keeping it, hence the toggle.
+ let customFetch = createCustomFetch(
httpFetch,
parameters,
true,
onLlamacppServerError
)
+ if (shouldStripReasoningFromContext(provider)) {
+ customFetch = withAssistantReasoningStripped(customFetch)
+ }
return new OpenAICompatibleChatLanguageModel(modelId, {
provider: 'llamacpp',
@@ -945,7 +961,10 @@ export class ModelFactory {
// rebuilds upstream errors from buffered text rather than re-decoding the
// raw stream) with every other provider, then layer MLX's /cancel-on-abort
// on top.
- const baseCustomFetch = createCustomFetch(httpFetch, parameters)
+ let baseCustomFetch = createCustomFetch(httpFetch, parameters)
+ if (shouldStripReasoningFromContext(provider)) {
+ baseCustomFetch = withAssistantReasoningStripped(baseCustomFetch)
+ }
const customFetch: typeof globalThis.fetch = async (
input: RequestInfo | URL,
init?: RequestInit
diff --git a/web-app/src/lib/thread-title-summarizer.ts b/web-app/src/lib/thread-title-summarizer.ts
index fc83fc89f..c461a0635 100644
--- a/web-app/src/lib/thread-title-summarizer.ts
+++ b/web-app/src/lib/thread-title-summarizer.ts
@@ -80,10 +80,22 @@ export async function generateThreadTitle(
}
console.log('[ThreadTitle] Creating model:', selectedModel.id, 'provider:', selectedProvider)
- const params: Record<string, unknown> =
- selectedProvider === 'llamacpp'
- ? { chat_template_kwargs: { enable_thinking: false } }
- : {}
+ // Pin to the reserved background slot (RESERVED_BACKGROUND_SLOTS in
+ // preset.ts) — one index past the user-visible "Parallel Sequences"
+ // count — so this call can never evict a chat request's KV cache.
+ // "Parallel Sequences" = 0 means auto (llama.cpp picks its own slot
+ // count); we can't safely reserve a slot in that case, so skip pinning.
+ const params: Record<string, unknown> = {}
+ if (selectedProvider === 'llamacpp') {
+ params.chat_template_kwargs = { enable_thinking: false }
+ const userParallel = Number(
+ provider.settings?.find((s) => s.key === 'parallel')?.controller_props
+ ?.value ?? 1
+ )
+ if (Number.isFinite(userParallel) && userParallel > 0) {
+ params.id_slot = userParallel
+ }
+ }
const model = await ModelFactory.createModel(
selectedModel.id,
provider,