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.

10.6 KB
Raw Blame
import type { DockerContainerUpdateStatus } from '@/types/api';
import type { ResourceActionReadiness } from '@/types/resource';

export interface ContainerUpdateBadgeProps {
  updateStatus?: DockerContainerUpdateStatus;
  compact?: boolean;
  showCurrent?: boolean;
}

export interface UpdateIconProps {
  updateStatus?: DockerContainerUpdateStatus;
}

export interface UpdateButtonProps {
  updateStatus?: DockerContainerUpdateStatus;
  agentId: string;
  containerId: string;
  containerName: string;
  // Unified resource id used to plan the audited update action. Without it
  // the button can only report that the update action is unavailable.
  resourceId?: string;
  // Server-evaluated readiness from the unified resource. When it carries an
  // unavailable 'update' entry the button renders disabled with the refusal
  // reason, instead of letting the click fail at POST /api/actions/plan.
  actionReadiness?: ResourceActionReadiness[];
  // Set when the server row does not advertise the update capability at all
  // (no refusal is recorded then), with the reason to show instead.
  updateNotOfferedReason?: string;
  // The container's host and whether its Pulse agent was installed with
  // command access. The server's refusal reads "not connected" either way;
  // these let the locked badge say which, and what to do about it.
  hostName?: string;
  hostCommandsEnabled?: boolean;
  compact?: boolean;
  /**
   * A 44px minimum height below the `sm` breakpoint, for a control a phone
   * user taps outside a dense table (the container drawer). Tables keep the
   * compact pill.
   */
  touchTarget?: boolean;
  onUpdateTriggered?: () => void;
  externalState?: 'updating' | 'queued' | 'error';
}

// The update click plans a governed action and opens the review dialog, which
// is the confirmation surface; there is no separate in-row confirming state.
export type UpdateState = 'idle' | 'queued' | 'updating' | 'success' | 'error' | 'inconclusive';

export interface ContainerUpdateButtonStoreState {
  startedAt: number;
  message?: string;
}

const UPDATE_BUTTON_BASE_CLASS =
  'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium transition-all';

function getDigestPreview(digest: string | undefined, length: number): string {
  return digest?.slice(0, length) || 'unknown';
}

export function hasContainerUpdate(updateStatus?: DockerContainerUpdateStatus): boolean {
  return updateStatus?.updateAvailable === true;
}

// Sentinel the agent reports for image@sha256 references, where there is no
// tag to resolve against the registry. Not a failure, so the surfaces render
// it as its own neutral state instead of "Check failed" (#1666).
const DIGEST_PINNED_SENTINEL = 'digest-pinned image';

// Sentinel for an image built or loaded on the host: it has no RepoDigest, so
// no registry holds a copy to compare against. Also not a failure.
const LOCAL_IMAGE_SENTINEL = 'local image';

export function isContainerUpdatePinned(updateStatus?: { error?: string }): boolean {
  return updateStatus?.error?.trim() === DIGEST_PINNED_SENTINEL;
}

export function isContainerUpdateLocalImage(updateStatus?: { error?: string }): boolean {
  return updateStatus?.error?.trim() === LOCAL_IMAGE_SENTINEL;
}

/** The image has no registry tag to check, which is a state, not a failed check. */
export function isContainerUpdateUncheckable(updateStatus?: { error?: string }): boolean {
  return isContainerUpdatePinned(updateStatus) || isContainerUpdateLocalImage(updateStatus);
}

export function getContainerUpdateUncheckableLabel(updateStatus?: { error?: string }): string {
  return isContainerUpdateLocalImage(updateStatus) ? 'Local' : 'Pinned';
}

export function hasContainerUpdateError(updateStatus?: DockerContainerUpdateStatus): boolean {
  return Boolean(updateStatus?.error) && !isContainerUpdateUncheckable(updateStatus);
}

export function hasContainerUpdateCurrent(updateStatus?: DockerContainerUpdateStatus): boolean {
  return updateStatus?.updateAvailable === false && !updateStatus?.error;
}

export function getContainerUpdateErrorTooltip(updateStatus?: DockerContainerUpdateStatus): string {
  return `Update check failed: ${updateStatus?.error || 'Unknown error'}`;
}

export function getContainerUpdatePinnedTooltip(): string {
  return 'This image is pinned to a specific digest, so there is no newer tag to check against';
}

export function getContainerUpdateLocalImageTooltip(): string {
  return 'This image was built or loaded on this host, so no registry has a newer version to check against';
}

export function getContainerUpdateUncheckableTooltip(updateStatus?: { error?: string }): string {
  return isContainerUpdateLocalImage(updateStatus)
    ? getContainerUpdateLocalImageTooltip()
    : getContainerUpdatePinnedTooltip();
}

export function getContainerUpdateCurrentTooltip(
  updateStatus?: DockerContainerUpdateStatus,
): string {
  if (!updateStatus?.currentDigest) return 'Image is current';

  const current = getDigestPreview(updateStatus.currentDigest, 12);
  return `Image is current\nDigest: ${current}...`;
}

/**
 * What the locked "Update available" badge says when Pulse cannot apply the
 * update. An agent that does not accept commands is the common case and has
 * one fix, so it is named outright instead of the server's transport wording,
 * with the exact place that hands over the command. An absent commandsEnabled
 * flag reads as false, so the copy says the agent does not accept commands
 * rather than claiming how it was installed.
 */
