All files / src/store connectionStore.ts

11.07% Statements 32/289
100% Branches 2/2
5.55% Functions 1/18
11.07% Lines 32/289

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 4971x                                                                       1x                                                                       1x                                                                                                                                                                                                               1x     1x     1x         1x           1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x                                                                                                                                                                                                                                                                                                                 1x                 1x   1x                                               1x                                               1x                                               1x                                             1x 1x             1x         1x         1x         1x         1x  
import { create } from 'zustand';
import {
  DEFAULT_GATEWAY_URL,
  FALLBACK_GATEWAY_URLS,
  GatewayClient,
  ConnectionState,
  getGatewayClient,
  getStoredGatewayToken,
  getStoredGatewayUrl,
  setStoredGatewayUrl,
} from '../lib/gateway-client';
import {
  isTauriRuntime,
  getLocalGatewayStatus as fetchLocalGatewayStatus,
  startLocalGateway as startLocalGatewayCommand,
  stopLocalGateway as stopLocalGatewayCommand,
  restartLocalGateway as restartLocalGatewayCommand,
  getUnsupportedLocalGatewayStatus,
  type LocalGatewayStatus,
} from '../lib/tauri-gateway';
import {
  KernelClient,
  getKernelClient,
} from '../lib/kernel-client';
import {
  type HealthCheckResult,
  type HealthStatus,
} from '../lib/health-check';
import { useConfigStore } from './configStore';
 
// === Mode Selection ===
// IMPORTANT: Check isTauriRuntime() at RUNTIME (inside functions), not at module load time.
// At module load time, window.__TAURI_INTERNALS__ may not be set yet by Tauri.
 
// === Custom Models Helpers ===
 
const CUSTOM_MODELS_STORAGE_KEY = 'zclaw-custom-models';
 
interface CustomModel {
  id: string;
  name: string;
  provider: string;
  apiKey?: string;
  apiProtocol: 'openai' | 'anthropic' | 'custom';
  baseUrl?: string;
  isDefault?: boolean;
  createdAt: string;
}
 
/**
 * Get custom models from localStorage
 */
function loadCustomModels(): CustomModel[] {
  try {
    const stored = localStorage.getItem(CUSTOM_MODELS_STORAGE_KEY);
    if (stored) {
      return JSON.parse(stored);
    }
  } catch (err) {
    console.error('[connectionStore] Failed to parse models:', err);
  }
  return [];
}
 
/**
 * Get the default model configuration
 *
 * Priority:
 * 1. Model with isDefault: true
 * 2. Model matching chatStore's currentModel
 * 3. First model in the list
 */
export function getDefaultModelConfig(): { provider: string; model: string; apiKey: string; baseUrl: string; apiProtocol: string } | null {
  const models = loadCustomModels();
 
  // Priority 1: Find model with isDefault: true
  let defaultModel = models.find(m => m.isDefault === true);
 
  // Priority 2: Find model matching chatStore's currentModel
  if (!defaultModel) {
    try {
      const chatStoreData = localStorage.getItem('zclaw-chat-storage');
      if (chatStoreData) {
        const parsed = JSON.parse(chatStoreData);
        const currentModelId = parsed?.state?.currentModel;
        if (currentModelId) {
          defaultModel = models.find(m => m.id === currentModelId);
        }
      }
    } catch (err) {
      console.warn('[connectionStore] Failed to read chatStore:', err);
    }
  }
 
  // Priority 3: First model
  if (!defaultModel) {
    defaultModel = models[0];
  }
 
  if (defaultModel) {
    return {
      provider: defaultModel.provider,
      model: defaultModel.id,
      apiKey: defaultModel.apiKey || '',
      baseUrl: defaultModel.baseUrl || '',
      apiProtocol: defaultModel.apiProtocol || 'openai',
    };
  }
 
  return null;
}
 
// === Types ===
 
export interface GatewayLog {
  timestamp: number;
  level: string;
  message: string;
}
 
// === Helper Functions ===
 
/**
 * Check if an error indicates we connection should retry with another candidate.
 */
function shouldRetryGatewayCandidate(error: unknown): boolean {
  const message = error instanceof Error ? error.message : String(error || '');
  return (
    message === 'WebSocket connection failed'
    || message.startsWith('Gateway handshake timed out')
    || message.startsWith('WebSocket closed before handshake completed')
  || message.startsWith('Connection refused')
    || message.includes('ECONNREFUSED')
  || message.includes('Failed to fetch')
  || message.includes('Network error')
  || message.includes('pairing required')
  );
}
 
/**
 * Normalize a gateway URL candidate.
 */
function normalizeGatewayUrlCandidate(url: string): string {
  return url.trim().replace(/\/+$/, '');
}
 
// === Store Interface ===
 
export interface ConnectionStateSlice {
  connectionState: ConnectionState;
  gatewayVersion: string | null;
  error: string | null;
  logs: GatewayLog[];
  localGateway: LocalGatewayStatus;
  localGatewayBusy: boolean;
  isLoading: boolean;
  healthStatus: HealthStatus;
  healthCheckResult: HealthCheckResult | null;
}
 
