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.

19.6 KB
Raw Blame
import { createSignal, Show } from 'solid-js';
import type { Accessor } from 'solid-js';
import type { PatrolRunRecord } from '@/api/patrol';
import { FindingsPanel } from '@/components/AI/FindingsPanel';
import { renderMarkdown } from '@/components/AI/aiChatUtils';
import { MetadataBadge } from '@/components/shared/MetadataBadge';
import { StatusIndicatorBadge } from '@/components/shared/StatusIndicatorBadge';
import { RunToolCallTrace } from './RunToolCallTrace';
import {
  formatDurationMs,
  formatPatrolRuntimeFailureDetail,
  formatTriggerReason,
  formatScope,
  getCanonicalScopeResourceIds,
  sanitizeAnalysis,
} from '@/utils/patrolFormat';
import { formatRelativeTime } from '@/utils/format';
import {
  getPatrolRunCoverageSummary,
  getPatrolRunResourcesHeading,
  getPatrolRunPrimaryActionPresentation,
  getPatrolRunOperatorRecordPresentation,
  getPatrolRunStatusPresentation,
  isPatrolRunHealthy,
} from '@/utils/patrolRunPresentation';

import BrainCircuitIcon from 'lucide-solid/icons/brain-circuit';
import ActivityIcon from 'lucide-solid/icons/activity';
import ShieldAlertIcon from 'lucide-solid/icons/shield-alert';
import CheckCircleIcon from 'lucide-solid/icons/check-circle';
import ServerIcon from 'lucide-solid/icons/server';
import MonitorIcon from 'lucide-solid/icons/monitor';
import BoxIcon from 'lucide-solid/icons/box';
import HardDriveIcon from 'lucide-solid/icons/hard-drive';
import GlobeIcon from 'lucide-solid/icons/globe';
import DatabaseIcon from 'lucide-solid/icons/database';
import SearchIcon from 'lucide-solid/icons/search';
import WrenchIcon from 'lucide-solid/icons/wrench';
import ClockIcon from 'lucide-solid/icons/clock';
import ZapIcon from 'lucide-solid/icons/zap';
import AlertTriangleIcon from 'lucide-solid/icons/alert-triangle';
import FilterXIcon from 'lucide-solid/icons/filter-x';
import SparklesIcon from 'lucide-solid/icons/sparkles';
import MailIcon from 'lucide-solid/icons/mail';
import RefreshCwIcon from 'lucide-solid/icons/refresh-cw';
import SettingsIcon from 'lucide-solid/icons/settings';

interface PatrolStreamState {
  phase: Accessor<string>;
  currentTool: Accessor<string>;
  tokens: Accessor<number>;
  resynced: Accessor<boolean>;
  resyncReason: Accessor<string>;
  bufferStartSeq: Accessor<number>;
  bufferEndSeq: Accessor<number>;
  outputTruncated: Accessor<boolean>;
  reconnectCount: Accessor<number>;
  isStreaming: Accessor<boolean>;
  errorMessage: Accessor<string>;
}

interface RunHistoryEntryProps {
  run: PatrolRunRecord;
  isLive: boolean;
  patrolStream: PatrolStreamState;
  selected: boolean;
  onSelect: (run: PatrolRunRecord | null) => void;
}

