settings-validation.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /**
  2. * Provider selection validation utilities.
  3. *
  4. * Pure functions used by fetchServerProviders() to detect and fix
  5. * stale provider/model selections after server config changes.
  6. */
  7. export type ProviderCfgLike = {
  8. isServerConfigured?: boolean;
  9. apiKey?: string;
  10. };
  11. /** Check whether a provider has a usable path (server config or client key). */
  12. export function isProviderUsable(cfg: ProviderCfgLike | undefined): boolean {
  13. if (!cfg) return false;
  14. return !!cfg.isServerConfigured || !!cfg.apiKey;
  15. }
  16. /**
  17. * Validate current provider selection against updated config.
  18. * Returns the current ID if still usable, otherwise the first usable
  19. * provider from fallbackOrder, or defaultId if provided, or ''.
  20. */
  21. export function validateProvider<T extends string>(
  22. currentId: T | '',
  23. configMap: Partial<Record<T, ProviderCfgLike>>,
  24. fallbackOrder: T[],
  25. defaultId?: T,
  26. ): T | '' {
  27. if (!currentId) return currentId;
  28. if (isProviderUsable(configMap[currentId])) return currentId;
  29. for (const id of fallbackOrder) {
  30. if (isProviderUsable(configMap[id])) return id;
  31. }
  32. return defaultId ?? '';
  33. }
  34. /**
  35. * Validate current model selection against available models list.
  36. * Falls back to first available model, or '' if list is empty.
  37. */
  38. export function validateModel(
  39. currentModelId: string,
  40. availableModels: Array<{ id: string }>,
  41. ): string {
  42. if (!currentModelId) return currentModelId;
  43. if (availableModels.some((m) => m.id === currentModelId)) return currentModelId;
  44. return availableModels[0]?.id ?? '';
  45. }