openmaic-custom/lib/store/settings-validation.ts
wyuc 3e1e9f083b
feat(tts): unify provider-enablement model, default browser-native off (#665) (#666)
A single TTS provider-enablement model honored everywhere (picker,
auto-assignment, fallback, lecture/playback, server).

Model
- lib/audio/provider-enablement.ts: isTTSProviderConfigured /
  isTTSProviderEnabled / listEnabledTTSProviderIds. Availability drops the
  registry defaultBaseUrl fallback (fixes Lemonade's always-shown voices),
  honors the per-provider `enabled` flag, server-disable overrides (server
  precedence).
- voice-resolver: getEnabledProvidersWithVoices (enabled server/custom
  providers) and getSelectableProvidersWithVoices (the ONE client source of
  truth = enabled providers + opt-in browser-native when the browser exposes
  voices). resolveAgentVoice picks deterministically among the given providers,
  honors a voiceConfig only while its provider is present.
- Picker + discussion build their list from getSelectableProvidersWithVoices, so
  the AgentBar and the live discussion agree on selectable voices (fixes
  student agents going silent in auto mode). Students resolve via
  resolveAgentVoice; the teacher uses the global lecture voice verbatim (same
  voice the pre-generated lecture sends), so lecture and discussion never
  diverge.
- Voice assignment vs fallback: an agent's voice is bound at generation (the
  agent-profile LLM picks from availableVoices; preset uses the user's pick).
  The fallback for a missing/invalid/unavailable voice is applied only at the
  live TTS calls, not baked into the saved agent — so it reflects current
  provider availability.

Defaults / opt-in
- Browser-native: first-class, default OFF, opt-in. Built-in providers default
  enabled:true (only surface once configured).
- TTS master toggle defaults OFF; first server-sync auto-enables it when a
  provider is configured (mirrors image/video).
- Persist v3->v4 migration normalizes the never-user-editable flags.

Server/admin disable (server precedence): server-providers.yml `enabled:false`
and env `TTS_<P>_ENABLED=false` (incl. browser-native). Surfaced as a per-provider
`disabled` flag on /api/server-providers; merged as serverDisabled; enforced at
the /api/generate/tts trust boundary, classroom media generation, and /api/health.

UI
- Settings TTS panel: per-provider enable toggle, disabled (with a hint) when the
  provider is unavailable, locked off (with a note) when server-disabled.
- AgentBar voice pills render disabled with a "No voice" placeholder when no
  provider is enabled. The toolbar media-popover TTS tab keeps its existing
  on/off toggle (no picker/CTA).

Tests: predicates, resolver determinism + unified selectable list, server
force-disable, store merge + migration + TTS auto-enable, i18n parity. Verified
in a real browser (Playwright): settings toggle states + a full Gemini classroom
generation whose TTS requests used the picked voice.

Found on main @ 2586cb5.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: 杨慎 <117187635+cosarah@users.noreply.github.com>
2026-06-07 17:25:57 +08:00

130 lines
4.7 KiB
TypeScript

/**
* Provider selection validation utilities.
*
* Pure functions used by fetchServerProviders() to detect and fix
* stale provider/model selections after server config changes.
*/
export type ProviderCfgLike = {
isServerConfigured?: boolean;
apiKey?: string;
requiresApiKey?: boolean;
baseUrl?: string;
/** Operator force-disabled (server precedence, TTS — #665). Never usable. */
serverDisabled?: boolean;
};
/**
* Check whether a provider has a usable *credential path* (server config or
* client key/baseUrl). This is the store-level notion and deliberately does
* NOT require ≥1 model — the UX-level "usable" predicate
* ({@link isLLMProviderConfigured}) additionally requires a model, so a
* pathological zero-model provider is classified State A at the UI boundary
* even though the store may keep it selected with an empty model (#580).
*/
export function isProviderUsable(cfg: ProviderCfgLike | undefined): boolean {
if (!cfg) return false;
// Operator force-disable wins over any local credential path so the current
// selection is re-pointed away from a server-disabled provider (#665).
if (cfg.serverDisabled) return false;
if (cfg.isServerConfigured) return true;
// Keyless providers (e.g. Ollama) need an explicit user-provided baseUrl
if (cfg.requiresApiKey === false) return !!cfg.baseUrl;
return !!cfg.apiKey;
}
/**
* Validate current provider selection against updated config.
* Returns the current ID if still usable, otherwise the first usable
* provider from fallbackOrder, or defaultId if provided, or ''.
*/
export function validateProvider<T extends string>(
currentId: T | '',
configMap: Partial<Record<T, ProviderCfgLike>>,
fallbackOrder: T[],
defaultId?: T,
): T | '' {
if (!currentId) return currentId;
if (isProviderUsable(configMap[currentId])) return currentId;
for (const id of fallbackOrder) {
if (isProviderUsable(configMap[id])) return id;
}
return defaultId ?? '';
}
/**
* Validate current model selection against available models list.
* Falls back to first available model, or '' if list is empty.
*/
export function validateModel(
currentModelId: string,
availableModels: Array<{ id: string }>,
): string {
if (!currentModelId) return currentModelId;
if (availableModels.some((m) => m.id === currentModelId)) return currentModelId;
return availableModels[0]?.id ?? '';
}
/**
* Resolve the model selection for a usable provider.
*
* Enforces the invariant "usable provider ⇒ a concrete model is selected":
* keeps the current model if still valid, otherwise falls back to the first
* available model. Unlike {@link validateModel} it has no empty-input
* short-circuit, so it returns '' ONLY when the model list is empty (i.e. the
* provider is not usable). Use this for model *selection resolution*; use
* validateModel only for pure validation.
*/
export function resolveSelectedModel(
currentModelId: string,
availableModels: Array<{ id: string }>,
): string {
if (availableModels.some((m) => m.id === currentModelId)) return currentModelId;
return availableModels[0]?.id ?? '';
}
export interface LLMProviderCfgLike {
requiresApiKey?: boolean;
apiKey?: string;
isServerConfigured?: boolean;
models: Array<{ id: string }>;
baseUrl?: string;
defaultBaseUrl?: string;
}
/**
* Canonical "this LLM provider is usable" predicate — single source of truth
* shared by the generation toolbar selector and the landing-page generate
* gate (#580). Deliberately consistent with {@link isProviderUsable} so the
* gate/toolbar can never claim a provider is usable when the server-sync
* reconcile would not actually select it:
*
* - server-configured ⇒ usable;
* - keyless provider (ollama/lemonade) ⇒ usable ONLY once the user sets an
* explicit baseUrl — the registry `defaultBaseUrl` alone is not user intent;
* - key-requiring provider ⇒ needs a client key AND a resolvable endpoint.
*
* Always also requires ≥1 model.
*/
export function isLLMProviderConfigured(config: LLMProviderCfgLike): boolean {
if (config.models.length < 1) return false;
if (config.isServerConfigured) return true;
if (config.requiresApiKey === false) return !!config.baseUrl;
if (!config.apiKey) return false;
return !!(config.baseUrl || config.defaultBaseUrl);
}
/**
* Whether at least one LLM provider is usable — i.e. the app is in state B
* (≥1 usable provider) rather than state A (must configure a provider). Under
* the #580 invariant this is exactly the condition under which a concrete
* model is guaranteed to be selected.
*/
export function hasUsableLLMProvider(
providersConfig: Record<string, LLMProviderCfgLike> | undefined | null,
): boolean {
if (!providersConfig) return false;
return Object.values(providersConfig).some(isLLMProviderConfigured);
}