Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat: bulk sync all models on gateway start
Vanalite70eb923e3eee
diff --git a/src-tauri/src/core/openclaw/commands.rs b/src-tauri/src/core/openclaw/commands.rsindex 280970082..5ef18fd61 100644--- a/src-tauri/src/core/openclaw/commands.rs+++ b/src-tauri/src/core/openclaw/commands.rs@@ -1316,6 +1316,115 @@ pub async fn openclaw_sync_model(Ok(())}+/// Bulk sync all models from Jan to OpenClaw+///+/// This replaces the entire model list in the 'jan' provider with the full+/// catalog from Jan's model provider store. Called when Remote Access starts+/// so that OpenClaw knows about all available models without requiring the+/// user to switch models in the dropdown.+#[tauri::command]+pub async fn openclaw_sync_all_models(+ models: Vec<ModelSyncEntry>,+ default_model_id: Option<String>,+) -> Result<BulkSyncResult, String> {+ log::info!("Bulk syncing {} models to OpenClaw", models.len());++ if models.is_empty() {+ log::warn!("No models to sync");+ return Ok(BulkSyncResult {+ synced_count: 0,+ default_model: None,+ });+ }++ // Build model definitions array+ let model_defs: Vec<serde_json::Value> = models+ .iter()+ .map(|entry| {+ let context_window = if entry.provider == "llamacpp" || entry.provider == "mlx" {+ 16000+ } else {+ 128000+ };++ serde_json::json!({+ "id": entry.model_id,+ "name": entry.display_name,+ "reasoning": false,+ "input": ["text"],+ "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },+ "contextWindow": context_window,+ "maxTokens": 4096+ })+ })+ .collect();++ let synced_count = model_defs.len() as u32;++ // Build the full jan provider config with all models+ let jan_provider = serde_json::json!({+ "baseUrl": DEFAULT_JAN_BASE_URL,+ "api": DEFAULT_JAN_API_TYPE,+ "authHeader": false,+ "apiKey": "not-needed",+ "models": model_defs+ });++ // Set the jan provider atomically (creates or replaces)+ let output = Command::new("openclaw")+ .args([+ "config",+ "set",+ "models.providers.jan",+ &jan_provider.to_string(),+ ])+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .output()+ .await+ .map_err(|e| format!("Failed to run openclaw config set: {}", e))?;++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ return Err(format!("Failed to set jan provider models: {}", stderr));+ }++ // Set the default model if provided+ let set_default = if let Some(ref model_id) = default_model_id {+ let openclaw_model_id = format!("jan/{}", model_id);+ let model_output = Command::new("openclaw")+ .args(["models", "set", &openclaw_model_id])+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .output()+ .await;++ match model_output {+ Ok(o) if o.status.success() => {+ log::info!("Set default model to {}", openclaw_model_id);+ Some(openclaw_model_id)+ }+ Ok(o) => {+ let stderr = String::from_utf8_lossy(&o.stderr);+ log::warn!("Failed to set default model: {}", stderr);+ None+ }+ Err(e) => {+ log::warn!("Failed to run openclaw models set: {}", e);+ None+ }+ }+ } else {+ None+ };++ log::info!("Successfully bulk synced {} models to OpenClaw", synced_count);+ Ok(BulkSyncResult {+ synced_count,+ default_model: set_default,+ })+}+/// Get the currently configured model in OpenClaw#[tauri::command]pub async fn openclaw_get_model() -> Result<String, String> {diff --git a/src-tauri/src/core/openclaw/models.rs b/src-tauri/src/core/openclaw/models.rsindex b8f2f4fd6..749175fd3 100644--- a/src-tauri/src/core/openclaw/models.rs+++ b/src-tauri/src/core/openclaw/models.rs@@ -518,6 +518,28 @@ pub struct AccessLogEntry {pub error: Option<String>,}+/// Entry for bulk model sync from Jan to OpenClaw+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ModelSyncEntry {+ /// Model ID (e.g., "llama-3.2-3b", "gpt-4o")+ #[serde(rename = "modelId")]+ pub model_id: String,+ /// Jan's internal provider name (e.g., "llamacpp", "openai", "anthropic")+ pub provider: String,+ /// Human-readable display name+ #[serde(rename = "displayName")]+ pub display_name: String,+}++/// Result of bulk model sync+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BulkSyncResult {+ /// Number of models synced+ pub synced_count: u32,+ /// Default model that was set (if any)+ pub default_model: Option<String>,+}+/// Security status response for the frontend#[derive(Debug, Clone, Serialize, Deserialize)]pub struct SecurityStatus {diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 32b0ee6bd..3c06c62b0 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -139,6 +139,7 @@ pub fn run() {core::openclaw::commands::openclaw_configure,core::openclaw::commands::openclaw_get_config,core::openclaw::commands::openclaw_sync_model,+ core::openclaw::commands::openclaw_sync_all_models,core::openclaw::commands::openclaw_get_model,core::openclaw::commands::openclaw_list_channels,core::openclaw::commands::openclaw_channel_status,diff --git a/web-app/src/routes/settings/remote-access.tsx b/web-app/src/routes/settings/remote-access.tsxindex 479dd42c5..039bddd65 100644--- a/web-app/src/routes/settings/remote-access.tsx+++ b/web-app/src/routes/settings/remote-access.tsx@@ -16,7 +16,8 @@ import { useTranslation } from '@/i18n/react-i18next-compat'import { useEffect, useState, useCallback } from 'react'import { invoke } from '@tauri-apps/api/core'import { toast } from 'sonner'-import { setOpenClawRunningState } from '@/utils/openclaw'+import { setOpenClawRunningState, syncAllModelsToOpenClaw } from '@/utils/openclaw'+import { useModelProvider } from '@/hooks/useModelProvider'import {IconPlugConnected,IconLink,@@ -286,12 +287,23 @@ function RemoteAccess() {}}+ // Bulk sync all models to OpenClaw after gateway starts+ const bulkSyncModels = useCallback(async () => {+ const { providers, selectedModel } = useModelProvider.getState()+ const count = await syncAllModelsToOpenClaw(providers, selectedModel?.id)+ if (count > 0) {+ console.debug(`[RemoteAccess] Synced ${count} models to OpenClaw`)+ }+ }, [])+const handleStart = async () => {try {setIsStarting(true)await invoke('openclaw_start')// Update the OpenClaw running cache immediately so model sync workssetOpenClawRunningState(true)+ // Sync all models so OpenClaw knows the full catalog+ await bulkSyncModels()toast.success(t('settings:remoteAccess.running'))await fetchStatus()} catch (error) {@@ -332,6 +344,8 @@ function RemoteAccess() {if (result.success) {// Install now auto-configures and starts the GatewaysetOpenClawRunningState(true)+ // Sync all models so OpenClaw knows the full catalog+ await bulkSyncModels()toast.success(t('settings:remoteAccess.backendInstallSuccess'))await fetchStatus()} else {diff --git a/web-app/src/utils/openclaw.ts b/web-app/src/utils/openclaw.tsindex d88a438a8..516803165 100644--- a/web-app/src/utils/openclaw.ts+++ b/web-app/src/utils/openclaw.ts@@ -112,6 +112,68 @@ export async function syncModelToOpenClaw(}}+/**+ * Bulk sync all models from Jan's provider store to OpenClaw.+ * Called after Remote Access starts so OpenClaw knows about all available models+ * without requiring the user to switch models in the dropdown.+ *+ * @param providers - All model providers from Jan's Zustand store+ * @param selectedModelId - Currently selected model ID to set as default+ * @returns Number of models synced+ */+export async function syncAllModelsToOpenClaw(+ providers: ModelProvider[],+ selectedModelId?: string+): Promise<number> {+ try {+ // Flatten all providers' models into sync entries+ const models: Array<{+ modelId: string+ provider: string+ displayName: string+ }> = []++ for (const provider of providers) {+ if (!provider.models || provider.models.length === 0) continue++ for (const model of provider.models) {+ const modelId = model.id ?? model.model+ if (!modelId || typeof modelId !== 'string') continue+ // Skip embedding models — they're not usable for chat+ if (model.embedding) continue++ models.push({+ modelId,+ provider: provider.provider,+ displayName: model.displayName || model.name || modelId,+ })+ }+ }++ if (models.length === 0) {+ console.debug('[OpenClaw] No models to sync')+ return 0+ }++ const result = await invoke<{ synced_count: number; default_model: string | null }>(+ 'openclaw_sync_all_models',+ {+ models,+ defaultModelId: selectedModelId || null,+ }+ )++ console.debug(+ `[OpenClaw] Bulk synced ${result.synced_count} models, default: ${result.default_model ?? 'none'}`+ )+ return result.synced_count+ } catch (error) {+ // Don't throw - this is a background sync operation+ console.debug('[OpenClaw] Failed to bulk sync models:', error)+ return 0+ }+}+/*** Get the currently configured model in OpenClaw*/