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.

15.8 KB
Raw Blame
import { Show, createEffect, createMemo, createSignal, onMount } from 'solid-js';
import { useLocation, useNavigate, useSearchParams } from '@solidjs/router';
import ChevronRightIcon from 'lucide-solid/icons/chevron-right';
import EyeIcon from 'lucide-solid/icons/eye';
import RefreshCwIcon from 'lucide-solid/icons/refresh-cw';
import { getPatrolAutonomySettings } from '@/api/patrol';
import { ResourceActionsAPI } from '@/api/resourceActions';
import { Button, ButtonLink } from '@/components/shared/Button';
import { Card } from '@/components/shared/Card';
import { UpgradeButtonLink } from '@/components/shared/UpgradeLink';
import { PATROL_AUTONOMY_FEATURE_KEY } from '@/features/patrol/patrolAutonomyAvailability';
import { PATROL_PATH } from '@/routing/resourceLinks';
import { aiAvailabilityStore } from '@/stores/aiAvailability';
import { hasFeature } from '@/stores/license';
import { getUpgradeActionDestination } from '@/stores/licenseCommercial';
import {
  presentationPolicyHidesCommercialSurfaces,
  presentationPolicyHidesUpgradePrompts,
} from '@/stores/sessionPresentationPolicy';
import { MetadataBadge } from '@/components/shared/MetadataBadge';
import { PageHeader } from '@/components/shared/PageHeader';
import { Subtabs } from '@/components/shared/Subtabs';
import { ActionReviewDialog } from '@/features/actions/ActionReviewDialog';
import { PlatformWindowedList } from '@/features/platformPage/PlatformWindowedList';
import {
  ACTION_REVIEW_QUERY_PARAM,
  buildActionsViewPath,
  parseActionReviewId,
  parseActionsView,
} from '@/features/actions/actionRouting';
import {
  formatActionName,
  getActionOriginLabel,
  getActionAuditStatePresentation,
  getActionResourcePresentation,
  getActionsWatchOnlyEmptyState,
  sortOpenActionsForReview,
} from '@/features/actions/actionPresentation';
import type {
  ActionAuditRecord,
  ActionAuditState,
  ActionDetailResponse,
  ActionInboxView,
} from '@/types/actionAudit';
import { formatRelativeTime } from '@/utils/format';

const getInboxViewForState = (state: ActionAuditState): ActionInboxView =>
  state === 'rejected' || state === 'expired' || state === 'completed' || state === 'failed'
    ? 'settled'
    : 'pending';

