Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

19.2 KB
Raw Blame
import { Component, For, createMemo, createUniqueId, Show } from 'solid-js';
import { useNavigate } from '@solidjs/router';
import { AISettingsDialogs } from '@/components/Settings/AISettingsDialogs';
import {
  AIModelOverrideField,
  AIModelSelectionSection,
} from '@/components/Settings/AIModelSelectionSection';
import { AIProviderRuntimeControlsSection } from '@/components/Settings/AIRuntimeControlsSection';
import { AISettingsStatusAndActions } from '@/components/Settings/AISettingsStatusAndActions';
import { useAISettingsState } from '@/components/Settings/useAISettingsState';
import { FormSelect } from '@/components/shared/FormSelect';
import { LoadingSpinner } from '@/components/shared/LoadingSpinner';
import SettingsPanel from '@/components/shared/SettingsPanel';
import { Toggle } from '@/components/shared/Toggle';
import { UpgradeLink } from '@/components/shared/UpgradeLink';
import { PATROL_PATH } from '@/routing/resourceLinks';
import {
  PATROL_ALERT_ANALYSIS_FEATURE_KEY,
  getPatrolAlertAnalysisAvailabilityPresentation,
  getPatrolAutonomyAvailabilityPresentation,
} from '@/features/patrol/patrolAutonomyAvailability';
import { getRuntimeCapabilityBlock, hasFeature, runtimeCapabilities } from '@/stores/license';
import { getUpgradeActionDestination } from '@/stores/licenseCommercial';
import { presentationPolicyHidesCommercialSurfaces } from '@/stores/sessionPresentationPolicy';
import {
  getPatrolCostPresentation,
  getPatrolIntervalCostHint,
} from '@/utils/aiPatrolCostPresentation';
import {
  AI_SETTINGS_PANEL_TITLE,
  getAISettingsLoadingState,
  getAISettingsLoadErrorMessage,
  getAISettingsRetryLabel,
} from '@/utils/aiSettingsPresentation';

type AISettingsPage = 'provider' | 'patrol';

const AI_SETTINGS_PAGE_META: Record<
  AISettingsPage,
  {
    resetLabel: string;
    saveErrorFallback: string;
    savedLabel: string;
    saveLabel: string;
    savingLabel: string;
    title: string;
  }
> = {
  provider: {
    resetLabel: 'Reset provider settings',
    saveErrorFallback: 'Unable to save Provider & Models settings.',
    savedLabel: 'Provider & Models settings saved',
    saveLabel: 'Save provider settings',
    savingLabel: 'Saving provider settings...',
    title: AI_SETTINGS_PANEL_TITLE,
  },
  patrol: {
    resetLabel: 'Reset Patrol settings',
    saveErrorFallback: 'Unable to save Patrol settings.',
    savedLabel: 'Patrol settings saved',
    saveLabel: 'Save Patrol settings',
    savingLabel: 'Saving Patrol settings...',
    title: 'Patrol',
  },
};

const formatPatrolInterval = (minutes: number): string => {
  if (minutes <= 0) return 'Manual only';
  if (minutes < 60) return `Every ${minutes} minute${minutes === 1 ? '' : 's'}`;
  const hours = Math.round(minutes / 60);
  return `Every ${hours} hour${hours === 1 ? '' : 's'}`;
};

const ProviderSettingsContent: Component<{ state: ReturnType<typeof useAISettingsState> }> = (
  props,
) => (
  <div class="space-y-6 p-4 sm:p-6">
    <AIModelSelectionSection state={props.state} />
    <AIProviderRuntimeControlsSection state={props.state} />
  </div>
);

