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.

26.5 KB
Raw Blame
import { Component, For, Show } from 'solid-js';
import { Button } from '@/components/shared/Button';
import { Card } from '@/components/shared/Card';
import { EmptyState } from '@/components/shared/EmptyState';
import SettingsPanel from '@/components/shared/SettingsPanel';
import { Dialog } from '@/components/shared/Dialog';
import { FormSelect } from '@/components/shared/FormSelect';
import { FormTextarea } from '@/components/shared/FormTextarea';
import { LoadingSpinner } from '@/components/shared/LoadingSpinner';
import { StatusIndicatorBadge } from '@/components/shared/StatusIndicatorBadge';
import { UpgradeButtonLink } from '@/components/shared/UpgradeLink';
import { SuggestProfileModal } from './SuggestProfileModal';
import { KNOWN_SETTINGS, type SelectSetting, type StringSetting } from './agentProfileSettings';
import {
  getAgentProfilesFeatureGateCopy,
  getAgentProfileAssignmentsEmptyState,
  getAgentProfilesEmptyState,
} from '@/utils/agentProfilesPresentation';
import Plus from 'lucide-solid/icons/plus';
import Pencil from 'lucide-solid/icons/pencil';
import Trash2 from 'lucide-solid/icons/trash-2';
import Crown from 'lucide-solid/icons/crown';
import Users from 'lucide-solid/icons/users';
import Settings from 'lucide-solid/icons/settings';
import Lightbulb from 'lucide-solid/icons/lightbulb';
import { PulseDataGrid } from '@/components/shared/PulseDataGrid';
import { useAgentProfilesPanelState } from './useAgentProfilesPanelState';
import { useRelativeTimeNow } from '@/utils/relativeTimeClock';