export function Actions() {
  const location = useLocation();
  const [, setSearchParams] = useSearchParams();
  const navigate = useNavigate();
  const view = createMemo<ActionInboxView>(() => parseActionsView(location.pathname));
  const setView = (next: ActionInboxView, options: { replace?: boolean } = {}) => {
    if (view() === next) return;
    // The views switch in place, so navigation must not scroll to the top.
    navigate(`${buildActionsViewPath(next)}${location.search}`, { ...options, scroll: false });
  };
  const [selected, setSelected] = createSignal<ActionDetailResponse | null>(null);
  const [detailError, setDetailError] = createSignal('');
  const [actions, setActions] = createSignal<ActionAuditRecord[]>([]);
  const [loading, setLoading] = createSignal(true);
  const [loadError, setLoadError] = createSignal('');
  const [readOnly, setReadOnly] = createSignal(false);
  const [patrolWatchOnly, setPatrolWatchOnly] = createSignal(false);
  let listRequestGeneration = 0;
  let detailRequestGeneration = 0;

  // The Open tab is where users land wondering why nothing is queued. When
  // Patrol runs Watch only it never proposes fixes, so the calm state must say
  // that instead of implying actions will eventually show up on their own.
  onMount(() => {
    void getPatrolAutonomySettings()
      .then((settings) => setPatrolWatchOnly(settings.effective_autonomy_level === 'monitor'))
      .catch(() => {});
  });

  const watchOnlyGuidance = createMemo(() =>
    getActionsWatchOnlyEmptyState({
      aiEnabled: aiAvailabilityStore.enabled === true,
      patrolWatchOnly: patrolWatchOnly(),
      patrolModesUnlocked: hasFeature(PATROL_AUTONOMY_FEATURE_KEY),
      commercialSurfacesHidden: presentationPolicyHidesCommercialSurfaces(),
      upgradePromptsHidden: presentationPolicyHidesUpgradePrompts(),
      upgradeDestination: getUpgradeActionDestination('ai_autofix'),
    }),
  );

  const loadActions = async () => {
    const generation = ++listRequestGeneration;
    const requestedView = view();
    setLoading(true);
    setLoadError('');
    try {
      const response = await ResourceActionsAPI.listActions(requestedView);
      if (generation !== listRequestGeneration) return;
      setActions(response.actions);
      setReadOnly(response.readOnly === true);
    } catch (cause) {
      if (generation !== listRequestGeneration) return;
      setActions([]);
      setReadOnly(false);
      setLoadError(cause instanceof Error ? cause.message : 'The action store is unavailable.');
    } finally {
      if (generation === listRequestGeneration) setLoading(false);
    }
  };

  const queueSummary = createMemo(() => {
    const count = actions().length;
    if (view() === 'settled') {
      return `${count} recorded ${count === 1 ? 'outcome' : 'outcomes'}`;
    }
    const approvals = actions().filter((action) => action.state === 'pending_approval').length;
    const base = `${count} open ${count === 1 ? 'action' : 'actions'}`;
    return approvals > 0
      ? `${base} · ${approvals} ${approvals === 1 ? 'awaits' : 'await'} approval`
      : base;
  });

  const displayedActions = createMemo(() =>
    view() === 'pending' ? sortOpenActionsForReview(actions()) : actions(),
  );

  const openActionById = async (actionId: string, generation: number) => {
    try {
      const detail = await ResourceActionsAPI.getAction(actionId);
      if (
        generation !== detailRequestGeneration ||
        parseActionReviewId(location.search) !== actionId
      )
        return;
      if (detail.audit.id !== actionId) {
        setDetailError('Action details did not match the selected action. Open it again.');
        return;
      }
      setSelected(detail);
      setView(getInboxViewForState(detail.audit.state), { replace: true });
    } catch (cause) {
      if (
        generation !== detailRequestGeneration ||
        parseActionReviewId(location.search) !== actionId
      )
        return;
      setDetailError(cause instanceof Error ? cause.message : 'Action details are unavailable.');
    }
  };

  const openAction = (record: ActionAuditRecord) => {
    setSearchParams({ [ACTION_REVIEW_QUERY_PARAM]: record.id }, { replace: true });
  };

  const closeAction = () => {
    ++detailRequestGeneration;
    setSelected(null);
    setDetailError('');
    setSearchParams({ [ACTION_REVIEW_QUERY_PARAM]: null }, { replace: true });
  };

  createEffect(() => {
    view();
    void loadActions();
  });

  createEffect(() => {
    const actionId = parseActionReviewId(location.search);
    const generation = ++detailRequestGeneration;
    setSelected(null);
    setDetailError('');
    if (actionId) void openActionById(actionId, generation);
  });

  return (
    <div class="space-y-6">
      <PageHeader
        title="Actions"
        description="Review approvals, run ready work, and see what happened."
        actions={
          <Button
            variant="ghost"
            size="sm"
            aria-label="Refresh actions"
            onClick={() => void loadActions()}
            isLoading={loading()}
          >
            <RefreshCwIcon class="mr-2 h-4 w-4" />
            Refresh
          </Button>
        }
      />
      <Subtabs
        value={view()}
        onChange={(nextView) => setView(nextView as ActionInboxView)}
        tabs={[
          { value: 'pending', label: 'Open' },
          { value: 'settled', label: 'History' },
        ]}
        ariaLabel="Action views"
        trailing={
          <Show when={!loading() && actions().length > 0}>
            <span class="pb-2 text-xs text-muted">{queueSummary()}</span>
          </Show>
        }
      />

      <Show when={readOnly()}>
        <div class="flex items-center gap-2 rounded-md border border-border-subtle px-3 py-2 text-xs text-muted">
          <EyeIcon class="h-4 w-4 shrink-0" aria-hidden="true" />
          <span>
            <strong class="font-medium text-base-content">Read-only demo data.</strong> You can
            inspect plans, policy evidence, and recorded outcomes.
          </span>
        </div>
      </Show>

      <Show when={detailError()}>
        <div
          role="alert"
          class="rounded-sm border border-amber-300 bg-amber-50 p-3 text-sm text-amber-800 dark:bg-amber-950/40 dark:text-amber-200"
        >
          {detailError()}
        </div>
      </Show>
      <Show when={loadError()}>
        <div
          role="alert"
          class="rounded-lg border border-red-300 bg-red-50 p-4 text-sm text-red-800 dark:bg-red-950/40 dark:text-red-200"
        >
          <p class="font-medium">Actions could not be loaded.</p>
          <p class="mt-1">{loadError()}</p>
          <Button class="mt-3" onClick={() => void loadActions()}>
            Try again
          </Button>
        </div>
      </Show>
      <Show when={!loading() && !loadError() && actions().length === 0}>
        <div
          data-testid="actions-calm-state"
          class="rounded-md border border-dashed border-border bg-surface p-6 text-center"
        >
          <h2 class="text-lg font-semibold">
            {view() === 'pending' ? 'No actions need attention' : 'No action history yet'}
          </h2>
          <Show
            when={view() === 'pending' ? watchOnlyGuidance() : undefined}
            keyed
            fallback={
              <p class="mt-2 text-sm text-muted">
                {view() === 'pending'
                  ? 'Pulse will place proposed or in-progress changes here for review.'
                  : 'Completed, rejected, expired, and failed actions will appear here.'}
              </p>
            }
          >
            {(guidance) => (
              <>
                <p class="mx-auto mt-2 max-w-xl text-sm text-muted">{guidance.body}</p>
                <Show when={guidance.kind === 'switch'}>
                  <ButtonLink href={PATROL_PATH} variant="primary" size="sm" class="mt-4">
                    {guidance.actionLabel}
                  </ButtonLink>
                </Show>
                <Show when={guidance.kind === 'upgrade' ? guidance.destination : undefined} keyed>
                  {(destination) => (
                    <div class="mt-4 flex justify-center">
                      <UpgradeButtonLink
                        destination={destination}
                        size="sm"
                        mobileFullWidth={false}
                      >
                        {guidance.actionLabel}
                      </UpgradeButtonLink>
                    </div>
                  )}
                </Show>
              </>
            )}
          </Show>
        </div>
      </Show>
      <Show when={actions().length > 0}>
        <Card padding="none" class="overflow-hidden" data-testid="actions-queue">
          <div
            role="list"
            class="divide-y divide-border-subtle"
            aria-label={view() === 'pending' ? 'Open actions' : 'Action history'}
          >
            <PlatformWindowedList
              items={displayedActions}
              estimatedItemHeight={92}
              enableThreshold={36}
              windowSize={48}
            >
              {(action) => {
                const state = () => getActionAuditStatePresentation(action);
                const resource = () =>
                  getActionResourcePresentation(action.request.resourceId, action.resource);
                const title = () => formatActionName(action.request.capabilityName);
                const originLabel = () => getActionOriginLabel(action.origin);
                return (
                  <div role="listitem">
                    <button
                      type="button"
                      aria-label={`Review ${title()} on ${action.request.resourceId}, ${state().label}`}
                      class={`group w-full border-l-2 px-3 py-3 text-left transition-colors hover:bg-surface-hover focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-blue-500 sm:px-4 ${state().accentClass}`}
                      onClick={() => openAction(action)}
                    >
                      <div class="flex items-center gap-3">
                        <div class="min-w-0 flex-1">
                          <div class="flex flex-wrap items-center gap-2">
                            <MetadataBadge
                              tone={state().tone}
                              size="xs"
                              shape="rounded"
                              appearance="outline"
                            >
                              {state().label}
                            </MetadataBadge>
                            <Show when={originLabel()}>
                              {(label) => (
                                <MetadataBadge tone="info" size="xs" shape="rounded">
                                  {label()}
                                </MetadataBadge>
                              )}
                            </Show>
                            <span class="truncate text-sm font-semibold text-base-content">
                              {title()}
                            </span>
                          </div>
                          <div
                            class="mt-1 flex min-w-0 items-center gap-1.5 text-xs text-muted"
                            title={action.request.resourceId}
                          >
                            {/* The name says what the action touches, so it keeps its
                                width and only the type, with its separator, gives way. */}
                            <span class="flex min-w-0 items-center gap-1.5">
                              <span class="max-w-full shrink-0 truncate">{resource().label}</span>
                              <Show when={resource().detail}>
                                <span class="min-w-0 flex-1 truncate">
                                  <span class="mr-1.5" aria-hidden="true">
                                    ·
                                  </span>
                                  <span class="font-mono text-[11px]">{resource().detail}</span>
                                </span>
                              </Show>
                            </span>
                            <span aria-hidden="true">·</span>
                            <span class="shrink-0">{formatRelativeTime(action.updatedAt)}</span>
                          </div>
                          <p class="mt-1.5 truncate text-sm text-muted">{action.request.reason}</p>
                        </div>
                        <span class="inline-flex shrink-0 items-center gap-1 rounded-sm border border-border px-2 py-1 text-xs font-medium text-muted transition-colors group-hover:bg-surface group-hover:text-base-content">
                          Review
                          <ChevronRightIcon class="h-3.5 w-3.5" aria-hidden="true" />
                        </span>
                      </div>
                    </button>
                  </div>
                );
              }}
            </PlatformWindowedList>
          </div>
        </Card>
      </Show>
      <ActionReviewDialog
        detail={selected()}
        showResourceLink
        onClose={closeAction}
        onChanged={async (detail) => {
          // A read or mutation started in an earlier review must not replace
          // the action currently selected by the URL (or reopen a closed one).
          if (
            selected()?.audit.id !== detail.audit.id ||
            parseActionReviewId(location.search) !== detail.audit.id
          )
            return;
          setSelected(detail);
          const nextView = getInboxViewForState(detail.audit.state);
          if (view() === nextView) await loadActions();
          else setView(nextView, { replace: true }); // the view effect loads the new list once
        }}
      />
    </div>
  );
}

export default Actions;