const PatrolSettingsContent: Component<{ state: ReturnType<typeof useAISettingsState> }> = (
  props,
) => {
  const navigate = useNavigate();
  const patrolModeAvailability = createMemo(() =>
    getPatrolAutonomyAvailabilityPresentation({
      autoFixLocked: !hasFeature('ai_autofix'),
      commercialSurfacesHidden: presentationPolicyHidesCommercialSurfaces(),
      // Settings is where an operator goes looking: plan-locked lines here
      // always link to Plans & Billing. Demo and white-label runtimes hide
      // commercial surfaces, which wins inside the presentation.
      upgradePromptsHidden: false,
      runtimeCapabilityBlock: getRuntimeCapabilityBlock('ai_autofix'),
      runtime: runtimeCapabilities()?.runtime,
      planUpgradeDestination: getUpgradeActionDestination('ai_autofix'),
    }),
  );
  const isPlanLockedPatrol = createMemo(() => patrolModeAvailability().kind === 'plan_locked');
  const alertAnalysisAvailability = createMemo(() =>
    getPatrolAlertAnalysisAvailabilityPresentation({
      alertAnalysisLocked: props.state.alertAnalysisLocked(),
      commercialSurfacesHidden: presentationPolicyHidesCommercialSurfaces(),
      upgradePromptsHidden: false,
      runtimeCapabilityBlock: getRuntimeCapabilityBlock(PATROL_ALERT_ANALYSIS_FEATURE_KEY),
      runtime: runtimeCapabilities()?.runtime,
      planUpgradeDestination: getUpgradeActionDestination(PATROL_ALERT_ANALYSIS_FEATURE_KEY),
    }),
  );
  const alertAnalysisLockId = createUniqueId();
  const intervalOptions = [
    { value: 0, label: 'Manual only' },
    { value: 60, label: 'Every hour' },
    { value: 180, label: 'Every 3 hours' },
    { value: 360, label: 'Every 6 hours' },
    { value: 720, label: 'Every 12 hours' },
    { value: 1440, label: 'Daily' },
  ];

  return (
    <div class="space-y-6 p-4 sm:p-6">
      <div class="rounded-md border border-border bg-surface-alt p-4">
        <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <h3 class="text-sm font-semibold text-base-content">Patrol mode</h3>
            <p class="mt-1 text-xs text-muted">
              <Show
                when={isPlanLockedPatrol()}
                fallback="Choose a Patrol mode on the Patrol page. Keep schedule, triggers, and model readiness here."
              >
                This install runs Watch only. Patrol monitors your infrastructure and reports
                issues.
              </Show>
            </p>
          </div>
          <button
            type="button"
            class="inline-flex min-h-10 items-center justify-center rounded-md border border-blue-300 px-3 py-2 text-sm font-medium text-blue-700 hover:bg-blue-50 dark:border-blue-700 dark:text-blue-300 dark:hover:bg-blue-900/25 sm:min-h-9"
            onClick={() => navigate(PATROL_PATH)}
          >
            Open Patrol
          </button>
        </div>
      </div>

      <div class="grid gap-4 lg:grid-cols-2">
        <FormSelect
          id="ai-patrol-schedule"
          label="Schedule"
          value={String(props.state.form.patrolIntervalMinutes)}
          onChange={(event) =>
            props.state.setForm('patrolIntervalMinutes', parseInt(event.currentTarget.value, 10))
          }
          disabled={props.state.saving()}
          fieldClass="gap-2"
          labelClass="text-xs font-medium text-muted"
          selectBaseClass="w-full min-h-10 rounded-md border border-border bg-surface px-3 py-2 text-sm"
        >
          <For each={intervalOptions}>
            {(option) => {
              const hint = () =>
                getPatrolIntervalCostHint(props.state.patrolCostPreview(), option.value);
              return (
                <option value={option.value}>
                  {option.label}
                  {hint() ? ` (${hint()})` : ''}
                </option>
              );
            }}
          </For>
        </FormSelect>

        <div class="rounded-md border border-border bg-surface-alt p-3">
          <p class="text-xs font-medium text-base-content">Current schedule</p>
          <p class="mt-1 text-sm text-muted">
            {formatPatrolInterval(props.state.form.patrolIntervalMinutes)}
          </p>
          <Show when={getPatrolCostPresentation(props.state.patrolCostPreview())}>
            {(cost) => (
              <p class="mt-1 text-xs text-muted" data-testid="patrol-schedule-cost">
                {cost().headline} with {props.state.effectivePatrolModel()}.
                <Show when={props.state.patrolCostPreview()?.billed_per_token}>
                  {' '}
                  Estimate. The Patrol model section below shows the assumptions.
                </Show>
              </p>
            )}
          </Show>
          <Show when={props.state.patrolIntervalAutoAdjust()}>
            {(adjust) => (
              <p class="mt-1 text-xs text-amber-700 dark:text-amber-300">
                Changed from {formatPatrolInterval(adjust().from).toLowerCase()} to keep the
                per-token bill down. Pick another option above to override it.
              </p>
            )}
          </Show>
        </div>
      </div>

      <div class="space-y-3">
        <h3 class="text-sm font-semibold text-base-content">Triggers</h3>

        <div class="grid gap-3 lg:grid-cols-2">
          <div class="rounded-md border border-border bg-surface-alt p-3">
            <div class="flex items-center justify-between gap-3">
              <div>
                <p class="text-sm font-medium text-base-content">Alert-triggered Patrols</p>
                <p class="mt-1 text-xs text-muted">Start Patrol when alerts fire or clear.</p>
              </div>
              <Toggle
                checked={props.state.form.patrolAlertTriggers}
                onChange={(event) =>
                  props.state.setForm('patrolAlertTriggers', event.currentTarget.checked)
                }
                disabled={props.state.saving()}
                ariaLabel="Enable alert-triggered Patrols"
              />
            </div>

            <Show when={props.state.form.patrolAlertTriggers}>
              <FormSelect
                id="ai-patrol-alert-min-severity"
                label="Investigate alerts at or above"
                value={props.state.form.patrolAlertTriggerMinSeverity}
                onChange={(event) =>
                  props.state.setForm(
                    'patrolAlertTriggerMinSeverity',
                    event.currentTarget.value === 'warning' ? 'warning' : 'critical',
                  )
                }
                disabled={props.state.saving()}
                fieldClass="mt-3 gap-2"
                labelClass="text-xs font-medium text-muted"
                selectBaseClass="w-full min-h-10 rounded-md border border-border bg-surface px-3 py-2 text-sm"
              >
                <option value="critical">Critical only</option>
                <option value="warning">Warning and critical</option>
              </FormSelect>
            </Show>
          </div>

          <div class="rounded-md border border-border bg-surface-alt p-3">
            <div class="flex items-center justify-between gap-3">
              <div>
                <p class="text-sm font-medium text-base-content">Anomaly-triggered Patrols</p>
                <p class="mt-1 text-xs text-muted">Start Patrol from learned baseline changes.</p>
              </div>
              <Toggle
                checked={props.state.form.patrolAnomalyTriggers}
                onChange={(event) =>
                  props.state.setForm('patrolAnomalyTriggers', event.currentTarget.checked)
                }
                disabled={props.state.saving()}
                ariaLabel="Enable anomaly-triggered Patrols"
              />
            </div>
          </div>

          <div class="rounded-md border border-border bg-surface-alt p-3 lg:col-span-2">
            <div class="flex items-center justify-between gap-3">
              <div>
                <p class="text-sm font-medium text-base-content">Container update risk</p>
                <p class="mt-1 text-xs text-muted">
                  Assess risk when container-update alerts fire.
                </p>
                <Show when={alertAnalysisAvailability().locked}>
                  <p id={alertAnalysisLockId} class="mt-1 text-xs text-muted">
                    <span class="font-medium text-base-content">
                      {alertAnalysisAvailability().title}.
                    </span>{' '}
                    {alertAnalysisAvailability().body}
                    <Show when={alertAnalysisAvailability().destination}>
                      {(destination) => (
                        <>
                          {' '}
                          <UpgradeLink
                            class="font-medium text-blue-600 hover:underline dark:text-blue-400"
                            destination={destination()}
                          >
                            {alertAnalysisAvailability().actionLabel}
                          </UpgradeLink>
                        </>
                      )}
                    </Show>
                  </p>
                </Show>
              </div>
              <Toggle
                checked={props.state.form.alertTriggeredAnalysis}
                onChange={(event) =>
                  props.state.setForm('alertTriggeredAnalysis', event.currentTarget.checked)
                }
                disabled={props.state.saving() || alertAnalysisAvailability().locked}
                ariaLabel="Enable container update risk analysis"
                ariaDescribedBy={
                  alertAnalysisAvailability().locked ? alertAnalysisLockId : undefined
                }
              />
            </div>
          </div>
        </div>
      </div>

      <div class="space-y-3">
        <h3 class="text-sm font-semibold text-base-content">Notifications</h3>
        <div class="rounded-md border border-border bg-surface-alt p-3">
          <div class="flex items-center justify-between gap-3">
            <div>
              <p class="text-sm font-medium text-base-content">Finding notifications</p>
              <p class="mt-1 text-xs text-muted">
                Send new findings to your alert notification channels (email, webhooks).
              </p>
            </div>
            <Toggle
              checked={props.state.form.patrolFindingNotifications}
              onChange={(event) =>
                props.state.setForm('patrolFindingNotifications', event.currentTarget.checked)
              }
              disabled={props.state.saving()}
              ariaLabel="Enable finding notifications"
            />
          </div>

          <Show when={props.state.form.patrolFindingNotifications}>
            <FormSelect
              id="ai-patrol-finding-notify-min-severity"
              label="Notify for findings at or above"
              value={props.state.form.patrolFindingNotifyMinSeverity}
              onChange={(event) =>
                props.state.setForm(
                  'patrolFindingNotifyMinSeverity',
                  event.currentTarget.value === 'critical' ? 'critical' : 'warning',
                )
              }
              disabled={props.state.saving()}
              fieldClass="mt-3 gap-2"
              labelClass="text-xs font-medium text-muted"
              selectBaseClass="w-full min-h-10 rounded-md border border-border bg-surface px-3 py-2 text-sm"
            >
              <option value="warning">Warning and critical</option>
              <option value="critical">Critical only</option>
            </FormSelect>
          </Show>
        </div>
      </div>

      <div class="space-y-3">
        <h3 class="text-sm font-semibold text-base-content">Model readiness</h3>
        <AIModelOverrideField state={props.state} kind="patrol" includePatrolReadiness />
      </div>
    </div>
  );
};