export const AgentProfilesPanel: Component = () => {
  const now = useRelativeTimeNow();
  const featureGateCopy = getAgentProfilesFeatureGateCopy();
  const {
    aiAvailable,
    checkingLicense,
    connectedAgents,
    editingProfile,
    formDescription,
    formName,
    formSettings,
    getAgentAssignment,
    getAssignmentCount,
    getAgentStatusIndicator,
    getProfileById,
    getProfileOptionLabel,
    getSettingsCount,
    getUpgradeActionDestination,
    handleAssign,
    handleCreate,
    handleDelete,
    handleEdit,
    handleSave,
    handleSuggest,
    handleSuggestionAccepted,
    hasAgentProfiles,
    loading,
    profiles,
    saving,
    setFormDescription,
    setFormName,
    setShowModal,
    setShowSuggestModal,
    showUpgradePrompts,
    showModal,
    showSuggestModal,
    unknownKeys,
    updateSetting,
    formatRelativeTime,
    UPGRADE_ACTION_LABEL,
  } = useAgentProfilesPanelState();

  // License gate - using Show components for proper SolidJS reactivity
  // (early returns don't re-render when signals change in SolidJS)
  return (
    <Show
      when={!checkingLicense()}
      fallback={
        <Card padding="lg">
          <div class="flex items-center justify-center py-8">
            <LoadingSpinner size="xl" tone="info" />
            <span class="ml-3 text-muted">Checking license...</span>
          </div>
        </Card>
      }
    >
      <Show
        when={hasAgentProfiles()}
        fallback={
          <Show when={showUpgradePrompts()}>
            <Card padding="lg" class="space-y-4">
              <div class="flex items-center gap-3">
                <div class="flex items-center justify-center w-10 h-10 rounded-md bg-amber-100 dark:bg-amber-900/25">
                  <Crown class="w-5 h-5 text-amber-600 dark:text-amber-400" />
                </div>
                <div>
                  <h3 class="text-base font-semibold text-base-content">{featureGateCopy.title}</h3>
                  <p class="text-sm text-muted">{featureGateCopy.subtitle}</p>
                </div>
              </div>
              <p class="text-sm text-muted">{featureGateCopy.body}</p>
              <div class="flex flex-wrap items-center gap-3">
                <UpgradeButtonLink
                  destination={getUpgradeActionDestination('agent_profiles')}
                  tone="warning"
                  mobileFullWidth={false}
                >
                  <Crown class="w-4 h-4" />
                  {UPGRADE_ACTION_LABEL}
                </UpgradeButtonLink>
              </div>
            </Card>
          </Show>
        }
      >
        <div class="space-y-6">
          {/* Profiles Section */}
          <SettingsPanel
            title="Configuration Profiles"
            description="Reusable agent configurations"
            action={
              <div class="flex items-center gap-2">
                <Button
                  type="button"
                  variant="primary"
                  size="mdCompact"
                  onClick={handleCreate}
                  class="min-h-10 gap-2 sm:min-h-9 sm:px-4"
                >
                  <Plus class="w-4 h-4" />
                  <span class="hidden sm:inline">New Profile</span>
                  <span class="sm:hidden">New</span>
                </Button>
                <Show when={aiAvailable()}>
                  <Button
                    type="button"
                    variant="secondary"
                    size="mdCompact"
                    onClick={handleSuggest}
                    title="Suggest profiles for your estate"
                    class="min-h-10 min-w-10 gap-1.5 sm:min-h-9"
                  >
                    <Lightbulb class="w-3.5 h-3.5" />
                    <span class="hidden sm:inline">Ideas</span>
                  </Button>
                </Show>
              </div>
            }
            noPadding
            bodyClass="divide-y divide-border"
          >
            <Show when={loading()}>
              <div class="flex items-center justify-center py-8">
                <LoadingSpinner size="xl" tone="info" label="Loading configuration profiles" />
              </div>
            </Show>

            <Show when={!loading() && profiles().length === 0}>
              <EmptyState
                variant="panel"
                icon={<Settings class="h-5 w-5" />}
                title={getAgentProfilesEmptyState()}
              />
            </Show>

            <Show when={!loading() && profiles().length > 0}>
              <PulseDataGrid
                data={profiles()}
                columns={[
                  {
                    key: 'name',
                    label: 'Name',
                    render: (profile) => (
                      <span class="font-medium text-base-content">{profile.name}</span>
                    ),
                  },
                  {
                    key: 'settings',
                    label: 'Settings',
                    hiddenOnMobile: true,
                    render: (profile) => (
                      <span class="text-muted">{getSettingsCount(profile)}</span>
                    ),
                  },
                  {
                    key: 'agents',
                    label: 'Agents',
                    render: (profile) => (
                      <span class="inline-flex items-center gap-1 text-muted">
                        <Users class="w-4 h-4" />
                        {getAssignmentCount(profile.id)}
                      </span>
                    ),
                  },
                  {
                    key: 'actions',
                    label: 'Actions',
                    align: 'right',
                    render: (profile) => (
                      <div class="inline-flex items-center gap-1">
                        <button
                          type="button"
                          onClick={() => handleEdit(profile)}
                          class="inline-flex min-h-11 min-w-11 items-center justify-center rounded-md p-1.5 hover:text-blue-600 hover:bg-blue-50 sm:min-h-0 sm:min-w-0 dark:hover:text-blue-400 dark:hover:bg-blue-900/25"
                          title="Edit profile"
                        >
                          <Pencil class="w-4 h-4" />
                        </button>
                        <button
                          type="button"
                          onClick={() => handleDelete(profile)}
                          class="inline-flex min-h-11 min-w-11 items-center justify-center rounded-md p-1.5 hover:text-red-600 hover:bg-red-50 sm:min-h-0 sm:min-w-0 dark:hover:text-red-400 dark:hover:bg-red-900/25"
                          title="Delete profile"
                        >
                          <Trash2 class="w-4 h-4" />
                        </button>
                      </div>
                    ),
                  },
                ]}
                keyExtractor={(profile) => profile.id}
                emptyState={getAgentProfilesEmptyState()}
                desktopMinWidth="600px"
                frame="flush"
              />
            </Show>
          </SettingsPanel>

          {/* Assignments Section */}
          <SettingsPanel
            title="Agent Assignments"
            description="Assign profiles to connected agents"
            noPadding
            bodyClass="divide-y divide-border"
          >
            <Show when={connectedAgents().length === 0}>
              <EmptyState
                variant="panel"
                icon={<Users class="h-5 w-5" />}
                title={getAgentProfileAssignmentsEmptyState()}
              />
            </Show>

            <Show when={connectedAgents().length > 0}>
              <PulseDataGrid
                data={connectedAgents()}
                columns={[
                  {
                    key: 'agent',
                    label: 'Agent',
                    render: (agent) => (
                      <div>
                        <span class="font-medium text-base-content">
                          {agent.displayName || agent.hostname}
                        </span>
                        <Show when={agent.displayName && agent.hostname !== agent.displayName}>
                          <span class="ml-2 text-xs text-muted">({agent.hostname})</span>
                        </Show>
                      </div>
                    ),
                  },
                  {
                    key: 'profile',
                    label: 'Profile',
                    render: (agent) => {
                      const assignment = () => getAgentAssignment(agent.assignmentId);
                      return (
                        <FormSelect
                          label={`Profile for ${agent.displayName || agent.hostname}`}
                          labelClass="sr-only"
                          fieldBaseClass="contents"
                          value={assignment()?.profile_id || ''}
                          onChange={(e) => handleAssign(agent.assignmentId, e.currentTarget.value)}
                          selectBaseClass="min-h-10 sm:min-h-9 w-full sm:max-w-xs rounded-md border border-border bg-surface px-2.5 py-1.5 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-1 focus:ring-blue-500"
                        >
                          <option value="">No profile</option>
                          <Show
                            when={
                              assignment()?.profile_id && !getProfileById(assignment()!.profile_id)
                            }
                          >
                            <option value={assignment()!.profile_id} selected>
                              {getProfileOptionLabel(assignment()!.profile_id)}
                            </option>
                          </Show>
                          <For each={profiles()}>
                            {(profile) => (
                              <option value={profile.id}>
                                {getProfileOptionLabel(profile.id)}
                              </option>
                            )}
                          </For>
                        </FormSelect>
                      );
                    },
                  },
                  {
                    key: 'status',
                    label: 'Status',
                    render: (agent) => {
                      const indicator = () => getAgentStatusIndicator({ status: agent.status });
                      return (
                        <StatusIndicatorBadge
                          variant={indicator().variant}
                          label={indicator().label}
                        />
                      );
                    },
                  },
                  {
                    key: 'lastSeen',
                    label: 'Last Seen',
                    hiddenOnMobile: true,
                    render: (agent) => (
                      <span class="text-muted">
                        {agent.lastSeen
                          ? formatRelativeTime(agent.lastSeen, { now: now() })
                          : 'Never'}
                      </span>
                    ),
                  },
                ]}
                keyExtractor={(agent) => agent.id}
                emptyState={getAgentProfileAssignmentsEmptyState()}
                desktopMinWidth="800px"
                frame="flush"
              />
            </Show>
          </SettingsPanel>

          {/* Profile Modal */}
          <Show when={showModal()}>
            <Dialog
              isOpen={true}
              onClose={() => setShowModal(false)}
              panelClass="max-w-lg"
              closeOnBackdrop={false}
              ariaLabel={editingProfile() ? 'Edit profile' : 'New profile'}
            >
              <div class="w-full">
                <div class="flex items-center justify-between px-6 py-4 border-b border-border">
                  <h3 class="text-lg font-semibold text-base-content">
                    {editingProfile() ? 'Edit Profile' : 'New Profile'}
                  </h3>
                  <button
                    type="button"
                    onClick={() => setShowModal(false)}
                    aria-label="Close agent profile editor"
                    class="p-1.5 rounded-md text-slate-500 hover:text-base-content hover:bg-surface-hover"
                  >
                    <svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M6 18L18 6M6 6l12 12"
                      />
                    </svg>
                  </button>
                </div>

                <div class="px-6 py-4 space-y-4 max-h-[60vh] overflow-y-auto">
                  {/* Profile Name */}
                  <div class="space-y-1">
                    <label
                      for="agent-profile-name"
                      class="block text-sm font-medium text-base-content"
                    >
                      Profile Name
                    </label>
                    <input
                      id="agent-profile-name"
                      type="text"
                      value={formName()}
                      onInput={(e) => setFormName(e.currentTarget.value)}
                      placeholder="e.g., Production Servers"
                      class="w-full rounded-md border border-border bg-surface px-3 py-2 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-2 focus:ring-blue-200 dark:focus:border-blue-400 dark:focus:ring-blue-800"
                    />
                  </div>

                  {/* Profile Description */}
                  <FormTextarea
                    label={
                      <>
                        Description <span class="text-slate-400 font-normal">(optional)</span>
                      </>
                    }
                    labelClass="block text-sm font-medium text-base-content"
                    fieldBaseClass="space-y-1"
                    value={formDescription()}
                    onInput={(e) => setFormDescription(e.currentTarget.value)}
                    placeholder="What is this profile for?"
                    rows={2}
                    textareaBaseClass="w-full rounded-md border border-border bg-surface px-3 py-2 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-2 focus:ring-blue-200 dark:focus:border-blue-400 dark:focus:ring-blue-800 resize-none"
                  />

                  {/* Settings */}
                  <div class="space-y-3">
                    <span class="block text-sm font-medium text-base-content">Settings</span>

                    <For each={KNOWN_SETTINGS}>
                      {(setting) => (
                        <div class="rounded-md border border-border p-3 space-y-1">
                          <div class="flex items-center justify-between">
                            <span class="text-sm font-medium text-base-content">
                              {setting.label}
                            </span>
                            <Show when={setting.type === 'boolean'}>
                              <button
                                type="button"
                                aria-label={`${setting.label}: ${String(formSettings()[setting.key] ?? 'default')}`}
                                aria-pressed={
                                  formSettings()[setting.key] === undefined
                                    ? 'mixed'
                                    : formSettings()[setting.key] === true
                                }
                                onClick={() => {
                                  const current = formSettings()[setting.key];
                                  if (current === undefined) {
                                    updateSetting(setting.key, true);
                                  } else if (current === true) {
                                    updateSetting(setting.key, false);
                                  } else {
                                    updateSetting(setting.key, undefined);
                                  }
                                }}
                                class={`relative inline-flex h-8 w-12 sm:h-7 sm:w-12 items-center rounded-full transition-colors ${
                                  formSettings()[setting.key] === true
                                    ? 'bg-blue-600'
                                    : formSettings()[setting.key] === false
                                      ? 'bg-slate-400'
                                      : 'bg-surface-hover'
                                }`}
                              >
                                <span
                                  class={`inline-block h-6 w-6 sm:h-5 sm:w-5 transform rounded-full bg-white transition-transform ${
                                    formSettings()[setting.key] === true
                                      ? 'translate-x-4 sm:translate-x-5'
                                      : formSettings()[setting.key] === false
                                        ? 'translate-x-1'
                                        : 'translate-x-3'
                                  }`}
                                />
                              </button>
                            </Show>
                            <Show when={setting.type === 'select'}>
                              <FormSelect
                                label={`${setting.label} value`}
                                labelClass="sr-only"
                                fieldBaseClass="contents"
                                value={(formSettings()[setting.key] as string) || ''}
                                onChange={(e) =>
                                  updateSetting(setting.key, e.currentTarget.value || undefined)
                                }
                                selectBaseClass="min-h-10 sm:min-h-9 rounded-md border border-border bg-surface px-2.5 py-1.5 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-1 focus:ring-blue-500"
                              >
                                <option value="">Default</option>
                                <For each={(setting as SelectSetting).options}>
                                  {(opt) => <option value={opt}>{opt}</option>}
                                </For>
                              </FormSelect>
                            </Show>
                            <Show when={setting.type === 'duration'}>
                              <input
                                type="text"
                                aria-label={setting.label}
                                value={(formSettings()[setting.key] as string) || ''}
                                onInput={(e) =>
                                  updateSetting(setting.key, e.currentTarget.value || undefined)
                                }
                                placeholder="30s"
                                class="min-h-10 sm:min-h-9 w-24 rounded-md border border-border bg-surface px-2.5 py-1.5 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-1 focus:ring-blue-500"
                              />
                            </Show>
                            <Show when={setting.type === 'string'}>
                              <input
                                type="text"
                                aria-label={setting.label}
                                value={(formSettings()[setting.key] as string) || ''}
                                onInput={(e) =>
                                  updateSetting(setting.key, e.currentTarget.value || undefined)
                                }
                                placeholder={(setting as StringSetting).placeholder || ''}
                                class="min-h-10 sm:min-h-9 w-40 rounded-md border bg-surface px-2.5 py-1.5 text-sm shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-1 focus:ring-blue-500"
                              />
                            </Show>
                          </div>
                          <p class="text-xs text-muted">{setting.description}</p>
                        </div>
                      )}
                    </For>

                    {/* Unknown Keys Section */}
                    <Show when={unknownKeys().length > 0}>
                      <div class="pt-3 mt-3 border-t border-border">
                        <p class="text-xs text-amber-600 dark:text-amber-400 mb-2">
                          Additional settings (not in standard list):
                        </p>
                        <For each={unknownKeys()}>
                          {(key) => (
                            <div class="rounded-md border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/25 p-3 mb-2">
                              <div class="flex items-center justify-between">
                                <span class="text-sm font-medium text-base-content font-mono">
                                  {key}
                                </span>
                                <div class="flex items-center gap-2">
                                  <input
                                    type="text"
                                    aria-label={key}
                                    value={String(formSettings()[key] ?? '')}
                                    onInput={(e) => {
                                      const val = e.currentTarget.value;
                                      // Try to parse as JSON for complex values
                                      try {
                                        updateSetting(key, JSON.parse(val));
                                      } catch {
                                        updateSetting(key, val || undefined);
                                      }
                                    }}
                                    class="min-h-10 sm:min-h-9 w-32 rounded-md border bg-surface px-2.5 py-1.5 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-1 focus:ring-blue-500"
                                  />
                                  <button
                                    type="button"
                                    onClick={() => updateSetting(key, undefined)}
                                    class="inline-flex min-h-10 min-w-10 sm:min-h-9 sm:min-w-9 items-center justify-center rounded-sm text-slate-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/25"
                                    title="Remove this setting"
                                  >
                                    <svg
                                      class="w-4 h-4"
                                      fill="none"
                                      viewBox="0 0 24 24"
                                      stroke="currentColor"
                                    >
                                      <path
                                        stroke-linecap="round"
                                        stroke-linejoin="round"
                                        stroke-width="2"
                                        d="M6 18L18 6M6 6l12 12"
                                      />
                                    </svg>
                                  </button>
                                </div>
                              </div>
                            </div>
                          )}
                        </For>
                      </div>
                    </Show>
                  </div>
                </div>

                <div class="flex items-center justify-end gap-3 px-6 py-4 border-t border-border">
                  <button
                    type="button"
                    onClick={() => setShowModal(false)}
                    class="rounded-md px-4 py-2 text-sm font-medium text-base-content hover:bg-surface-hover"
                  >
                    Cancel
                  </button>
                  <button
                    type="button"
                    onClick={handleSave}
                    disabled={saving() || !formName().trim()}
                    class="inline-flex items-center gap-2 rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-60"
                  >
                    {saving()
                      ? 'Saving...'
                      : editingProfile()
                        ? 'Update Profile'
                        : 'Create Profile'}
                  </button>
                </div>
              </div>
            </Dialog>
          </Show>

          {/* Suggest Profile Modal */}
          <Show when={showSuggestModal()}>
            <SuggestProfileModal
              onClose={() => setShowSuggestModal(false)}
              onSuggestionAccepted={handleSuggestionAccepted}
            />
          </Show>
        </div>
      </Show>
    </Show>
  );
};

export default AgentProfilesPanel;