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.

25.1 KB
Raw Blame
import { createEffect, createMemo, createSignal, onCleanup } from 'solid-js';
import type { ClusterEndpoint, NodeConfig } from '@/types/nodes';

import { notificationStore } from '@/stores/notifications';
import { NodesAPI } from '@/api/nodes';
import type { ProxmoxSetupCommandResponse } from '@/api/nodes';
import { copyToClipboard } from '@/utils/clipboard';
import { logger } from '@/utils/logger';
import { showTokenReveal } from '@/stores/tokenReveal';
import {
  buildNodeModalMonitoringPayload,
  getNodeModalDefaultFormData,
  getNodeModalTestResultPresentation,
  type NodeModalFormData,
} from '@/utils/nodeModalPresentation';

import {
  buildClusterEndpointOverridesPayload,
  buildClusterEndpointTrustOverridesPayload,
  buildClusterNodeDisplayNameOverridesPayload,
  deriveNameFromHost,
  type NodeModalProps,
} from './nodeModalModel';

type NodeModalTestResult = {
  status: string;
  message: string;
  isCluster?: boolean;
  warnings?: string[];
  endpoint?: string;
};

const PROXMOX_SETUP_HOST_REQUIRED_MESSAGE = 'Proxmox setup host is required';

export const useNodeModalState = (props: NodeModalProps) => {
  const [testResult, setTestResult] = createSignal<NodeModalTestResult | null>(null);
  const [isTesting, setIsTesting] = createSignal(false);
  let probeGeneration = 0;
  const [formData, setFormData] = createSignal<NodeModalFormData>(
    getNodeModalDefaultFormData(props.nodeType),
  );
  const [quickSetupBootstrap, setQuickSetupBootstrap] = createSignal<{
    cacheKey: string;
    response: ProxmoxSetupCommandResponse;
  } | null>(null);
  const [quickSetupTokenHint, setQuickSetupTokenHint] = createSignal('');
  const [quickSetupExpiry, setQuickSetupExpiry] = createSignal<number | null>(null);
  const [agentInstallCommand, setAgentInstallCommand] = createSignal('');
  const [loadingAgentCommand, setLoadingAgentCommand] = createSignal(false);
  const [agentCommandError, setAgentCommandError] = createSignal<string | null>(null);
  const [agentInstallInsecure, setAgentInstallInsecure] = createSignal(false);

  const isAdvancedSetupMode = () => formData().setupMode === 'manual';
  const showTemperatureMonitoringSection = () =>
    typeof props.temperatureMonitoringEnabled === 'boolean';
  const temperatureMonitoringEnabledValue = () => props.temperatureMonitoringEnabled ?? true;
  const isEditingExistingNode = () => Boolean(props.editingNode?.id);
  const quickSetupCommandReady = () => quickSetupBootstrap() !== null;

  const quickSetupExpiryLabel = () => {
    const expiry = quickSetupExpiry();
    if (!expiry) {
      return '';
    }
    try {
      return new Date(expiry * 1000).toLocaleTimeString();
    } catch {
      return '';
    }
  };

  const clearQuickSetupState = () => {
    setQuickSetupBootstrap(null);
    setQuickSetupTokenHint('');
    setQuickSetupExpiry(null);
  };

  let bootstrapGeneration = 0;
  const bootstrapActive = (generation: number) =>
    generation === bootstrapGeneration && props.isOpen !== false;
  onCleanup(() => {
    bootstrapGeneration++;
    clearQuickSetupState();
  });

  const copyCommand = async (command: string, successMessage = 'Command copied!') => {
    if (await copyToClipboard(command)) {
      notificationStore.success(successMessage);
    }
  };

  const copyProxmoxAgentInstallCommand = async (type: 'pve' | 'pbs', successMessage: string) => {
    const generation = bootstrapGeneration;
    try {
      setLoadingAgentCommand(true);
      setAgentCommandError(null);
      const data = await NodesAPI.getAgentInstallCommand({
        type,
        enableProxmox: true,
        enableCommands: false,
        insecure: agentInstallInsecure(),
      });
      if (!bootstrapActive(generation)) return;
      setAgentInstallCommand(data.command);
      if (data.token) {
        showTokenReveal({
          token: data.token,
          source: type,
          note: 'Run the copied install command first. Then copy this token and paste it only at the silent “Pulse agent token” prompt. It is not part of the command.',
        });
      }
      const copied = await copyToClipboard(data.command);
      if (copied) {
        notificationStore.success(successMessage);
        return;
      }

      const copyFailureMessage = 'Failed to copy to clipboard';
      setAgentCommandError(copyFailureMessage);
      notificationStore.error(copyFailureMessage);
    } catch (error) {
      if (!bootstrapActive(generation)) return;
      logger.error('[Host Telemetry Agent] Error:', error);
      const message = error instanceof Error ? error.message : 'Failed to generate install command';
      setAgentCommandError(message);
      notificationStore.error(message);
    } finally {
      if (bootstrapActive(generation)) setLoadingAgentCommand(false);
    }
  };

  const quickSetupCacheKey = (type: 'pve' | 'pbs', backupPerms: boolean) =>
    `${type}:${backupPerms ? 'backup' : 'standard'}:${formData().host?.trim() ?? ''}:${formData().name?.trim() ?? ''}`;

  const loadQuickSetupBootstrap = async (
    type: 'pve' | 'pbs',
    backupPerms: boolean,
  ): Promise<ProxmoxSetupCommandResponse | null> => {
    const generation = bootstrapGeneration;
    const host = formData().host?.trim() ?? '';
    if (!host) {
      notificationStore.error('Please enter the Endpoint URL first');
      throw new Error(PROXMOX_SETUP_HOST_REQUIRED_MESSAGE);
    }

    const cacheKey = quickSetupCacheKey(type, backupPerms);
    const cached = quickSetupBootstrap();
    const nowUnix = Date.now() / 1000;
    if (cached && cached.cacheKey === cacheKey && cached.response.expires > nowUnix) {
      setQuickSetupTokenHint(cached.response.tokenHint);
      setQuickSetupExpiry(cached.response.expires);
      return cached.response;
    }

    const response = await NodesAPI.getProxmoxSetupCommand({
      type,
      host,
      backupPerms,
      name: formData().name?.trim() || undefined,
    });
    if (!bootstrapActive(generation) || quickSetupCacheKey(type, backupPerms) !== cacheKey)
      return null;
    setQuickSetupBootstrap({ cacheKey, response });
    setQuickSetupTokenHint(response.tokenHint);
    setQuickSetupExpiry(response.expires);
    return response;
  };

  const copyQuickSetupCommand = async (
    type: 'pve' | 'pbs',
    backupPerms: boolean,
    successMessage: string,
  ) => {
    const generation = bootstrapGeneration;
    logger.debug('[Quick Setup] Copy button clicked');
    try {
      logger.debug('[Quick Setup] Generating setup URL for host', {
        host: formData().host,
      });
      const data = await loadQuickSetupBootstrap(type, backupPerms);
      if (!data || !bootstrapActive(generation)) return;
      showSetupToken(data);
      if (await copyToClipboard(data.command)) {
        notificationStore.success(successMessage);
        return;
      }
      throw new Error('Failed to copy to clipboard');
    } catch (error) {
      if (!bootstrapActive(generation)) return;
      logger.error('[Quick Setup] Error:', error);
      clearQuickSetupState();
      if (!(error instanceof Error && error.message === PROXMOX_SETUP_HOST_REQUIRED_MESSAGE)) {
        notificationStore.error('Failed to copy command');
      }
    }
  };

  const showSetupToken = (bootstrap: ProxmoxSetupCommandResponse) => {
    showTokenReveal({
      token: bootstrap.setupToken,
      source: bootstrap.type,
      note: `Run the copied setup command (or downloaded script) first. Then copy this token and paste it only at the silent “Pulse setup token” prompt. It expires at ${new Date(bootstrap.expires * 1000).toLocaleTimeString()}. Never paste it into a shell command.`,
    });
  };

  const setupScriptRunHint = (fileName: string) => `bash ${fileName}`;

  const downloadProxmoxSetupScript = async (type: 'pve' | 'pbs', backupPerms = false) => {
    const generation = bootstrapGeneration;
    try {
      const bootstrap = await loadQuickSetupBootstrap(type, backupPerms);
      if (!bootstrap || !bootstrapActive(generation)) return;
      const data = await NodesAPI.downloadProxmoxSetupScript(bootstrap);
      if (!bootstrapActive(generation)) return;
      showSetupToken(bootstrap);

      const blob = new Blob([data.content], {
        type: data.contentType,
      });
      const url = URL.createObjectURL(blob);
      const anchor = document.createElement('a');
      anchor.href = url;
      anchor.download = data.fileName;
      document.body.appendChild(anchor);
      anchor.click();
      document.body.removeChild(anchor);
      URL.revokeObjectURL(url);

      notificationStore.success(
        `Script downloaded! Upload it to your server and run: ${setupScriptRunHint(data.fileName)}`,
      );
    } catch (error) {
      if (!bootstrapActive(generation)) return;
      logger.error('Failed to download script:', error);
      notificationStore.error('Failed to download script. Please check your connection.');
    }
  };

  const testResultPresentation = createMemo(() =>
    getNodeModalTestResultPresentation(testResult()?.status),
  );

  let previousResetKey: number | undefined;
  let previousNodeType: string | undefined;
  let previousFormSourceSignature: string | null = null;
  let previousFormSourceIdentity: string | null = null;
  // Once the user has typed into the form, background refreshes of the editing
  // target (poll cycles, adoption progress) must not rebuild formData and wipe
  // their unsaved input. Only an explicit reset or a different editing target
  // may resync after that point.
  let formEditedByUser = false;

  createEffect(() => {
    const key = props.resetKey;
    const nodeType = props.nodeType;
    const isOpen = props.isOpen;
    const editingNode = props.editingNode;
    const prefillNode = props.prefillNode;

    if (isOpen === false || key !== previousResetKey || nodeType !== previousNodeType) {
      bootstrapGeneration++;
      clearQuickSetupState();
      setLoadingAgentCommand(false);
    }

    if (key !== undefined && key !== previousResetKey) {
      previousResetKey = key;
      setFormData(() => getNodeModalDefaultFormData(props.nodeType));
      clearQuickSetupState();
      setTestResult(null);
      previousFormSourceSignature = null;
      previousFormSourceIdentity = null;
      formEditedByUser = false;
      return;
    }

    if (nodeType !== previousNodeType && previousNodeType !== undefined) {
      previousNodeType = nodeType;
      setFormData(() => getNodeModalDefaultFormData(props.nodeType));
      clearQuickSetupState();
      setTestResult(null);
      previousFormSourceSignature = null;
      previousFormSourceIdentity = null;
      formEditedByUser = false;
      return;
    }
    previousNodeType = nodeType;

    if (isOpen && !editingNode && !prefillNode) {
      setFormData(() => getNodeModalDefaultFormData(props.nodeType));
      clearQuickSetupState();
      setTestResult(null);
      previousFormSourceSignature = null;
      previousFormSourceIdentity = null;
      formEditedByUser = false;
    }
  });

  createEffect(() => {
    const node = props.editingNode ?? props.prefillNode;
    if (!node || node.type !== props.nodeType) {
      previousFormSourceSignature = null;
      previousFormSourceIdentity = null;
      return;
    }

    // Identify the editing target independently of its polled content, so a
    // refreshed snapshot of the same node counts as the same target while a
    // genuinely different node still resyncs the form.
    const formSourceIdentity = `${node.type}:${('id' in node && node.id) || `${node.name ?? ''}|${node.host ?? ''}`}`;
    if (formSourceIdentity !== previousFormSourceIdentity) {
      previousFormSourceIdentity = formSourceIdentity;
      formEditedByUser = false;
    } else if (formEditedByUser) {
      return;
    }

    let username = ('user' in node ? node.user : '') || '';
    const tokenName = node.tokenName || '';

    const usesToken =
      node.type !== 'pve' && tokenName && tokenName.includes('!') && !node.hasPassword;
    if (usesToken) {
      const parts = tokenName.split('!');
      username = parts[0];
    }

    const pveConfig =
      node.type === 'pve'
        ? (node as NodeConfig & {
            monitorVMs?: boolean;
            monitorContainers?: boolean;
            monitorStorage?: boolean;
            monitorBackups?: boolean;
          })
        : undefined;

    const pbsConfig =
      node.type === 'pbs'
        ? (node as NodeConfig & {
            monitorDatastores?: boolean;
            monitorSyncJobs?: boolean;
            monitorVerifyJobs?: boolean;
            monitorPruneJobs?: boolean;
            monitorGarbageJobs?: boolean;
            excludeDatastores?: string[];
          })
        : undefined;

    const pmgConfig =
      node.type === 'pmg'
        ? (node as NodeConfig & {
            monitorMailStats?: boolean;
            monitorQueues?: boolean;
            monitorQuarantine?: boolean;
            monitorDomainStats?: boolean;
          })
        : undefined;

    const formSource: NodeModalFormData = {
      name: node.name || '',
      host: node.host || '',
      guestURL: ('guestURL' in node ? node.guestURL : '') || '',
      authType: node.type === 'pmg' ? 'password' : node.hasPassword ? 'password' : 'token',
      setupMode: node.source === 'agent' ? 'agent' : 'auto',
      user: username,
      password: '',
      tokenName,
      tokenValue: '',
      fingerprint: ('fingerprint' in node ? node.fingerprint : '') || '',
      verifySSL: node.verifySSL ?? true,
      monitorVMs: pveConfig?.monitorVMs ?? true,
      monitorContainers: pveConfig?.monitorContainers ?? true,
      monitorStorage: pveConfig?.monitorStorage ?? true,
      monitorBackups: pveConfig?.monitorBackups ?? true,
      monitorPhysicalDisks:
        node.type === 'pve'
          ? ((node as NodeConfig & { monitorPhysicalDisks?: boolean }).monitorPhysicalDisks ?? true)
          : false,
      physicalDiskPollingMinutes:
        node.type === 'pve'
          ? ((node as NodeConfig & { physicalDiskPollingMinutes?: number })
              .physicalDiskPollingMinutes ?? 5)
          : 5,
      monitorDatastores: pbsConfig?.monitorDatastores ?? true,
      monitorSyncJobs: pbsConfig?.monitorSyncJobs ?? true,
      monitorVerifyJobs: pbsConfig?.monitorVerifyJobs ?? true,
      monitorPruneJobs: pbsConfig?.monitorPruneJobs ?? true,
      monitorGarbageJobs: pbsConfig?.monitorGarbageJobs ?? true,
      excludeDatastores: pbsConfig?.excludeDatastores?.join(', ') ?? '',
      monitorMailStats: pmgConfig?.monitorMailStats ?? true,
      monitorQueues: pmgConfig?.monitorQueues ?? true,
      monitorQuarantine: pmgConfig?.monitorQuarantine ?? true,
      monitorDomainStats: pmgConfig?.monitorDomainStats ?? false,
      clusterEndpointOverrides:
        node.type === 'pve' && 'clusterEndpoints' in node
          ? Object.fromEntries(
              (node.clusterEndpoints ?? []).map((endpoint) => [
                endpoint.nodeName,
                endpoint.ipOverride ?? '',
              ]),
            )
          : {},
      clusterEndpointTrustEdited: {},
      clusterEndpointFingerprints:
        node.type === 'pve' && 'clusterEndpoints' in node
          ? Object.fromEntries(
              (node.clusterEndpoints ?? []).flatMap((endpoint) =>
                endpoint.tlsEndpoint ? [[endpoint.tlsEndpoint, endpoint.fingerprint ?? '']] : [],
              ),
            )
          : {},
      clusterNodeDisplayNames:
        node.type === 'pve' && 'clusterEndpoints' in node
          ? Object.fromEntries(
              (node.clusterEndpoints ?? [])
                .filter((endpoint) => endpoint.nodeIdentity)
                .map((endpoint) => [endpoint.nodeIdentity, endpoint.displayName ?? '']),
            )
          : {},
    };

    const formSourceSignature = JSON.stringify(formSource);
    if (formSourceSignature === previousFormSourceSignature) {
      return;
    }

    previousFormSourceSignature = formSourceSignature;
    setFormData(formSource);
  });

  const handleSubmit = (event: Event) => {
    event.preventDefault();
    const data = formData();

    if (
      !isEditingExistingNode() &&
      props.nodeType !== 'pmg' &&
      data.authType === 'token' &&
      data.setupMode !== 'manual'
    ) {
      const setupPath =
        data.setupMode === 'agent' ? 'Host Telemetry Agent command' : 'API Inventory setup command';
      notificationStore.info(
        `Run the ${setupPath} on the host. Pulse will add the node automatically.`,
      );
      return;
    }

    const normalizedName = data.name.trim() || deriveNameFromHost(data.host);
    if (!normalizedName) {
      notificationStore.error('Node name is required');
      return;
    }

    if (normalizedName !== data.name) {
      setFormData((prev) => ({ ...prev, name: normalizedName }));
    }

    const nodeData: Partial<NodeConfig> = {
      type: props.nodeType,
      name: normalizedName,
      host: data.host,
      guestURL: data.guestURL,
      fingerprint: data.fingerprint,
      verifySSL: data.verifySSL,
    };

    if (data.authType === 'password') {
      nodeData.user = data.user;
      if (data.password) {
        nodeData.password = data.password;
      }
    } else {
      nodeData.tokenName = data.tokenName;
      if (data.tokenValue) {
        nodeData.tokenValue = data.tokenValue;
      }
    }

    Object.assign(nodeData, buildNodeModalMonitoringPayload(props.nodeType, data));

    if (props.nodeType === 'pve' && isEditingExistingNode()) {
      const editingNode = props.editingNode;
      const endpoints =
        editingNode && 'clusterEndpoints' in editingNode ? editingNode.clusterEndpoints : undefined;
      const overrides = buildClusterEndpointOverridesPayload(
        endpoints,
        data.clusterEndpointOverrides,
      );
      if (overrides) {
        Object.assign(nodeData, { clusterEndpointOverrides: overrides });
      }
      const trustOverrides = buildClusterEndpointTrustOverridesPayload(
        endpoints,
        data.clusterEndpointFingerprints,
        data.clusterEndpointTrustEdited,
      );
      if (trustOverrides)
        Object.assign(nodeData, { clusterEndpointTrustOverrides: trustOverrides });
      const displayNameOverrides = buildClusterNodeDisplayNameOverridesPayload(
        endpoints,
        data.clusterNodeDisplayNames,
      );
      if (displayNameOverrides) {
        Object.assign(nodeData, { clusterNodeDisplayNameOverrides: displayNameOverrides });
      }
    }

    props.onSave(nodeData);
  };

  const updateField = (field: string, value: string | boolean | number) => {
    formEditedByUser = true;
    probeGeneration++;
    setTestResult(null);
    if (field === 'host' && typeof value === 'string') {
      setFormData((prev) => {
        const next = { ...prev, host: value };
        const derivedName = deriveNameFromHost(value);
        const previousDerivedName = deriveNameFromHost(prev.host || '');
        const shouldAutoUpdate =
          !prev.name.trim() || (previousDerivedName && prev.name === previousDerivedName);
        if (derivedName && shouldAutoUpdate) {
          next.name = derivedName;
        }
        return next;
      });
      clearQuickSetupState();
      return;
    }

    setFormData((prev) => ({ ...prev, [field]: value }));
    if (field === 'setupMode') {
      if (value !== 'auto') {
        clearQuickSetupState();
      }
      if (value !== 'agent') {
        setAgentInstallCommand('');
      }
    }
  };

  const updateClusterEndpointOverride = (nodeName: string, value: string) => {
    formEditedByUser = true;
    probeGeneration++;
    setTestResult(null);
    setFormData((prev) => ({
      ...prev,
      clusterEndpointOverrides: { ...prev.clusterEndpointOverrides, [nodeName]: value },
    }));
  };

  const updateClusterNodeDisplayName = (nodeIdentity: string, value: string) => {
    formEditedByUser = true;
    setFormData((prev) => ({
      ...prev,
      clusterNodeDisplayNames: { ...prev.clusterNodeDisplayNames, [nodeIdentity]: value },
    }));
  };

  const updateClusterEndpointFingerprint = (endpoint: string, value: string) => {
    formEditedByUser = true;
    probeGeneration++;
    setTestResult(null);
    setFormData((prev) => ({
      ...prev,
      clusterEndpointFingerprints: { ...prev.clusterEndpointFingerprints, [endpoint]: value },
      clusterEndpointTrustEdited: { ...prev.clusterEndpointTrustEdited, [endpoint]: true },
    }));
  };

  const testSavedEndpoint = async (endpoint?: ClusterEndpoint) => {
    const data = formData();
    if (
      data.host !== props.editingNode?.host ||
      (endpoint &&
        (data.clusterEndpointOverrides[endpoint.nodeName] ?? '') !== (endpoint.ipOverride ?? '')) ||
      (endpoint && (data.password || data.tokenValue))
    ) {
      setTestResult({
        endpoint: endpoint?.tlsEndpoint,
        status: 'error',
        message:
          'Save changed addresses or credentials before testing this endpoint with stored credentials.',
      });
      return;
    }
    if (endpoint && !endpoint.tlsEndpoint) return;
    const generation = ++probeGeneration;
    setIsTesting(true);
    setTestResult(null);
    try {
      const result = await NodesAPI.testExistingNode(props.editingNode!.id, {
        verifySSL: data.verifySSL,
        ...(!endpoint || endpoint.usesPrimaryTLS
          ? { fingerprint: data.fingerprint }
          : data.clusterEndpointTrustEdited[endpoint.tlsEndpoint!]
            ? { fingerprint: data.clusterEndpointFingerprints[endpoint.tlsEndpoint!] ?? '' }
            : {}),
        ...(endpoint ? { endpoint: endpoint.tlsEndpoint } : {}),
      });
      if (generation !== probeGeneration) return;
      setTestResult({
        endpoint: endpoint?.tlsEndpoint,
        status: result.warnings?.length ? 'warning' : 'success',
        message: `${endpoint ? endpoint.nodeName + ': ' : ''}${result.message || 'Endpoint connection successful. Background collection was not tested.'}`,
        warnings: result.warnings,
      });
    } catch (error) {
      if (generation !== probeGeneration) return;
      const message =
        error instanceof Error
          ? error.message.replace(/^API request failed: \d{3}\s*/, '')
          : 'Connection failed';
      setTestResult({
        endpoint: endpoint?.tlsEndpoint,
        status: 'error',
        message: `${endpoint ? endpoint.nodeName + ': ' : ''}${message}`,
      });
    } finally {
      setIsTesting(false);
    }
  };

  const handleTestClusterEndpoint = (endpoint: ClusterEndpoint) => testSavedEndpoint(endpoint);

  const handleTestConnection = async () => {
    const data = formData();
    const normalizedName = data.name.trim() || deriveNameFromHost(data.host);

    if (!data.name.trim() && normalizedName) {
      setFormData((prev) => ({ ...prev, name: normalizedName }));
    }

    if (isEditingExistingNode()) {
      const hasNewPassword = data.authType === 'password' && data.password;
      const hasNewToken = data.authType === 'token' && data.tokenValue;

      if (!hasNewPassword && !hasNewToken) {
        await testSavedEndpoint();
        return;
      }
    }

    if (!data.host) {
      setTestResult({ status: 'error', message: 'Endpoint URL is required' });
      return;
    }

    if (data.authType === 'password' && (!data.user || !data.password)) {
      setTestResult({ status: 'error', message: 'Username and password are required' });
      return;
    }

    if (data.authType === 'token' && (!data.tokenName || !data.tokenValue)) {
      setTestResult({ status: 'error', message: 'Token ID and token value are required' });
      return;
    }

    const testData: Partial<NodeConfig> = {
      type: props.nodeType,
      name: normalizedName || '',
      host: data.host,
      fingerprint: data.fingerprint,
      verifySSL: data.verifySSL,
    };

    if (data.authType === 'password') {
      testData.user = data.user;
      testData.password = data.password;
    } else {
      testData.tokenName = data.tokenName;
      testData.tokenValue = data.tokenValue;
    }

    setIsTesting(true);
    setTestResult(null);

    try {
      const result = await NodesAPI.testConnection(testData as NodeConfig);
      setTestResult({
        status: result.warnings && result.warnings.length > 0 ? 'warning' : 'success',
        message: result.message || 'Connection successful',
        isCluster: result.isCluster,
        warnings: result.warnings,
      });
    } catch (error) {
      logger.error('Test connection error:', error);
      let errorMessage = 'Connection failed';
      if (error instanceof Error) {
        errorMessage = error.message.replace(/^API request failed: \d{3}\s*/, '');
      }
      setTestResult({
        status: 'error',
        message: errorMessage,
      });
    } finally {
      setIsTesting(false);
    }
  };

  return {
    agentCommandError,
    agentInstallCommand,
    agentInstallInsecure,
    copyCommand,
    copyProxmoxAgentInstallCommand,
    copyQuickSetupCommand,
    downloadProxmoxSetupScript,
    formData,
    handleSubmit,
    handleTestConnection,
    handleTestClusterEndpoint,
    isAdvancedSetupMode,
    isEditingExistingNode,
    isTesting,
    loadingAgentCommand,
    quickSetupExpiry,
    quickSetupExpiryLabel,
    quickSetupCommandReady,
    quickSetupTokenHint,
    setAgentInstallInsecure,
    showTemperatureMonitoringSection,
    temperatureMonitoringEnabledValue,
    testResult,
    testResultPresentation,
    updateClusterEndpointOverride,
    updateClusterEndpointFingerprint,
    updateClusterNodeDisplayName,
    updateField,
  };
};

export type NodeModalState = ReturnType<typeof useNodeModalState>;