export function RunHistoryEntry(props: RunHistoryEntryProps) {
  const [showRunAnalysis, setShowRunAnalysis] = createSignal(true);
  const [showTechnicalDetails, setShowTechnicalDetails] = createSignal(false);

  // Live in-progress entry
  if (props.isLive) {
    const hasError = () => !!props.patrolStream.errorMessage();
    const resyncTitle = () => {
      const reason = props.patrolStream.resyncReason();
      const start = props.patrolStream.bufferStartSeq();
      const end = props.patrolStream.bufferEndSeq();
      const parts: string[] = [];
      if (reason) parts.push(`reason=${reason}`);
      if (start > 0 || end > 0) parts.push(`buffer=${start || '?'}..${end || '?'}`);
      if (props.patrolStream.outputTruncated()) parts.push('output_truncated=true');
      if (props.patrolStream.reconnectCount() > 0)
        parts.push(`reconnects=${props.patrolStream.reconnectCount()}`);
      return parts.length ? parts.join(' ') : '';
    };
    return (
      <div
        class={`rounded-md border transition-colors ${
          hasError()
            ? 'border-red-300 dark:border-red-700 bg-red-50 dark:bg-red-900/25'
            : 'border-blue-300 dark:border-blue-700 bg-blue-50 dark:bg-blue-900/25'
        }`}
      >
        <div class="px-3 py-2">
          <div class="flex flex-wrap items-center gap-2 text-xs">
            <Show when={!hasError()}>
              <span class="relative flex h-2.5 w-2.5">
                <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75" />
                <span class="relative inline-flex rounded-full h-2.5 w-2.5 bg-blue-500" />
              </span>
              <span class="font-medium text-blue-800 dark:text-blue-200">Running now</span>
            </Show>
            <Show
              when={
                !hasError() &&
                (props.patrolStream.resynced() || props.patrolStream.reconnectCount() > 0)
              }
            >
              <MetadataBadge title={resyncTitle()} tone="info" size="xs" shape="rounded">
                <RefreshCwIcon class="w-3 h-3" />
                <span>
                  {props.patrolStream.resynced()
                    ? props.patrolStream.resyncReason() === 'buffer_rotated'
                      ? 'Resynced (truncated)'
                      : 'Resynced'
                    : `Reconnected${props.patrolStream.reconnectCount() > 1 ? ` x${props.patrolStream.reconnectCount()}` : ''}`}
                </span>
              </MetadataBadge>
            </Show>
            <Show when={hasError()}>
              <ShieldAlertIcon class="w-3.5 h-3.5 text-red-500" />
              <span class="font-medium text-red-800 dark:text-red-200">Error</span>
            </Show>
            <Show when={!hasError() && props.patrolStream.phase()}>
              <span class="text-blue-700 dark:text-blue-300">{props.patrolStream.phase()}</span>
            </Show>
            <Show when={!hasError() && props.patrolStream.currentTool()}>
              <MetadataBadge tone="info" size="xs" shape="rounded" class="font-mono">
                {props.patrolStream.currentTool()}
              </MetadataBadge>
            </Show>
            <Show when={!hasError() && props.patrolStream.tokens() > 0}>
              <span class="text-blue-500 dark:text-blue-400 ml-auto">
                {props.patrolStream.tokens().toLocaleString()} tokens
              </span>
            </Show>
          </div>
          <Show when={hasError()}>
            <p class="mt-1.5 text-xs text-red-700 dark:text-red-300">
              {props.patrolStream.errorMessage()}
            </p>
          </Show>
        </div>
      </div>
    );
  }

  // Completed run entry
  const run = props.run;
  const canonicalScopeResourceIds = getCanonicalScopeResourceIds(run);
  const runIsHealthy = isPatrolRunHealthy(run.status, run.error_count);
  const coverageSummary = getPatrolRunCoverageSummary(run);
  const hasFindingsSnapshot = run.finding_ids !== undefined;
  const runStatus = getPatrolRunStatusPresentation(
    run.status,
    run.error_count,
    hasFindingsSnapshot,
  );
  const operatorRecord = getPatrolRunOperatorRecordPresentation(run);
  const runErrorSummary = formatPatrolRuntimeFailureDetail(run.error_summary);
  const runErrorDetail = formatPatrolRuntimeFailureDetail(run.error_detail);
  const hasRunErrorDetail = run.error_count > 0 && (runErrorSummary || runErrorDetail);
  const primaryAction = getPatrolRunPrimaryActionPresentation(run);

  return (
    <div
      class={`rounded-md border transition-colors ${
        props.selected
          ? 'border-blue-300 dark:border-blue-700 bg-blue-50 dark:bg-blue-900/25'
          : 'border-border'
      }`}
    >
      <button
        type="button"
        onClick={() => props.onSelect(props.selected ? null : run)}
        class={`w-full text-left px-3 py-2 rounded-md transition-colors ${!props.selected ? 'hover:bg-surface-hover' : ''}`}
      >
        <div class="min-w-0">
          <div class="flex flex-wrap items-center gap-2 text-xs text-muted">
            <span class="text-base-content font-medium">
              {formatRelativeTime(run.started_at, { compact: true })}
            </span>
            <StatusIndicatorBadge
              label={runStatus.label}
              variant={runStatus.variant}
              size="xs"
              shape="rounded"
            />
            <span class="font-medium text-base-content">{operatorRecord.headline}</span>
          </div>
          <p class="mt-1 text-xs leading-5 text-muted">{operatorRecord.detail}</p>
        </div>
      </button>

      {/* Inline expansion details */}
      <Show when={props.selected}>
        <div class="px-3 pb-3 border-t border-blue-200 dark:border-blue-800 mt-0">
          {/* Section 1: Narrative Summary */}
          <div class="mt-3 flex min-w-0 items-start gap-2 text-sm text-base-content">
            <SparklesIcon class="w-4 h-4 text-blue-500 dark:text-blue-400 mt-0.5 shrink-0" />
            <p>
              <strong>{operatorRecord.headline}.</strong> {operatorRecord.detail}
            </p>
          </div>

          <Show when={hasRunErrorDetail}>
            <div class="mt-3 flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-800 dark:bg-red-950/40 dark:text-red-200">
              <AlertTriangleIcon class="mt-0.5 h-4 w-4 shrink-0" />
              <div class="min-w-0 space-y-1">
                <p class="font-medium">{runErrorSummary || 'Patrol analysis did not complete'}</p>
                <Show when={runErrorDetail && runErrorDetail !== runErrorSummary}>
                  <p class="wrap-break-word text-xs leading-relaxed text-red-700 dark:text-red-300">
                    {runErrorDetail}
                  </p>
                </Show>
                <Show when={primaryAction}>
                  {(action) => (
                    <a
                      href={action().href}
                      class="mt-2 inline-flex items-center gap-1.5 rounded-md border border-red-200 bg-white px-2.5 py-1.5 text-xs font-semibold text-red-800 transition-colors hover:bg-red-100 dark:border-red-800 dark:bg-red-950/25 dark:text-red-100 dark:hover:bg-red-900/25"
                    >
                      <SettingsIcon class="h-3.5 w-3.5" aria-hidden="true" />
                      <span>{action().label}</span>
                    </a>
                  )}
                </Show>
              </div>
            </div>
          </Show>

          {/* Section 2: Resources Scanned */}
          <Show when={run.resources_checked > 0}>
            <div class="mt-3">
              <div class="flex items-center gap-1.5 mb-2">
                <SearchIcon class="w-3.5 h-3.5 text-muted" />
                <span class="text-[10px] font-semibold tracking-wider uppercase text-muted">
                  {getPatrolRunResourcesHeading(run)}
                </span>
              </div>
              <div class="flex flex-wrap gap-1.5">
                <Show when={run.nodes_checked > 0}>
                  <MetadataBadge tone="neutral">
                    <ServerIcon class="w-3 h-3" /> {run.nodes_checked} node
                    {run.nodes_checked !== 1 ? 's' : ''}
                  </MetadataBadge>
                </Show>
                <Show when={run.guests_checked > 0}>
                  <MetadataBadge tone="neutral">
                    <MonitorIcon class="w-3 h-3" /> {run.guests_checked} VM
                    {run.guests_checked !== 1 ? 's' : ''}
                  </MetadataBadge>
                </Show>
                <Show when={run.docker_checked > 0}>
                  <MetadataBadge tone="neutral">
                    <BoxIcon class="w-3 h-3" /> {run.docker_checked} container
                    {run.docker_checked !== 1 ? 's' : ''}
                  </MetadataBadge>
                </Show>
                <Show when={run.storage_checked > 0}>
                  <MetadataBadge tone="neutral">
                    <HardDriveIcon class="w-3 h-3" /> {run.storage_checked} storage
                  </MetadataBadge>
                </Show>
                <Show when={run.hosts_checked > 0}>
                  <MetadataBadge tone="neutral">
                    <GlobeIcon class="w-3 h-3" /> {run.hosts_checked} agent
                    {run.hosts_checked !== 1 ? 's' : ''}
                  </MetadataBadge>
                </Show>
                <Show when={run.truenas_checked > 0}>
                  <MetadataBadge tone="neutral">
                    <HardDriveIcon class="w-3 h-3" /> {run.truenas_checked} TrueNAS
                    {run.truenas_checked !== 1 ? ' systems' : ' system'}
                  </MetadataBadge>
                </Show>
                <Show when={run.pbs_checked > 0}>
                  <MetadataBadge tone="neutral">
                    <DatabaseIcon class="w-3 h-3" /> {run.pbs_checked} PBS
                  </MetadataBadge>
                </Show>
                <Show when={run.pmg_checked > 0}>
                  <MetadataBadge tone="neutral">
                    <MailIcon class="w-3 h-3" /> {run.pmg_checked} PMG
                  </MetadataBadge>
                </Show>
                <Show when={run.kubernetes_checked > 0}>
                  <MetadataBadge tone="neutral">
                    <ActivityIcon class="w-3 h-3" /> {run.kubernetes_checked} K8s
                  </MetadataBadge>
                </Show>
              </div>
            </div>
          </Show>

          {/* Section 3: Outcomes */}
          <div class="mt-3">
            <div class="flex items-center gap-1.5 mb-2">
              <ShieldAlertIcon class="w-3.5 h-3.5 text-muted" />
              <span class="text-[10px] font-semibold tracking-wider uppercase text-muted">
                Outcomes
              </span>
            </div>
            <div class="flex flex-wrap gap-1.5">
              <Show when={run.new_findings > 0}>
                <MetadataBadge tone="warning">
                  <AlertTriangleIcon class="w-3 h-3" /> {run.new_findings} new
                </MetadataBadge>
              </Show>
              <Show when={run.existing_findings > 0}>
                <MetadataBadge tone="muted">
                  <ActivityIcon class="w-3 h-3" /> {run.existing_findings} existing
                </MetadataBadge>
              </Show>
              <Show when={run.resolved_findings > 0}>
                <MetadataBadge tone="success">
                  <CheckCircleIcon class="w-3 h-3" /> {run.resolved_findings} resolved
                </MetadataBadge>
              </Show>
              <Show when={run.auto_fix_count > 0}>
                <MetadataBadge tone="info">
                  <WrenchIcon class="w-3 h-3" /> {run.auto_fix_count} remediated
                </MetadataBadge>
              </Show>
              <Show when={run.rejected_findings > 0}>
                <MetadataBadge tone="muted">
                  <FilterXIcon class="w-3 h-3" /> {run.rejected_findings} rejected
                </MetadataBadge>
              </Show>
              <Show
                when={!hasFindingsSnapshot && run.new_findings === 0 && run.existing_findings === 0}
              >
                <MetadataBadge tone="info">
                  <ActivityIcon class="w-3 h-3" /> Finding record unavailable
                </MetadataBadge>
              </Show>
              <Show
                when={
                  hasFindingsSnapshot &&
                  runIsHealthy &&
                  run.new_findings === 0 &&
                  run.existing_findings === 0
                }
              >
                <MetadataBadge tone="success">
                  <CheckCircleIcon class="w-3 h-3" /> All clear
                </MetadataBadge>
              </Show>
            </div>
          </div>

          {/* Section 4: Patrol Analysis */}
          <Show when={run.ai_analysis}>
            <div class="mt-3">
              <div class="flex items-center justify-between">
                <div class="flex items-center gap-1.5">
                  <BrainCircuitIcon class="w-3.5 h-3.5 text-muted" />
                  <span class="text-[10px] font-semibold tracking-wider uppercase text-muted">
                    Patrol Analysis
                  </span>
                </div>
                <button
                  type="button"
                  onClick={() => setShowRunAnalysis(!showRunAnalysis())}
                  class="text-xs font-medium text-blue-600 dark:text-blue-400 hover:underline"
                >
                  {showRunAnalysis() ? 'Collapse' : 'Expand'}
                </button>
              </div>
              <Show when={showRunAnalysis()}>
                <div
                  class="mt-2 p-3 rounded-sm bg-surface text-sm leading-relaxed text-base-content max-h-64 overflow-auto prose prose-sm max-w-none dark:prose-invert prose-headings:text-sm prose-headings:mt-2 prose-headings:mb-1 prose-p:my-1 prose-ul:my-1 prose-li:my-0"
                  // eslint-disable-next-line solid/no-innerhtml
                  innerHTML={renderMarkdown(sanitizeAnalysis(run.ai_analysis))}
                />
              </Show>
            </div>
          </Show>

          {/* Technical run trace: useful for debugging, hidden from the default operator record. */}
          <details
            class="mt-3 rounded-md border border-border bg-surface-alt px-3 py-2 text-xs text-muted"
            onToggle={(event) => setShowTechnicalDetails(event.currentTarget.open)}
          >
            <summary class="cursor-pointer font-medium text-base-content">
              Technical details
            </summary>
            <div class="mt-2 flex flex-wrap items-center gap-3">
              <Show when={formatDurationMs(run.duration_ms)}>
                <span class="inline-flex items-center gap-1">
                  <ClockIcon class="w-3.5 h-3.5" /> {formatDurationMs(run.duration_ms)}
                </span>
              </Show>
              <Show when={run.tool_call_count > 0}>
                <span class="inline-flex items-center gap-1">
                  <ZapIcon class="w-3.5 h-3.5" /> {run.tool_call_count} tool call
                  {run.tool_call_count !== 1 ? 's' : ''}
                </span>
              </Show>
              <Show when={run.triage_flags > 0}>
                <span class="inline-flex items-center gap-1">
                  <ShieldAlertIcon class="w-3.5 h-3.5" /> {run.triage_flags} triage flag
                  {run.triage_flags !== 1 ? 's' : ''}
                </span>
              </Show>
              <Show when={run.triage_skipped_llm}>
                <span class="inline-flex items-center gap-1 text-amber-700 dark:text-amber-300">
                  <BrainCircuitIcon class="w-3.5 h-3.5" /> LLM skipped
                </span>
              </Show>
              <Show when={(run.input_tokens || 0) + (run.output_tokens || 0) > 0}>
                <span class="inline-flex items-center gap-1">
                  <BrainCircuitIcon class="w-3.5 h-3.5" />{' '}
                  {((run.input_tokens || 0) + (run.output_tokens || 0)).toLocaleString()} tokens
                </span>
              </Show>
              <Show when={run.type === 'scoped' && !coverageSummary}>
                <MetadataBadge tone="info" size="xs" shape="rounded">
                  {formatScope(run) || 'Scoped'}
                </MetadataBadge>
              </Show>
              <Show when={formatTriggerReason(run.trigger_reason)}>
                <span>{formatTriggerReason(run.trigger_reason)}</span>
              </Show>
            </div>
            <Show when={showTechnicalDetails()}>
              <RunToolCallTrace runId={run.id} toolCallCount={run.tool_call_count} />
            </Show>
          </details>

          {/* Section 5: Inline Findings */}
          <div class="mt-3 pt-3 border-t border-blue-200 dark:border-blue-800">
            <FindingsPanel
              filterFindingIds={run.finding_ids}
              filterOverride="all"
              scopeResourceIds={canonicalScopeResourceIds}
              scopeResourceTypes={run.scope_resource_types}
              showScopeWarnings={true}
              showControls={false}
              findingsSource="patrol"
              runSnapshot={run}
            />
          </div>
        </div>
      </Show>
    </div>
  );
}