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.

27.5 KB
Raw Blame
import { createEffect, createMemo, createSignal, onCleanup, onMount } from 'solid-js';
import { AIAPI } from '@/api/ai';
import {
  createPatrolAutopilotAcknowledgement,
  getPatrolAutonomySettings,
  getPatrolRunHistory,
  getPatrolStatus,
  revokePatrolAutopilotAcknowledgement,
  triggerPatrolRun,
  updatePatrolAutonomySettings,
  type PatrolAutonomyLevel,
  type PatrolAutopilotStatus,
  type PatrolRunRecord,
  type PatrolRuntimeState,
  type PatrolStatus,
} from '@/api/patrol';
import {
  PULSE_OPERATIONS_LOOP_WORKFLOW_PROMPT_NAME,
  PULSE_PATROL_CONTROL_WORKFLOW_PROMPT_SURFACE,
  recordWorkflowPromptActivity,
  type WorkflowPromptActivitySurface,
} from '@/api/workflowPrompts';
import { aiIntelligenceStore } from '@/stores/aiIntelligence';
import {
  aiRuntimeSettings,
  loadAIRuntimeModels,
  loadAIRuntimeSettings,
  syncAIRuntimeSettings,
} from '@/stores/aiRuntimeState';
import { notificationStore } from '@/stores/notifications';
import { usePatrolStream } from '@/hooks/usePatrolStream';
import { createNonSuspendingQuery } from '@/hooks/createNonSuspendingQuery';
import {
  getRuntimeCapabilityBlock,
  hasFeature,
  loadRuntimeCapabilities,
  runtimeCapabilities,
} from '@/stores/license';
import { PATROL_AUTONOMY_FEATURE_KEY } from './patrolAutonomyAvailability';
import type { AISettings } from '@/types/ai';
import { apiErrorStatus } from '@/api/responseUtils';
import { isPatrolRuntimeFinding } from '@/utils/aiFindingPresentation';
import { getCanonicalScopeResourceIds } from '@/utils/patrolFormat';
import { normalizePatrolRuntimeBlockedReason } from '@/utils/patrolRuntimePresentation';
import { logger } from '@/utils/logger';
import {
  parsePatrolControlStarter,
  PATROL_CONTROL_STARTER,
  PATROL_CONTROL_STARTER_QUERY_PARAM,
  PATROL_OPERATIONS_LOOP_STARTER_QUERY_PARAM,
} from '@/routing/resourceLinks';
import { schedulePatrolRunAcceptanceReconciliation } from './patrolRunAcceptance';

type PatrolTab = 'findings' | 'history';

const recordPatrolWorkflowStarterActivityForSurface = async (
  surface: WorkflowPromptActivitySurface,
  logContext: string,
): Promise<void> => {
  try {
    await recordWorkflowPromptActivity({
      name: PULSE_OPERATIONS_LOOP_WORKFLOW_PROMPT_NAME,
      surface,
    });
  } catch (error) {
    logger.debug(`[${logContext}] Failed to record Patrol workflow starter`, error);
  }
};

export const PATROL_MANUAL_SYNC_TIMEOUT_MS = 5000;
export const PATROL_ACCEPTANCE_RECONCILE_MS = 15000;
export const PATROL_ACCEPTANCE_REFRESH_TIMEOUT_MS = 5000;

export function recordPatrolControlStarterActivity(): Promise<void> {
  return recordPatrolWorkflowStarterActivityForSurface(
    PULSE_PATROL_CONTROL_WORKFLOW_PROMPT_SURFACE,
    'Patrol mode handoff',
  );
}

const patrolErrorMessage = (error: unknown, fallback: string) =>
  error instanceof Error && error.message.trim() ? error.message : fallback;

export const patrolStartFailureMessage = (error: unknown): string =>
  apiErrorStatus(error) === null
    ? `Could not reach Pulse to start Patrol: ${patrolErrorMessage(error, 'network request failed')}`
    : patrolErrorMessage(error, 'Pulse rejected the Patrol run');

/**
 * A Patrol on/off save whose response reports Patrol not ready was still
 * saved, so it raises a warning rather than an error.
 */
export function getPatrolSavedReadinessWarning(
  settings: AISettings | null | undefined,
): string | null {
  return settings?.patrol_readiness?.status === 'not_ready'
    ? 'Patrol setting was saved, but Patrol is not ready to run.'
    : null;
}

