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.

23.1 KB
Raw Blame
import { Show, createSignal, createEffect, createMemo, For, onCleanup } from 'solid-js';
import { updateStore } from '@/stores/updates';
import { runtimeCapabilities } from '@/stores/license';
import { UpdatesAPI, type UpdatePlan } from '@/api/updates';
import { UpdateConfirmationModal } from './UpdateConfirmationModal';
import { copyToClipboard } from '@/utils/clipboard';
import { logger } from '@/utils/logger';
import { buildReleaseNotesUrl, normalizeReleaseVersion } from '@/components/updateVersion';
import { extractHighlights } from '@/components/whatsNewModel';
import { renderMarkdown } from '@/components/AI/aiChatUtils';

// The Pro binary self-updates from the license server download broker (see
// internal/updates/pro_update.go), so in-app apply keeps the Pro runtime.
// The portal is the manual path for deployments the updater cannot drive
// (e.g. Docker), where the community pull/instructions would strip Pro.
const PRO_RELEASE_ACCESS_URL = 'https://pulserelay.pro/download.html';

export function UpdateBanner() {
  const [isExpanded, setIsExpanded] = createSignal(false);
  const [updatePlan, setUpdatePlan] = createSignal<UpdatePlan | null>(null);
  const [showConfirmModal, setShowConfirmModal] = createSignal(false);
  const [isApplying, setIsApplying] = createSignal(false);
  const [copiedIndex, setCopiedIndex] = createSignal<number | null>(null);
  let latestPlanRequestID = 0;
  let copiedTimer: ReturnType<typeof setTimeout> | undefined;

  onCleanup(() => {
    // Invalidate any plan request still settling after this banner unmounts.
    // Navigation-aborted requests are stale work, not user-visible failures.
    latestPlanRequestID += 1;
    if (copiedTimer) clearTimeout(copiedTimer);
  });

  // Fetch update plan when update info is available
  createEffect(() => {
    const info = updateStore.updateInfo();
    const version = info?.available ? info.latestVersion?.trim() : '';
    const requestID = ++latestPlanRequestID;
    setUpdatePlan(null);

    if (!version) {
      return;
    }

    void UpdatesAPI.getUpdatePlan(version)
      .then((plan) => {
        if (requestID === latestPlanRequestID) {
          setUpdatePlan(plan);
        }
      })
      .catch((error) => {
        if (requestID !== latestPlanRequestID) return;
        setUpdatePlan(null);
        logger.error('Failed to fetch update plan', error);
      });
  });

  const releaseNotesUrl = createMemo(() =>
    buildReleaseNotesUrl(updateStore.updateInfo()?.latestVersion),
  );

  // Curated customer-facing improvements from the upcoming release help
  // answer "is this update worth taking now?" without leaving for GitHub.
  // Historical `Highlights` notes remain supported. Empty notes stay hidden.
  const highlightsHtml = createMemo(() => {
    const info = updateStore.updateInfo();
    if (!info?.available || !info.releaseNotes) return '';
    const highlights = extractHighlights(info.releaseNotes);
    return highlights ? renderMarkdown(highlights) : '';
  });

  // The compiled Pro binary self-updates from the license server download
  // broker, so in-app apply is safe and keeps the Pro runtime; only the
  // manual instructions differ (community pull/console steps would install
  // the community build). This keys off the binary's runtime identity
  // (business hooks presence), NOT the license tier: a community binary with
  // an active Pro license follows the normal community paths.
  const isProEdition = () => runtimeCapabilities()?.runtime?.build === 'pro';

  const handleApplyUpdate = () => {
    setShowConfirmModal(true);
  };

  const handleConfirmUpdate = async () => {
    setIsApplying(true);
    try {
      // The shared store action owns the POST and error toast.
      const started = await updateStore.applyUpdate();
      if (started) {
        // Close confirmation - GlobalUpdateProgressWatcher will auto-open the progress modal
        setShowConfirmModal(false);
      }
    } finally {
      setIsApplying(false);
    }
  };

  const handleCopy = async (text: string, index: number) => {
    const success = await copyToClipboard(text);
    if (!success) {
      logger.error(
        'Failed to copy update instruction to clipboard',
        new Error('clipboard copy failed'),
      );
      return;
    }
    setCopiedIndex(index);
    if (copiedTimer) clearTimeout(copiedTimer);
    copiedTimer = setTimeout(() => setCopiedIndex(null), 2000);
  };

  // Get deployment type message
  const getUpdateInstructions = () => {
    const versionInfo = updateStore.versionInfo();
    const deploymentType = versionInfo?.deploymentType || 'systemd';

    switch (deploymentType) {
      case 'proxmoxve':
        return updatePlan()?.canAutoUpdate
          ? "ProxmoxVE LXC: use Apply Update here. Do not use a legacy community 'update' helper"
          : 'ProxmoxVE LXC: use the signed Pulse installer, not a legacy community update helper';
      case 'docker':
        return 'Docker: pull image and recreate container';
      case 'source':
        return 'Source: pull and rebuild';
      case 'mock':
        return 'Mock environment: updates run automatically for integration tests';
      default:
        return ''; // No message, just the version info
    }
  };

  const getShortMessage = () => {
    const info = updateStore.updateInfo();
    if (!info) return '';
    return `New version available: ${info.latestVersion}`;
  };

  return (
    <Show when={updateStore.isUpdateVisible()}>
      <div
        data-testid="update-banner"
        class="update-banner bg-blue-50 dark:bg-blue-900/25 border-b border-blue-200 dark:border-blue-800 text-blue-800 dark:text-blue-200 relative animate-slideDown"
      >
        <div class="px-4 py-1.5">
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-3">
              {/* Update icon */}
              <svg
                class="w-4 h-4 shrink-0"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
              >
                <path
                  d="M12 2v6m0 0l3-3m-3 3l-3-3"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                />
                <path
                  d="M2 17l.621 2.485A2 2 0 0 0 4.561 21h14.878a2 2 0 0 0 1.94-1.515L22 17"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                />
              </svg>

              <div class="flex items-center gap-3 flex-wrap">
                <span class="text-sm font-medium">{getShortMessage()}</span>

                {/* Pre-release badge */}
                <Show when={updateStore.updateInfo()?.isPrerelease && !isExpanded()}>
                  <span class="px-2 py-0.5 text-xs font-medium bg-orange-100 dark:bg-orange-900 text-orange-800 dark:text-orange-200 rounded-sm">
                    Pre-release
                  </span>
                </Show>

                {/* Apply Update Button (automated deployments; Pro applies
                    the private build from the license server broker) */}
                <Show when={updatePlan()?.canAutoUpdate && !isExpanded()}>
                  <button
                    onClick={handleApplyUpdate}
                    class="px-3 py-1 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-sm transition-colors"
                  >
                    Apply Update
                  </button>
                </Show>

                {/* Manual Steps Badge (non-automated community deployments) */}
                <Show
                  when={
                    updatePlan() && !updatePlan()?.canAutoUpdate && !isExpanded() && !isProEdition()
                  }
                >
                  <span class="px-2 py-0.5 text-xs font-medium bg-orange-100 dark:bg-orange-900 text-orange-800 dark:text-orange-200 rounded-sm">
                    Manual steps required
                  </span>
                </Show>

                {/* Pro edition without auto-update (e.g. Docker): the community
                    pull instructions would strip Pro, so route to the portal */}
                <Show
                  when={
                    isProEdition() && updatePlan() && !updatePlan()?.canAutoUpdate && !isExpanded()
                  }
                >
                  <a
                    href={PRO_RELEASE_ACCESS_URL}
                    target="_blank"
                    rel="noopener noreferrer"
                    class="px-3 py-1 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-sm transition-colors"
                  >
                    Update via Private Release Access →
                  </a>
                </Show>

                {!isExpanded() && !isProEdition() && getUpdateInstructions() && (
                  <>
                    <span class="text-blue-600 dark:text-blue-400 text-sm hidden sm:inline">•</span>
                    <span class="text-blue-600 dark:text-blue-400 text-sm hidden sm:inline">
                      {getUpdateInstructions()}
                    </span>
                  </>
                )}
                {!isExpanded() && (
                  <a
                    href={releaseNotesUrl()}
                    target="_blank"
                    rel="noopener noreferrer"
                    class="text-blue-600 dark:text-blue-400 underline text-sm hidden sm:inline hover:text-blue-700 dark:hover:text-blue-300"
                  >
                    View details →
                  </a>
                )}
              </div>
            </div>

            <div class="flex items-center gap-2">
              {/* Expand/Collapse button */}
              <button
                onClick={() => setIsExpanded(!isExpanded())}
                class="p-1 hover:bg-blue-100 dark:hover:bg-blue-800 rounded-sm transition-colors"
                title={isExpanded() ? 'Show less' : 'Show more'}
              >
                <svg
                  class={`w-4 h-4 transform transition-transform ${isExpanded() ? 'rotate-180' : ''}`}
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                >
                  <polyline points="6 9 12 15 18 9"></polyline>
                </svg>
              </button>

              {/* Dismiss button */}
              <button
                onClick={() => updateStore.dismissUpdate()}
                class="p-1 hover:bg-blue-100 dark:hover:bg-blue-800 rounded-sm transition-colors"
                title="Dismiss this update"
              >
                <svg
                  class="w-4 h-4"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                >
                  <line x1="18" y1="6" x2="6" y2="18"></line>
                  <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
              </button>
            </div>
          </div>

          {/* Expanded content */}
          <Show when={isExpanded()}>
            <div class="mt-2 pb-1">
              <div class="text-sm text-blue-700 dark:text-blue-300 space-y-1">
                <p>
                  <span class="font-medium">Current:</span>{' '}
                  {updateStore.versionInfo()?.version || 'Unknown'} →
                  <span class="font-medium ml-1">Latest:</span>{' '}
                  {updateStore.updateInfo()?.latestVersion}
                </p>

                {/* What's new preview (customer-facing improvements or historical Highlights) */}
                <Show when={highlightsHtml()}>
                  <div class="mt-2 p-3 rounded-md border bg-blue-100 dark:bg-blue-950/25 border-blue-300 dark:border-blue-700 text-blue-800 dark:text-blue-200">
                    <div class="font-medium mb-1">
                      What's new in v
                      {normalizeReleaseVersion(updateStore.updateInfo()?.latestVersion)}
                    </div>
                    <div
                      class="max-h-40 overflow-y-auto [&_ul]:list-disc [&_ul]:pl-4 [&_ol]:list-decimal [&_ol]:pl-4 [&_li]:mt-0.5 [&_p]:mt-1 [&_a]:underline [&_code]:font-mono [&_code]:text-xs"
                      // eslint-disable-next-line solid/no-innerhtml -- renderMarkdown sanitizes via DOMPurify
                      innerHTML={highlightsHtml()}
                    />
                  </div>
                </Show>

                {/* Pro edition with in-app apply: updates install the private
                    Pulse Pro build from the license server */}
                <Show when={isProEdition() && updatePlan()?.canAutoUpdate}>
                  <p class="text-xs">
                    Updates install the private Pulse Pro build from the license server, so applying
                    keeps Pro features (Audit, RBAC, Reporting, SSO).
                  </p>
                </Show>

                {/* Pro edition without auto-update: portal update path (the
                    community instructions below would strip Pro features) */}
                <Show when={isProEdition() && updatePlan() && !updatePlan()?.canAutoUpdate}>
                  <div class="mt-2 p-3 rounded-md border bg-blue-100 dark:bg-blue-950/25 border-blue-300 dark:border-blue-700 text-blue-800 dark:text-blue-200">
                    <div class="font-medium mb-1">Pulse Pro update</div>
                    <Show
                      when={updateStore.updateInfo()?.dockerUpdate}
                      fallback={
                        <>
                          <p>
                            This deployment updates manually, and the public community build would
                            remove Pro features (Audit, RBAC, Reporting, SSO). Update from Private
                            Release Access instead:
                          </p>
                          <ol class="list-decimal ml-5 mt-1 space-y-0.5">
                            <li>
                              Download the new Pro archive and its{' '}
                              <code class="font-mono text-xs">.sshsig</code> sidecar from the
                              portal.
                            </li>
                            <li>
                              Run{' '}
                              <code class="font-mono text-xs">
                                sudo bash install.sh --archive ./pulse-pro-…tar.gz
                              </code>
                              .
                            </li>
                          </ol>
                        </>
                      }
                    >
                      {(dockerUpdate) => (
                        <>
                          <p>
                            This container runs the Pulse Pro image (the public rcourtman/pulse
                            image would remove Pro features). Run these digest-pinned commands on
                            the Docker host, or copy them from Settings → Updates:
                          </p>
                          <ol class="list-decimal ml-5 mt-1 space-y-0.5">
                            <li>
                              <code class="font-mono text-xs break-all">
                                {dockerUpdate().composePullCommand}
                              </code>
                            </li>
                            <li>
                              <code class="font-mono text-xs break-all">
                                {dockerUpdate().composeUpCommand}
                              </code>
                            </li>
                          </ol>
                        </>
                      )}
                    </Show>
                    <a
                      href={PRO_RELEASE_ACCESS_URL}
                      target="_blank"
                      rel="noopener noreferrer"
                      class="inline-block mt-2 underline hover:text-blue-900 dark:hover:text-blue-100"
                    >
                      Open Private Release Access →
                    </a>
                  </div>
                </Show>

                {!isProEdition() && getUpdateInstructions() && (
                  <p>
                    <span class="font-medium">Safe upgrade:</span> {getUpdateInstructions()}
                  </p>
                )}
                <Show when={updateStore.updateInfo()?.warning}>
                  <div
                    class={`mt-2 p-3 rounded-md border text-sm ${
                      updateStore.updateInfo()?.isMajorUpgrade &&
                      updateStore.updateInfo()?.isPrerelease
                        ? 'bg-orange-50 dark:bg-orange-950 border-orange-300 dark:border-orange-700 text-orange-800 dark:text-orange-200'
                        : updateStore.updateInfo()?.isMajorUpgrade
                          ? 'bg-amber-50 dark:bg-amber-950/25 border-amber-300 dark:border-amber-700 text-amber-800 dark:text-amber-200'
                          : 'bg-blue-100 dark:bg-blue-950/25 border-blue-300 dark:border-blue-700 text-blue-800 dark:text-blue-200'
                    }`}
                  >
                    <div class="flex items-start gap-2">
                      <svg
                        class="w-4 h-4 mt-0.5 shrink-0"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          stroke-width="2"
                          d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
                        />
                      </svg>
                      <span>{updateStore.updateInfo()?.warning}</span>
                    </div>
                  </div>
                </Show>

                {/* Manual Update Instructions (community deployments; Pro uses the portal block above) */}
                <Show
                  when={
                    !isProEdition() &&
                    updatePlan()?.instructions &&
                    (updatePlan()?.instructions?.length ?? 0) > 0
                  }
                >
                  <div class="mt-3 pt-3 border-t border-blue-200 dark:border-blue-800">
                    <div class="font-medium mb-2">Update Instructions:</div>
                    <div class="space-y-2">
                      <For each={updatePlan()?.instructions || []}>
                        {(instruction, index) => (
                          <div class="bg-surface-alt rounded-sm border border-blue-200 dark:border-blue-700 p-2">
                            <div class="flex items-start justify-between gap-2">
                              <code class="text-xs text-base-content font-mono flex-1 break-all">
                                {instruction}
                              </code>
                              <button
                                onClick={() => handleCopy(instruction, index())}
                                class="shrink-0 p-1 hover:bg-blue-100 dark:hover:bg-blue-800 rounded-sm transition-colors"
                                title="Copy to clipboard"
                              >
                                <Show
                                  when={copiedIndex() === index()}
                                  fallback={
                                    <svg
                                      class="w-4 h-4"
                                      fill="none"
                                      stroke="currentColor"
                                      viewBox="0 0 24 24"
                                    >
                                      <path
                                        stroke-linecap="round"
                                        stroke-linejoin="round"
                                        stroke-width="2"
                                        d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
                                      />
                                    </svg>
                                  }
                                >
                                  <svg
                                    class="w-4 h-4 text-green-600 dark:text-green-400"
                                    fill="none"
                                    stroke="currentColor"
                                    viewBox="0 0 24 24"
                                  >
                                    <path
                                      stroke-linecap="round"
                                      stroke-linejoin="round"
                                      stroke-width="2"
                                      d="M5 13l4 4L19 7"
                                    />
                                  </svg>
                                </Show>
                              </button>
                            </div>
                          </div>
                        )}
                      </For>
                    </div>
                  </div>
                </Show>

                {/* Apply Update Button (expanded view for automated deployments) */}
                <Show when={updatePlan()?.canAutoUpdate}>
                  <div class="mt-3 pt-3 border-t border-blue-200 dark:border-blue-800">
                    <button
                      onClick={handleApplyUpdate}
                      class="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-sm transition-colors"
                    >
                      Apply Update Automatically
                    </button>
                  </div>
                </Show>

                <div class="flex gap-3 mt-2">
                  <a
                    href={releaseNotesUrl()}
                    target="_blank"
                    rel="noopener noreferrer"
                    class="text-blue-600 dark:text-blue-400 underline hover:text-blue-700 dark:hover:text-blue-300 text-xs"
                  >
                    View release notes
                  </a>
                  <button
                    onClick={() => updateStore.dismissUpdate()}
                    class="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 text-xs underline"
                  >
                    Don't show again for this version
                  </button>
                </div>
              </div>
            </div>
          </Show>
        </div>
      </div>

      {/* Update Confirmation Modal */}
      <UpdateConfirmationModal
        isOpen={showConfirmModal()}
        onClose={() => setShowConfirmModal(false)}
        onConfirm={handleConfirmUpdate}
        currentVersion={updateStore.versionInfo()?.version || 'Unknown'}
        latestVersion={updateStore.updateInfo()?.latestVersion || ''}
        plan={
          updatePlan() || {
            canAutoUpdate: false,
            requiresRoot: false,
            rollbackSupport: false,
          }
        }
        isApplying={isApplying()}
        isPrerelease={updateStore.updateInfo()?.isPrerelease}
        isMajorUpgrade={updateStore.updateInfo()?.isMajorUpgrade}
        warning={updateStore.updateInfo()?.warning}
      />
    </Show>
  );
}