Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
chore: code clean up
Vanalite3856b8323c01
diff --git a/src-tauri/src/core/openclaw/commands.rs b/src-tauri/src/core/openclaw/commands.rsindex 5ef18fd61..3722ece32 100644--- a/src-tauri/src/core/openclaw/commands.rs+++ b/src-tauri/src/core/openclaw/commands.rs@@ -1463,6 +1463,148 @@ async fn check_gateway_responding() -> bool {}}+/// 1-click enable: orchestrates dependency check, install, configure, and start+#[tauri::command]+pub async fn openclaw_enable(+ app: tauri::AppHandle,+ config_input: Option<OpenClawConfigInput>,+ state: State<'_, OpenClawState>,+) -> Result<EnableResult, String> {+ use tauri::Emitter;+ log::info!("Starting 1-click OpenClaw enable flow");++ let mut steps_completed: Vec<EnableStep> = vec![];++ let emit = |step: &str, progress: u32, message: &str| {+ let _ = app.emit(+ "openclaw-enable-progress",+ EnableProgressEvent {+ step: step.to_string(),+ progress,+ message: message.to_string(),+ },+ );+ };++ // Step 1: Check Node.js dependencies+ emit("checking_dependencies", 10, "Checking Node.js installation...");+ steps_completed.push(EnableStep::CheckingDependencies);+ let node_check = openclaw_check_dependencies().await;+ if !node_check.installed {+ return Err(serde_json::to_string(&EnableError {+ code: EnableErrorCode::NodeNotFound,+ message: "Node.js is not installed. OpenClaw requires Node.js 22+.".to_string(),+ recovery: vec![RecoveryOption {+ label: "Download Node.js".to_string(),+ action: RecoveryAction::OpenNodeDownload,+ description: "Opens the Node.js download page in your browser.".to_string(),+ }],+ })+ .unwrap_or_else(|_| "Node.js is not installed".to_string()));+ }+ if !node_check.meets_requirements {+ return Err(serde_json::to_string(&EnableError {+ code: EnableErrorCode::NodeVersionTooLow,+ message: format!(+ "Node.js 22+ required. Found: {}",+ node_check.version.as_deref().unwrap_or("unknown")+ ),+ recovery: vec![RecoveryOption {+ label: "Download Node.js".to_string(),+ action: RecoveryAction::OpenNodeDownload,+ description: "Opens the Node.js download page to get the latest version.".to_string(),+ }],+ })+ .unwrap_or_else(|_| "Node.js version too low".to_string()));+ }++ // Step 2: Check if OpenClaw is already installed+ emit("checking_installation", 25, "Checking OpenClaw installation...");+ steps_completed.push(EnableStep::CheckingInstallation);+ let already_installed = check_openclaw_installed().await.ok().flatten().is_some();++ // Step 3: Install if needed+ if !already_installed {+ emit("installing", 40, "Installing OpenClaw (this may take a moment)...");+ steps_completed.push(EnableStep::Installing);+ let install_result = openclaw_install().await?;+ if !install_result.success {+ return Err(serde_json::to_string(&EnableError {+ code: EnableErrorCode::NpmInstallFailed,+ message: install_result+ .error+ .unwrap_or_else(|| "npm install failed".to_string()),+ recovery: vec![RecoveryOption {+ label: "Retry".to_string(),+ action: RecoveryAction::Retry,+ description: "Try installing OpenClaw again.".to_string(),+ }],+ })+ .unwrap_or_else(|_| "Installation failed".to_string()));+ }+ } else {+ emit("already_installed", 40, "OpenClaw is already installed.");+ }++ // Step 4: Configure+ emit("configuring", 60, "Configuring OpenClaw...");+ steps_completed.push(EnableStep::Configuring);+ openclaw_configure(config_input).await.map_err(|e| {+ serde_json::to_string(&EnableError {+ code: EnableErrorCode::ConfigWriteFailed,+ message: format!("Failed to write configuration: {}", e),+ recovery: vec![RecoveryOption {+ label: "Retry".to_string(),+ action: RecoveryAction::Retry,+ description: "Try configuring again.".to_string(),+ }],+ })+ .unwrap_or(e)+ })?;++ // Step 5: Start the gateway+ emit("starting", 75, "Starting OpenClaw gateway...");+ steps_completed.push(EnableStep::Starting);+ openclaw_start(state.clone()).await.map_err(|e| {+ if e.contains("Port") || e.contains("port") {+ serde_json::to_string(&EnableError {+ code: EnableErrorCode::PortInUse,+ message: e.clone(),+ recovery: vec![RecoveryOption {+ label: "Use different port".to_string(),+ action: RecoveryAction::UseDifferentPort {+ port: OPENCLAW_PORT + 1,+ },+ description: format!("Try port {} instead.", OPENCLAW_PORT + 1),+ }],+ })+ .unwrap_or(e)+ } else {+ serde_json::to_string(&EnableError {+ code: EnableErrorCode::GatewayStartFailed,+ message: e.clone(),+ recovery: vec![RecoveryOption {+ label: "Retry".to_string(),+ action: RecoveryAction::Retry,+ description: "Try starting the gateway again.".to_string(),+ }],+ })+ .unwrap_or(e)+ }+ })?;++ // Step 6: Get final status+ emit("complete", 100, "OpenClaw is ready!");+ let final_status = openclaw_status(state).await?;++ Ok(EnableResult {+ success: true,+ already_installed,+ steps_completed,+ status: final_status,+ })+}+/// Start the OpenClaw gateway#[tauri::command]pub async fn openclaw_start(_state: State<'_, OpenClawState>) -> Result<(), String> {diff --git a/src-tauri/src/core/openclaw/models.rs b/src-tauri/src/core/openclaw/models.rsindex 749175fd3..7e6275948 100644--- a/src-tauri/src/core/openclaw/models.rs+++ b/src-tauri/src/core/openclaw/models.rs@@ -540,6 +540,86 @@ pub struct BulkSyncResult {pub default_model: Option<String>,}+// ============================================+// 1-Click Enable Models+// ============================================++/// Steps in the 1-click enable flow+#[derive(Debug, Clone, Serialize, Deserialize)]+pub enum EnableStep {+ CheckingDependencies,+ CheckingInstallation,+ Installing,+ Configuring,+ Starting,+ SyncingModels,+}++/// Result of the 1-click enable orchestrator+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct EnableResult {+ /// Whether the enable flow completed successfully+ pub success: bool,+ /// Whether OpenClaw was already installed before this run+ pub already_installed: bool,+ /// Steps that were completed+ pub steps_completed: Vec<EnableStep>,+ /// Final OpenClaw status+ pub status: OpenClawStatus,+}++/// Progress event emitted during the enable flow+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct EnableProgressEvent {+ /// Current step identifier+ pub step: String,+ /// Progress percentage (0-100)+ pub progress: u32,+ /// Human-readable message+ pub message: String,+}++/// Error with recovery options for the enable flow+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct EnableError {+ /// Error code for programmatic handling+ pub code: EnableErrorCode,+ /// Human-readable error message+ pub message: String,+ /// Recovery options the user can take+ pub recovery: Vec<RecoveryOption>,+}++/// Error codes for the enable flow+#[derive(Debug, Clone, Serialize, Deserialize)]+pub enum EnableErrorCode {+ NodeNotFound,+ NodeVersionTooLow,+ NpmInstallFailed,+ PortInUse,+ ConfigWriteFailed,+ GatewayStartFailed,+}++/// A recovery option the user can take+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct RecoveryOption {+ /// Button label+ pub label: String,+ /// Recovery action type+ pub action: RecoveryAction,+ /// Description of what this action does+ pub description: String,+}++/// Recovery actions the frontend can execute+#[derive(Debug, Clone, Serialize, Deserialize)]+pub enum RecoveryAction {+ Retry,+ OpenNodeDownload,+ UseDifferentPort { port: u16 },+}+/// 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 3c06c62b0..bd519181f 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -143,6 +143,7 @@ pub fn run() {core::openclaw::commands::openclaw_get_model,core::openclaw::commands::openclaw_list_channels,core::openclaw::commands::openclaw_channel_status,+ core::openclaw::commands::openclaw_enable,core::openclaw::commands::openclaw_start,core::openclaw::commands::openclaw_stop,core::openclaw::commands::openclaw_status,diff --git a/src-tauri/tauri.macos.conf.json b/src-tauri/tauri.macos.conf.jsonindex fd24e2e4f..a512345a6 100644--- a/src-tauri/tauri.macos.conf.json+++ b/src-tauri/tauri.macos.conf.json@@ -30,7 +30,7 @@},"bundle": {"targets": ["app", "dmg"],- "resources": ["resources/pre-install/**/*", "resources/LICENSE", "resources/bin/mlx-server", "resources/bin/mlx-swift_Cmlx.bundle"],+ "resources": ["resources/pre-install/**/*", "resources/LICENSE"],"externalBin": ["resources/bin/bun", "resources/bin/uv"],"macOS": {"entitlements": "./Entitlements.plist"diff --git a/web-app/src/containers/ChannelCard.tsx b/web-app/src/containers/ChannelCard.tsxindex 96e765cd8..f6eecfad6 100644--- a/web-app/src/containers/ChannelCard.tsx+++ b/web-app/src/containers/ChannelCard.tsx@@ -7,29 +7,9 @@ import {IconTrash,} from '@tabler/icons-react'import { cn } from '@/lib/utils'+import type { ChannelType, ChannelConfig, TelegramConfig, WhatsAppConfig } from '@/types/openclaw'-export type ChannelType = 'telegram' | 'whatsapp'--// Channel configuration interfaces-export interface TelegramConfig {- bot_token: string- bot_username: string | null- connected: boolean- pairing_code: string | null- paired_users: number-}--export interface WhatsAppConfig {- account_id: string- session_path: string- connected: boolean- phone_number: string | null- qr_code: string | null- contacts_count: number-}--// Union type for all channel configs-export type ChannelConfig = TelegramConfig | WhatsAppConfig+export type { ChannelType, ChannelConfig, TelegramConfig, WhatsAppConfig }interface ChannelCardProps {type: ChannelType@@ -80,8 +60,6 @@ export function ChannelCard({const wa = config as WhatsAppConfigreturn wa.phone_number || ''}- default:- return ''}}@@ -93,7 +71,6 @@ export function ChannelCard({: 'border-border bg-card')}>- {/* Header */}<div className="flex items-center justify-between p-2 px-3"><div className="flex items-center gap-2"><div className="shrink-0">{getChannelIcon()}</div>@@ -140,7 +117,6 @@ export function ChannelCard({</div></div>- {/* Not Connected State */}{!isConnected && OCIsInstalled && (<div className="border-t border-border/40 px-4 py-3 bg-muted/30"><p className="text-xs text-muted-foreground">diff --git a/web-app/src/containers/dialogs/AddChannelDialog.tsx b/web-app/src/containers/dialogs/AddChannelDialog.tsxindex c96829fd7..abdc951f5 100644--- a/web-app/src/containers/dialogs/AddChannelDialog.tsx+++ b/web-app/src/containers/dialogs/AddChannelDialog.tsx@@ -11,11 +11,11 @@ import { Button } from '@/components/ui/button'import {IconBrandTelegram,IconBrandWhatsapp,- IconBrandDiscord,IconArrowRight,} from '@tabler/icons-react'+import type { ChannelType } from '@/types/openclaw'-export type ChannelType = 'telegram' | 'whatsapp' | 'discord'+export type { ChannelType }interface AddChannelDialogProps {isOpen: boolean@@ -59,12 +59,6 @@ export function AddChannelDialog({icon: <IconBrandWhatsapp size={32} className="text-green-500" />,description: t('settings:remoteAccess.channelDescriptions.whatsapp'),},- {- id: 'discord',- name: t('settings:remoteAccess.discord'),- icon: <IconBrandDiscord size={32} className="text-indigo-500" />,- description: t('settings:remoteAccess.channelDescriptions.discord'),- },]const handleChannelSelect = (channel: ChannelType) => {diff --git a/web-app/src/containers/dialogs/DiscordWizardDialog.tsx b/web-app/src/containers/dialogs/DiscordWizardDialog.tsxdeleted file mode 100644index f30b09566..000000000--- a/web-app/src/containers/dialogs/DiscordWizardDialog.tsx+++ /dev/null@@ -1,428 +0,0 @@-import { useState, useEffect } from 'react'-import { useTranslation } from '@/i18n/react-i18next-compat'-import { invoke } from '@tauri-apps/api/core'-import { toast } from 'sonner'-import {- IconBrandDiscord,- IconCheck,- IconArrowRight,- IconArrowLeft,- IconLoader2,- IconAlertCircle,-} from '@tabler/icons-react'-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@/components/ui/dialog'-import { Button } from '@/components/ui/button'-import { Input } from '@/components/ui/input'--// Types mirroring Rust backend-interface DiscordTokenValidation {- valid: boolean- bot_username: string | null- bot_discriminator: string | null- error: string | null-}--export interface DiscordConfig {- account_id: string- bot_token: string- bot_username: string | null- bot_discriminator: string | null- connected: boolean- guilds_count: number- channels_count: number-}--interface DiscordWizardDialogProps {- isOpen: boolean- onOpenChange: (open: boolean) => void- onConnected?: (config: DiscordConfig) => void-}--type WizardStep = 'instructions' | 'token' | 'configure' | 'success'--const TOTAL_STEPS = 4--export function DiscordWizardDialog({- isOpen,- onOpenChange,-}: DiscordWizardDialogProps) {- const { t } = useTranslation()- const [step, setStep] = useState<WizardStep>('instructions')- const [token, setToken] = useState('')- const [validation, setValidation] = useState<DiscordTokenValidation | null>(null)- const [isValidating, setIsValidating] = useState(false)- const [isConfiguring, setIsConfiguring] = useState(false)- const [config, setConfig] = useState<DiscordConfig | null>(null)-- // Reset state when dialog closes- useEffect(() => {- if (!isOpen) {- setStep('instructions')- setToken('')- setValidation(null)- setConfig(null)- }- }, [isOpen])-- const getStepNumber = (): number => {- const stepMap: Record<WizardStep, number> = {- instructions: 1,- token: 2,- configure: 3,- success: 4,- }- return stepMap[step]- }-- const handleValidateToken = async () => {- if (!token.trim()) {- toast.error(t('settings:remoteAccess.discordWizard.errors.tokenRequired'))- return- }-- setIsValidating(true)- try {- const result = await invoke<DiscordTokenValidation>('discord_validate_token', {- token: token.trim(),- })- setValidation(result)- if (result.valid) {- toast.success(- t('settings:remoteAccess.discordWizard.step2.validToken', {- username: result.bot_username,- })- )- } else {- toast.error(- result.error || t('settings:remoteAccess.discordWizard.step2.invalidToken')- )- }- } catch (error) {- console.error('Token validation error:', error)- toast.error(t('settings:remoteAccess.discordWizard.errors.networkError'))- } finally {- setIsValidating(false)- }- }-- const handleConfigure = async () => {- if (!validation?.valid) return-- setIsConfiguring(true)- try {- const result = await invoke<DiscordConfig>('discord_configure', {- token: token.trim(),- })- setConfig(result)- setStep('success')- toast.success(t('settings:remoteAccess.discordWizard.step3.success'))- } catch (error) {- console.error('Configure error:', error)- toast.error(- t('settings:remoteAccess.discordWizard.step3.error', {- error: error instanceof Error ? error.message : String(error),- })- )- } finally {- setIsConfiguring(false)- }- }-- const handleDisconnect = async () => {- try {- await invoke('discord_disconnect')- setConfig(null)- setToken('')- setValidation(null)- setStep('instructions')- toast.success(t('settings:remoteAccess.discordWizard.status.notConnected'))- } catch (error) {- console.error('Disconnect error:', error)- }- }-- const renderStepIndicator = () => {- const currentStep = getStepNumber()- return (- <div className="flex items-center justify-center gap-2 mb-6">- {Array.from({ length: TOTAL_STEPS }, (_, i) => (- <div- key={i}- className={`flex items-center justify-center w-8 h-8 rounded-full text-sm font-medium ${- i + 1 < currentStep- ? 'bg-green-500 text-white'- : i + 1 === currentStep- ? 'bg-primary text-primary-foreground'- : 'bg-secondary text-muted-foreground'- }`}- >- {i + 1 < currentStep ? (- <IconCheck size={16} />- ) : (- i + 1- )}- </div>- ))}- </div>- )- }-- const renderInstructionsStep = () => (- <div className="space-y-4">- <DialogDescription className="text-center">- {t('settings:remoteAccess.discordWizard.description')}- </DialogDescription>-- <div className="bg-secondary/50 rounded-lg p-4 space-y-3">- <h4 className="font-medium text-foreground">- {t('settings:remoteAccess.discordWizard.step1.title')}- </h4>- <ol className="list-decimal list-inside space-y-2 text-sm text-muted-foreground">- <li>{t('settings:remoteAccess.discordWizard.step1.instruction1')}</li>- <li>{t('settings:remoteAccess.discordWizard.step1.instruction2')}</li>- <li>{t('settings:remoteAccess.discordWizard.step1.instruction3')}</li>- <li>{t('settings:remoteAccess.discordWizard.step1.instruction4')}</li>- <li>{t('settings:remoteAccess.discordWizard.step1.instruction5')}</li>- </ol>- </div>-- <div className="flex justify-center">- <Button- variant="outline"- onClick={() => window.open('https://discord.com/developers/applications', '_blank')}- className="gap-2"- >- <IconBrandDiscord size={18} />- Open Discord Developer Portal- </Button>- </div>- </div>- )-- const renderTokenStep = () => (- <div className="space-y-4">- <DialogDescription className="text-center">- {t('settings:remoteAccess.discordWizard.step2.title')}- </DialogDescription>-- <div className="space-y-2">- <Input- type="password"- value={token}- onChange={(e) => {- setToken(e.target.value)- setValidation(null)- }}- placeholder={t('settings:remoteAccess.discordWizard.step2.placeholder')}- className="font-mono"- onKeyDown={(e) => {- if (e.key === 'Enter' && !isValidating) {- handleValidateToken()- }- }}- />- </div>-- {validation?.valid && (- <div className="flex items-center gap-2 text-green-500 text-sm">- <IconCheck size={16} />- <span>- {t('settings:remoteAccess.discordWizard.step2.validToken', {- username: validation.bot_username,- })}- </span>- </div>- )}-- {validation && !validation.valid && (- <div className="flex items-center gap-2 text-red-500 text-sm">- <IconAlertCircle size={16} />- <span>{validation.error}</span>- </div>- )}-- <Button- onClick={handleValidateToken}- disabled={isValidating || !token.trim()}- className="w-full"- >- {isValidating ? (- <>- <IconLoader2 className="animate-spin mr-2 h-4 w-4" />- {t('settings:remoteAccess.discordWizard.step2.validating')}- </>- ) : (- t('settings:remoteAccess.discordWizard.step2.validate')- )}- </Button>- </div>- )-- const renderConfigureStep = () => (- <div className="space-y-4">- <DialogDescription className="text-center">- {t('settings:remoteAccess.discordWizard.step3.title')}- </DialogDescription>-- <div className="flex flex-col items-center justify-center py-8">- <IconBrandDiscord size={48} className="text-indigo-500 mb-4" />- <p className="text-muted-foreground">- {isConfiguring- ? t('settings:remoteAccess.discordWizard.step3.connecting')- : validation?.bot_username- ? validation.bot_username- : ''}- </p>- </div>-- {isConfiguring && (- <div className="flex justify-center">- <IconLoader2 className="animate-spin h-8 w-8 text-primary" />- </div>- )}- </div>- )-- const renderSuccessStep = () => (- <div className="space-y-4">- <div className="flex flex-col items-center justify-center py-4">- <div className="w-16 h-16 rounded-full bg-green-500/20 flex items-center justify-center mb-4">- <IconCheck size={32} className="text-green-500" />- </div>- <DialogTitle className="text-center">- {t('settings:remoteAccess.discordWizard.step4.success')}- </DialogTitle>- </div>-- <DialogDescription className="text-center">- {t('settings:remoteAccess.discordWizard.step4.instruction')}- </DialogDescription>-- <div className="bg-secondary/50 rounded-lg p-4 text-center space-y-2">- {config?.bot_username && (- <p className="text-foreground">- {t('settings:remoteAccess.discordWizard.step4.botUsername', {- username: config.bot_username,- })}- </p>- )}- </div>-- <Button variant="outline" onClick={handleDisconnect} className="w-full">- {t('settings:remoteAccess.discordWizard.buttons.disconnect')}- </Button>- </div>- )-- const renderStep = () => {- switch (step) {- case 'instructions':- return renderInstructionsStep()- case 'token':- return renderTokenStep()- case 'configure':- return renderConfigureStep()- case 'success':- return renderSuccessStep()- default:- return null- }- }-- const handleNext = () => {- switch (step) {- case 'instructions':- setStep('token')- break- case 'token':- if (validation?.valid) {- setStep('configure')- handleConfigure()- }- break- case 'configure':- // Handled by configure function- break- case 'success':- onOpenChange(false)- break- }- }-- const handleBack = () => {- switch (step) {- case 'token':- setStep('instructions')- break- case 'configure':- setStep('token')- setValidation(null)- break- case 'success':- // Cannot go back from success- break- }- }-- const canGoNext = (): boolean => {- switch (step) {- case 'instructions':- return true- case 'token':- return validation?.valid ?? false- case 'configure':- return false // Auto-progresses- case 'success':- return true- default:- return false- }- }-- const canGoBack = (): boolean => {- return step !== 'instructions' && step !== 'success' && step !== 'configure'- }-- return (- <Dialog open={isOpen} onOpenChange={onOpenChange}>- <DialogContent className="sm:max-w-[480px] max-w-[90vw]">- <DialogHeader>- <div className="flex items-center justify-center gap-2 mb-2">- <IconBrandDiscord size={24} className="text-indigo-500" />- <DialogTitle>{t('settings:remoteAccess.discordWizard.title')}</DialogTitle>- </div>- </DialogHeader>-- {renderStepIndicator()}-- {renderStep()}-- {step !== 'configure' && step !== 'success' && (- <DialogFooter className="gap-2 sm:gap-0">- {canGoBack() && (- <Button variant="outline" onClick={handleBack} className="gap-1">- <IconArrowLeft size={16} />- {t('settings:remoteAccess.discordWizard.buttons.back')}- </Button>- )}- <Button- onClick={handleNext}- disabled={!canGoNext()}- className="gap-1"- >- {t('settings:remoteAccess.discordWizard.buttons.next')}- <IconArrowRight size={16} />- </Button>- </DialogFooter>- )}- </DialogContent>- </Dialog>- )-}\ No newline at end of filediff --git a/web-app/src/containers/dialogs/EnableProgressDialog.tsx b/web-app/src/containers/dialogs/EnableProgressDialog.tsxnew file mode 100644index 000000000..b55630854--- /dev/null+++ b/web-app/src/containers/dialogs/EnableProgressDialog.tsx@@ -0,0 +1,342 @@+import { useState, useEffect, useCallback } from 'react'+import { invoke } from '@tauri-apps/api/core'+import { listen } from '@tauri-apps/api/event'+import { toast } from 'sonner'+import {+ Dialog,+ DialogContent,+ DialogTitle,+ DialogDescription,+ DialogHeader,+} from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { Progress } from '@/components/ui/progress'+import {+ IconCheck,+ IconLoader2,+ IconAlertTriangle,+ IconExternalLink,+ IconRefresh,+} from '@tabler/icons-react'+import { setOpenClawRunningState, syncAllModelsToOpenClaw } from '@/utils/openclaw'+import { useModelProvider } from '@/hooks/useModelProvider'++interface EnableProgressEvent {+ step: string+ progress: number+ message: string+}++interface EnableResult {+ success: boolean+ already_installed: boolean+ steps_completed: string[]+ status: {+ installed: boolean+ running: boolean+ node_version: string | null+ openclaw_version: string | null+ port_available: boolean+ error: string | null+ }+}++interface EnableError {+ code: string+ message: string+ recovery: {+ label: string+ action: RecoveryAction+ description: string+ }[]+}++type RecoveryAction =+ | 'Retry'+ | 'OpenNodeDownload'+ | { UseDifferentPort: { port: number } }++interface EnableProgressDialogProps {+ isOpen: boolean+ onOpenChange: (open: boolean) => void+ onSuccess?: () => void+}++const STEP_LABELS: Record<string, string> = {+ checking_dependencies: 'Checking Node.js',+ checking_installation: 'Checking OpenClaw',+ installing: 'Installing OpenClaw',+ already_installed: 'OpenClaw installed',+ configuring: 'Configuring',+ starting: 'Starting gateway',+ syncing_models: 'Syncing models',+ complete: 'Complete',+}++function parseEnableError(errorStr: string): EnableError | null {+ try {+ return JSON.parse(errorStr) as EnableError+ } catch {+ return null+ }+}++export function EnableProgressDialog({+ isOpen,+ onOpenChange,+ onSuccess,+}: EnableProgressDialogProps) {+ const [progress, setProgress] = useState(0)+ const [message, setMessage] = useState('')+ const [completedSteps, setCompletedSteps] = useState<string[]>([])+ const [currentStep, setCurrentStep] = useState('')+ const [error, setError] = useState<EnableError | null>(null)+ const [isRunning, setIsRunning] = useState(false)+ const [isDone, setIsDone] = useState(false)++ const resetState = useCallback(() => {+ setProgress(0)+ setMessage('')+ setCompletedSteps([])+ setCurrentStep('')+ setError(null)+ setIsRunning(false)+ setIsDone(false)+ }, [])++ const runEnable = useCallback(async () => {+ resetState()+ setIsRunning(true)++ try {+ const result = await invoke<EnableResult>('openclaw_enable', {+ configInput: null,+ })++ if (result.success) {+ setOpenClawRunningState(true)+ // Sync models after gateway starts+ setProgress(95)+ setMessage('Syncing models...')+ setCurrentStep('syncing_models')+ try {+ const { providers, selectedModel } = useModelProvider.getState()+ await syncAllModelsToOpenClaw(providers, selectedModel?.id)+ } catch {+ // Non-fatal — models can be synced later+ }++ setProgress(100)+ setMessage('OpenClaw is ready!')+ setCurrentStep('complete')+ setIsDone(true)+ toast.success('Remote access enabled successfully')+ onSuccess?.()+ }+ } catch (err) {+ const errorStr = err instanceof Error ? err.message : String(err)+ const parsed = parseEnableError(errorStr)+ if (parsed) {+ setError(parsed)+ } else {+ setError({+ code: 'Unknown',+ message: errorStr,+ recovery: [+ {+ label: 'Retry',+ action: 'Retry',+ description: 'Try again.',+ },+ ],+ })+ }+ } finally {+ setIsRunning(false)+ }+ }, [resetState, onSuccess])++ // Listen for progress events+ useEffect(() => {+ if (!isOpen) return++ const unlisten = listen<EnableProgressEvent>(+ 'openclaw-enable-progress',+ (event) => {+ const { step, progress: p, message: msg } = event.payload+ setProgress(p)+ setMessage(msg)+ setCurrentStep(step)+ setCompletedSteps((prev) => {+ if (step !== prev[prev.length - 1]) {+ return [...prev, step]+ }+ return prev+ })+ }+ )++ return () => {+ unlisten.then((f) => f())+ }+ }, [isOpen])++ // Start the enable flow when dialog opens+ useEffect(() => {+ if (isOpen && !isRunning && !isDone && !error) {+ runEnable()+ }+ }, [isOpen, isRunning, isDone, error, runEnable])++ // Reset when dialog closes+ useEffect(() => {+ if (!isOpen) {+ resetState()+ }+ }, [isOpen, resetState])++ const handleRecoveryAction = (action: RecoveryAction) => {+ if (action === 'Retry') {+ setError(null)+ // runEnable will be triggered by the useEffect+ } else if (action === 'OpenNodeDownload') {+ window.open('https://nodejs.org/', '_blank')+ } else if (+ typeof action === 'object' &&+ 'UseDifferentPort' in action+ ) {+ // For now, retry is the main action - port config can be extended later+ setError(null)+ }+ }++ const allSteps = [+ 'checking_dependencies',+ 'checking_installation',+ 'installing',+ 'configuring',+ 'starting',+ 'complete',+ ]++ return (+ <Dialog open={isOpen} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>+ {error+ ? 'Setup Failed'+ : isDone+ ? 'Setup Complete'+ : 'Setting Up Remote Access'}+ </DialogTitle>+ <DialogDescription>+ {error+ ? 'An error occurred during setup.'+ : isDone+ ? 'OpenClaw is running and ready to use.'+ : 'Installing and configuring OpenClaw...'}+ </DialogDescription>+ </DialogHeader>++ <div className="space-y-4 py-2">+ {/* Progress bar */}+ {!error && (+ <div className="space-y-2">+ <Progress value={progress} />+ <p className="text-sm text-muted-foreground text-center">+ {message}+ </p>+ </div>+ )}++ {/* Step list */}+ {!error && (+ <div className="space-y-2">+ {allSteps.map((step) => {+ const isCompleted = completedSteps.includes(step)+ const isCurrent = currentStep === step && !isDone+ const label = STEP_LABELS[step] || step++ // Skip install step if it didn't happen+ if (+ step === 'installing' &&+ !completedSteps.includes('installing') &&+ completedSteps.includes('configuring')+ ) {+ return null+ }++ return (+ <div+ key={step}+ className="flex items-center gap-2 text-sm"+ >+ {isCompleted && !isCurrent ? (+ <IconCheck className="h-4 w-4 text-green-500 shrink-0" />+ ) : isCurrent ? (+ <IconLoader2 className="h-4 w-4 animate-spin text-primary shrink-0" />+ ) : (+ <div className="h-4 w-4 rounded-full border border-muted-foreground/30 shrink-0" />+ )}+ <span+ className={+ isCurrent+ ? 'text-foreground font-medium'+ : isCompleted+ ? 'text-muted-foreground'+ : 'text-muted-foreground/50'+ }+ >+ {label}+ </span>+ </div>+ )+ })}+ </div>+ )}++ {/* Error state */}+ {error && (+ <div className="space-y-3">+ <div className="flex items-start gap-2 rounded-md border border-destructive/50 bg-destructive/10 p-3">+ <IconAlertTriangle className="h-5 w-5 text-destructive shrink-0 mt-0.5" />+ <p className="text-sm text-destructive">{error.message}</p>+ </div>+ <div className="flex flex-col gap-2">+ {error.recovery.map((option, i) => (+ <Button+ key={i}+ variant="outline"+ size="sm"+ className="w-full justify-start"+ onClick={() => handleRecoveryAction(option.action)}+ >+ {option.action === 'OpenNodeDownload' ? (+ <IconExternalLink className="mr-2 h-4 w-4" />+ ) : (+ <IconRefresh className="mr-2 h-4 w-4" />+ )}+ {option.label}+ <span className="ml-auto text-xs text-muted-foreground">+ {option.description}+ </span>+ </Button>+ ))}+ </div>+ </div>+ )}++ {/* Done state - close button */}+ {isDone && (+ <div className="flex justify-end">+ <Button size="sm" onClick={() => onOpenChange(false)}>+ Done+ </Button>+ </div>+ )}+ </div>+ </DialogContent>+ </Dialog>+ )+}diff --git a/web-app/src/containers/dialogs/SecurityConfigDialog.tsx b/web-app/src/containers/dialogs/SecurityConfigDialog.tsxindex b2acab90a..0b71bb8ca 100644--- a/web-app/src/containers/dialogs/SecurityConfigDialog.tsx+++ b/web-app/src/containers/dialogs/SecurityConfigDialog.tsx@@ -125,8 +125,7 @@ export function SecurityConfigDialog({setStatus(result)setAuthMode(result.auth_mode)setRequirePairing(result.require_pairing)- } catch (error) {- console.error('Failed to fetch security status:', error)+ } catch {toast.error('Failed to load security settings')} finally {setIsLoadingStatus(false)@@ -139,8 +138,7 @@ export function SecurityConfigDialog({try {const result = await invoke<DeviceInfo[]>('security_get_devices')setDevices(result)- } catch (error) {- console.error('Failed to fetch devices:', error)+ } catch {toast.error('Failed to load devices')} finally {setIsLoadingDevices(false)@@ -153,8 +151,7 @@ export function SecurityConfigDialog({try {const result = await invoke<AccessLogEntry[]>('security_get_logs', { limit: 100 })setLogs(result)- } catch (error) {- console.error('Failed to fetch logs:', error)+ } catch {toast.error('Failed to load access logs')} finally {setIsLoadingLogs(false)@@ -204,8 +201,7 @@ export function SecurityConfigDialog({await fetchStatus()toast.success(`Authentication mode changed to ${newMode}`)onSave?.()- } catch (error) {- console.error('Failed to change auth mode:', error)+ } catch {toast.error('Failed to change authentication mode')} finally {setIsChangingAuthMode(false)@@ -223,8 +219,7 @@ export function SecurityConfigDialog({await fetchStatus()toast.success('New access token generated')onSave?.()- } catch (error) {- console.error('Failed to generate token:', error)+ } catch {toast.error('Failed to generate token')} finally {setIsGeneratingToken(false)@@ -239,8 +234,7 @@ export function SecurityConfigDialog({setTokenCopied(true)toast.success('Token copied to clipboard')setTimeout(() => setTokenCopied(false), 2000)- } catch (error) {- console.error('Failed to copy token:', error)+ } catch {toast.error('Failed to copy token')}}@@ -265,8 +259,7 @@ export function SecurityConfigDialog({await fetchStatus()toast.success('Password set successfully')onSave?.()- } catch (error) {- console.error('Failed to set password:', error)+ } catch {toast.error('Failed to set password')} finally {setIsSettingPassword(false)@@ -284,8 +277,7 @@ export function SecurityConfigDialog({enabled ? 'Device pairing required' : 'Device pairing disabled')onSave?.()- } catch (error) {- console.error('Failed to toggle pairing:', error)+ } catch {toast.error('Failed to update pairing setting')} finally {setIsTogglingPairing(false)@@ -301,8 +293,7 @@ export function SecurityConfigDialog({await fetchStatus()toast.success('Device access revoked')onSave?.()- } catch (error) {- console.error('Failed to revoke device:', error)+ } catch {toast.error('Failed to revoke device access')} finally {setRevokingDeviceId(null)@@ -317,8 +308,7 @@ export function SecurityConfigDialog({await invoke('security_clear_logs')setLogs([])toast.success('Access logs cleared')- } catch (error) {- console.error('Failed to clear logs:', error)+ } catch {toast.error('Failed to clear logs')} finally {setIsClearingLogs(false)diff --git a/web-app/src/containers/dialogs/TailscaleSetupDialog.tsx b/web-app/src/containers/dialogs/TailscaleSetupDialog.tsxindex e91524fd1..58998ba29 100644--- a/web-app/src/containers/dialogs/TailscaleSetupDialog.tsx+++ b/web-app/src/containers/dialogs/TailscaleSetupDialog.tsx@@ -83,8 +83,8 @@ export function TailscaleSetupDialog({try {const result = await invoke<TailscaleInfo>('tailscale_get_status')setInfo(result)- } catch (error) {- console.error('Failed to fetch Tailscale info:', error)+ } catch {+ // Info fetch may fail if Tailscale is not configured}}, [])@@ -102,7 +102,6 @@ export function TailscaleSetupDialog({await fetchTailscaleInfo()}} catch (error) {- console.error('Failed to detect Tailscale:', error)setErrorMessage(error instanceof Error ? error.message : 'Failed to detect Tailscale')@@ -144,7 +143,6 @@ export function TailscaleSetupDialog({}await fetchTailscaleInfo()} catch (error) {- console.error('Failed to configure Tailscale Serve:', error)toast.error(error instanceof Error? error.message@@ -170,7 +168,6 @@ export function TailscaleSetupDialog({}await fetchTailscaleInfo()} catch (error) {- console.error('Failed to configure Tailscale Funnel:', error)toast.error(error instanceof Error? error.messagediff --git a/web-app/src/containers/dialogs/TelegramWizardDialog.tsx b/web-app/src/containers/dialogs/TelegramWizardDialog.tsxindex 678e40a98..13dd92b38 100644--- a/web-app/src/containers/dialogs/TelegramWizardDialog.tsx+++ b/web-app/src/containers/dialogs/TelegramWizardDialog.tsx@@ -20,8 +20,8 @@ import {IconAlertCircle,IconExternalLink,} from '@tabler/icons-react'+import type { TelegramConfig } from '@/types/openclaw'-// Types mirroring Rust backendinterface TelegramTokenValidation {valid: booleanbot_username: string | null@@ -29,14 +29,6 @@ interface TelegramTokenValidation {error: string | null}-interface TelegramConfig {- bot_token: string- bot_username: string | null- connected: boolean- pairing_code: string | null- paired_users: number-}-interface TelegramWizardProps {isOpen: booleanonOpenChange: (open: boolean) => void@@ -107,8 +99,7 @@ export function TelegramWizard({result.error || t('settings:remoteAccess.telegramWizard.step2.invalidToken'))}- } catch (error) {- console.error('Token validation error:', error)+ } catch {toast.error(t('settings:remoteAccess.telegramWizard.errors.networkError'))} finally {setIsValidating(false)@@ -127,7 +118,6 @@ export function TelegramWizard({setStep('pairing')toast.success(t('settings:remoteAccess.telegramWizard.step3.success'))} catch (error) {- console.error('Configure error:', error)toast.error(t('settings:remoteAccess.telegramWizard.step3.error', {error: error instanceof Error ? error.message : String(error),@@ -157,7 +147,6 @@ export function TelegramWizard({onConnected(updatedConfig)}} catch (error) {- console.error('Pairing approval error:', error)const errorMsg = error instanceof Error ? error.message : String(error)toast.error(t('settings:remoteAccess.telegramWizard.step4.approveError', { error: errorMsg })@@ -182,8 +171,8 @@ export function TelegramWizard({setValidation(null)setStep('instructions')toast.success(t('settings:remoteAccess.telegramWizard.status.notConnected'))- } catch (error) {- console.error('Disconnect error:', error)+ } catch {+ // Disconnect may fail if already disconnected}}diff --git a/web-app/src/containers/dialogs/TunnelSelectionDialog.tsx b/web-app/src/containers/dialogs/TunnelSelectionDialog.tsxindex 86cfcc24c..291ef8e10 100644--- a/web-app/src/containers/dialogs/TunnelSelectionDialog.tsx+++ b/web-app/src/containers/dialogs/TunnelSelectionDialog.tsx@@ -31,8 +31,7 @@ import {IconAlertCircle,} from '@tabler/icons-react'-// Types mirroring Rust backend-type TunnelProvider = 'none' | 'tailscale' | 'ngrok' | 'cloudflare' | 'localonly'+import type { TunnelProvider } from '@/types/openclaw'interface TunnelProviderStatus {provider: TunnelProvider@@ -248,8 +247,7 @@ export function TunnelSelectionDialog({if (status.active_provider) {setSelectedProvider(status.active_provider)}- } catch (error) {- console.error('Failed to fetch tunnel providers status:', error)+ } catch {toast.error(t('settings:tunnel.fetchStatusError'))} finally {setIsDetecting(false)@@ -264,8 +262,8 @@ export function TunnelSelectionDialog({setNgrokToken(tunnelConfig.ngrok_auth_token || '')setCloudflareTunnelId(tunnelConfig.cloudflare_tunnel_id || '')setAutoStart(tunnelConfig.auto_start)- } catch (error) {- console.error('Failed to fetch tunnel config:', error)+ } catch {+ // Config may not exist yet}}, [])@@ -290,8 +288,7 @@ export function TunnelSelectionDialog({const status = await invoke<TunnelProvidersStatus>('tunnel_detect_all')setProvidersStatus(status)toast.success(t('settings:tunnel.detectionComplete'))- } catch (error) {- console.error('Failed to detect tunnel providers:', error)+ } catch {toast.error(t('settings:tunnel.detectionError'))} finally {setIsDetecting(false)@@ -311,8 +308,7 @@ export function TunnelSelectionDialog({await invoke('tunnel_set_ngrok_token', { token: ngrokToken.trim() })toast.success(t('settings:tunnel.ngrok.tokenSaved'))await fetchProvidersStatus()- } catch (error) {- console.error('Failed to save ngrok token:', error)+ } catch {toast.error(t('settings:tunnel.ngrok.tokenSaveError'))}}, [ngrokToken, t, fetchProvidersStatus])@@ -326,8 +322,7 @@ export function TunnelSelectionDialog({await invoke('tunnel_set_cloudflare_tunnel', { tunnelId: cloudflareTunnelId.trim() })toast.success(t('settings:tunnel.cloudflare.tunnelIdSaved'))await fetchProvidersStatus()- } catch (error) {- console.error('Failed to save Cloudflare tunnel ID:', error)+ } catch {toast.error(t('settings:tunnel.cloudflare.tunnelIdSaveError'))}}, [cloudflareTunnelId, t, fetchProvidersStatus])@@ -340,7 +335,6 @@ export function TunnelSelectionDialog({toast.success(t('settings:tunnel.startSuccess'))await fetchProvidersStatus()} catch (error) {- console.error('Failed to start tunnel:', error)const errorMsg = error instanceof Error ? error.message : String(error)toast.error(t('settings:tunnel.startError', { error: errorMsg }))} finally {@@ -355,8 +349,7 @@ export function TunnelSelectionDialog({toast.success(t('settings:tunnel.stopSuccess'))setShowStopConfirm(false)await fetchProvidersStatus()- } catch (error) {- console.error('Failed to stop tunnel:', error)+ } catch {toast.error(t('settings:tunnel.stopError'))} finally {setIsStopping(false)@@ -370,8 +363,7 @@ export function TunnelSelectionDialog({toast.success(t('settings:tunnel.saved'))onSave?.()onClose()- } catch (error) {- console.error('Failed to save tunnel settings:', error)+ } catch {toast.error(t('settings:tunnel.saveError'))} finally {setIsSaving(false)diff --git a/web-app/src/containers/dialogs/WhatsAppWizardDialog.tsx b/web-app/src/containers/dialogs/WhatsAppWizardDialog.tsxindex a608703b0..29f08de2e 100644--- a/web-app/src/containers/dialogs/WhatsAppWizardDialog.tsx+++ b/web-app/src/containers/dialogs/WhatsAppWizardDialog.tsx@@ -16,19 +16,11 @@ import {DialogFooter,} from '@/components/ui/dialog'import { Button } from '@/components/ui/button'+import type { WhatsAppConfig } from '@/types/openclaw'-// WhatsApp configuration types (mirroring Rust backend)-export interface WhatsAppConfig {- account_id: string- session_path: string- connected: boolean- phone_number: string | null- qr_code: string | null- contacts_count: number-}+export type { WhatsAppConfig }-// WhatsApp authentication status-export interface WhatsAppAuthStatus {+interface WhatsAppAuthStatus {in_progress: booleanqr_code_ready: booleanqr_code: string | null@@ -98,28 +90,17 @@ export function WhatsAppWizardDialog({setIsLoading(true)setErrorMessage(null)- // Show "setting up" step while OpenClaw is being configuredsetStep('setting_up')-- // Start WhatsApp authentication (this now handles all setup automatically)- // - Installs OpenClaw if needed- // - Starts the Gateway if not running- // - Configures allowed origins- // - Handles device pairing- // - Enables WhatsApp pluginconst status = await invoke<WhatsAppAuthStatus>('whatsapp_start_auth')setAuthStatus(status)- // Check if there was an error during setupif (status.error) {setErrorMessage(status.error)setStep('error')return}- // Check if already authenticated (WhatsApp was already linked)if (status.authenticated) {- // Get the final configconst whatsappConfig = await invoke<WhatsAppConfig>('whatsapp_get_config')setConfig(whatsappConfig)setStep('success')@@ -127,16 +108,13 @@ export function WhatsAppWizardDialog({return}- // Check if QR code is already available in the responseif (status.qr_code) {setQrCodeImage(status.qr_code)}- // Move to scanning stepsetStep('scanning')startPolling()} catch (error) {- console.error('Failed to start WhatsApp auth:', error)setErrorMessage(error instanceof Error ? error.message : String(error))@@ -147,37 +125,28 @@ export function WhatsAppWizardDialog({}, [])const startPolling = useCallback(() => {- // Poll for QR code and authentication statusconst interval = setInterval(async () => {try {const status = await invoke<WhatsAppAuthStatus>('whatsapp_check_auth')setAuthStatus(status)- // If we get a QR code, display itif (status.qr_code) {setQrCodeImage(status.qr_code)}- // If authenticated, stop polling and show successif (status.authenticated) {clearInterval(interval)setPollingInterval(null)setIsPolling(false)- // Get the final configconst whatsappConfig = await invoke<WhatsAppConfig>('whatsapp_get_config')setConfig(whatsappConfig)setStep('success')onConnected(whatsappConfig)}- // If there's an error, check if it's a fatal error or transient- // Transient errors (like 515 stream errors) should not stop polling- // as the connection often succeeds on retry- // "not linked" and "not configured" are not errors - they just mean waiting for QR scan+ // Only treat non-transient errors as fatalif (status.error && !status.in_progress) {- // Only stop polling if the error is final (not in progress anymore)- // Transient errors during connection attempts should be ignoredconst isFatalError = !status.error.includes('515') &&!status.error.includes('restart required') &&!status.error.includes('Stream Errored') &&@@ -190,13 +159,10 @@ export function WhatsAppWizardDialog({setIsPolling(false)setErrorMessage(status.error)setStep('error')- } else {- // Transient error, log it but keep polling- console.log('Transient WhatsApp error, continuing to poll:', status.error)}}- } catch (error) {- console.error('Polling error:', error)+ } catch {+ // Polling error — will retry on next interval}}, 2000)@@ -216,8 +182,7 @@ export function WhatsAppWizardDialog({setPollingInterval(null)}setIsPolling(false)- } catch (error) {- console.error('Failed to disconnect WhatsApp:', error)+ } catch {toast.error(t('settings:remoteAccess.disconnectError'))} finally {setIsLoading(false)diff --git a/web-app/src/containers/dialogs/index.ts b/web-app/src/containers/dialogs/index.tsindex c014f6753..30358b145 100644--- a/web-app/src/containers/dialogs/index.ts+++ b/web-app/src/containers/dialogs/index.ts@@ -11,4 +11,3 @@ export { AddProviderDialog } from './AddProviderDialog'export { SearchDialog } from './SearchDialog'export { TelegramWizard as TelegramWizardDialog } from './TelegramWizardDialog'export { WhatsAppWizardDialog } from './WhatsAppWizardDialog'-export { DiscordWizardDialog } from './DiscordWizardDialog'diff --git a/web-app/src/routes/settings/remote-access.tsx b/web-app/src/routes/settings/remote-access.tsxindex f141e6f9d..90b1b5b91 100644--- a/web-app/src/routes/settings/remote-access.tsx+++ b/web-app/src/routes/settings/remote-access.tsx@@ -5,12 +5,13 @@ import HeaderPage from '@/containers/HeaderPage'import { Button } from '@/components/ui/button'import { Card, CardItem } from '@/containers/Card'import { TelegramWizard as TelegramWizardDialog } from '@/containers/dialogs/TelegramWizardDialog'-import { WhatsAppWizardDialog, WhatsAppConfig } from '@/containers/dialogs/WhatsAppWizardDialog'-import { AddChannelDialog, ChannelType } from '@/containers/dialogs/AddChannelDialog'+import { WhatsAppWizardDialog } from '@/containers/dialogs/WhatsAppWizardDialog'+import { AddChannelDialog } from '@/containers/dialogs/AddChannelDialog'import { TailscaleSetupDialog } from '@/containers/dialogs/TailscaleSetupDialog'import { SecurityConfigDialog } from '@/containers/dialogs/SecurityConfigDialog'import { TunnelSelectionDialog } from '@/containers/dialogs/TunnelSelectionDialog'-import { ChannelCard, TelegramConfig as ChannelTelegramConfig, WhatsAppConfig as ChannelWhatsAppConfig } from '@/containers/ChannelCard'+import { EnableProgressDialog } from '@/containers/dialogs/EnableProgressDialog'+import { ChannelCard } from '@/containers/ChannelCard'import { useTranslation } from '@/i18n/react-i18next-compat'import { useEffect, useState, useCallback } from 'react'import { invoke } from '@tauri-apps/api/core'@@ -26,248 +27,127 @@ import {IconExternalLink,} from '@tabler/icons-react'import { cn } from '@/lib/utils'+import type {+ ChannelType,+ TelegramConfig,+ WhatsAppConfig,+ OpenClawStatus,+ TunnelProvider,+ TunnelProvidersStatus,+ SecurityStatus,+} from '@/types/openclaw'// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const Route = createFileRoute(route.settings.remote_access as any)({component: RemoteAccess,})-// OpenClaw Status types (mirroring Rust backend)-interface OpenClawStatus {- installed: boolean- running: boolean- node_version: string | null- openclaw_version: string | null- port_available: boolean- error: string | null-}--interface InstallResult {- success: boolean- version: string | null- error: string | null-}--// Telegram configuration-interface TelegramConfig {- bot_token: string- bot_username: string | null- connected: boolean- pairing_code: string | null- paired_users: number-}--const OPENCLAW_PORT = 18789-// Tunnel types (mirroring Rust backend)-type TunnelProvider = 'none' | 'tailscale' | 'ngrok' | 'cloudflare' | 'localonly'--interface TunnelInfo {- provider: TunnelProvider- url: string- started_at: string- port: number- is_public: boolean-}--interface TunnelProvidersStatus {- tailscale: { installed: boolean; authenticated: boolean; version: string | null }- ngrok: { installed: boolean; authenticated: boolean; version: string | null }- cloudflare: { installed: boolean; authenticated: boolean; version: string | null }- active_provider: TunnelProvider- active_tunnel: TunnelInfo | null-}--interface SecurityStatus {- auth_mode: 'token' | 'password' | 'none'- has_token: boolean- has_password: boolean- require_pairing: boolean- approved_device_count: number- recent_auth_failures: number-}--// Convert backend config types to ChannelCard types-const convertTelegramConfig = (config: TelegramConfig | null): ChannelTelegramConfig | null => {- if (!config) return null- return {- bot_token: config.bot_token,- bot_username: config.bot_username,- connected: config.connected,- pairing_code: config.pairing_code,- paired_users: config.paired_users,- }-}--const convertWhatsAppConfig = (config: WhatsAppConfig | null): ChannelWhatsAppConfig | null => {- if (!config) return null- return {- account_id: config.account_id,- session_path: config.session_path,- connected: config.connected,- phone_number: config.phone_number,- qr_code: config.qr_code,- contacts_count: config.contacts_count,- }-}-function RemoteAccess() {const { t } = useTranslation()const [status, setStatus] = useState<OpenClawStatus | null>(null)- const [, setIsLoading] = useState(true)const [isStarting, setIsStarting] = useState(false)const [isStopping, setIsStopping] = useState(false)- const [isInstalling, setIsInstalling] = useState(false)const [isTelegramWizardOpen, setIsTelegramWizardOpen] = useState(false)const [isWhatsAppWizardOpen, setIsWhatsAppWizardOpen] = useState(false)const [isAddChannelDialogOpen, setIsAddChannelDialogOpen] = useState(false)const [isTailscaleDialogOpen, setIsTailscaleDialogOpen] = useState(false)const [isSecurityDialogOpen, setIsSecurityDialogOpen] = useState(false)const [isTunnelDialogOpen, setIsTunnelDialogOpen] = useState(false)+ const [isEnableDialogOpen, setIsEnableDialogOpen] = useState(false)const [tunnelStatus, setTunnelStatus] = useState<TunnelProvidersStatus | null>(null)const [, setSecurityStatus] = useState<SecurityStatus | null>(null)const [telegramConfig, setTelegramConfig] = useState<TelegramConfig | null>(null)const [whatsappConfig, setWhatsAppConfig] = useState<WhatsAppConfig | null>(null)- // Fetch status on mountconst fetchStatus = useCallback(async () => {try {- setIsLoading(true)const statusData = await invoke<OpenClawStatus>('openclaw_status')setStatus(statusData)- // If OpenClaw is running, ensure Jan's origin is configured for WebSocket access- // This handles cases where OpenClaw was started externally+ // Ensure Jan's origin is configured when OpenClaw was started externallyif (statusData.running) {- await invoke('openclaw_ensure_jan_origin').catch((err) => {- console.debug('Failed to ensure Jan origin (may be expected):', err)- })+ await invoke('openclaw_ensure_jan_origin').catch(() => {})}- } catch (error) {- console.error('Failed to fetch OpenClaw status:', error)+ } catch {toast.error(t('settings:remoteAccess.startError'))- } finally {- setIsLoading(false)}}, [t])- useEffect(() => {- fetchStatus()- }, [fetchStatus])-- // Fetch Telegram config on mountconst fetchTelegramConfig = useCallback(async () => {try {const config = await invoke<TelegramConfig>('telegram_get_config')setTelegramConfig(config)- } catch (error) {- console.error('Failed to fetch Telegram config:', error)+ } catch {+ // Telegram may not be configured yet}}, [])- useEffect(() => {- fetchTelegramConfig()- }, [fetchTelegramConfig])-- const handleTelegramWizardConnected = useCallback((config: TelegramConfig) => {- setTelegramConfig(config)- }, [])-- const handleWhatsAppWizardConnected = useCallback((config: WhatsAppConfig) => {- setWhatsAppConfig(config)- }, [])-- // Fetch WhatsApp config on mountconst fetchWhatsAppConfig = useCallback(async () => {try {const config = await invoke<WhatsAppConfig>('whatsapp_get_config')setWhatsAppConfig(config)- } catch (error) {- console.error('Failed to fetch WhatsApp config:', error)+ } catch {+ // WhatsApp may not be configured yet}}, [])- useEffect(() => {- fetchWhatsAppConfig()- }, [fetchWhatsAppConfig])-- // Fetch tunnel status on mountconst fetchTunnelStatus = useCallback(async () => {try {const tunnelData = await invoke<TunnelProvidersStatus>('tunnel_get_providers')setTunnelStatus(tunnelData)- } catch (error) {- console.error('Failed to fetch tunnel status:', error)+ } catch {+ // Tunnel providers may not be available}}, [])- useEffect(() => {- fetchTunnelStatus()- }, [fetchTunnelStatus])-- // Fetch security status on mountconst fetchSecurityStatus = useCallback(async () => {try {const securityData = await invoke<SecurityStatus>('security_get_status')setSecurityStatus(securityData)- } catch (error) {- console.error('Failed to fetch security status:', error)+ } catch {+ // Security config may not be available}}, [])useEffect(() => {+ fetchStatus()+ fetchTelegramConfig()+ fetchWhatsAppConfig()+ fetchTunnelStatus()fetchSecurityStatus()- }, [fetchSecurityStatus])+ }, [fetchStatus, fetchTelegramConfig, fetchWhatsAppConfig, fetchTunnelStatus, fetchSecurityStatus])- // Refresh all status dataconst refreshAllStatus = useCallback(async () => {- await Promise.all([- fetchStatus(),- fetchTunnelStatus(),- fetchSecurityStatus(),- ])+ await Promise.all([fetchStatus(), fetchTunnelStatus(), fetchSecurityStatus()])}, [fetchStatus, fetchTunnelStatus, fetchSecurityStatus])- // Copy URL to clipboardconst handleCopyUrl = useCallback((url: string) => {navigator.clipboard.writeText(url)toast.success(t('settings:remoteAccess.urlCopied'))}, [t])- // Get display name for tunnel providerconst getTunnelProviderName = (provider: TunnelProvider): string => {switch (provider) {- case 'tailscale':- return 'Tailscale'- case 'ngrok':- return 'ngrok'- case 'cloudflare':- return 'Cloudflare Tunnel'- case 'localonly':- return t('settings:remoteAccess.localNetworkOnly')- case 'none':- default:- return t('settings:remoteAccess.notConfigured')+ case 'tailscale': return 'Tailscale'+ case 'ngrok': return 'ngrok'+ case 'cloudflare': return 'Cloudflare Tunnel'+ case 'localonly': return t('settings:remoteAccess.localNetworkOnly')+ default: return t('settings:remoteAccess.notConfigured')}}- // Bulk sync all models to OpenClaw after gateway startsconst 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`)- }+ await syncAllModelsToOpenClaw(providers, selectedModel?.id)}, [])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 catalogawait bulkSyncModels()toast.success(t('settings:remoteAccess.running'))await fetchStatus()@@ -289,68 +169,31 @@ function RemoteAccess() {try {setIsStopping(true)await invoke('openclaw_stop')- // The backend now verifies the port is released before returning,- // so we can trust this state update without re-fetching statussetOpenClawRunningState(false)setStatus((prev) => prev ? { ...prev, running: false } : prev)toast.success(t('settings:remoteAccess.stopped'))- } catch (error) {- console.error('Failed to stop OpenClaw:', error)+ } catch {toast.error(t('settings:remoteAccess.stopError'))} finally {setIsStopping(false)}}- const handleInstall = async () => {- try {- setIsInstalling(true)- const result = await invoke<InstallResult>('openclaw_install')- if (result.success) {- // Install now auto-configures and starts the Gateway- setOpenClawRunningState(true)- // Sync all models so OpenClaw knows the full catalog- await bulkSyncModels()- toast.success(t('settings:remoteAccess.backendInstallSuccess'))- await fetchStatus()- } else {- toast.error(result.error || t('settings:remoteAccess.installError'))- }- } catch (error) {- console.error('Failed to install OpenClaw:', error)- toast.error(t('settings:remoteAccess.installError'))- } finally {- setIsInstalling(false)- }- }-const getChannelName = (channel: string): string => {switch (channel) {- case 'telegram':- return t('settings:remoteAccess.telegram')- case 'whatsapp':- return t('settings:remoteAccess.whatsapp')- default:- return channel+ case 'telegram': return t('settings:remoteAccess.telegram')+ case 'whatsapp': return t('settings:remoteAccess.whatsapp')+ default: return channel}}- // Channel management handlersconst handleAddChannel = (channel: ChannelType) => {switch (channel) {- case 'telegram':- setIsTelegramWizardOpen(true)- break- case 'whatsapp':- setIsWhatsAppWizardOpen(true)- break+ case 'telegram': setIsTelegramWizardOpen(true); break+ case 'whatsapp': setIsWhatsAppWizardOpen(true); break}}- const handleChannelSettings = (channel: ChannelType) => {- handleAddChannel(channel)- }-const handleDisconnectChannel = async (channel: ChannelType) => {try {switch (channel) {@@ -366,13 +209,11 @@ function RemoteAccess() {toast.success(t('settings:remoteAccess.channelDisconnected', { channel: getChannelName(channel) }))- } catch (error) {- console.error(`Failed to disconnect ${channel}:`, error)+ } catch {toast.error(t('settings:remoteAccess.disconnectError'))}}- // Get connected channels listconst getConnectedChannels = (): ChannelType[] => {const channels: ChannelType[] = []if (telegramConfig?.connected) channels.push('telegram')@@ -396,9 +237,8 @@ function RemoteAccess() {<SettingsMenu /><div className="p-4 pt-0 w-full overflow-y-auto"><div className="flex flex-col justify-between gap-4 gap-y-3 w-full">- {/* Status Card */}<Card title={t('settings:remoteAccess.title')}>- <CardItem+ <CardItemtitle={t('settings:remoteAccess.status')}actions={<div className="flex items-center gap-2">@@ -447,26 +287,18 @@ function RemoteAccess() {{status?.node_version && (<CardItemtitle={t('settings:remoteAccess.nodeVersion')}- actions={- <span className="text-foreground">{status.node_version}</span>- }+ actions={<span className="text-foreground">{status.node_version}</span>}/>)}{status?.openclaw_version && (<CardItemtitle={t('settings:remoteAccess.openclawVersion')}- actions={- <span className="text-foreground">- {status.openclaw_version}- </span>- }+ actions={<span className="text-foreground">{status.openclaw_version}</span>}/>)}</Card>- {/* Quick Setup Card */}<Card title={t('settings:remoteAccess.quickSetup')}>- {/* Enable/Disable Remote Access */}<CardItemtitle={isRunning@@ -483,35 +315,18 @@ function RemoteAccess() {onClick={handleStop}disabled={isStopping}>- {isStopping && (- <IconLoader2 className="animate-spin size-4" />- )}+ {isStopping && <IconLoader2 className="animate-spin size-4" />}{t('settings:remoteAccess.stop')}</Button>) : (- <Button- size="sm"- onClick={handleStart}- disabled={isStarting}- >- {isStarting && (- <IconLoader2 className="animate-spin size-4" />- )}+ <Button size="sm" onClick={handleStart} disabled={isStarting}>+ {isStarting && <IconLoader2 className="animate-spin size-4" />}{t('settings:remoteAccess.start')}</Button>)) : (- <Button- variant="secondary"- size="sm"- onClick={handleInstall}- disabled={isInstalling}- >- {isInstalling ? (- <IconLoader2 className="animate-spin size-4 text-muted-foreground" />- ) : (- <IconPlugConnected className="size-4 text-muted-foreground" />- )}+ <Button variant="secondary" size="sm" onClick={() => setIsEnableDialogOpen(true)}>+ <IconPlugConnected className="size-4 text-muted-foreground" />{t('settings:remoteAccess.install')}</Button>)}@@ -519,7 +334,6 @@ function RemoteAccess() {}/>- {/* Connect Channels - New Unified Channel Management */}<CardItemtitle={t('settings:remoteAccess.channels')}actions={@@ -534,25 +348,23 @@ function RemoteAccess() {}/>- {/* Channel Cards */}<div className="space-y-3 mt-4"><ChannelCardtype="telegram"- config={convertTelegramConfig(telegramConfig)}- onSettings={() => handleChannelSettings('telegram')}+ config={telegramConfig}+ onSettings={() => handleAddChannel('telegram')}onDisconnect={() => handleDisconnectChannel('telegram')}OCIsInstalled={isInstalled}/><ChannelCardtype="whatsapp"- config={convertWhatsAppConfig(whatsappConfig)}- onSettings={() => handleChannelSettings('whatsapp')}+ config={whatsappConfig}+ onSettings={() => handleAddChannel('whatsapp')}onDisconnect={() => handleDisconnectChannel('whatsapp')}OCIsInstalled={isInstalled}/></div>- {/* Share Access */}<CardItemtitle={t('settings:remoteAccess.shareAccess')}className='mt-5'@@ -565,7 +377,6 @@ function RemoteAccess() {/></Card>- {/* Active Tunnel Status Card */}{tunnelStatus?.active_tunnel && (<Card title={t('settings:remoteAccess.activeTunnel')}><div className="flex items-center gap-3 mb-4">@@ -613,48 +424,36 @@ function RemoteAccess() {/></Card>)}-</div></div></div>- {/* Telegram Wizard Dialog */}<TelegramWizardDialogisOpen={isTelegramWizardOpen}onOpenChange={setIsTelegramWizardOpen}- onConnected={handleTelegramWizardConnected}+ onConnected={setTelegramConfig}/>-- {/* WhatsApp Wizard Dialog */}<WhatsAppWizardDialogisOpen={isWhatsAppWizardOpen}onOpenChange={setIsWhatsAppWizardOpen}- onConnected={handleWhatsAppWizardConnected}+ onConnected={setWhatsAppConfig}/>-- {/* Add Channel Dialog */}<AddChannelDialogisOpen={isAddChannelDialogOpen}onOpenChange={setIsAddChannelDialogOpen}onSelectChannel={handleAddChannel}connectedChannels={getConnectedChannels()}/>-- {/* Tailscale Setup Dialog */}<TailscaleSetupDialogisOpen={isTailscaleDialogOpen}onClose={() => setIsTailscaleDialogOpen(false)}onSuccess={refreshAllStatus}/>-- {/* Security Config Dialog */}<SecurityConfigDialogisOpen={isSecurityDialogOpen}onClose={() => setIsSecurityDialogOpen(false)}onSave={refreshAllStatus}/>-- {/* Tunnel Selection Dialog */}<TunnelSelectionDialogisOpen={isTunnelDialogOpen}onClose={() => setIsTunnelDialogOpen(false)}@@ -664,6 +463,11 @@ function RemoteAccess() {}}onSave={refreshAllStatus}/>+ <EnableProgressDialog+ isOpen={isEnableDialogOpen}+ onOpenChange={setIsEnableDialogOpen}+ onSuccess={fetchStatus}+ /></div>)-}\ No newline at end of file+}diff --git a/web-app/src/types/openclaw.ts b/web-app/src/types/openclaw.tsnew file mode 100644index 000000000..e50c1c9fa--- /dev/null+++ b/web-app/src/types/openclaw.ts@@ -0,0 +1,61 @@+/**+ * Shared types for the OpenClaw remote access integration.+ * These mirror the Rust backend types in src-tauri/src/core/openclaw/models.rs.+ */++export type ChannelType = 'telegram' | 'whatsapp'++export interface TelegramConfig {+ bot_token: string+ bot_username: string | null+ connected: boolean+ pairing_code: string | null+ paired_users: number+}++export interface WhatsAppConfig {+ account_id: string+ session_path: string+ connected: boolean+ phone_number: string | null+ qr_code: string | null+ contacts_count: number+}++export type ChannelConfig = TelegramConfig | WhatsAppConfig++export interface OpenClawStatus {+ installed: boolean+ running: boolean+ node_version: string | null+ openclaw_version: string | null+ port_available: boolean+ error: string | null+}++export type TunnelProvider = 'none' | 'tailscale' | 'ngrok' | 'cloudflare' | 'localonly'++export interface TunnelInfo {+ provider: TunnelProvider+ url: string+ started_at: string+ port: number+ is_public: boolean+}++export interface TunnelProvidersStatus {+ tailscale: { installed: boolean; authenticated: boolean; version: string | null }+ ngrok: { installed: boolean; authenticated: boolean; version: string | null }+ cloudflare: { installed: boolean; authenticated: boolean; version: string | null }+ active_provider: TunnelProvider+ active_tunnel: TunnelInfo | null+}++export interface SecurityStatus {+ auth_mode: 'token' | 'password' | 'none'+ has_token: boolean+ has_password: boolean+ require_pairing: boolean+ approved_device_count: number+ recent_auth_failures: number+}diff --git a/web-app/src/utils/openclaw.ts b/web-app/src/utils/openclaw.tsindex 516803165..21b395767 100644--- a/web-app/src/utils/openclaw.ts+++ b/web-app/src/utils/openclaw.ts@@ -1,26 +1,12 @@import { invoke } from '@tauri-apps/api/core'-// Cache the OpenClaw running state to avoid repeated IPC calls-// This is updated when:-// 1. User enables/disables Remote Access in settings-// 2. On app startup if Remote Access was previously enabledlet openClawRunningCache: boolean | null = nulllet lastCheckTime = 0-const CACHE_TTL_MS = 30000 // Re-check every 30 seconds at most+const CACHE_TTL_MS = 30_000-/**- * Check if OpenClaw is running (with caching to avoid excessive IPC calls)- *- * This function is designed to be cheap to call frequently.- * It caches the result and only makes an IPC call if:- * - The cache is empty (first call)- * - The cache is stale (older than 30 seconds)- * - forceRefresh is true- */+/** Check if OpenClaw is running, with a 30s cache to avoid excessive IPC calls. */export async function isOpenClawRunning(forceRefresh = false): Promise<boolean> {const now = Date.now()-- // Return cached value if freshif (!forceRefresh && openClawRunningCache !== null && (now - lastCheckTime) < CACHE_TTL_MS) {return openClawRunningCache}@@ -31,34 +17,25 @@ export async function isOpenClawRunning(forceRefresh = false): Promise<boolean>lastCheckTime = nowreturn status.running} catch {- // If the invoke fails, OpenClaw is likely not installedopenClawRunningCache = falselastCheckTime = nowreturn false}}-/**- * Update the OpenClaw running cache directly- * Called from the Remote Access settings page when user enables/disables OpenClaw- */+/** Update the running cache directly (called when user enables/disables OpenClaw). */export function setOpenClawRunningState(isRunning: boolean): void {openClawRunningCache = isRunninglastCheckTime = Date.now()}-/**- * Clear the OpenClaw cache (e.g., on app startup)- */+/** Clear the cache (e.g., on app startup). */export function clearOpenClawCache(): void {openClawRunningCache = nulllastCheckTime = 0}-/**- * Get cached OpenClaw state without making an IPC call- * Returns null if cache is empty/stale- */+/** Get cached state without IPC. Returns null if stale. */export function getOpenClawRunningCached(): boolean | null {const now = Date.now()if (openClawRunningCache !== null && (now - lastCheckTime) < CACHE_TTL_MS) {@@ -68,17 +45,8 @@ export function getOpenClawRunningCached(): boolean | null {}/**- * Sync the selected model from Jan to OpenClaw- * This allows OpenClaw to use the same model that Jan is using- *- * This function is designed to have minimal impact on users who don't use OpenClaw:- * - It first checks a cached state (no IPC call)- * - Only makes IPC calls if OpenClaw is known to be running- * - Fails silently if OpenClaw is not available- *- * @param modelId - The model ID (e.g., "minimax-m2.5")- * @param provider - The provider name (e.g., "minimaxai", "openai", "llamacpp")- * @param modelName - Optional display name for the model+ * Sync the selected model to OpenClaw. Skips silently if OpenClaw is not running.+ * Designed to have minimal impact on users who don't use OpenClaw.*/export async function syncModelToOpenClaw(modelId: string,@@ -86,60 +54,38 @@ export async function syncModelToOpenClaw(modelName?: string): Promise<void> {try {- // Quick check: if we know OpenClaw is not running, skip entirelyconst cachedState = getOpenClawRunningCached()- if (cachedState === false) {- // We know OpenClaw is not running, skip without any IPC call- return- }+ if (cachedState === false) return- // If cache is null/stale, do a fresh checkconst running = await isOpenClawRunning()- if (!running) {- console.debug('[OpenClaw] Not running, skipping model sync')- return- }+ if (!running) returnawait invoke('openclaw_sync_model', {modelId,provider: provider || null,modelName: modelName || null,})- console.debug('[OpenClaw] Model synced:', modelId, provider)- } catch (error) {- // Don't throw - this is a background sync operation- console.debug('[OpenClaw] Failed to sync model:', error)+ } catch {+ // Background sync — fail silently}}/*** 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+ * Called after Remote Access starts so OpenClaw knows the full catalog.*/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- }> = []+ 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.modelif (!modelId || typeof modelId !== 'string') continue- // Skip embedding models — they're not usable for chatif (model.embedding) continuemodels.push({@@ -150,37 +96,22 @@ export async function syncAllModelsToOpenClaw(}}- if (models.length === 0) {- console.debug('[OpenClaw] No models to sync')- return 0- }+ if (models.length === 0) return 0const 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'}`+ { models, defaultModelId: selectedModelId || null })return result.synced_count- } catch (error) {- // Don't throw - this is a background sync operation- console.debug('[OpenClaw] Failed to bulk sync models:', error)+ } catch {return 0}}-/**- * Get the currently configured model in OpenClaw- */+/** Get the currently configured model in OpenClaw. */export async function getOpenClawModel(): Promise<string | null> {try {- const model = await invoke<string>('openclaw_get_model')- return model+ return await invoke<string>('openclaw_get_model')} catch {return null}