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.

Restore UI improvements and refine Docker/Hosts display

rcourtman422efdde6100
diff --git a/frontend-modern/src/components/Dashboard/StackedDiskBar.tsx b/frontend-modern/src/components/Dashboard/StackedDiskBar.tsx
index 158b311912..d2a9259e01 100644
--- a/frontend-modern/src/components/Dashboard/StackedDiskBar.tsx
+++ b/frontend-modern/src/components/Dashboard/StackedDiskBar.tsx
@@ -9,6 +9,8 @@ interface StackedDiskBarProps {
disks?: Disk[];
/** Aggregate disk data (fallback when disks array unavailable) */
aggregateDisk?: Disk;
+ /** Display mode for multi-disk hosts */
+ mode?: 'stacked' | 'aggregate' | 'mini';
/** Baseline anomaly if detected */
anomaly?: AnomalyReport | null;
}
@@ -78,10 +80,9 @@ export function StackedDiskBar(props: StackedDiskBarProps) {
return disks && disks.length > 1;
});
- const hasSingleDisk = createMemo(() => {
- const disks = props.disks;
- return disks && disks.length === 1;
- });
+ const aggregateMode = createMemo(() => props.mode === 'aggregate');
+ const miniMode = createMemo(() => props.mode === 'mini');
+ const useStackedSegments = createMemo(() => hasMultipleDisks() && !aggregateMode() && !miniMode());
// Calculate total capacity across all disks
const totalCapacity = createMemo(() => {
@@ -104,23 +105,11 @@ export function StackedDiskBar(props: StackedDiskBarProps) {
return (totalUsed() / total) * 100;
});
- // For single disk or aggregate, get the percentage
- const singleDiskPercent = createMemo(() => {
- if (hasSingleDisk() && props.disks?.[0]) {
- const disk = props.disks[0];
- if (!disk.total || disk.total <= 0) return 0;
- return (disk.used / disk.total) * 100;
- }
- if (props.aggregateDisk) {
- if (!props.aggregateDisk.total || props.aggregateDisk.total <= 0) return 0;
- return (props.aggregateDisk.used / props.aggregateDisk.total) * 100;
- }
- return 0;
- });
+ const barPercent = createMemo(() => Math.min(overallPercent(), 100));
// Calculate segment widths for stacked bar (each disk's used space as % of total capacity)
const segments = createMemo(() => {
- if (!hasMultipleDisks() || !props.disks) return [];
+ if (!useStackedSegments() || !props.disks) return [];
const total = totalCapacity();
if (total <= 0) return [];
@@ -147,8 +136,58 @@ export function StackedDiskBar(props: StackedDiskBarProps) {
return props.disks && props.disks.length > 0;
});
+ const miniDisks = createMemo(() => {
+ if (!props.disks) return [];
+ return props.disks.map((disk, idx) => {
+ const percent = disk.total > 0 ? (disk.used / disk.total) * 100 : 0;
+ const label = disk.mountpoint || disk.device || `Disk ${idx + 1}`;
+ return {
+ label,
+ percent,
+ color: getUsageColor(percent),
+ };
+ });
+ });
+
+ const maxDiskInfo = createMemo(() => {
+ if (!props.disks || props.disks.length === 0) return null;
+ let maxPercent = -1;
+ let maxLabel = '';
+ for (const disk of props.disks) {
+ const percent = disk.total > 0 ? (disk.used / disk.total) * 100 : 0;
+ if (percent > maxPercent) {
+ maxPercent = percent;
+ maxLabel = disk.mountpoint || disk.device || 'Disk';
+ }
+ }
+ if (maxPercent < 0) return null;
+ return { percent: maxPercent, label: maxLabel };
+ });
+
+ const maxLabelShort = createMemo(() => {
+ const info = maxDiskInfo();
+ if (!info) return '';
+ return `max ${formatPercent(info.percent)}`;
+ });
+
+ const maxLabelFull = createMemo(() => {
+ const info = maxDiskInfo();
+ if (!info) return '';
+ if (info.label) return `Max ${formatPercent(info.percent)} (${info.label})`;
+ return `Max ${formatPercent(info.percent)}`;
+ });
+
+ const barColor = createMemo(() => {
+ const info = maxDiskInfo();
+ if (aggregateMode() && hasMultipleDisks() && info) {
+ return getUsageColor(info.percent);
+ }
+ return getUsageColor(overallPercent());
+ });
+
// Generate tooltip content
const tooltipContent = createMemo(() => {
+ const useUsageColors = aggregateMode() || miniMode();
if (hasDisks() && props.disks) {
return props.disks.map((disk, idx) => {
const percent = disk.total > 0 ? (disk.used / disk.total) * 100 : 0;
@@ -158,9 +197,13 @@ export function StackedDiskBar(props: StackedDiskBarProps) {
used: formatBytes(disk.used, 0),
total: formatBytes(disk.total, 0),
percent: formatPercent(percent),
- color: percent >= 90 ? getUsageColor(90) :
- percent >= 80 ? getUsageColor(80) :
- SEGMENT_COLORS[idx % SEGMENT_COLORS.length],
+ color: useUsageColors
+ ? getUsageColor(percent)
+ : percent >= 90
+ ? getUsageColor(90)
+ : percent >= 80
+ ? getUsageColor(80)
+ : SEGMENT_COLORS[idx % SEGMENT_COLORS.length],
};
});
}
@@ -180,10 +223,7 @@ export function StackedDiskBar(props: StackedDiskBarProps) {
// Label for the bar
const displayLabel = createMemo(() => {
- if (hasMultipleDisks()) {
- return formatPercent(overallPercent());
- }
- return formatPercent(singleDiskPercent());
+ return formatPercent(overallPercent());
});
// Sublabel showing used/total
@@ -191,12 +231,27 @@ export function StackedDiskBar(props: StackedDiskBarProps) {
return `${formatBytes(totalUsed(), 0)}/${formatBytes(totalCapacity(), 0)}`;
});
+ const showMaxLabel = createMemo(() => {
+ if (!aggregateMode() || !hasMultipleDisks()) return false;
+ const shortLabel = maxLabelShort();
+ if (!shortLabel) return false;
+ const fullText = `${displayLabel()} ${shortLabel}`;
+ return containerWidth() >= estimateTextWidth(fullText);
+ });
+
// Check if sublabel fits
const showSublabel = createMemo(() => {
- const fullText = `${displayLabel()} (${displaySublabel()})`;
+ const baseText = `${displayLabel()}${showMaxLabel() ? ` ${maxLabelShort()}` : ''}`;
+ const fullText = `${baseText} (${displaySublabel()})`;
return containerWidth() >= estimateTextWidth(fullText);
});
+ const containerClass = createMemo(() => {
+ return miniMode() && hasDisks()
+ ? 'metric-text w-full'
+ : 'metric-text w-full h-4 flex items-center justify-center';
+ });
+
const handleMouseEnter = (e: MouseEvent) => {
if (tooltipContent().length > 0) {
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
@@ -210,67 +265,108 @@ export function StackedDiskBar(props: StackedDiskBarProps) {
};
return (
- <div ref={containerRef} class="metric-text w-full h-4 flex items-center justify-center">
- <div
- class="relative w-full h-full overflow-hidden bg-gray-200 dark:bg-gray-600 rounded"
- onMouseEnter={handleMouseEnter}
- onMouseLeave={handleMouseLeave}
- >
- {/* Stacked segments for multiple disks */}
- <Show when={hasMultipleDisks()}>
- <div class="absolute top-0 left-0 h-full w-full flex">
- <For each={segments()}>
- {(segment, idx) => (
- <div
- class="h-full"
- style={{
- width: `${segment.widthPercent}%`,
- 'background-color': segment.color,
- 'border-right': idx() < segments().length - 1 ? '1px solid rgba(255,255,255,0.3)' : 'none',
- }}
- />
- )}
- </For>
- </div>
- </Show>
-
- {/* Single bar for single disk or aggregate */}
- <Show when={!hasMultipleDisks()}>
+ <div ref={containerRef} class={containerClass()}>
+ <Show
+ when={miniMode() && hasDisks()}
+ fallback={
<div
- class="absolute top-0 left-0 h-full"
- style={{
- width: `${Math.min(singleDiskPercent(), 100)}%`,
- 'background-color': getUsageColor(singleDiskPercent()),
- }}
- />
- </Show>
-
- {/* Label overlay */}
- <span class="absolute inset-0 flex items-center justify-center text-[10px] font-semibold text-gray-700 dark:text-gray-100 leading-none">
- <span class="flex items-center gap-1 whitespace-nowrap px-0.5">
- <span>{displayLabel()}</span>
- <Show when={showSublabel()}>
- <span class="metric-sublabel font-normal text-gray-500 dark:text-gray-300">
- ({displaySublabel()})
- </span>
+ class="relative w-full h-full overflow-hidden bg-gray-200 dark:bg-gray-600 rounded"
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ >
+ {/* Stacked segments for multiple disks */}
+ <Show when={useStackedSegments()}>
+ <div class="absolute top-0 left-0 h-full w-full flex">
+ <For each={segments()}>
+ {(segment, idx) => (
+ <div
+ class="h-full"
+ style={{
+ width: `${segment.widthPercent}%`,
+ 'background-color': segment.color,
+ 'border-right': idx() < segments().length - 1 ? '1px solid rgba(255,255,255,0.3)' : 'none',
+ }}
+ />
+ )}
+ </For>
+ </div>
</Show>
- <Show when={hasMultipleDisks()}>
- <span class="text-[8px] font-normal text-gray-500 dark:text-gray-400">
- [{props.disks?.length}]
- </span>
+
+ {/* Single bar for aggregate or single disk */}
+ <Show when={!useStackedSegments()}>
+ <div
+ class="absolute top-0 left-0 h-full"
+ style={{
+ width: `${barPercent()}%`,
+ 'background-color': barColor(),
+ }}
+ />
</Show>
- {/* Anomaly indicator */}
- <Show when={props.anomaly && anomalyRatio()}>
- <span
- class={`ml-0.5 font-bold animate-pulse ${anomalySeverityClass[props.anomaly!.severity] || 'text-yellow-400'}`}
- title={props.anomaly!.description}
- >
- {anomalyRatio()}
+
+ {/* Label overlay */}
+ <span class="absolute inset-0 flex items-center justify-center text-[10px] font-semibold text-gray-700 dark:text-gray-100 leading-none">
+ <span class="flex items-center gap-1 whitespace-nowrap px-0.5">
+ <span>{displayLabel()}</span>
+ <Show when={showMaxLabel()}>
+ <span
+ class="text-[8px] font-normal text-gray-500 dark:text-gray-400"
+ title={maxLabelFull()}
+ >
+ {maxLabelShort()}
+ </span>
+ </Show>
+ <Show when={showSublabel()}>
+ <span class="metric-sublabel font-normal text-gray-500 dark:text-gray-300">
+ ({displaySublabel()})
+ </span>
+ </Show>
+ <Show when={useStackedSegments()}>
+ <span class="text-[8px] font-normal text-gray-500 dark:text-gray-400">
+ [{props.disks?.length}]
+ </span>
+ </Show>
+ {/* Anomaly indicator */}
+ <Show when={props.anomaly && anomalyRatio()}>
+ <span
+ class={`ml-0.5 font-bold animate-pulse ${anomalySeverityClass[props.anomaly!.severity] || 'text-yellow-400'}`}
+ title={props.anomaly!.description}
+ >
+ {anomalyRatio()}
+ </span>
+ </Show>
</span>
- </Show>
- </span>
- </span>
- </div>
+ </span>
+ </div>
+ }
+ >
+ <div class="w-full" onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
+ <div
+ class="grid gap-1"
+ style={{
+ 'grid-template-columns': `repeat(${miniDisks().length}, minmax(0, 1fr))`,
+ }}
+ >
+ <For each={miniDisks()}>
+ {(disk) => (
+ <div class="flex flex-col items-stretch gap-0.5">
+ <span class="text-[8px] text-gray-500 dark:text-gray-400 truncate" title={disk.label}>
+ {disk.label}
+ </span>
+ <div class="relative h-2.5 rounded-sm bg-gray-300/70 dark:bg-gray-500/70 overflow-hidden">
+ <div
+ class="h-full"
+ style={{
+ width: `${Math.min(disk.percent, 100)}%`,
+ 'background-color': disk.color,
+ }}
+ />
+ </div>
+ </div>
+ )}
+ </For>
+ </div>
+ </div>
+ </Show>
{/* Tooltip for disk breakdown */}
<Show when={showTooltip() && tooltipContent().length > 0}>
@@ -289,16 +385,27 @@ export function StackedDiskBar(props: StackedDiskBarProps) {
</div>
<For each={tooltipContent()}>
{(item, idx) => (
- <div class="flex justify-between gap-3 py-0.5" classList={{ 'border-t border-gray-700/50': idx() > 0 }}>
- <span
- class="truncate max-w-[100px]"
- style={{ color: item.color }}
- >
- {item.label}
- </span>
- <span class="whitespace-nowrap text-gray-300">
- {item.percent} ({item.used}/{item.total})
- </span>
+ <div class="flex flex-col gap-1 py-0.5" classList={{ 'border-t border-gray-700/50': idx() > 0 }}>
+ <div class="flex justify-between gap-3">
+ <span
+ class="truncate max-w-[100px]"
+ style={{ color: item.color }}
+ >
+ {item.label}
+ </span>
+ <span class="whitespace-nowrap text-gray-300">
+ {item.percent} ({item.used}/{item.total})
+ </span>
+ </div>
+ <div class="h-1.5 w-full rounded bg-gray-700/70 overflow-hidden">
+ <div
+ class="h-full"
+ style={{
+ width: item.percent,
+ 'background-color': item.color,
+ }}
+ />
+ </div>
</div>
)}
</For>
diff --git a/frontend-modern/src/components/Docker/DockerHostSummaryTable.tsx b/frontend-modern/src/components/Docker/DockerHostSummaryTable.tsx
index 3a18e7825c..1a3405574c 100644
--- a/frontend-modern/src/components/Docker/DockerHostSummaryTable.tsx
+++ b/frontend-modern/src/components/Docker/DockerHostSummaryTable.tsx
@@ -1,5 +1,4 @@
import { Component, For, Show, createMemo, createSignal } from 'solid-js';
-import { StackedContainerBar } from './StackedContainerBar';
import type { DockerHost } from '@/types/api';
import { Card } from '@/components/shared/Card';
import { renderDockerStatusBadge } from './DockerStatusBadge';
@@ -430,12 +429,9 @@ export const DockerHostSummaryTable: Component<DockerHostSummaryTableProps> = (p
when={summary.totalCount > 0}
fallback={<span class="text-xs text-gray-400 dark:text-gray-500">—</span>}
>
- <StackedContainerBar
- running={summary.runningCount}
- stopped={summary.stoppedCount}
- error={summary.errorCount}
- total={summary.totalCount}
- />
+ <span class="text-xs font-semibold text-gray-700 dark:text-gray-200">
+ {summary.totalCount}
+ </span>
</Show>
</div>
</td>
diff --git a/frontend-modern/src/components/Docker/DockerUnifiedTable.tsx b/frontend-modern/src/components/Docker/DockerUnifiedTable.tsx
index 48a0131015..603b5fa4ff 100644
--- a/frontend-modern/src/components/Docker/DockerUnifiedTable.tsx
+++ b/frontend-modern/src/components/Docker/DockerUnifiedTable.tsx
@@ -3,7 +3,14 @@ import type { DockerHost, DockerContainer, DockerService, DockerTask } from '@/t
import { Card } from '@/components/shared/Card';
import { EmptyState } from '@/components/shared/EmptyState';
import { MetricBar } from '@/components/Dashboard/MetricBar';
-import { formatBytes, formatPercent, formatUptime, formatRelativeTime, formatAbsoluteTime, getShortImageName } from '@/utils/format';
+import {
+ formatPercent,
+ formatBytes,
+ formatUptime,
+ formatRelativeTime,
+ getShortImageName,
+ formatAbsoluteTime,
+} from '@/utils/format';
import type { DockerMetadata } from '@/api/dockerMetadata';
import { DockerMetadataAPI } from '@/api/dockerMetadata';
import type { DockerHostMetadata } from '@/api/dockerHostMetadata';
@@ -42,7 +49,6 @@ const typeBadgeClass = (type: 'container' | 'service' | 'task' | 'unknown') => {
}
};
-
type StatsFilter =
| { type: 'host-status'; value: string }
| { type: 'container-state'; value: string }
@@ -131,9 +137,9 @@ interface DockerColumnDef extends ColumnConfig {
// - supplementary: Visible on large screens and up (lg: 1024px+)
// - detailed: Visible on extra large screens and up (xl: 1280px+)
export const DOCKER_COLUMNS: DockerColumnDef[] = [
- { id: 'resource', label: 'Resource', priority: 'essential', minWidth: 'auto', flex: 1, sortKey: 'resource', width: '22%' },
+ { id: 'resource', label: 'Resource', priority: 'essential', minWidth: 'auto', flex: 1, sortKey: 'resource', width: '15%' },
{ id: 'type', label: 'Type', priority: 'essential', minWidth: 'auto', maxWidth: 'auto', sortKey: 'type', width: '70px' },
- { id: 'image', label: 'Image / Stack', priority: 'essential', minWidth: '80px', maxWidth: '200px', sortKey: 'image', width: '12%' },
+ { id: 'image', label: 'Image / Stack', priority: 'essential', minWidth: '80px', maxWidth: '200px', sortKey: 'image', width: '15%' },
{ id: 'status', label: 'Status', priority: 'essential', minWidth: 'auto', maxWidth: 'auto', sortKey: 'status', width: '90px' },
// Metric columns - need fixed width to match progress bar max-width (140px + padding)
// Note: Disk column removed - Docker API rarely provides this data
@@ -154,6 +160,10 @@ const [dockerPopoverPosition, setDockerPopoverPosition] = createSignal<{ top: nu
const toLower = (value?: string | null) => value?.toLowerCase() ?? '';
+
+
+
+
const ensureMs = (value?: number | string | null): number | null => {
if (!value) return null;
if (typeof value === 'number') {
@@ -1129,23 +1139,23 @@ const DockerContainerRow: Component<{
ariaLabel={containerStatusIndicator().label}
size="xs"
/>
- <div class="flex-1 min-w-0">
+ <div class="flex-1 min-w-0 truncate">
<div class="flex items-center gap-1.5 flex-1 min-w-0 group/name">
<span
- class="text-sm font-semibold text-gray-900 dark:text-gray-100 select-none truncate min-w-0 flex-1"
+ class="text-sm font-semibold text-gray-900 dark:text-gray-100 select-none truncate"
title={containerTitle()}
>
{container.name || container.id}
</span>
<Show when={podName()}>
{(name) => (
- <span class="inline-flex items-center gap-0.5 rounded bg-purple-100 px-1 py-0.5 text-[10px] font-medium text-purple-700 dark:bg-purple-900/40 dark:text-purple-200 flex-shrink-0 max-w-[90px]" title={`Pod: ${name()}`}>
- <span class="truncate">{name()}</span>
- <Show when={isPodInfra()}>
- <span class="rounded bg-purple-200 px-1 py-0.5 text-[9px] uppercase text-purple-800 dark:bg-purple-800/50 dark:text-purple-200 ml-1">
- infra
- </span>
- </Show>
+ <span
+ class="flex-shrink-0 text-purple-500 dark:text-purple-400 cursor-help"
+ title={`Pod: ${name()}${isPodInfra() ? ' (Infra)' : ''}`}
+ >
+ <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="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
+ </svg>
</span>
)}
</Show>
@@ -1176,14 +1186,13 @@ const DockerContainerRow: Component<{
</button>
<Show when={props.showHostContext}>
<span
- class="inline-flex items-center gap-0.5 rounded bg-gray-100 px-1 py-0.5 text-[10px] font-medium text-gray-600 dark:bg-gray-800 dark:text-gray-300 flex-shrink-0 max-w-[80px]"
+ class="inline-flex items-center gap-1 rounded bg-gray-100 px-1.5 py-0.5 text-[10px] font-medium text-gray-600 dark:bg-gray-800 dark:text-gray-300 flex-shrink-0 max-w-[120px]"
title={`Host: ${hostDisplayName()}`}
>
<StatusDot variant={hostStatus().variant} title={hostStatus().label} ariaLabel={hostStatus().label} size="xs" />
<span class="truncate">{hostDisplayName()}</span>
</span>
</Show>
-
</div>
</div>
</div>
@@ -1313,7 +1322,7 @@ const DockerContainerRow: Component<{
<For each={DOCKER_COLUMNS}>
{(column) => (
<td
- class={`py-0.5 align-middle whitespace-nowrap ${column.id === 'resource' ? 'max-w-[400px]' : ''}`}
+ class={`py-0.5 align-middle whitespace-nowrap ${column.id === 'resource' ? 'max-w-[300px]' : ''}`}
style={{
"min-width": (column.id === 'cpu' || column.id === 'memory') ? (props.isMobile() ? '60px' : '140px') : undefined,
"width": (column.id === 'cpu' || column.id === 'memory') && !props.isMobile() ? '140px' : undefined,
@@ -1964,7 +1973,7 @@ const DockerServiceRow: Component<{
<div class="flex-1 min-w-0">
<div class="flex items-center gap-1.5 flex-1 min-w-0 group/name">
<span
- class="text-sm font-semibold text-gray-900 dark:text-gray-100 select-none truncate min-w-0 flex-1"
+ class="text-sm font-semibold text-gray-900 dark:text-gray-100 select-none"
title={serviceTitle()}
>
{service.name || service.id || 'Service'}
@@ -2083,7 +2092,7 @@ const DockerServiceRow: Component<{
<For each={DOCKER_COLUMNS}>
{(column) => (
<td
- class={`py-0.5 align-middle whitespace-nowrap ${column.id === 'resource' ? 'max-w-[400px]' : ''}`}
+ class={`py-0.5 align-middle whitespace-nowrap ${column.id === 'resource' ? 'max-w-[300px]' : ''}`}
style={{
"min-width": (column.id === 'cpu' || column.id === 'memory') ? (props.isMobile() ? '60px' : '140px') : undefined,
"width": (column.id === 'cpu' || column.id === 'memory') && !props.isMobile() ? '140px' : undefined,
diff --git a/frontend-modern/src/components/Hosts/HostsOverview.tsx b/frontend-modern/src/components/Hosts/HostsOverview.tsx
index d39e1e8461..1cc6327475 100644
--- a/frontend-modern/src/components/Hosts/HostsOverview.tsx
+++ b/frontend-modern/src/components/Hosts/HostsOverview.tsx
@@ -17,7 +17,6 @@ import { StackedMemoryBar } from '@/components/Dashboard/StackedMemoryBar';
import { EnhancedCPUBar } from '@/components/Dashboard/EnhancedCPUBar';
import { useBreakpoint, type ColumnPriority } from '@/hooks/useBreakpoint';
import { useColumnVisibility } from '@/hooks/useColumnVisibility';
-import { aiChatStore } from '@/stores/aiChat';
import { STORAGE_KEYS } from '@/utils/localStorage';
import { useResourcesAsLegacy } from '@/hooks/useResources';
import { useAlertsActivation } from '@/stores/alertsActivation';
@@ -41,11 +40,11 @@ export interface HostColumnDef {
// Host table column definitions - all essential for horizontal scroll like Docker
export const HOST_COLUMNS: HostColumnDef[] = [
// Core columns - all essential (visible on all screens with horizontal scroll)
- { id: 'name', label: 'Host', priority: 'essential', width: '100px', sortKey: 'name' },
- { id: 'platform', label: 'Platform', priority: 'essential', width: '70px', sortKey: 'platform' },
+ { id: 'name', label: 'Host', priority: 'essential', width: '210px', sortKey: 'name' },
+ { id: 'platform', label: 'Platform', priority: 'essential', width: '110px', sortKey: 'platform' },
{ id: 'cpu', label: 'CPU', priority: 'essential', width: '60px', sortKey: 'cpu' },
{ id: 'memory', label: 'Memory', priority: 'essential', width: '60px', sortKey: 'memory' },
- { id: 'disk', label: 'Disk', priority: 'essential', width: '60px', sortKey: 'disk' },
+ { id: 'disk', label: 'Disk', priority: 'essential', width: '220px', sortKey: 'disk' },
// Additional columns - essential but toggleable by user
{ id: 'temp', label: 'Temp', icon: <svg class="w-3.5 h-3.5 block" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" /></svg>, priority: 'essential', width: '50px', toggleable: true },
@@ -173,6 +172,7 @@ interface HostSensorSummaryForCell {
function HostTemperatureCell(props: { sensors: HostSensorSummaryForCell | null | undefined }) {
const [showTooltip, setShowTooltip] = createSignal(false);
const [tooltipPos, setTooltipPos] = createSignal({ x: 0, y: 0 });
+ const [tooltipDirection, setTooltipDirection] = createSignal<'above' | 'below'>('above');
const alertsActivation = useAlertsActivation();
const threshold = createMemo(() => alertsActivation.getTemperatureThreshold());
let closeTimeout: number | undefined;
@@ -240,7 +240,22 @@ function HostTemperatureCell(props: { sensors: HostSensorSummaryForCell | null |
const handleMouseEnter = (e: MouseEvent) => {
if (closeTimeout) window.clearTimeout(closeTimeout);
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
- setTooltipPos({ x: rect.left + rect.width / 2, y: rect.top });
+ const x = rect.left + rect.width / 2;
+ const y = rect.top;
+
+ // Estimate tooltip height (~400px max) and check if it fits above
+ const estimatedTooltipHeight = 400;
+ const spaceAbove = rect.top;
+ const spaceBelow = window.innerHeight - rect.bottom;
+
+ // Position below if not enough space above, but also check if below has more space
+ if (spaceAbove < estimatedTooltipHeight && spaceBelow > spaceAbove) {
+ setTooltipDirection('below');
+ setTooltipPos({ x, y: rect.bottom });
+ } else {
+ setTooltipDirection('above');
+ setTooltipPos({ x, y });
+ }
setShowTooltip(true);
};
@@ -323,8 +338,12 @@ function HostTemperatureCell(props: { sensors: HostSensorSummaryForCell | null |
class="fixed z-[9999]"
style={{
left: `${tooltipPos().x}px`,
- top: `${tooltipPos().y - 8}px`,
- transform: 'translate(-50%, -100%)',
+ top: tooltipDirection() === 'above'
+ ? `${tooltipPos().y - 8}px`
+ : `${tooltipPos().y + 8}px`,
+ transform: tooltipDirection() === 'above'
+ ? 'translate(-50%, -100%)'
+ : 'translate(-50%, 0)',
}}
onMouseEnter={handleTooltipEnter}
onMouseLeave={handleTooltipLeave}
@@ -965,26 +984,26 @@ export const HostsOverview: Component = () => {
<thead>
<tr class="bg-gray-50 dark:bg-gray-700/50 text-gray-600 dark:text-gray-300 border-b border-gray-200 dark:border-gray-700">
{/* Essential columns */}
- <th class={`${thClass} text-left pl-4`} onClick={() => handleSort('name')}>
+ <th class={`${thClass} text-left pl-4`} style={{ "width": isMobile() ? "140px" : "210px" }} onClick={() => handleSort('name')}>
Host {renderSortIndicator('name')}
</th>
<Show when={isColVisible('platform')}>
- <th class={thClass} onClick={() => handleSort('platform')}>
+ <th class={thClass} style={{ "width": isMobile() ? "100px" : "120px" }} onClick={() => handleSort('platform')}>
Platform {renderSortIndicator('platform')}
</th>
</Show>
<Show when={isColVisible('cpu')}>
- <th class={thClass} style={{ "min-width": isMobile() ? "60px" : "140px" }} onClick={() => handleSort('cpu')}>
+ <th class={thClass} style={{ "width": isMobile() ? "60px" : "140px" }} onClick={() => handleSort('cpu')}>
CPU {renderSortIndicator('cpu')}
</th>
</Show>
<Show when={isColVisible('memory')}>
- <th class={thClass} style={{ "min-width": isMobile() ? "60px" : "140px" }} onClick={() => handleSort('memory')}>
+ <th class={thClass} style={{ "width": isMobile() ? "60px" : "140px" }} onClick={() => handleSort('memory')}>
Memory {renderSortIndicator('memory')}
</th>
</Show>
<Show when={isColVisible('disk')}>
- <th class={thClass} style={{ "min-width": isMobile() ? "60px" : "140px" }} onClick={() => handleSort('disk')}>
+ <th class={thClass} style={{ "width": isMobile() ? "90px" : "220px" }} onClick={() => handleSort('disk')}>
Disk {renderSortIndicator('disk')}
</th>
</Show>
@@ -1087,8 +1106,6 @@ const HostRow: Component<HostRowProps> = (props) => {
// NOTE: Do NOT destructure props.host - it breaks SolidJS reactivity!
// Always access props.host directly to ensure updates flow through.
- // Check if this host is in AI context
- const isInAIContext = createMemo(() => aiChatStore.enabled && aiChatStore.hasContextItem(props.host.id));
// URL editing using shared hook
const urlEdit = createUrlEditState();
@@ -1129,39 +1146,7 @@ const HostRow: Component<HostRowProps> = (props) => {
}
};
- // Build context for AI - includes routing fields
- const buildHostContext = (): Record<string, unknown> => ({
- hostName: props.host.displayName || props.host.hostname,
- hostname: props.host.hostname,
- node: props.host.hostname, // Used by AI for command routing
- target_host: props.host.hostname, // Explicit routing hint
- platform: props.host.platform,
- osName: props.host.osName,
- osVersion: props.host.osVersion,
- cpuUsage: props.host.cpuUsage ? `${props.host.cpuUsage.toFixed(1)}%` : undefined,
- memoryUsage: props.host.memory?.usage ? `${props.host.memory.usage.toFixed(1)}%` : undefined,
- uptime: props.host.uptimeSeconds ? formatUptime(props.host.uptimeSeconds) : undefined,
- });
- // Handle row click - toggle AI context selection
- const handleRowClick = (event: MouseEvent) => {
- const target = event.target as HTMLElement;
- if (target.closest('a, button, [data-prevent-toggle], [data-url-editor]')) {
- return;
- }
-
- // If AI is enabled, toggle AI context
- if (aiChatStore.enabled) {
- if (aiChatStore.hasContextItem(props.host.id)) {
- aiChatStore.removeContextItem(props.host.id);
- } else {
- aiChatStore.addContextItem('host', props.host.id, props.host.displayName || props.host.hostname, buildHostContext());
- if (!aiChatStore.isOpen) {
- aiChatStore.open();
- }
- }
- }
- };
// Reactive getters to ensure values update when WebSocket data changes
const hostStatus = createMemo(() => getHostStatusIndicator(props.host));
@@ -1172,17 +1157,15 @@ const HostRow: Component<HostRowProps> = (props) => {
const rowClass = () => {
const base = 'transition-all duration-200';
const hover = 'hover:bg-gray-50 dark:hover:bg-gray-800/50';
- const clickable = aiChatStore.enabled ? 'cursor-pointer' : '';
- const aiContext = isInAIContext() ? 'ai-context-row' : '';
const offline = !isOnline() ? 'opacity-60' : '';
- return `${base} ${hover} ${clickable} ${aiContext} ${offline}`;
+ return `${base} ${hover} ${offline}`;
};
return (
<>
- <tr class={rowClass()} onClick={handleRowClick}>
+ <tr class={rowClass()}>
{/* Host Name - always visible */}
- <td class="pl-4 pr-2 py-1 align-middle">
+ <td class="pl-4 pr-2 py-1 align-middle overflow-hidden">
<div class="flex items-center gap-2 min-w-0">
<StatusDot
variant={hostStatus().variant}
@@ -1190,18 +1173,21 @@ const HostRow: Component<HostRowProps> = (props) => {
ariaLabel={hostStatus().label}
size="xs"
/>
- <div class="min-w-0 flex items-center gap-1.5 group/name">
- <div>
- <p class="text-sm font-semibold text-gray-900 dark:text-gray-100 whitespace-nowrap">
+ <div class="min-w-0 flex items-center gap-1.5 group/name flex-1">
+ <div class="min-w-0 flex-1">
+ <p
+ class="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate"
+ title={props.host.displayName || props.host.hostname || props.host.id}
+ >
{props.host.displayName || props.host.hostname || props.host.id}
</p>
<Show when={props.host.displayName && props.host.displayName !== props.host.hostname}>
- <p class="text-xs text-gray-500 dark:text-gray-400 mt-0.5 whitespace-nowrap">
+ <p class="text-xs text-gray-500 dark:text-gray-400 mt-0.5 truncate" title={props.host.hostname}>
{props.host.hostname}
</p>
</Show>
<Show when={props.host.lastSeen}>
- <p class="text-[10px] text-gray-500 dark:text-gray-400 mt-0.5 whitespace-nowrap">
+ <p class="text-[10px] text-gray-500 dark:text-gray-400 mt-0.5 truncate">
Updated {formatRelativeTime(props.host.lastSeen!)}
</p>
</Show>
@@ -1242,25 +1228,18 @@ const HostRow: Component<HostRowProps> = (props) => {
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
</svg>
</button>
- {/* AI context indicator */}
- <Show when={isInAIContext()}>
- <span class="flex-shrink-0 text-purple-500 dark:text-purple-400" title="Selected for AI context">
- <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
- <path stroke-linecap="round" stroke-linejoin="round" d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456z" />
- </svg>
- </span>
- </Show>
+
</div>
</div>
</td>
{/* Platform */}
<Show when={props.isColVisible('platform')}>
- <td class="px-2 py-1 align-middle">
- <div class="text-xs text-gray-700 dark:text-gray-300">
- <p class="font-medium capitalize whitespace-nowrap">{props.host.platform || '—'}</p>
+ <td class="px-2 py-1 align-middle overflow-hidden">
+ <div class="text-xs text-gray-700 dark:text-gray-300 min-w-0">
+ <p class="font-medium capitalize truncate" title={props.host.platform || '—'}>{props.host.platform || '—'}</p>
<Show when={props.host.osName}>
- <p class="text-[10px] text-gray-500 dark:text-gray-400 mt-0.5 whitespace-nowrap">
+ <p class="text-[10px] text-gray-500 dark:text-gray-400 mt-0.5 truncate" title={`${props.host.osName} ${props.host.osVersion}`.trim()}>
{props.host.osName} {props.host.osVersion}
</p>
</Show>
@@ -1270,7 +1249,7 @@ const HostRow: Component<HostRowProps> = (props) => {
{/* CPU */}
<Show when={props.isColVisible('cpu')}>
- <td class="px-2 py-1 align-middle" style={{ "min-width": props.isMobile() ? "60px" : "140px", "width": props.isMobile() ? undefined : "140px", "max-width": props.isMobile() ? undefined : "140px" }}>
+ <td class="px-2 py-1 align-middle">
<Show when={isOnline()} fallback={<div class="flex justify-center"><span class="text-xs text-gray-400">—</span></div>}>
<EnhancedCPUBar
usage={cpuPercent()}
@@ -1283,7 +1262,7 @@ const HostRow: Component<HostRowProps> = (props) => {
{/* Memory */}
<Show when={props.isColVisible('memory')}>
- <td class="px-2 py-1 align-middle" style={{ "min-width": props.isMobile() ? "60px" : "140px", "width": props.isMobile() ? undefined : "140px", "max-width": props.isMobile() ? undefined : "140px" }}>
+ <td class="px-2 py-1 align-middle">
<Show when={isOnline()} fallback={<div class="flex justify-center"><span class="text-xs text-gray-400">—</span></div>}>
<StackedMemoryBar
used={props.host.memory?.used || 0}
@@ -1298,10 +1277,11 @@ const HostRow: Component<HostRowProps> = (props) => {
{/* Disk */}
<Show when={props.isColVisible('disk')}>
- <td class="px-2 py-1 align-middle" style={{ "min-width": props.isMobile() ? "60px" : "140px", "width": props.isMobile() ? undefined : "140px", "max-width": props.isMobile() ? undefined : "140px" }}>
+ <td class="px-2 py-1 align-middle">
<Show when={isOnline()} fallback={<div class="flex justify-center"><span class="text-xs text-gray-400">—</span></div>}>
<StackedDiskBar
disks={props.host.disks}
+ mode="mini"
aggregateDisk={{
total: diskStats().total,
used: diskStats().used,
diff --git a/frontend-modern/src/components/shared/HistoryChart.tsx b/frontend-modern/src/components/shared/HistoryChart.tsx
index 60f242b6b6..ef1b295313 100644
--- a/frontend-modern/src/components/shared/HistoryChart.tsx
+++ b/frontend-modern/src/components/shared/HistoryChart.tsx
@@ -2,7 +2,7 @@
* HistoryChart Component
*
* Canvas-based chart for displaying historical metrics data (up to 90 days).
- * Includes user-friendly empty states and Pro-tier gating for >24h data.
+ * Includes user-friendly empty states and Pro-tier gating for 30d/90d data.
*/
import { Component, createEffect, createSignal, onCleanup, Show, createMemo, onMount } from 'solid-js';
@@ -63,6 +63,8 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {
return !isLongTermEnabled() && (r === '30d' || r === '90d');
});
+ const lockDays = createMemo(() => (range() === '30d' ? '30' : '90'));
+
// Hover state for tooltip
const [hoveredPoint, setHoveredPoint] = createSignal<{
value: number;
@@ -79,17 +81,15 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {
const type = props.resourceType;
const id = props.resourceId;
const metric = props.metric;
+ const locked = isLocked();
if (!id || !type) return;
- // If locked, we don't fetch data (or we fetch 24h data to show blurred?)
- // Better: Fetch data even if locked, let the API enforce the cap (which we did),
- // or just don't fetch and show the lock screen immediately?
- // Decision: If locked, show the lock screen over the *previous* data or just empty.
- // But to make it look nice "blurred", we might want some data.
- // However, the API enforces 24h cap. So fetching '7d' will return 24h data.
- // We can display that 24h data scaled to 7d (which would look short) or just show the lock overlay.
- // Let's just fetch. The API will return what's allowed.
+ if (locked) {
+ setLoading(false);
+ setError(null);
+ return;
+ }
setLoading(true);
setError(null);
@@ -362,9 +362,9 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {
<path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
</svg>
</div>
- <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-1">90-Day History</h3>
+ <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-1">{lockDays()}-Day History</h3>
<p class="text-sm text-gray-600 dark:text-gray-300 text-center max-w-[200px] mb-4">
- Upgrade to Pulse Pro to unlock 90 days of historical data retention.
+ Upgrade to Pulse Pro to unlock {lockDays()} days of historical data retention.
</p>
<a
href="https://pulserelay.pro/pricing"
diff --git a/frontend-modern/src/components/shared/NodeSummaryTable.tsx b/frontend-modern/src/components/shared/NodeSummaryTable.tsx
index ac4d888635..7a991c00b6 100644
--- a/frontend-modern/src/components/shared/NodeSummaryTable.tsx
+++ b/frontend-modern/src/components/shared/NodeSummaryTable.tsx
@@ -200,12 +200,12 @@ export const NodeSummaryTable: Component<NodeSummaryTableProps> = (props) => {
if (isPVE(item)) {
const node = item;
if (!node.disk) return undefined;
- return `${formatBytes(node.disk.used, 0)}/${formatBytes(node.disk.total, 0)}`;
+ return `${formatBytes(node.disk.used)}/${formatBytes(node.disk.total)}`;
}
const pbs = item;
if (!pbs.datastores || pbs.datastores.length === 0) return undefined;
const totals = getPbsTotals(pbs);
- return `${formatBytes(totals.used, 0)}/${formatBytes(totals.total, 0)}`;
+ return `${formatBytes(totals.used)}/${formatBytes(totals.total)}`;
};
const getTemperatureValue = (item: TableItem) => {
@@ -346,7 +346,7 @@ export const NodeSummaryTable: Component<NodeSummaryTableProps> = (props) => {
// Cell class constants for consistency
const tdClass = "px-2 py-1 align-middle";
- const metricColumnStyle = { width: "200px", "min-width": "200px", "max-width": "200px" } as const;
+ const metricColumnStyle = { "min-width": "140px", "max-width": "180px" } as const;
return (
<Card padding="none" tone="glass" class="mb-4 overflow-hidden">
@@ -360,41 +360,41 @@ export const NodeSummaryTable: Component<NodeSummaryTableProps> = (props) => {
>
{props.currentTab === 'backups' ? 'Node / PBS' : 'Node'} {renderSortIndicator('name')}
</th>
- <th class={thClass} style={{ "min-width": '80px' }} onClick={() => handleSort('uptime')}>
+ <th class={thClass} style={{ width: '80px', "min-width": '80px', "max-width": '80px' }} onClick={() => handleSort('uptime')}>
Uptime {renderSortIndicator('uptime')}
</th>
- <th class={thClass} style={isMobile() ? { "min-width": "80px" } : { width: "140px", "min-width": "140px", "max-width": "140px" }} onClick={() => handleSort('cpu')}>
+ <th class={thClass} style={isMobile() ? { "min-width": "80px" } : { "min-width": "140px", "max-width": "180px" }} onClick={() => handleSort('cpu')}>
CPU {renderSortIndicator('cpu')}
</th>
- <th class={thClass} style={isMobile() ? { "min-width": "80px" } : { width: "140px", "min-width": "140px", "max-width": "140px" }} onClick={() => handleSort('memory')}>
+ <th class={thClass} style={isMobile() ? { "min-width": "80px" } : { "min-width": "140px", "max-width": "180px" }} onClick={() => handleSort('memory')}>
Memory {renderSortIndicator('memory')}
</th>
- <th class={thClass} style={isMobile() ? { "min-width": "80px" } : { width: "140px", "min-width": "140px", "max-width": "140px" }} onClick={() => handleSort('disk')}>
+ <th class={thClass} style={isMobile() ? { "min-width": "80px" } : { "min-width": "140px", "max-width": "180px" }} onClick={() => handleSort('disk')}>
Disk {renderSortIndicator('disk')}
</th>
<Show when={hasAnyTemperatureData()}>
- <th class={thClass} style={{ "min-width": '60px' }} onClick={() => handleSort('temperature')}>
+ <th class={thClass} style={{ width: '60px', "min-width": '60px', "max-width": '60px' }} onClick={() => handleSort('temperature')}>
Temp {renderSortIndicator('temperature')}
</th>
</Show>
<Show when={props.currentTab === 'dashboard'}>
- <th class={thClass} style={{ "min-width": '50px' }} onClick={() => handleSort('vmCount')}>
+ <th class={thClass} style={{ width: '50px', "min-width": '50px', "max-width": '50px' }} onClick={() => handleSort('vmCount')}>
VMs {renderSortIndicator('vmCount')}
</th>
- <th class={thClass} style={{ "min-width": '50px' }} onClick={() => handleSort('containerCount')}>
+ <th class={thClass} style={{ width: '50px', "min-width": '50px', "max-width": '50px' }} onClick={() => handleSort('containerCount')}>
CTs {renderSortIndicator('containerCount')}
</th>
</Show>
<Show when={props.currentTab === 'storage'}>
- <th class={thClass} style={{ "min-width": '70px' }} onClick={() => handleSort('storageCount')}>
+ <th class={thClass} style={{ width: '70px', "min-width": '70px', "max-width": '70px' }} onClick={() => handleSort('storageCount')}>
Storage {renderSortIndicator('storageCount')}
</th>
- <th class={thClass} style={{ "min-width": '60px' }} onClick={() => handleSort('diskCount')}>
+ <th class={thClass} style={{ width: '60px', "min-width": '60px', "max-width": '60px' }} onClick={() => handleSort('diskCount')}>
Disks {renderSortIndicator('diskCount')}
</th>
</Show>
<Show when={props.currentTab === 'backups'}>
- <th class={thClass} style={{ "min-width": '70px' }} onClick={() => handleSort('backupCount')}>
+ <th class={thClass} style={{ width: '70px', "min-width": '70px', "max-width": '70px' }} onClick={() => handleSort('backupCount')}>
Backups {renderSortIndicator('backupCount')}
</th>
</Show>
@@ -490,8 +490,8 @@ export const NodeSummaryTable: Component<NodeSummaryTableProps> = (props) => {
onClick={() => props.onNodeClick(nodeId, isPVEItem ? 'pve' : 'pbs')}
>
{/* Name */}
- <td class={`pr-2 py-1 align-middle ${showAlertHighlight() ? 'pl-4' : 'pl-3'}`}>
- <div class="flex items-center gap-1.5">
+ <td class={`pr-2 py-1 align-middle overflow-hidden ${showAlertHighlight() ? 'pl-4' : 'pl-3'}`}>
+ <div class="flex items-center gap-1.5 min-w-0">
<StatusDot
variant={statusIndicator().variant}
title={statusIndicator().label}
@@ -516,7 +516,7 @@ export const NodeSummaryTable: Component<NodeSummaryTableProps> = (props) => {
({(node as Node).name})
</span>
</Show>
- <div class="hidden xl:flex items-center gap-1.5 ml-1">
+ <div class="hidden xl:flex items-center gap-1.5 ml-1 flex-shrink min-w-0 overflow-hidden">
<Show when={isPVEItem}>
<span class="text-[9px] px-1 py-0 rounded font-medium bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400">
PVE
@@ -545,6 +545,17 @@ export const NodeSummaryTable: Component<NodeSummaryTableProps> = (props) => {
+Agent
</span>
</Show>
+ <Show when={isPVEItem && online && node!.pendingUpdates !== undefined && node!.pendingUpdates > 0}>
+ <span
+ class={`text-[9px] px-1 py-0 rounded font-medium whitespace-nowrap ${(node!.pendingUpdates ?? 0) >= 10
+ ? 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400'
+ : 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400'
+ }`}
+ title={`${node!.pendingUpdates} pending apt update${node!.pendingUpdates !== 1 ? 's' : ''}`}
+ >
+ {node!.pendingUpdates} updates
+ </span>
+ </Show>
<Show when={isPBSItem}>
<span class="text-[9px] px-1 py-0 rounded font-medium bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400">
PBS
@@ -598,7 +609,7 @@ export const NodeSummaryTable: Component<NodeSummaryTableProps> = (props) => {
value={memoryPercentValue}
type="memory"
resourceId={metricsKey}
- sublabel={pbs!.memoryTotal ? `${formatBytes(pbs!.memoryUsed, 0)}/${formatBytes(pbs!.memoryTotal, 0)}` : undefined}
+ sublabel={pbs!.memoryTotal ? `${formatBytes(pbs!.memoryUsed)}/${formatBytes(pbs!.memoryTotal)}` : undefined}
isRunning={online}
showMobile={false}
/>
diff --git a/frontend-modern/src/components/shared/UnifiedHistoryChart.tsx b/frontend-modern/src/components/shared/UnifiedHistoryChart.tsx
index 68ecb2f516..06e690e958 100644
--- a/frontend-modern/src/components/shared/UnifiedHistoryChart.tsx
+++ b/frontend-modern/src/components/shared/UnifiedHistoryChart.tsx
@@ -1,4 +1,4 @@
-import { Component, createSignal, createEffect, onCleanup, onMount, Show, For } from 'solid-js';
+import { Component, createSignal, createEffect, onCleanup, onMount, Show, For, createMemo } from 'solid-js';
import { Portal } from 'solid-js/web';
import { AggregatedMetricPoint, ChartsAPI, HistoryTimeRange, ResourceType } from '@/api/charts';
import { formatBytes } from '@/utils/format';
@@ -37,6 +37,9 @@ export const UnifiedHistoryChart: Component<UnifiedHistoryChartProps> = (props)
disk: { label: 'Disk', color: '#10b981', unit: '%' } // emerald-500
};
+ const isLocked = createMemo(() => (range() === '30d' || range() === '90d') && !hasFeature('long_term_metrics'));
+ const lockDays = createMemo(() => (range() === '30d' ? '30' : '90'));
+
const loadData = async (resourceType: ResourceType, resourceId: string, rangeValue: HistoryTimeRange) => {
setLoading(true);
setError(null);
@@ -74,8 +77,14 @@ export const UnifiedHistoryChart: Component<UnifiedHistoryChartProps> = (props)
const resourceType = props.resourceType;
const resourceId = props.resourceId;
const rangeValue = props.range ?? range();
+ const locked = isLocked();
if (!resourceType || !resourceId) return;
+ if (locked) {
+ setLoading(false);
+ setError(null);
+ return;
+ }
loadData(resourceType, resourceId, rangeValue);
});
@@ -228,8 +237,6 @@ export const UnifiedHistoryChart: Component<UnifiedHistoryChartProps> = (props)
if (props.onRangeChange) props.onRangeChange(r);
};
- const isLocked = () => (range() === '30d' || range() === '90d') && !hasFeature('long_term_metrics');
-
return (
<div class="flex flex-col bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-4">
<div class="flex items-center justify-between mb-4">
@@ -292,7 +299,10 @@ export const UnifiedHistoryChart: Component<UnifiedHistoryChartProps> = (props)
<path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
</svg>
</div>
- <h3 class="text-sm font-bold text-gray-900 dark:text-white mb-3 text-center">90-Day History Locked</h3>
+ <h3 class="text-sm font-bold text-gray-900 dark:text-white mb-1 text-center">{lockDays()}-Day History Locked</h3>
+ <p class="text-[10px] text-gray-600 dark:text-gray-300 mb-3 text-center">
+ Upgrade to Pulse Pro to unlock {lockDays()} days of history.
+ </p>
<a href="https://pulserelay.pro/pricing" target="_blank" class="px-4 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold rounded-full shadow-lg transition-all transform hover:scale-105">Upgrade to Pro</a>
</div>
</Show>
diff --git a/frontend-modern/src/test/setup.ts b/frontend-modern/src/test/setup.ts
index 7b0828bfa8..8f8ef98f96 100644
--- a/frontend-modern/src/test/setup.ts
+++ b/frontend-modern/src/test/setup.ts
@@ -1 +1,66 @@
import '@testing-library/jest-dom';
+
+type StorageValue = string | null;
+
+const ensureLocalStorage = () => {
+ const existing = globalThis.localStorage as Storage | undefined;
+ const hasApi =
+ existing &&
+ typeof existing.getItem === 'function' &&
+ typeof existing.setItem === 'function' &&
+ typeof existing.removeItem === 'function' &&
+ typeof existing.clear === 'function';
+
+ if (hasApi) return;
+
+ class InMemoryStorage {
+ private store: Record<string, string> = {};
+
+ get length() {
+ return Object.keys(this.store).length;
+ }
+
+ key(index: number): StorageValue {
+ return Object.keys(this.store)[index] ?? null;
+ }
+
+ getItem(key: string): StorageValue {
+ return Object.prototype.hasOwnProperty.call(this.store, key) ? this.store[key] : null;
+ }
+
+ setItem(key: string, value: string) {
+ this.store[key] = String(value);
+ }
+
+ removeItem(key: string) {
+ delete this.store[key];
+ }
+
+ clear() {
+ this.store = {};
+ }
+ }
+
+ Object.defineProperty(globalThis, 'Storage', {
+ value: InMemoryStorage,
+ writable: true,
+ configurable: true,
+ });
+
+ const storage = new InMemoryStorage();
+ Object.defineProperty(globalThis, 'localStorage', {
+ value: storage,
+ writable: true,
+ configurable: true,
+ });
+
+ if (typeof window !== 'undefined') {
+ Object.defineProperty(window, 'localStorage', {
+ value: storage,
+ writable: true,
+ configurable: true,
+ });
+ }
+};
+
+ensureLocalStorage();
diff --git a/internal/ai/chat/service_test.go b/internal/ai/chat/service_test.go
index 6d07e0c6bb..3e1686207e 100644
--- a/internal/ai/chat/service_test.go
+++ b/internal/ai/chat/service_test.go
@@ -2,12 +2,16 @@ package chat
import (
"context"
+ "errors"
"testing"
"github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
@@ -38,6 +42,24 @@ func (m *mockAgentServer) ExecuteCommand(ctx context.Context, agentID string, cm
return &agentexec.CommandResultPayload{}, nil
}
+func hasTool(toolsList []tools.Tool, name string) bool {
+ for _, tool := range toolsList {
+ if tool.Name == name {
+ return true
+ }
+ }
+ return false
+}
+
+func hasProviderTool(toolsList []providers.Tool, name string) bool {
+ for _, tool := range toolsList {
+ if tool.Name == name {
+ return true
+ }
+ }
+ return false
+}
+
func TestNewService(t *testing.T) {
cfg := Config{
AIConfig: &config.AIConfig{
@@ -390,3 +412,107 @@ func TestParseRunCommandDecision(t *testing.T) {
})
}
}
+
+func TestService_SettersAndUpdateControlSettings(t *testing.T) {
+ service := NewService(Config{
+ AIConfig: &config.AIConfig{ControlLevel: config.ControlLevelReadOnly},
+ // Agent server makes pulse_run_command eligible when control is enabled.
+ AgentServer: &mockAgentServer{},
+ })
+
+ require.NotNil(t, service.executor)
+ assert.False(t, hasTool(service.executor.ListTools(), "pulse_run_command"))
+
+ service.SetAlertProvider(nil)
+ service.SetFindingsProvider(nil)
+ service.SetBaselineProvider(nil)
+ service.SetPatternProvider(nil)
+ service.SetMetricsHistory(nil)
+ service.SetBackupProvider(nil)
+ service.SetStorageProvider(nil)
+ service.SetDiskHealthProvider(nil)
+ service.SetUpdatesProvider(nil)
+ service.SetAgentProfileManager(nil)
+ service.SetFindingsManager(nil)
+ service.SetMetadataUpdater(nil)
+
+ service.UpdateControlSettings(nil)
+ service.UpdateControlSettings(&config.AIConfig{
+ ControlLevel: config.ControlLevelControlled,
+ ProtectedGuests: []string{"101"},
+ })
+
+ assert.True(t, hasTool(service.executor.ListTools(), "pulse_run_command"))
+}
+
+func TestService_ClassifyRunCommand(t *testing.T) {
+ t.Run("ProviderMissing", func(t *testing.T) {
+ service := &Service{}
+ _, err := service.classifyRunCommand(context.Background(), "run ls")
+ assert.Error(t, err)
+ })
+
+ t.Run("AllowTrue", func(t *testing.T) {
+ mockProvider := &MockProvider{}
+ mockProvider.On("Chat", mock.Anything, mock.Anything).
+ Return(&providers.ChatResponse{Content: `{"allow_run_command": true}`}, nil).
+ Once()
+
+ service := &Service{provider: mockProvider}
+ allow, err := service.classifyRunCommand(context.Background(), "run ls")
+ require.NoError(t, err)
+ assert.True(t, allow)
+ mockProvider.AssertExpectations(t)
+ })
+}
+
+func TestService_FilterToolsForPrompt_ClassificationError(t *testing.T) {
+ service := NewService(Config{
+ AIConfig: &config.AIConfig{ControlLevel: config.ControlLevelControlled},
+ AgentServer: &mockAgentServer{},
+ })
+ require.True(t, hasTool(service.executor.ListTools(), "pulse_run_command"))
+
+ mockProvider := &MockProvider{}
+ mockProvider.On("Chat", mock.Anything, mock.Anything).
+ Return((*providers.ChatResponse)(nil), errors.New("boom")).
+ Once()
+ service.provider = mockProvider
+
+ filtered := service.filterToolsForPrompt(context.Background(), "run uptime")
+ assert.False(t, hasProviderTool(filtered, "pulse_run_command"))
+ mockProvider.AssertExpectations(t)
+}
+
+func TestService_Execute_NonStreaming(t *testing.T) {
+ tmpDir := t.TempDir()
+ store, err := NewSessionStore(tmpDir)
+ require.NoError(t, err)
+
+ mockProvider := &MockProvider{}
+ mockProvider.On("Chat", mock.Anything, mock.Anything).
+ Return(&providers.ChatResponse{Content: `{"allow_run_command": false}`}, nil).
+ Once()
+ mockProvider.On("ChatStream", mock.Anything, mock.Anything, mock.Anything).
+ Return(nil).
+ Run(func(args mock.Arguments) {
+ callback := args.Get(2).(providers.StreamCallback)
+ callback(providers.StreamEvent{Type: "content", Data: providers.ContentEvent{Text: "Hello"}})
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{}})
+ }).
+ Once()
+
+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
+ service := &Service{
+ executor: executor,
+ sessions: store,
+ agenticLoop: NewAgenticLoop(mockProvider, executor, "prompt"),
+ provider: mockProvider,
+ started: true,
+ }
+
+ resp, err := service.Execute(context.Background(), ExecuteRequest{Prompt: "Hi"})
+ require.NoError(t, err)
+ assert.Equal(t, "Hello", resp["content"])
+ mockProvider.AssertExpectations(t)
+}
diff --git a/internal/ai/providers/anthropic.go b/internal/ai/providers/anthropic.go
index f0974c24b6..13a24f03db 100644
--- a/internal/ai/providers/anthropic.go
+++ b/internal/ai/providers/anthropic.go
@@ -598,7 +598,7 @@ func (c *AnthropicClient) ChatStream(ctx context.Context, req ChatRequest, callb
// Parse SSE stream
reader := resp.Body
buf := make([]byte, 4096)
- var eventData string
+ var pendingData string
var toolCalls []ToolCall
var currentToolID string
var currentToolName string
@@ -607,29 +607,24 @@ func (c *AnthropicClient) ChatStream(ctx context.Context, req ChatRequest, callb
for {
n, err := reader.Read(buf)
- if err != nil {
- if err == io.EOF {
- break
- }
- return fmt.Errorf("stream read error: %w", err)
- }
-
- data := string(buf[:n])
- lines := strings.Split(data, "\n")
+ if n > 0 {
+ pendingData += string(buf[:n])
+ lines := strings.Split(pendingData, "\n")
+ pendingData = lines[len(lines)-1]
+ lines = lines[:len(lines)-1]
- for _, line := range lines {
- line = strings.TrimSpace(line)
+ for _, line := range lines {
+ line = strings.TrimSpace(line)
- if strings.HasPrefix(line, "event:") {
- // New event type, reset data
- eventData = ""
- continue
- }
+ if strings.HasPrefix(line, "event:") {
+ continue
+ }
- if strings.HasPrefix(line, "data:") {
- eventData = strings.TrimPrefix(line, "data:")
- eventData = strings.TrimSpace(eventData)
+ if !strings.HasPrefix(line, "data:") {
+ continue
+ }
+ eventData := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
if eventData == "" {
continue
}
@@ -725,6 +720,12 @@ func (c *AnthropicClient) ChatStream(ctx context.Context, req ChatRequest, callb
}
}
}
+ if err != nil {
+ if err == io.EOF {
+ break
+ }
+ return fmt.Errorf("stream read error: %w", err)
+ }
}
return nil
diff --git a/internal/ai/providers/gemini.go b/internal/ai/providers/gemini.go
index 7cd3499b7b..940362bedd 100644
--- a/internal/ai/providers/gemini.go
+++ b/internal/ai/providers/gemini.go
@@ -610,77 +610,78 @@ func (c *GeminiClient) ChatStream(ctx context.Context, req ChatRequest, callback
for {
n, err := reader.Read(buf)
- if err != nil {
- if err == io.EOF {
- break
- }
- return fmt.Errorf("stream read error: %w", err)
- }
-
- pendingData += string(buf[:n])
- lines := strings.Split(pendingData, "\n")
+ if n > 0 {
+ pendingData += string(buf[:n])
+ lines := strings.Split(pendingData, "\n")
- // Keep the last incomplete line for next iteration
- pendingData = lines[len(lines)-1]
- lines = lines[:len(lines)-1]
+ // Keep the last incomplete line for next iteration
+ pendingData = lines[len(lines)-1]
+ lines = lines[:len(lines)-1]
- for _, line := range lines {
- line = strings.TrimSpace(line)
+ for _, line := range lines {
+ line = strings.TrimSpace(line)
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimPrefix(line, "data:")
- data = strings.TrimSpace(data)
+ if !strings.HasPrefix(line, "data:") {
+ continue
+ }
- if data == "" {
- continue
- }
+ data := strings.TrimPrefix(line, "data:")
+ data = strings.TrimSpace(data)
- var event geminiStreamEvent
- if err := json.Unmarshal([]byte(data), &event); err != nil {
- log.Debug().Err(err).Str("data", data).Msg("Failed to parse Gemini stream event")
- continue
- }
+ if data == "" {
+ continue
+ }
- if event.UsageMetadata != nil {
- inputTokens = event.UsageMetadata.PromptTokenCount
- outputTokens = event.UsageMetadata.CandidatesTokenCount
- }
+ var event geminiStreamEvent
+ if err := json.Unmarshal([]byte(data), &event); err != nil {
+ log.Debug().Err(err).Str("data", data).Msg("Failed to parse Gemini stream event")
+ continue
+ }
- for _, candidate := range event.Candidates {
- if candidate.FinishReason != "" {
- finishReason = candidate.FinishReason
+ if event.UsageMetadata != nil {
+ inputTokens = event.UsageMetadata.PromptTokenCount
+ outputTokens = event.UsageMetadata.CandidatesTokenCount
}
- for _, part := range candidate.Content.Parts {
- if part.Text != "" {
- callback(StreamEvent{
- Type: "content",
- Data: ContentEvent{Text: part.Text},
- })
+ for _, candidate := range event.Candidates {
+ if candidate.FinishReason != "" {
+ finishReason = candidate.FinishReason
}
- if part.FunctionCall != nil {
- toolID := fmt.Sprintf("%s_%d", part.FunctionCall.Name, len(toolCalls))
- callback(StreamEvent{
- Type: "tool_start",
- Data: ToolStartEvent{
+ for _, part := range candidate.Content.Parts {
+ if part.Text != "" {
+ callback(StreamEvent{
+ Type: "content",
+ Data: ContentEvent{Text: part.Text},
+ })
+ }
+
+ if part.FunctionCall != nil {
+ toolID := fmt.Sprintf("%s_%d", part.FunctionCall.Name, len(toolCalls))
+ callback(StreamEvent{
+ Type: "tool_start",
+ Data: ToolStartEvent{
+ ID: toolID,
+ Name: part.FunctionCall.Name,
+ Input: part.FunctionCall.Args,
+ },
+ })
+ toolCalls = append(toolCalls, ToolCall{
ID: toolID,
Name: part.FunctionCall.Name,
Input: part.FunctionCall.Args,
- },
- })
- toolCalls = append(toolCalls, ToolCall{
- ID: toolID,
- Name: part.FunctionCall.Name,
- Input: part.FunctionCall.Args,
- })
+ })
+ }
}
}
}
}
+ if err != nil {
+ if err == io.EOF {
+ break
+ }
+ return fmt.Errorf("stream read error: %w", err)
+ }
}
// Send done event
diff --git a/internal/ai/providers/notable_models.go b/internal/ai/providers/notable_models.go
index 7a532e5fc4..51732d7066 100644
--- a/internal/ai/providers/notable_models.go
+++ b/internal/ai/providers/notable_models.go
@@ -4,6 +4,7 @@ package providers
import (
"context"
"encoding/json"
+ "fmt"
"net/http"
"strings"
"sync"
@@ -322,5 +323,5 @@ func parseFlexibleDate(dateStr string) (time.Time, error) {
}
}
- return time.Time{}, nil
+ return time.Time{}, fmt.Errorf("invalid date format: %s", dateStr)
}
diff --git a/internal/ai/tools/tools_patrol_test.go b/internal/ai/tools/tools_patrol_test.go
index 9e0607ad53..233b77b2f1 100644
--- a/internal/ai/tools/tools_patrol_test.go
+++ b/internal/ai/tools/tools_patrol_test.go
@@ -286,3 +286,147 @@ func TestExecuteResolveAndDismissFinding(t *testing.T) {
t.Fatalf("unexpected dismiss response: %+v", okResp)
}
}
+
+func TestExecuteGetMetrics_InvalidResourceType(t *testing.T) {
+ executor := NewPulseToolExecutor(ExecutorConfig{})
+ result, _ := executor.executeGetMetrics(context.Background(), map[string]interface{}{
+ "period": "24h",
+ "resource_type": "bad",
+ })
+ if !result.IsError {
+ t.Fatal("expected error for invalid resource_type")
+ }
+}
+
+func TestExecuteGetMetrics_FilterAndPagination(t *testing.T) {
+ metricsProv := &mockMetricsHistoryProvider{}
+ metricsProv.On("GetAllMetricsSummary", mock.Anything).Return(map[string]ResourceMetricsSummary{
+ "vm1": {ResourceID: "vm1", ResourceType: "vm"},
+ "vm2": {ResourceID: "vm2", ResourceType: "vm"},
+ "ct1": {ResourceID: "ct1", ResourceType: "container"},
+ }, nil)
+
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ StateProvider: &mockStateProvider{},
+ MetricsHistory: metricsProv,
+ })
+
+ result, _ := executor.executeGetMetrics(context.Background(), map[string]interface{}{
+ "period": "24h",
+ "resource_type": "vm",
+ "limit": 1,
+ "offset": 1,
+ })
+ var resp MetricsResponse
+ if err := json.Unmarshal([]byte(result.Content[0].Text), &resp); err != nil {
+ t.Fatalf("decode metrics response: %v", err)
+ }
+ if len(resp.Summary) != 1 {
+ t.Fatalf("unexpected summary: %+v", resp.Summary)
+ }
+ if resp.Pagination == nil || resp.Pagination.Total != 2 || resp.Pagination.Offset != 1 {
+ t.Fatalf("unexpected pagination: %+v", resp.Pagination)
+ }
+}
+
+func TestExecuteGetBaselines_FilterAndErrors(t *testing.T) {
+ executor := NewPulseToolExecutor(ExecutorConfig{})
+ result, _ := executor.executeGetBaselines(context.Background(), map[string]interface{}{
+ "resource_type": "bad",
+ })
+ if !result.IsError {
+ t.Fatal("expected error for invalid resource_type")
+ }
+
+ executor = NewPulseToolExecutor(ExecutorConfig{
+ BaselineProvider: &stubBaselineProvider{
+ baselines: map[string]map[string]*MetricBaseline{"100": {"cpu": {Mean: 1}}},
+ },
+ })
+ result, _ = executor.executeGetBaselines(context.Background(), map[string]interface{}{
+ "resource_type": "vm",
+ })
+ if !result.IsError {
+ t.Fatal("expected error without state provider")
+ }
+
+ executor = NewPulseToolExecutor(ExecutorConfig{
+ StateProvider: &mockStateProvider{state: models.StateSnapshot{
+ VMs: []models.VM{{VMID: 100}, {VMID: 101}},
+ }},
+ BaselineProvider: &stubBaselineProvider{
+ baselines: map[string]map[string]*MetricBaseline{
+ "100": {"cpu": {Mean: 1}},
+ "101": {"cpu": {Mean: 2}},
+ },
+ },
+ })
+ result, _ = executor.executeGetBaselines(context.Background(), map[string]interface{}{
+ "resource_type": "vm",
+ "limit": 1,
+ "offset": 1,
+ })
+ var baselines BaselinesResponse
+ if err := json.Unmarshal([]byte(result.Content[0].Text), &baselines); err != nil {
+ t.Fatalf("decode baselines: %v", err)
+ }
+ if len(baselines.Baselines) != 1 {
+ t.Fatalf("unexpected baselines: %+v", baselines.Baselines)
+ }
+ if baselines.Pagination == nil || baselines.Pagination.Total != 2 || baselines.Pagination.Offset != 1 {
+ t.Fatalf("unexpected pagination: %+v", baselines.Pagination)
+ }
+}
+
+func TestExecuteGetPatterns_EmptySlices(t *testing.T) {
+ executor := NewPulseToolExecutor(ExecutorConfig{})
+ executor.patternProvider = &stubPatternProvider{}
+ result, _ := executor.executeGetPatterns(context.Background(), map[string]interface{}{})
+ var resp PatternsResponse
+ if err := json.Unmarshal([]byte(result.Content[0].Text), &resp); err != nil {
+ t.Fatalf("decode patterns: %v", err)
+ }
+ if resp.Patterns == nil || resp.Predictions == nil {
+ t.Fatal("expected non-nil slices")
+ }
+ if len(resp.Patterns) != 0 || len(resp.Predictions) != 0 {
+ t.Fatalf("unexpected patterns: %+v", resp)
+ }
+}
+
+func TestExecuteListFindings_ResourceTypeFilter(t *testing.T) {
+ executor := NewPulseToolExecutor(ExecutorConfig{})
+ result, _ := executor.executeListFindings(context.Background(), map[string]interface{}{
+ "resource_type": "bad",
+ })
+ if !result.IsError {
+ t.Fatal("expected error for invalid resource_type")
+ }
+
+ findingsProv := &mockFindingsProvider{}
+ findingsProv.On("GetActiveFindings").Return([]Finding{
+ {ID: "f1", Severity: "warning", ResourceType: "docker container", ResourceID: "r1"},
+ {ID: "f2", Severity: "warning", ResourceType: "lxc container", ResourceID: "r2"},
+ })
+ findingsProv.On("GetDismissedFindings").Return([]Finding{
+ {ID: "f3", Severity: "warning", ResourceType: "docker-container", ResourceID: "r3"},
+ })
+
+ executor.findingsProvider = findingsProv
+ result, _ = executor.executeListFindings(context.Background(), map[string]interface{}{
+ "resource_type": "docker",
+ "include_dismissed": true,
+ "limit": 1,
+ "offset": 1,
+ })
+ var resp FindingsResponse
+ if err := json.Unmarshal([]byte(result.Content[0].Text), &resp); err != nil {
+ t.Fatalf("decode findings: %v", err)
+ }
+ if resp.Counts.Active != 1 || resp.Counts.Dismissed != 1 {
+ t.Fatalf("unexpected counts: %+v", resp.Counts)
+ }
+ if resp.Pagination == nil || resp.Pagination.Offset != 1 {
+ t.Fatalf("unexpected pagination: %+v", resp.Pagination)
+ }
+}
diff --git a/internal/ai/tools/tools_query_test.go b/internal/ai/tools/tools_query_test.go
index 816eb874af..1c645a3d5a 100644
--- a/internal/ai/tools/tools_query_test.go
+++ b/internal/ai/tools/tools_query_test.go
@@ -3,6 +3,7 @@ package tools
import (
"context"
"encoding/json"
+ "net"
"net/http"
"net/http/httptest"
"testing"
@@ -239,6 +240,27 @@ func TestExecuteSearchResources(t *testing.T) {
}
}
+func TestExecuteSearchResources_Errors(t *testing.T) {
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ StateProvider: &mockStateProvider{state: models.StateSnapshot{}},
+ })
+
+ result, _ := executor.executeSearchResources(context.Background(), map[string]interface{}{
+ "query": "",
+ })
+ if !result.IsError {
+ t.Fatal("expected error for empty query")
+ }
+
+ result, _ = executor.executeSearchResources(context.Background(), map[string]interface{}{
+ "query": "node",
+ "type": "bad",
+ })
+ if !result.IsError {
+ t.Fatal("expected error for invalid type")
+ }
+}
+
func TestExecuteSetResourceURLAndGetResource(t *testing.T) {
executor := NewPulseToolExecutor(ExecutorConfig{StateProvider: &mockStateProvider{}})
@@ -306,6 +328,83 @@ func TestExecuteSetResourceURLAndGetResource(t *testing.T) {
}
}
+func TestExecuteGetResource_DockerDetails(t *testing.T) {
+ state := models.StateSnapshot{
+ DockerHosts: []models.DockerHost{{
+ Hostname: "dock1",
+ Containers: []models.DockerContainer{{
+ ID: "abcd1234",
+ Name: "web",
+ State: "running",
+ Image: "nginx:latest",
+ Health: "healthy",
+ CPUPercent: 1.2,
+ MemoryPercent: 3.4,
+ MemoryUsage: 1024,
+ MemoryLimit: 2048,
+ RestartCount: 2,
+ Labels: map[string]string{
+ "service": "web",
+ },
+ UpdateStatus: &models.DockerContainerUpdateStatus{
+ UpdateAvailable: true,
+ },
+ Ports: []models.DockerContainerPort{
+ {PrivatePort: 80, PublicPort: 8080, Protocol: "tcp", IP: "0.0.0.0"},
+ },
+ Networks: []models.DockerContainerNetworkLink{
+ {Name: "bridge", IPv4: "172.17.0.2"},
+ },
+ Mounts: []models.DockerContainerMount{
+ {Source: "/src", Destination: "/dst", RW: true},
+ },
+ }},
+ }},
+ }
+
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ StateProvider: &mockStateProvider{state: state},
+ })
+
+ result, _ := executor.executeGetResource(context.Background(), map[string]interface{}{
+ "resource_type": "docker",
+ "resource_id": "web",
+ })
+ var res ResourceResponse
+ if err := json.Unmarshal([]byte(result.Content[0].Text), &res); err != nil {
+ t.Fatalf("decode docker resource: %v", err)
+ }
+ if !res.UpdateAvailable || len(res.Ports) != 1 || len(res.Networks) != 1 || len(res.Mounts) != 1 {
+ t.Fatalf("unexpected docker details: %+v", res)
+ }
+}
+
+func TestExecuteSetResourceURL_ClearAndMissingUpdater(t *testing.T) {
+ executor := NewPulseToolExecutor(ExecutorConfig{})
+ result, _ := executor.executeSetResourceURL(context.Background(), map[string]interface{}{
+ "resource_type": "vm",
+ "resource_id": "100",
+ })
+ if result.Content[0].Text != "Metadata updater not available." {
+ t.Fatalf("unexpected response: %s", result.Content[0].Text)
+ }
+
+ updater := &fakeMetadataUpdater{}
+ executor.metadataUpdater = updater
+ result, _ = executor.executeSetResourceURL(context.Background(), map[string]interface{}{
+ "resource_type": "vm",
+ "resource_id": "100",
+ "url": "",
+ })
+ var resp map[string]interface{}
+ if err := json.Unmarshal([]byte(result.Content[0].Text), &resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if resp["action"] != "cleared" {
+ t.Fatalf("unexpected response: %+v", resp)
+ }
+}
+
func TestIntArg(t *testing.T) {
if got := intArg(map[string]interface{}{}, "limit", 10); got != 10 {
t.Fatalf("unexpected default: %d", got)
@@ -314,3 +413,252 @@ func TestIntArg(t *testing.T) {
t.Fatalf("unexpected value: %d", got)
}
}
+
+func TestParseAndValidateFetchURL(t *testing.T) {
+ t.Run("Empty", func(t *testing.T) {
+ if _, err := parseAndValidateFetchURL(context.Background(), ""); err == nil {
+ t.Fatal("expected error for empty URL")
+ }
+ })
+
+ t.Run("InvalidURL", func(t *testing.T) {
+ if _, err := parseAndValidateFetchURL(context.Background(), "http://%"); err == nil {
+ t.Fatal("expected error for invalid URL")
+ }
+ })
+
+ t.Run("NotAbsolute", func(t *testing.T) {
+ if _, err := parseAndValidateFetchURL(context.Background(), "example.com"); err == nil {
+ t.Fatal("expected error for relative URL")
+ }
+ })
+
+ t.Run("BadScheme", func(t *testing.T) {
+ if _, err := parseAndValidateFetchURL(context.Background(), "ftp://example.com"); err == nil {
+ t.Fatal("expected error for scheme")
+ }
+ })
+
+ t.Run("Credentials", func(t *testing.T) {
+ if _, err := parseAndValidateFetchURL(context.Background(), "http://user:[email protected]"); err == nil {
+ t.Fatal("expected error for credentials")
+ }
+ })
+
+ t.Run("Fragment", func(t *testing.T) {
+ if _, err := parseAndValidateFetchURL(context.Background(), "https://example.com/#frag"); err == nil {
+ t.Fatal("expected error for fragment")
+ }
+ })
+
+ t.Run("MissingHost", func(t *testing.T) {
+ if _, err := parseAndValidateFetchURL(context.Background(), "http:///"); err == nil {
+ t.Fatal("expected error for missing host")
+ }
+ })
+
+ t.Run("BlockedHost", func(t *testing.T) {
+ if _, err := parseAndValidateFetchURL(context.Background(), "http://localhost"); err == nil {
+ t.Fatal("expected error for blocked host")
+ }
+ })
+
+ t.Run("BlockedIP", func(t *testing.T) {
+ if _, err := parseAndValidateFetchURL(context.Background(), "http://127.0.0.1"); err == nil {
+ t.Fatal("expected error for blocked IP")
+ }
+ })
+
+ t.Run("AllowLoopback", func(t *testing.T) {
+ t.Setenv("PULSE_AI_ALLOW_LOOPBACK", "true")
+ parsed, err := parseAndValidateFetchURL(context.Background(), "http://127.0.0.1:8080")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if parsed.Hostname() != "127.0.0.1" {
+ t.Fatalf("unexpected host: %s", parsed.Hostname())
+ }
+ })
+}
+
+func TestIsBlockedFetchIP(t *testing.T) {
+ if !isBlockedFetchIP(nil) {
+ t.Fatal("expected nil IP to be blocked")
+ }
+ if !isBlockedFetchIP(net.ParseIP("0.0.0.0")) {
+ t.Fatal("expected unspecified IP to be blocked")
+ }
+ if !isBlockedFetchIP(net.ParseIP("169.254.1.1")) {
+ t.Fatal("expected link-local IP to be blocked")
+ }
+ if isBlockedFetchIP(net.ParseIP("8.8.8.8")) {
+ t.Fatal("expected global IP to be allowed")
+ }
+
+ t.Run("LoopbackAllowed", func(t *testing.T) {
+ t.Setenv("PULSE_AI_ALLOW_LOOPBACK", "true")
+ if isBlockedFetchIP(net.ParseIP("127.0.0.1")) {
+ t.Fatal("expected loopback IP to be allowed")
+ }
+ })
+}
+
+func TestExecuteListInfrastructurePaginationAndDockerFilter(t *testing.T) {
+ state := models.StateSnapshot{
+ Nodes: []models.Node{
+ {ID: "node1", Name: "node1", Status: "online"},
+ {ID: "node2", Name: "node2", Status: "offline"},
+ },
+ DockerHosts: []models.DockerHost{
+ {
+ ID: "host1",
+ Hostname: "dock1",
+ Containers: []models.DockerContainer{
+ {ID: "c1", Name: "app", State: "running"},
+ {ID: "c2", Name: "db", State: "stopped"},
+ },
+ },
+ {
+ ID: "host2",
+ Hostname: "dock2",
+ Containers: []models.DockerContainer{
+ {ID: "c3", Name: "cache", State: "stopped"},
+ },
+ },
+ },
+ }
+
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ StateProvider: &mockStateProvider{state: state},
+ })
+
+ result, err := executor.executeListInfrastructure(context.Background(), map[string]interface{}{
+ "type": "nodes",
+ "limit": 1,
+ "offset": 1,
+ })
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ var nodesResp InfrastructureResponse
+ if err := json.Unmarshal([]byte(result.Content[0].Text), &nodesResp); err != nil {
+ t.Fatalf("decode nodes response: %v", err)
+ }
+ if len(nodesResp.Nodes) != 1 || nodesResp.Nodes[0].Name != "node2" {
+ t.Fatalf("unexpected nodes response: %+v", nodesResp.Nodes)
+ }
+ if nodesResp.Pagination == nil || nodesResp.Pagination.Total != 2 || nodesResp.Pagination.Offset != 1 {
+ t.Fatalf("unexpected pagination: %+v", nodesResp.Pagination)
+ }
+
+ result, err = executor.executeListInfrastructure(context.Background(), map[string]interface{}{
+ "type": "docker",
+ "status": "running",
+ "max_docker_containers_per_host": 1,
+ })
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ var dockerResp InfrastructureResponse
+ if err := json.Unmarshal([]byte(result.Content[0].Text), &dockerResp); err != nil {
+ t.Fatalf("decode docker response: %v", err)
+ }
+ if len(dockerResp.DockerHosts) != 1 || dockerResp.DockerHosts[0].Hostname != "dock1" {
+ t.Fatalf("unexpected docker hosts: %+v", dockerResp.DockerHosts)
+ }
+ if len(dockerResp.DockerHosts[0].Containers) != 1 || dockerResp.DockerHosts[0].Containers[0].State != "running" {
+ t.Fatalf("unexpected docker containers: %+v", dockerResp.DockerHosts[0].Containers)
+ }
+}
+
+func TestExecuteGetResourceErrorsAndContainer(t *testing.T) {
+ executor := NewPulseToolExecutor(ExecutorConfig{})
+ result, _ := executor.executeGetResource(context.Background(), map[string]interface{}{
+ "resource_type": "vm",
+ "resource_id": "100",
+ })
+ if result.Content[0].Text != "State information not available." {
+ t.Fatalf("unexpected response: %s", result.Content[0].Text)
+ }
+
+ executor.stateProvider = &mockStateProvider{state: models.StateSnapshot{
+ Containers: []models.Container{
+ {ID: "ct1", VMID: 200, Name: "ct1", Status: "running", Node: "node1"},
+ },
+ }}
+
+ result, _ = executor.executeGetResource(context.Background(), map[string]interface{}{
+ "resource_type": "container",
+ "resource_id": "ct1",
+ })
+ var res ResourceResponse
+ if err := json.Unmarshal([]byte(result.Content[0].Text), &res); err != nil {
+ t.Fatalf("decode container response: %v", err)
+ }
+ if res.Type != "container" || res.Name != "ct1" {
+ t.Fatalf("unexpected container response: %+v", res)
+ }
+
+ result, _ = executor.executeGetResource(context.Background(), map[string]interface{}{
+ "resource_type": "vm",
+ "resource_id": "999",
+ })
+ var notFound map[string]interface{}
+ if err := json.Unmarshal([]byte(result.Content[0].Text), &notFound); err != nil {
+ t.Fatalf("decode not found response: %v", err)
+ }
+ if notFound["error"] != "not_found" {
+ t.Fatalf("unexpected not found response: %+v", notFound)
+ }
+
+ result, _ = executor.executeGetResource(context.Background(), map[string]interface{}{
+ "resource_type": "bad",
+ "resource_id": "1",
+ })
+ if !result.IsError {
+ t.Fatal("expected error for invalid resource_type")
+ }
+}
+
+func TestExecuteListInfrastructure_NoStateProvider(t *testing.T) {
+ executor := NewPulseToolExecutor(ExecutorConfig{})
+ result, _ := executor.executeListInfrastructure(context.Background(), map[string]interface{}{})
+ if !result.IsError {
+ t.Fatal("expected error without state provider")
+ }
+}
+
+func TestExecuteGetResource_MissingArgs(t *testing.T) {
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ StateProvider: &mockStateProvider{state: models.StateSnapshot{}},
+ })
+
+ result, _ := executor.executeGetResource(context.Background(), map[string]interface{}{})
+ if !result.IsError {
+ t.Fatal("expected error for missing resource_type")
+ }
+
+ result, _ = executor.executeGetResource(context.Background(), map[string]interface{}{
+ "resource_type": "vm",
+ })
+ if !result.IsError {
+ t.Fatal("expected error for missing resource_id")
+ }
+}
+
+func TestExecuteGetURLContent_InvalidURL(t *testing.T) {
+ executor := NewPulseToolExecutor(ExecutorConfig{})
+ result, err := executor.executeGetURLContent(context.Background(), map[string]interface{}{
+ "url": "ftp://example.com",
+ })
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ var response URLFetchResponse
+ if err := json.Unmarshal([]byte(result.Content[0].Text), &response); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if response.Error == "" {
+ t.Fatalf("expected error response: %+v", response)
+ }
+}