const AISettingsPageContent: Component<{
  page: AISettingsPage;
  state: ReturnType<typeof useAISettingsState>;
}> = (props) => (
  <Show when={props.page === 'provider'} fallback={<PatrolSettingsContent state={props.state} />}>
    <ProviderSettingsContent state={props.state} />
  </Show>
);

export const AISettings: Component<{ page?: AISettingsPage }> = (props) => {
  const page = () => props.page ?? 'provider';
  const pageMeta = () => AI_SETTINGS_PAGE_META[page()];
  const state = useAISettingsState({
    get saveErrorFallback() {
      return pageMeta().saveErrorFallback;
    },
    get savedLabel() {
      return pageMeta().savedLabel;
    },
  });
  const isProviderPage = () => page() === 'provider';

  return (
    <>
      <div class="space-y-6">
        <SettingsPanel
          title={pageMeta().title}
          action={
            isProviderPage() ? (
              <Toggle
                checked={state.form.enabled}
                onChange={async (event) => {
                  const newValue = event.currentTarget.checked;
                  await state.handleEnableRequest(newValue);
                }}
                disabled={state.loading() || state.saving() || state.loadError()}
                containerClass="items-center gap-2"
                ariaLabel="Enable Pulse Intelligence"
                label={
                  <span class="text-xs font-medium text-muted">
                    {state.form.enabled ? 'Enabled' : 'Disabled'}
                  </span>
                }
              />
            ) : undefined
          }
          noPadding
        >
          <form class="divide-y divide-border" autocomplete="off" onSubmit={state.handleSave}>
            <Show when={state.loading()}>
              <div class="flex items-center gap-3 text-sm text-muted p-4 sm:p-6">
                <LoadingSpinner size="md" tone="current" />
                {getAISettingsLoadingState().text}
              </div>
            </Show>

            <Show when={!state.loading() && state.loadError()}>
              <div
                role="alert"
                aria-live="assertive"
                class="flex items-center justify-between gap-3 p-4 sm:p-6 bg-red-50 dark:bg-red-900/30 border-b border-red-200 dark:border-red-800"
              >
                <div class="flex items-center gap-2 text-sm text-red-700 dark:text-red-300">
                  <svg
                    class="h-4 w-4 shrink-0"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    stroke-width="2"
                  >
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"
                    />
                  </svg>
                  <span>{getAISettingsLoadErrorMessage()}</span>
                </div>
                <button
                  type="button"
                  class="shrink-0 px-3 py-1.5 text-sm font-medium text-red-700 dark:text-red-300 border border-red-300 dark:border-red-700 rounded-md hover:bg-red-100 dark:hover:bg-red-900/50"
                  onClick={() => state.loadSettings()}
                >
                  {getAISettingsRetryLabel()}
                </button>
              </div>
            </Show>

            <Show when={!state.loading() && !state.loadError()}>
              <AISettingsPageContent page={page()} state={state} />

              <AISettingsStatusAndActions
                resetLabel={pageMeta().resetLabel}
                saveLabel={pageMeta().saveLabel}
                savingLabel={pageMeta().savingLabel}
                state={state}
                showConnectionControls={isProviderPage()}
              />
            </Show>
          </form>
        </SettingsPanel>
      </div>

      <AISettingsDialogs
        showSetupModal={state.showSetupModal}
        setupProvider={state.setupProvider}
        setSetupProvider={state.setSetupProvider}
        setupApiKey={state.setupApiKey}
        setSetupApiKey={state.setSetupApiKey}
        setupOllamaUrl={state.setupOllamaUrl}
        setSetupOllamaUrl={state.setSetupOllamaUrl}
        setupSaving={state.setupSaving}
        handleCloseSetupModal={state.handleCloseSetupModal}
        handleSetupSubmit={state.handleSetupSubmit}
      />
    </>
  );
};

export const AIPatrolSettings: Component = () => <AISettings page="patrol" />;

export default AISettings;