export function getUpdateUnavailableExplanation(input: {
  reason: string;
  reasonCode?: string;
  hostName?: string;
  hostCommandsEnabled?: boolean;
}): string {
  const host = input.hostName?.trim() || 'this host';
  if (input.reasonCode === 'command_agent_disconnected') {
    if (input.hostCommandsEnabled === false) {
      return (
        `Update available. Pulse cannot apply it because the Pulse agent on ${host} does not accept commands from Pulse.\n` +
        `To allow it, open Settings → Infrastructure, choose Manage on ${host}, and follow Remote commands. ` +
        'Or apply the update with your container manager.'
      );
    }
    if (input.hostCommandsEnabled === true) {
      return (
        `Update available. Pulse cannot apply it at the moment because the command channel to the Pulse agent on ${host} is not connected.\n` +
        'Check that the agent is running, or apply the update with your container manager.'
      );
    }
  }
  return `Update available. Pulse cannot apply it: ${input.reason}\nApply this update using your container manager on the host.`;
}

export function getContainerUpdateBadgeTooltip(updateStatus?: DockerContainerUpdateStatus): string {
  const current = getDigestPreview(updateStatus?.currentDigest, 19);
  const latest = getDigestPreview(updateStatus?.latestDigest, 19);
  return `Image update available\nCurrent: ${current}...\nLatest: ${latest}...`;
}

export function getUpdateIconTooltip(updateStatus?: DockerContainerUpdateStatus): string {
  if (!updateStatus) return 'Image update available';

  const current = getDigestPreview(updateStatus.currentDigest, 12);
  const latest = getDigestPreview(updateStatus.latestDigest, 12);
  return `Update available\nCurrent: ${current}...\nLatest: ${latest}...`;
}

export function getUpdateButtonClass(state: UpdateState, unavailable = false): string {
  if (unavailable && state === 'idle') {
    return `${UPDATE_BUTTON_BASE_CLASS} bg-surface-alt text-muted cursor-not-allowed opacity-70`;
  }
  switch (state) {
    case 'updating':
      return `${UPDATE_BUTTON_BASE_CLASS} bg-blue-100 text-blue-700 dark:bg-blue-900/25 dark:text-blue-300 cursor-wait`;
    case 'queued':
    case 'inconclusive':
      return `${UPDATE_BUTTON_BASE_CLASS} bg-amber-100 text-amber-800 dark:bg-amber-900/25 dark:text-amber-200 cursor-pointer hover:bg-amber-200 dark:hover:bg-amber-800`;
    case 'success':
      return `${UPDATE_BUTTON_BASE_CLASS} bg-green-100 text-green-700 dark:bg-green-900/25 dark:text-green-300`;
    case 'error':
      return `${UPDATE_BUTTON_BASE_CLASS} bg-red-100 text-red-700 dark:bg-red-900/25 dark:text-red-300 cursor-help`;
    default:
      return `${UPDATE_BUTTON_BASE_CLASS} bg-blue-100 text-blue-700 dark:bg-blue-900/25 dark:text-blue-300 cursor-pointer hover:bg-blue-200 dark:hover:bg-blue-900/25`;
  }
}

export function getUpdateButtonLabel(state: UpdateState, settingsLoaded: boolean): string {
  if (!settingsLoaded) return 'Update';

  switch (state) {
    case 'updating':
      return 'Updating...';
    case 'queued':
    case 'inconclusive':
      return 'Review action';
    case 'success':
      return 'Completed';
    case 'error':
      return 'Failed';
    default:
      return 'Update';
  }
}

export function getUpdateButtonTooltip(options: {
  state: UpdateState;
  updateStatus?: DockerContainerUpdateStatus;
  storeState?: ContainerUpdateButtonStoreState;
  errorMessage?: string;
  now?: number;
}): string {
  const now = options.now ?? Date.now();

  switch (options.state) {
    case 'queued':
      return 'Action sent. Outcome not yet known. Select to check its receipt. Do not start another update.';
    case 'inconclusive':
      return 'Action outcome unknown. Check the running container and image before any retry. Select to review the audit.';
    case 'updating': {
      const elapsed = options.storeState
        ? Math.round((now - options.storeState.startedAt) / 1000)
        : 0;
      const step = options.storeState?.message || 'Processing...';
      if (elapsed > 60) {
        return `${step} (${Math.floor(elapsed / 60)}m ${elapsed % 60}s)`;
      }
      return `${step} (${elapsed}s)`;
    }
    case 'success':
      return 'Update action completed. Check the running container and image.';
    case 'error':
      return `✗ Update failed: ${options.storeState?.message || options.errorMessage || 'Unknown error'}`;
    default:
      if (!options.updateStatus) return 'Update container';

      const current = getDigestPreview(options.updateStatus.currentDigest, 12);
      const latest = getDigestPreview(options.updateStatus.latestDigest, 12);
      return `Click to review and update\nCurrent: ${current}...\nLatest: ${latest}...`;
  }
}

/**
 * Pick the user-facing message for a failed update plan request.
 *
 * Availability refusals carry the actionable explanation (agent disconnected,
 * agent too old, stale inventory) in the API error's details.reason; the
 * top-level message is just "Action execution is unavailable".
 */
export function getUpdatePlanErrorMessage(error: unknown): string {
  const apiError = error as (Error & { details?: Record<string, string> }) | null;
  return (
    apiError?.details?.reason?.trim() || apiError?.message?.trim() || 'Failed to plan the update'
  );
}