/**
 * The blocked banner's action must follow the runtime block cause when there
 * is one: a used-up cost budget is fixed on Provider & Models, while the
 * readiness cause (often "none" while blocked) would send the operator to
 * the model check (#1789).
 */
export function resolvePatrolBlockedActionCause(
  blockedCause?: string | null,
  readinessCause?: string | null,
): string | undefined {
  const blocked = blockedCause?.trim();
  if (blocked && blocked !== 'none') return blocked;
  const readiness = readinessCause?.trim();
  return readiness || undefined;
}

export function usePatrolIntelligenceState() {
  const [activeTab, setActiveTab] = createSignal<PatrolTab>('findings');
  const [findingsFilterOverride, setFindingsFilterOverride] = createSignal<
    'all' | 'active' | 'resolved' | 'approvals' | 'attention' | undefined
  >(undefined);
  const [isManualRefreshRunning, setIsManualRefreshRunning] = createSignal(false);
  const [autonomyLevel, setAutonomyLevel] = createSignal<PatrolAutonomyLevel>('monitor');
  const [requestedAutonomyLevel, setRequestedAutonomyLevel] =
    createSignal<PatrolAutonomyLevel>('monitor');
  const [autopilotStatus, setAutopilotStatus] = createSignal<PatrolAutopilotStatus | null>(null);
  const [defaultModeApplied, setDefaultModeApplied] = createSignal(false);
  const [autopilotDialogOpen, setAutopilotDialogOpen] = createSignal(false);
  const [isUpdatingAutonomy, setIsUpdatingAutonomy] = createSignal(false);
  const [activityRefreshTrigger, setActivityRefreshTrigger] = createSignal(0);
  const [manualRunRequested, setManualRunRequested] = createSignal(false);
  const [acceptedManualRunId, setAcceptedManualRunId] = createSignal('');
  const [patrolEnabledLocal, setPatrolEnabledLocal] = createSignal<boolean>(true);
  const [liveRunStartedAt, setLiveRunStartedAt] = createSignal('');
  const [investigationBudget, setInvestigationBudget] = createSignal(15);
  const [investigationTimeout, setInvestigationTimeout] = createSignal(300);
  const [isTogglingPatrol, setIsTogglingPatrol] = createSignal(false);
  const [isTriggeringPatrol, setIsTriggeringPatrol] = createSignal(false);
  const [selectedRun, setSelectedRun] = createSignal<PatrolRunRecord | null>(null);
  const [patrolLoadError, setPatrolLoadError] = createSignal('');

  let cancelAcceptanceReconciliation: (() => void) | undefined;
  let findingScrollTimerRef: ReturnType<typeof setTimeout> | undefined;
  let manualRefreshTimeoutRef: ReturnType<typeof setTimeout> | undefined;
  let refreshRequestId = 0;
  let manualRefreshRequestId = 0;
  let manualRunRequestId = 0;
  let refreshInterval: ReturnType<typeof setInterval>;
  let approvalPollInterval: ReturnType<typeof setInterval>;

  const clearAcceptanceReconcileTimer = () => {
    if (cancelAcceptanceReconciliation !== undefined) {
      cancelAcceptanceReconciliation();
      cancelAcceptanceReconciliation = undefined;
    }
  };

  const finishManualRunTracking = () => {
    clearAcceptanceReconcileTimer();
    setAcceptedManualRunId('');
    setManualRunRequested(false);
  };

  const clearManualRefreshTimeout = () => {
    if (manualRefreshTimeoutRef !== undefined) {
      clearTimeout(manualRefreshTimeoutRef);
      manualRefreshTimeoutRef = undefined;
    }
  };

  const rememberPatrolLoadError = (error: unknown, fallback: string) => {
    const message = patrolErrorMessage(error, fallback);
    setPatrolLoadError(message);
    logger.debug('[Patrol] Failed to refresh Patrol data', error);
    return message;
  };

  const clearPatrolLoadError = () => {
    if (patrolLoadError()) {
      setPatrolLoadError('');
    }
  };

  const patrolStatusState = createNonSuspendingQuery<PatrolStatus | null, string>({
    source: () => 'patrol-status',
    cacheKey: () => 'patrol-status',
    fetcher: async () => {
      try {
        return await getPatrolStatus();
      } catch {
        return null;
      }
    },
    initialValue: null,
  });
  const patrolStatus = patrolStatusState.value;
  const refetchPatrolStatus = patrolStatusState.refetch;
  const historicalRegressionCount = createMemo(() => {
    const count = patrolStatus()?.trust?.regressed_at_least_once;
    return typeof count === 'number' && Number.isFinite(count) ? Math.max(0, count) : 0;
  });

  const patrolStream = usePatrolStream({
    running: () =>
      patrolEnabledLocal() && ((patrolStatus()?.running ?? false) || manualRunRequested()),
    onComplete: () => {
      finishManualRunTracking();
      loadAllData();
    },
    onError: () => {
      finishManualRunTracking();
      loadAllData();
    },
  });

  const autoFixLocked = createMemo(() => !hasFeature(PATROL_AUTONOMY_FEATURE_KEY));
  const autoFixCapabilityBlock = createMemo(() =>
    getRuntimeCapabilityBlock(PATROL_AUTONOMY_FEATURE_KEY),
  );
  const licenseRuntimeIdentity = createMemo(() => runtimeCapabilities()?.runtime);

  const applyPatrolAISettings = (data: AISettings | null | undefined) => {
    setPatrolEnabledLocal(data?.patrol_enabled ?? true);
  };

  createEffect(() => {
    applyPatrolAISettings(aiRuntimeSettings());
  });

  async function handleTogglePatrol() {
    if (isTogglingPatrol()) return;
    setIsTogglingPatrol(true);
    const previousValue = patrolEnabledLocal();
    const newValue = !previousValue;
    setPatrolEnabledLocal(newValue);
    if (!newValue) {
      manualRunRequestId += 1;
      finishManualRunTracking();
      setIsTriggeringPatrol(false);
    }
    try {
      const data = await AIAPI.updateSettings({ patrol_enabled: newValue });
      syncAIRuntimeSettings(data);
      if (typeof data?.patrol_enabled === 'boolean') {
        setPatrolEnabledLocal(data.patrol_enabled);
      } else {
        setPatrolEnabledLocal(newValue);
      }
      const readinessWarning = getPatrolSavedReadinessWarning(data);
      if (readinessWarning) {
        notificationStore.warning(readinessWarning);
      }
      if (refetchPatrolStatus) {
        refetchPatrolStatus();
      }
    } catch (err) {
      console.error('Failed to toggle patrol:', err);
      setPatrolEnabledLocal(previousValue);
      notificationStore.error(patrolErrorMessage(err, 'Failed to toggle patrol'));
    } finally {
      setIsTogglingPatrol(false);
    }
  }

  async function handleRunPatrol() {
    if (
      isTriggeringPatrol() ||
      !canTriggerPatrol() ||
      manualRunRequested() ||
      patrolStream.isStreaming()
    ) {
      return;
    }
    const requestId = ++manualRunRequestId;
    setIsTriggeringPatrol(true);
    setManualRunRequested(true);
    clearAcceptanceReconcileTimer();

    try {
      const acceptance = await triggerPatrolRun();
      if (requestId !== manualRunRequestId || !manualRunRequested()) {
        return;
      }
      const runId = acceptance?.run_id?.trim() || '';
      setAcceptedManualRunId(runId);
      cancelAcceptanceReconciliation = schedulePatrolRunAcceptanceReconciliation({
        runId,
        delayMs: PATROL_ACCEPTANCE_RECONCILE_MS,
        refreshTimeoutMs: PATROL_ACCEPTANCE_REFRESH_TIMEOUT_MS,
        getStatus: refetchPatrolStatus,
        getHistory: () => getPatrolRunHistory(30),
        isCurrent: () =>
          requestId === manualRunRequestId &&
          manualRunRequested() &&
          acceptedManualRunId() === runId,
        onResult: (outcome) => {
          cancelAcceptanceReconciliation = undefined;
          finishManualRunTracking();
          if (outcome.kind === 'running' || outcome.kind === 'recorded') {
            setActivityRefreshTrigger((prev) => prev + 1);
            return;
          }
          if (outcome.kind === 'refresh_failed') {
            rememberPatrolLoadError(
              outcome.error,
              'Patrol accepted the run, but its live status could not be refreshed.',
            );
            return;
          }
          notificationStore.error(
            runId
              ? `Pulse accepted Patrol run ${runId}, but the backend no longer reports it as running and did not record it in history.`
              : 'Pulse accepted the Patrol run, but the backend no longer reports it as running and did not record it in history.',
          );
        },
      });
    } catch (err) {
      console.error('Failed to trigger patrol run:', err);
      if (requestId === manualRunRequestId) {
        finishManualRunTracking();
        notificationStore.error(patrolStartFailureMessage(err));
      }
      return;
    } finally {
      if (requestId === manualRunRequestId) {
        setIsTriggeringPatrol(false);
      }
    }

    void loadAllData().catch((err) => {
      console.error('Failed to refresh Patrol after starting run:', err);
    });
  }

  const patrolRunHistory = createNonSuspendingQuery<PatrolRunRecord[], number>({
    source: activityRefreshTrigger,
    cacheKey: () => 'patrol-run-history',
    fetcher: async () => {
      try {
        return await getPatrolRunHistory(30);
      } catch (err) {
        console.error('Failed to load patrol run history:', err);
        return [];
      }
    },
    initialValue: [],
  });

  const licenseRequired = createMemo(() => patrolStatus()?.license_required ?? false);
  const runtimeState = createMemo<PatrolRuntimeState>(() => {
    if (!patrolEnabledLocal()) return 'disabled';
    return patrolStatus()?.runtime_state ?? 'active';
  });
  const blockedReason = createMemo(() =>
    normalizePatrolRuntimeBlockedReason(patrolStatus()?.blocked_reason),
  );
  const blockedAt = createMemo(() => patrolStatus()?.blocked_at);
  const blockedCause = createMemo(() => patrolStatus()?.blocked_cause);
  const patrolReadiness = createMemo(() => patrolStatus()?.readiness ?? null);
  // Pulse records the last preflight result on AISettings.patrol_preflight
  // (provider/model/duration/recommendation) so we can surface a concrete
  // diagnosis on the readiness banner instead of a one-line "Provider
  // connection issue" that forces operators to spelunk dev tools.
  const patrolPreflight = createMemo(() => aiRuntimeSettings()?.patrol_preflight ?? null);
  const readinessBlocksPatrol = createMemo(() => patrolReadiness()?.status === 'not_ready');
  const showBlockedBanner = createMemo(() => runtimeState() === 'blocked');
  const showReadinessBanner = createMemo(() => {
    const readiness = patrolReadiness();
    return runtimeState() === 'active' && readiness !== null && readiness.status !== 'ready';
  });
  const canTriggerPatrol = createMemo(
    () => runtimeState() === 'active' && !readinessBlocksPatrol(),
  );
  const triggerPatrolDisabledReason = createMemo(() => {
    if (runtimeState() === 'disabled') return 'Patrol is disabled';
    if (runtimeState() === 'blocked') return blockedReason() || 'Patrol is paused';
    if (runtimeState() === 'running') return 'Patrol is already running';
    if (runtimeState() === 'unavailable') return 'Patrol service is unavailable';
    if (readinessBlocksPatrol()) return patrolReadiness()?.summary || 'Patrol is not ready';
    return '';
  });

  const shouldShowLiveRun = createMemo(
    () =>
      patrolEnabledLocal() &&
      ((patrolStatus()?.running ?? false) || manualRunRequested() || patrolStream.isStreaming()),
  );

  createEffect(() => {
    if (shouldShowLiveRun()) {
      if (!liveRunStartedAt()) {
        setLiveRunStartedAt(new Date().toISOString());
      }
      return;
    }
    if (liveRunStartedAt()) {
      setLiveRunStartedAt('');
    }
  });

  const selectedRunFindingIds = createMemo(() => {
    const run = selectedRun();
    if (!run) return undefined;
    return run.finding_ids;
  });
  const selectedRunHasFindingsSnapshot = createMemo(() => {
    const run = selectedRun();
    if (!run) return undefined;
    return run.finding_ids !== undefined;
  });

  const selectedRunScopeResourceIds = createMemo(() => getCanonicalScopeResourceIds(selectedRun()));
  const allPatrolFindings = createMemo(() => aiIntelligenceStore.patrolFindings);
  const patrolPendingApprovalCount = createMemo(
    () => aiIntelligenceStore.patrolPendingApprovals.length,
  );
  const selectedRunPatrolFindings = createMemo(() => {
    const run = selectedRun();
    if (!run) return null;
    if (run.finding_ids === undefined) return undefined;
    const snapshotFindingIds = new Set(run.finding_ids);
    return allPatrolFindings().filter((finding) => snapshotFindingIds.has(finding.id));
  });

  const intelligenceSummary = createMemo(() => aiIntelligenceStore.intelligenceSummary);
  const liveRunRecord = createMemo<PatrolRunRecord | null>(() => {
    if (!shouldShowLiveRun()) return null;
    return {
      id: '__live__',
      started_at: liveRunStartedAt() || new Date().toISOString(),
      completed_at: '',
      duration_ms: 0,
      type: 'full',
      trigger_reason: 'manual',
      resources_checked: 0,
      nodes_checked: 0,
      guests_checked: 0,
      docker_checked: 0,
      storage_checked: 0,
      hosts_checked: 0,
      truenas_checked: 0,
      pbs_checked: 0,
      pmg_checked: 0,
      kubernetes_checked: 0,
      new_findings: 0,
      existing_findings: 0,
      rejected_findings: 0,
      resolved_findings: 0,
      auto_fix_count: 0,
      findings_summary: '',
      finding_ids: [],
      error_count: 0,
      status: 'healthy',
      triage_flags: 0,
      tool_call_count: 0,
    };
  });

  const displayRunHistory = createMemo(() => {
    const live = liveRunRecord();
    const history = patrolRunHistory.value() || [];
    return live ? [live, ...history] : history;
  });

  async function loadAutonomySettings() {
    try {
      const settings = await getPatrolAutonomySettings();
      if (!settings) return;
      setRequestedAutonomyLevel(settings.requested_autonomy_level);
      setDefaultModeApplied(settings.default_mode_applied === true);
      setAutonomyLevel(settings.effective_autonomy_level);
      setAutopilotStatus(settings.autopilot_acknowledgement);
      setInvestigationBudget(settings.investigation_budget);
      setInvestigationTimeout(settings.investigation_timeout_sec);
    } catch (err) {
      console.error('Failed to load autonomy settings:', err);
    }
  }

  async function handleAutonomyChange(level: PatrolAutonomyLevel) {
    if (isUpdatingAutonomy()) return;
    const controlLocked = autoFixLocked();
    if (controlLocked && level !== 'monitor') return;

    if (level === 'full') {
      setAutopilotDialogOpen(true);
      return;
    }
    const previousLevel = autonomyLevel();
    const shouldRecordPatrolControlStarter = !controlLocked && level !== previousLevel;
    setIsUpdatingAutonomy(true);

    try {
      await updatePatrolAutonomySettings({
        autonomy_level: level,
        investigation_budget: investigationBudget(),
        investigation_timeout_sec: investigationTimeout(),
      });
      // The paid runtime intentionally returns a compact mutation receipt,
      // while GET is the authoritative projection of effective mode and the
      // server-owned Autopilot acknowledgement. Reconcile after every write
      // instead of assuming both runtime editions return the same envelope.
      await loadAutonomySettings();
      if (shouldRecordPatrolControlStarter) {
        await recordPatrolControlStarterActivity();
        await loadVisiblePatrolData();
      }
    } catch (err) {
      console.error('Failed to update autonomy:', err);
      setAutonomyLevel(previousLevel);
      notificationStore.error((err as Error).message || 'Failed to update Patrol mode');
    } finally {
      setIsUpdatingAutonomy(false);
    }
  }

  async function acknowledgeAndActivateAutopilot() {
    if (isUpdatingAutonomy() || autoFixLocked()) return;
    setIsUpdatingAutonomy(true);
    const acknowledgementId =
      typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
        ? crypto.randomUUID()
        : `patrol-autopilot-${Date.now()}-${Math.random().toString(16).slice(2)}`;
    try {
      const acknowledgement = await createPatrolAutopilotAcknowledgement(acknowledgementId);
      await updatePatrolAutonomySettings({
        autonomy_level: 'full',
        acknowledgement_id: acknowledgement.acknowledgement.acknowledgementId || acknowledgementId,
        investigation_budget: investigationBudget(),
        investigation_timeout_sec: investigationTimeout(),
      });
      await loadAutonomySettings();
      setAutopilotDialogOpen(false);
      await recordPatrolControlStarterActivity();
      await loadVisiblePatrolData();
      notificationStore.success('Autopilot acknowledgement recorded and mode activated.');
    } catch (err) {
      await loadAutonomySettings();
      notificationStore.error((err as Error).message || 'Autopilot could not be activated.');
    } finally {
      setIsUpdatingAutonomy(false);
    }
  }

  async function revokeAutopilot() {
    const acknowledgementId = autopilotStatus()?.acknowledgementId;
    if (!acknowledgementId || isUpdatingAutonomy()) return;
    setIsUpdatingAutonomy(true);
    try {
      await revokePatrolAutopilotAcknowledgement(acknowledgementId);
      await loadAutonomySettings();
      notificationStore.success('Autopilot acknowledgement revoked. Effective mode refreshed.');
    } catch (err) {
      notificationStore.error(
        (err as Error).message || 'Autopilot acknowledgement could not be revoked.',
      );
    } finally {
      setIsUpdatingAutonomy(false);
    }
  }

  function startPolling() {
    clearInterval(refreshInterval);
    clearInterval(approvalPollInterval);
    refreshInterval = setInterval(() => loadAllData(), 60000);
    approvalPollInterval = setInterval(() => aiIntelligenceStore.loadPendingApprovals(), 10000);
  }

  function stopPolling() {
    clearInterval(refreshInterval);
    clearInterval(approvalPollInterval);
  }

  async function loadAllData() {
    const requestId = ++refreshRequestId;
    try {
      await Promise.all([
        // The Patrol surface needs dismissed findings too: the attention
        // detail shows the decision Patrol already remembers for a mirrored
        // finding, and the store's default load is active-only. Listed first
        // so it flips the store's sticky include-resolved preference before
        // loadDashboardData issues its own findings read; otherwise the two
        // responses race and the active-only one can win.
        aiIntelligenceStore.loadPatrolFindings({ includeResolved: true }),
        aiIntelligenceStore.loadDashboardData(),
        refetchPatrolStatus(),
        loadAutonomySettings(),
      ]);
      if (requestId === refreshRequestId) {
        clearPatrolLoadError();
        setActivityRefreshTrigger((prev) => prev + 1);
      }
    } catch (error) {
      if (requestId === refreshRequestId) {
        rememberPatrolLoadError(error, 'Patrol could not refresh.');
      }
    }
  }

  async function loadVisiblePatrolData() {
    try {
      await Promise.all([
        refetchPatrolStatus(),
        // Include dismissed and resolved findings: the attention detail shows
        // the decision Patrol already remembers for a mirrored finding, and a
        // dismissed finding is not in the active-only default set.
        aiIntelligenceStore.loadPatrolFindings({ includeResolved: true }),
        aiIntelligenceStore.loadPendingApprovals(),
        patrolRunHistory.refetch({ background: true }),
      ]);
      clearPatrolLoadError();
    } catch (error) {
      rememberPatrolLoadError(error, 'Patrol could not refresh.');
    }
  }

  function loadSupportingPatrolDataInBackground() {
    void Promise.allSettled([
      aiIntelligenceStore.loadIntelligenceSummary(),
      aiIntelligenceStore.loadFindings(),
    ]);
  }

  async function handleRefreshPatrol() {
    if (isManualRefreshRunning()) return;
    const requestId = ++manualRefreshRequestId;
    clearManualRefreshTimeout();
    setIsManualRefreshRunning(true);
    manualRefreshTimeoutRef = setTimeout(() => {
      if (requestId === manualRefreshRequestId) {
        manualRefreshTimeoutRef = undefined;
        setIsManualRefreshRunning(false);
      }
    }, PATROL_MANUAL_SYNC_TIMEOUT_MS);

    try {
      await loadVisiblePatrolData();
      loadSupportingPatrolDataInBackground();
    } finally {
      if (requestId === manualRefreshRequestId) {
        clearManualRefreshTimeout();
        setIsManualRefreshRunning(false);
      }
    }
  }

  async function consumeRoutePatrolControlStarterHandoff() {
    if (typeof window === 'undefined') {
      return;
    }

    const starter = parsePatrolControlStarter(window.location.search);
    if (starter !== PATROL_CONTROL_STARTER) {
      return;
    }

    const nextUrl = new URL(window.location.href);
    nextUrl.searchParams.delete(PATROL_CONTROL_STARTER_QUERY_PARAM);
    nextUrl.searchParams.delete(PATROL_OPERATIONS_LOOP_STARTER_QUERY_PARAM);
    const nextPath = `${nextUrl.pathname}${nextUrl.search}${nextUrl.hash}`;

    await recordPatrolControlStarterActivity();
    window.history.replaceState(window.history.state, '', nextPath);
  }

  const activePatrolFindings = () =>
    allPatrolFindings().filter((finding) => finding.status === 'active');
  const shouldShowPatrolSetupOnly = createMemo(() => {
    const activeFindings = activePatrolFindings();
    if (readinessBlocksPatrol() && activeFindings.length === 0) {
      return true;
    }
    return activeFindings.length > 0 && activeFindings.every(isPatrolRuntimeFinding);
  });
  const findingsTabBadgeFindings = createMemo(() => {
    const snapshotFindings = selectedRunPatrolFindings();
    if (snapshotFindings === null) {
      return activePatrolFindings();
    }
    return snapshotFindings ?? [];
  });
  const findingsTabBadgeCount = createMemo(() => {
    const snapshotFindings = selectedRunPatrolFindings();
    if (snapshotFindings === null) {
      return activePatrolFindings().length;
    }
    if (snapshotFindings === undefined) {
      return undefined;
    }
    return snapshotFindings.length;
  });

  onMount(async () => {
    await consumeRoutePatrolControlStarterHandoff();
    const initialLoads = await Promise.allSettled([
      loadRuntimeCapabilities(),
      loadAllData(),
      loadAutonomySettings(),
      loadAIRuntimeModels(),
      loadAIRuntimeSettings(),
    ]);
    const failedLoad = initialLoads.find(
      (result): result is PromiseRejectedResult => result.status === 'rejected',
    );
    if (failedLoad) {
      rememberPatrolLoadError(failedLoad.reason, 'Patrol could not refresh.');
    }
  });

  onMount(() => {
    startPolling();

    const handleVisibility = () => {
      if (document.hidden) {
        stopPolling();
      } else {
        loadAllData();
        startPolling();
      }
    };

    document.addEventListener('visibilitychange', handleVisibility);
    onCleanup(() => {
      document.removeEventListener('visibilitychange', handleVisibility);
      clearManualRefreshTimeout();
    });
  });

  onCleanup(() => {
    stopPolling();
    manualRunRequestId += 1;
    clearAcceptanceReconcileTimer();
    clearManualRefreshTimeout();
    if (findingScrollTimerRef !== undefined) {
      clearTimeout(findingScrollTimerRef);
      findingScrollTimerRef = undefined;
    }
  });

  return {
    activeTab,
    autonomyLevel,
    requestedAutonomyLevel,
    defaultModeApplied,
    autopilotStatus,
    autopilotDialogOpen,
    acknowledgeAndActivateAutopilot,
    autoFixCapabilityBlock,
    autoFixLocked,
    blockedAt,
    blockedCause,
    blockedReason,
    canTriggerPatrol,
    displayRunHistory,
    findingsTabBadgeCount,
    findingsTabBadgeFindings,
    findingsFilterOverride,
    handleAutonomyChange,
    handleRefreshPatrol,
    handleRunPatrol,
    handleTogglePatrol,
    historicalRegressionCount,
    intelligenceSummary,
    isManualRefreshRunning,
    isTogglingPatrol,
    isTriggeringPatrol,
    isUpdatingAutonomy,
    revokeAutopilot,
    licenseRequired,
    licenseRuntimeIdentity,
    manualRunRequested,
    patrolEnabledLocal,
    patrolPreflight,
    patrolLoadError,
    patrolPendingApprovalCount,
    patrolReadiness,
    patrolRunHistory,
    runtimeState,
    patrolStatus,
    patrolStream,
    selectedRun,
    selectedRunFindingIds,
    selectedRunHasFindingsSnapshot,
    selectedRunScopeResourceIds,
    setActiveTab,
    setFindingsFilterOverride,
    setAutopilotDialogOpen,
    setSelectedRun,
    setFindingScrollTimer: (timer: ReturnType<typeof setTimeout> | undefined) => {
      findingScrollTimerRef = timer;
    },
    showBlockedBanner,
    showReadinessBanner,
    shouldShowPatrolSetupOnly,
    triggerPatrolDisabledReason,
  };
}

export type PatrolIntelligenceState = ReturnType<typeof usePatrolIntelligenceState>;