export interface ConnectionActionsSlice {
  connect: (url?: string, token?: string) => Promise<void>;
  disconnect: () => void;
  clearLogs: () => void;
  refreshLocalGateway: () => Promise<LocalGatewayStatus>;
  startLocalGateway: () => Promise<LocalGatewayStatus | undefined>;
  stopLocalGateway: () => Promise<LocalGatewayStatus | undefined>;
  restartLocalGateway: () => Promise<LocalGatewayStatus | undefined>;
}
 
export interface ConnectionStore extends ConnectionStateSlice, ConnectionActionsSlice {
  client: GatewayClient | KernelClient;
}
 
// === Store Implementation ===
 
export const useConnectionStore = create<ConnectionStore>((set, get) => {
  // Initialize with external gateway client by default.
  // Will switch to internal kernel client at connect time if in Tauri.
  const client: GatewayClient | KernelClient = getGatewayClient();
 
  // Wire up state change callback
  client.onStateChange = (state: ConnectionState) => {
    set({ connectionState: state });
  };
 
  // Wire up log callback
  client.onLog = (level, message) => {
    set((s) => ({
      logs: [...s.logs.slice(-99), { timestamp: Date.now(), level, message }],
    }));
  };
 
  return {
    // === Initial State ===
    connectionState: 'disconnected',
    gatewayVersion: null,
    error: null,
    logs: [],
    localGateway: getUnsupportedLocalGatewayStatus(),
    localGatewayBusy: false,
    isLoading: false,
    healthStatus: 'unknown',
    healthCheckResult: null,
    client,
 
    // === Actions ===
 
    connect: async (url?: string, token?: string) => {
      try {
        set({ error: null });
 
        // === Internal Kernel Mode (Tauri) ===
        // Check at RUNTIME, not at module load time, to ensure __TAURI_INTERNALS__ is available
        const useInternalKernel = isTauriRuntime();
        console.log('[ConnectionStore] isTauriRuntime():', useInternalKernel);
 
        if (useInternalKernel) {
          console.log('[ConnectionStore] Using internal ZCLAW Kernel (no external process needed)');
          const kernelClient = getKernelClient();
 
          // Get model config from custom models settings
          const modelConfig = getDefaultModelConfig();
 
          if (!modelConfig) {
            throw new Error('请先在"模型与 API"设置页面添加自定义模型配置');
          }
 
          if (!modelConfig.apiKey) {
            throw new Error(`模型 ${modelConfig.model} 未配置 API Key,请在"模型与 API"设置页面配置`);
          }
 
          console.log('[ConnectionStore] Model config:', {
            provider: modelConfig.provider,
            model: modelConfig.model,
            hasApiKey: !!modelConfig.apiKey,
            baseUrl: modelConfig.baseUrl,
            apiProtocol: modelConfig.apiProtocol,
          });
 
          kernelClient.setConfig({
            provider: modelConfig.provider,
            model: modelConfig.model,
            apiKey: modelConfig.apiKey,
            baseUrl: modelConfig.baseUrl,
            apiProtocol: modelConfig.apiProtocol,
          });
 
          // Wire up state change callback
          kernelClient.onStateChange = (state: ConnectionState) => {
            set({ connectionState: state });
          };
 
          // Wire up log callback
          kernelClient.onLog = (level, message) => {
            set((s) => ({
              logs: [...s.logs.slice(-99), { timestamp: Date.now(), level, message }],
            }));
          };
 
          // Update the stored client reference
          set({ client: kernelClient });
 
          // Re-inject client to all stores so they get the kernel client
          const { initializeStores } = await import('./index');
          initializeStores();
 
          // Connect to internal kernel
          await kernelClient.connect();
 
          // Set version
          set({ gatewayVersion: '0.2.0-internal' });
 
          console.log('[ConnectionStore] Connected to internal ZCLAW Kernel');
          return;
        }
 
        // === External Gateway Mode (non-Tauri or fallback) ===
        const c = get().client;
 
        // Resolve connection URL candidates
        const resolveCandidates = async (): Promise<string[]> => {
          const explicitUrl = url?.trim();
          if (explicitUrl) {
            return [normalizeGatewayUrlCandidate(explicitUrl)];
          }
 
          const candidates: string[] = [];
 
          // Add quick config gateway URL if available
          const quickConfigGatewayUrl = useConfigStore.getState().quickConfig?.gatewayUrl?.trim();
          if (quickConfigGatewayUrl) {
            candidates.push(quickConfigGatewayUrl);
          }
 
          // Add stored URL, default, and fallbacks
          candidates.push(
            getStoredGatewayUrl(),
            DEFAULT_GATEWAY_URL,
            ...FALLBACK_GATEWAY_URLS
          );
 
          // Return unique, non-empty candidates
          return Array.from(
            new Set(
              candidates
                .filter(Boolean)
                .map(normalizeGatewayUrlCandidate)
            )
          );
        };
 
        // Resolve effective token
        const effectiveToken = token || useConfigStore.getState().quickConfig?.gatewayToken || getStoredGatewayToken();
        console.log('[ConnectionStore] Connecting with token:', effectiveToken ? '[REDACTED]' : '(empty)');
 
        const candidateUrls = await resolveCandidates();
        let lastError: unknown = null;
        let connectedUrl: string | null = null;
 
        // Try each candidate URL
        for (const candidateUrl of candidateUrls) {
          try {
            c.updateOptions({
              url: candidateUrl,
              token: effectiveToken,
            });
            await c.connect();
            connectedUrl = candidateUrl;
            break;
          } catch (err) {
            lastError = err;
 
            // Check if we should try next candidate
            if (!shouldRetryGatewayCandidate(err)) {
              throw err;
            }
          }
        }
 
        if (!connectedUrl) {
          throw (lastError instanceof Error ? lastError : new Error('Failed to connect to any available Gateway'));
        }
 
        // Store successful URL
        setStoredGatewayUrl(connectedUrl);
 
        // Fetch gateway version
        try {
          const health = await c.health();
          set({ gatewayVersion: health?.version });
        } catch { /* health may not return version */ }
 
        console.log('[ConnectionStore] Connected to:', connectedUrl);
      } catch (err: unknown) {
        const errorMessage = err instanceof Error ? err.message : String(err);
        set({ error: errorMessage });
        throw err;
      }
    },
 
    disconnect: () => {
      get().client.disconnect();
      set({
        connectionState: 'disconnected',
        gatewayVersion: null,
        error: null,
      });
    },
 
    clearLogs: () => set({ logs: [] }),
 
    refreshLocalGateway: async () => {
      if (!isTauriRuntime()) {
        const unsupported = getUnsupportedLocalGatewayStatus();
        set({ localGateway: unsupported, localGatewayBusy: false });
        return unsupported;
      }
 
      set({ localGatewayBusy: true });
      try {
        const status = await fetchLocalGatewayStatus();
        set({ localGateway: status, localGatewayBusy: false });
        return status;
      } catch (err: unknown) {
        const message = err instanceof Error ? err.message : 'Failed to read local Gateway status';
        const nextStatus = {
          ...get().localGateway,
          supported: true,
          error: message,
        };
        set({ localGateway: nextStatus, localGatewayBusy: false, error: message });
        return nextStatus;
      }
    },
 
    startLocalGateway: async () => {
      if (!isTauriRuntime()) {
        const unsupported = getUnsupportedLocalGatewayStatus();
        set({ localGateway: unsupported, localGatewayBusy: false });
        return unsupported;
      }
 
      set({ localGatewayBusy: true, error: null });
      try {
        const status = await startLocalGatewayCommand();
        set({ localGateway: status, localGatewayBusy: false });
        return status;
      } catch (err: unknown) {
        const message = err instanceof Error ? err.message : 'Failed to start local Gateway';
        const nextStatus = {
          ...get().localGateway,
          supported: true,
          error: message,
        };
        set({ localGateway: nextStatus, localGatewayBusy: false, error: message });
        return undefined;
      }
    },
 
    stopLocalGateway: async () => {
      if (!isTauriRuntime()) {
        const unsupported = getUnsupportedLocalGatewayStatus();
        set({ localGateway: unsupported, localGatewayBusy: false });
        return unsupported;
      }
 
      set({ localGatewayBusy: true, error: null });
      try {
        const status = await stopLocalGatewayCommand();
        set({ localGateway: status, localGatewayBusy: false });
        return status;
      } catch (err: unknown) {
        const message = err instanceof Error ? err.message : 'Failed to stop local Gateway';
        const nextStatus = {
          ...get().localGateway,
          supported: true,
          error: message,
        };
        set({ localGateway: nextStatus, localGatewayBusy: false, error: message });
        return undefined;
      }
    },
 
    restartLocalGateway: async () => {
      if (!isTauriRuntime()) {
        const unsupported = getUnsupportedLocalGatewayStatus();
        set({ localGateway: unsupported, localGatewayBusy: false });
        return unsupported;
      }
 
      set({ localGatewayBusy: true, error: null });
      try {
        const status = await restartLocalGatewayCommand();
        set({ localGateway: status, localGatewayBusy: false });
        return status;
      } catch (err: unknown) {
        const message = err instanceof Error ? err.message : 'Failed to restart local Gateway';
        const nextStatus = {
          ...get().localGateway,
          supported: true,
          error: message,
        };
        set({ localGateway: nextStatus, localGatewayBusy: false, error: message });
        return undefined;
      }
    },
  };
});
 
// === Exported Accessors for Coordinator ===
 
/**
 * Get current connection state.
 */
export const getConnectionState = () => useConnectionStore.getState().connectionState;
 
/**
 * Get gateway client instance.
 */
export const getClient = () => useConnectionStore.getState().client;
 
/**
 * Get current error message.
 */
export const getConnectionError = () => useConnectionStore.getState().error;
 
/**
 * Get local gateway status.
 */
export const getLocalGatewayStatus = () => useConnectionStore.getState().localGateway;
 
/**
 * Get gateway version.
 */
export const getGatewayVersion = () => useConnectionStore.getState().gatewayVersion;