An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.
PHP coolifydatabasesdeploymentdockerdocker-composeinertiajslaravelmariadbmysqlnextjsnodejsphppostgresredisself-hostedself-hostingserverstatic-sitesveltesvelte5
feat(analytics): lazy-load traffic pages and batch Sentinel calls
Aditya Tripathi19752da6af03
diff --git a/app/Livewire/Analytics.php b/app/Livewire/Analytics.phpindex 236cd40bc1..4764acfc41 100644--- a/app/Livewire/Analytics.php+++ b/app/Livewire/Analytics.php@@ -7,10 +7,14 @@ use App\Models\Application;use App\Models\Server;use App\Services\SentinelTrafficClient;use App\Services\TrafficAnalyticsAggregator;+use Illuminate\Contracts\View\View;use Illuminate\Support\Collection;+use Illuminate\Support\Facades\Log;+use Livewire\Attributes\Lazy;use Livewire\Attributes\Url;use Livewire\Component;+#[Lazy]class Analytics extends Component{use BuildsTrafficChartPayload;@@ -87,6 +91,13 @@ class Analytics extends Componentpublic string $nudgeKey = '';+ /**+ * Upper bound on per-app overviews fetched for the leaderboard, so a server with a huge+ * number of recorded apps can't reintroduce a per-app round-trip storm. Truncation is+ * logged (see loadData) rather than silently swallowed.+ */+ private const MAX_LEADERBOARD_APPS = 200;+/** @var array<int, string> */protected array $breakdownDimensions = ['country', 'referer', 'browser', 'os', 'device', 'protocol', 'cache', 'status', 'agent', 'ip', 'useragent'];@@ -178,7 +189,7 @@ class Analytics extends Component{$enabledUuids = $this->servers->pluck('uuid');- $apps = Application::ownedByCurrentTeam()->with('environment.project')->get()+ $apps = Application::ownedByCurrentTeam()->with(['environment.project', 'destination.server'])->get()->filter(function (Application $app) use ($enabledUuids): bool {$serverUuid = $app->destination?->server?->uuid;@@ -252,15 +263,28 @@ class Analytics extends Componenttry {$client = $this->trafficClient($server);- $overviews[] = $client->overview($appKey, $from, $to);+ // Warm every server-wide endpoint in one docker exec instead of ~15 serial+ // SSH round-trips; the per-call methods below then read from cache.+ $leaderboardUuids = $client->prefetchServerWide($appKey, $from, $to, $this->breakdownDimensions, $this->range, appsLimit: self::MAX_LEADERBOARD_APPS);// Per-application leaderboard only makes sense when not already filtered to one app.- if ($appKey === null) {- foreach ($client->apps() as $uuid) {- if (! is_string($uuid) || $uuid === '') {- continue;- }+ if ($appKey === null && $leaderboardUuids !== []) {+ if (count($leaderboardUuids) > self::MAX_LEADERBOARD_APPS) {+ Log::warning('Traffic analytics leaderboard truncated', [+ 'server' => $server->uuid,+ 'total' => count($leaderboardUuids),+ 'shown' => self::MAX_LEADERBOARD_APPS,+ ]);+ $leaderboardUuids = array_slice($leaderboardUuids, 0, self::MAX_LEADERBOARD_APPS);+ }+ // Warm the leaderboard's per-app overviews in a second batched exec.+ $client->prefetchAppOverviews($leaderboardUuids, $from, $to);+ }+ $overviews[] = $client->overview($appKey, $from, $to);++ if ($appKey === null) {+ foreach ($leaderboardUuids as $uuid) {$appOverview = $client->overview($uuid, $from, $to)->toArray();$meta = $this->appMeta($uuid);@@ -512,6 +536,12 @@ class Analytics extends Componentreturn [$from->toIso8601ZuluString(), $to->toIso8601ZuluString()];}+ public function placeholder(): View+ {+ // Rendered instantly; the Sentinel round-trips run in the deferred lazy-load request.+ return view('livewire.analytics-placeholder');+ }+public function render(){return view('livewire.analytics');diff --git a/app/Livewire/Concerns/BuildsTrafficChartPayload.php b/app/Livewire/Concerns/BuildsTrafficChartPayload.phpindex 6963cfd0ad..66af46efa5 100644--- a/app/Livewire/Concerns/BuildsTrafficChartPayload.php+++ b/app/Livewire/Concerns/BuildsTrafficChartPayload.php@@ -25,6 +25,16 @@ trait BuildsTrafficChartPayload);}+ /**+ * Whether there is plottable request-over-time data for the Requests chart. False when+ * Sentinel returned no series buckets (older builds) or every bucket is empty (no traffic+ * in the range), so the views can render a no-data state instead of a blank chart.+ */+ public function hasRequestSeries(): bool+ {+ return array_sum($this->requestsSpark()) > 0;+ }+/*** Per-bucket error requests (4xx + 5xx), for the Error-rate spark.*diff --git a/app/Livewire/Dashboard/TrafficAnalytics.php b/app/Livewire/Dashboard/TrafficAnalytics.phpindex b8b2ce3ed9..394bb0faa7 100644--- a/app/Livewire/Dashboard/TrafficAnalytics.php+++ b/app/Livewire/Dashboard/TrafficAnalytics.php@@ -6,9 +6,12 @@ use App\Livewire\Concerns\BuildsTrafficChartPayload;use App\Models\Server;use App\Services\SentinelTrafficClient;use App\Services\TrafficAnalyticsAggregator;+use Illuminate\Contracts\View\View;use Illuminate\Support\Collection;+use Livewire\Attributes\Lazy;use Livewire\Component;+#[Lazy]class TrafficAnalytics extends Component{use BuildsTrafficChartPayload;@@ -163,6 +166,12 @@ class TrafficAnalytics extends Componentreturn [$from->toIso8601ZuluString(), $to->toIso8601ZuluString()];}+ public function placeholder(): View+ {+ // Rendered instantly on the dashboard; Sentinel round-trips run in the deferred request.+ return view('livewire.dashboard.traffic-analytics-placeholder');+ }+public function render(){return view('livewire.dashboard.traffic-analytics');diff --git a/app/Livewire/Project/Application/Analytics.php b/app/Livewire/Project/Application/Analytics.phpindex 2496ba3187..e495d93b4f 100644--- a/app/Livewire/Project/Application/Analytics.php+++ b/app/Livewire/Project/Application/Analytics.php@@ -5,8 +5,11 @@ namespace App\Livewire\Project\Application;use App\Livewire\Concerns\BuildsTrafficChartPayload;use App\Models\Application;use App\Services\SentinelTrafficClient;+use Illuminate\Contracts\View\View;+use Livewire\Attributes\Lazy;use Livewire\Component;+#[Lazy]class Analytics extends Component{use BuildsTrafficChartPayload;@@ -88,6 +91,10 @@ class Analytics extends Component$client = $this->trafficClient();$key = $this->application->uuid;+ // Warm every endpoint for this app in one docker exec instead of ~14 serial+ // SSH round-trips; the per-call methods below then read from cache.+ $client->prefetchServerWide($key, $from, $to, $this->breakdownDimensions, $this->range);+$this->overview = $client->overview($key, $from, $to)->toArray();// Every path belongs to this one app, so decorate each row with its domain@@ -213,6 +220,12 @@ class Analytics extends Componentreturn [$from->toIso8601ZuluString(), $to->toIso8601ZuluString()];}+ public function placeholder(): View+ {+ // Rendered instantly; the Sentinel round-trip runs in the deferred lazy-load request.+ return view('livewire.project.application.analytics-placeholder');+ }+public function render(){return view('livewire.project.application.analytics');diff --git a/app/Models/ServerSetting.php b/app/Models/ServerSetting.phpindex 4744f25a99..58f28ba32d 100644--- a/app/Models/ServerSetting.php+++ b/app/Models/ServerSetting.php@@ -204,7 +204,12 @@ class ServerSetting extends Model$settings->wasChanged('geoip_refresh_days') ||$settings->wasChanged('geoip_maxmind_license_key')) {- $settings->server->restartSentinel();+ // Only recreate Sentinel when it is already enabled. Otherwise a change to a+ // traffic/geoip tuning knob would turn Sentinel on as a side effect, because+ // StartSentinel unconditionally sets is_sentinel_enabled = true.+ if ($settings->is_sentinel_enabled) {+ $settings->server->restartSentinel();+ }}});}diff --git a/app/Services/SentinelTrafficClient.php b/app/Services/SentinelTrafficClient.phpindex b7722d03bd..aacc4b4b4b 100644--- a/app/Services/SentinelTrafficClient.php+++ b/app/Services/SentinelTrafficClient.php@@ -14,6 +14,9 @@ class SentinelTrafficClient{private string $base = 'http://localhost:8888/api';+ /** Record separator (0x1E) framing the batched curl responses in warm(). */+ private const RECORD_SEPARATOR = "\x1e";+/** @var array<int, string> */private const ALLOWED_DIMENSIONS = ['status', 'method', 'country', 'referer', 'browser', 'os', 'device', 'protocol', 'scheme', 'tls', 'cache', 'bot', 'agent', 'ip', 'useragent',@@ -25,11 +28,7 @@ class SentinelTrafficClient// (e.g. "2024-01-14T10:00:00Z"), confirmed against sentinel/API.md.public function overview(?string $appKey, string $from, string $to): TrafficOverviewData{- if ($appKey !== null) {- $this->assertSafeKey($appKey);- }- $path = $appKey ? "/app/{$appKey}/traffic/overview" : '/traffic/overview';- $json = json_decode($this->raw($this->url($path, ['from' => $from, 'to' => $to])), true) ?? [];+ $json = json_decode($this->raw($this->overviewUrl($appKey, $from, $to)), true) ?? [];return TrafficOverviewData::fromSentinel($json);}@@ -64,23 +63,14 @@ class SentinelTrafficClientpublic function paths(?string $appKey, string $from, string $to, int $limit = 50): Collection{- if ($appKey !== null) {- $this->assertSafeKey($appKey);- }- $path = $appKey ? "/app/{$appKey}/traffic/paths" : '/traffic/paths';- $rows = json_decode($this->raw($this->url($path, ['from' => $from, 'to' => $to, 'limit' => (int) $limit])), true) ?? [];+ $rows = json_decode($this->raw($this->pathsUrl($appKey, $from, $to, $limit)), true) ?? [];return collect($rows)->map(fn ($r) => TrafficPathData::fromSentinel($r));}public function breakdown(?string $appKey, string $dimension, string $from, string $to, int $limit = 50): Collection{- if ($appKey !== null) {- $this->assertSafeKey($appKey);- }- $this->assertSafeDimension($dimension);- $path = $appKey ? "/app/{$appKey}/traffic/breakdown/{$dimension}" : "/traffic/breakdown/{$dimension}";- $rows = json_decode($this->raw($this->url($path, ['from' => $from, 'to' => $to, 'limit' => (int) $limit])), true) ?? [];+ $rows = json_decode($this->raw($this->breakdownUrl($appKey, $dimension, $from, $to, $limit)), true) ?? [];return collect($rows)->map(fn ($r) => TrafficBreakdownData::fromSentinel($r));}@@ -98,12 +88,7 @@ class SentinelTrafficClient*/public function series(?string $appKey, string $range = '24h'): Collection{- if ($appKey !== null) {- $this->assertSafeKey($appKey);- }- $range = in_array($range, ['24h', '7d', '30d'], true) ? $range : '24h';- $path = $appKey ? "/app/{$appKey}/traffic/series" : '/traffic/series';- $rows = json_decode($this->raw($this->url($path, ['range' => $range])), true);+ $rows = json_decode($this->raw($this->seriesUrl($appKey, $range)), true);if (! is_array($rows) || $rows === []) {return collect();@@ -114,20 +99,215 @@ class SentinelTrafficClientpublic function apps(): array{- return json_decode($this->raw($this->url('/traffic/apps')), true) ?? [];+ return json_decode($this->raw($this->appsUrl()), true) ?? [];}public function attribution(): ?string{- $json = json_decode($this->raw($this->url('/traffic/attribution')), true) ?? [];+ $json = json_decode($this->raw($this->attributionUrl()), true) ?? [];return data_get($json, 'attribution');}+ /**+ * Warm the 60s response cache for every endpoint the dashboard reads, in as few SSH+ * round-trips as possible. Prefers Sentinel's aggregate `/traffic/dashboard` (one call+ * that returns every shape, including the per-app leaderboard), and falls back to a+ * single batched `docker exec` over the individual endpoints when that route is absent+ * (older Sentinel). Best-effort: any failure leaves the per-call methods to fetch+ * individually. Returns the recorded app uuids so the caller can warm the per-app+ * overviews when the fallback path is taken.+ *+ * @param array<int, string> $dimensions+ * @return array<int, string>+ */+ public function prefetchServerWide(?string $appKey, string $from, string $to, array $dimensions, string $range, int $pathLimit = 50, int $breakdownLimit = 50, int $appsLimit = 200): array+ {+ $bundle = $this->fetchDashboard($appKey, $from, $to, $range, $pathLimit, $breakdownLimit, $appsLimit);+ if ($bundle !== null) {+ $this->seedFromDashboard($appKey, $from, $to, $range, $dimensions, $pathLimit, $breakdownLimit, $bundle);++ if ($appKey !== null) {+ return [];+ }++ return array_values(array_filter(+ array_map(fn ($app) => is_array($app) ? ($app['uuid'] ?? null) : null, $bundle['apps'] ?? []),+ fn ($uuid) => is_string($uuid) && $uuid !== ''+ ));+ }++ // Fallback for older Sentinel without /traffic/dashboard: batch the individual endpoints.+ $urls = [+ $this->overviewUrl($appKey, $from, $to),+ $this->pathsUrl($appKey, $from, $to, $pathLimit),+ $this->seriesUrl($appKey, $range),+ $this->attributionUrl(),+ ];+ foreach ($dimensions as $dimension) {+ $urls[] = $this->breakdownUrl($appKey, $dimension, $from, $to, $breakdownLimit);+ }+ // The per-application leaderboard only exists on the unfiltered view.+ if ($appKey === null) {+ $urls[] = $this->appsUrl();+ }++ $this->warm($urls);++ if ($appKey !== null) {+ return [];+ }++ return array_values(array_filter(+ $this->apps(),+ fn ($uuid) => is_string($uuid) && $uuid !== ''+ ));+ }++ /**+ * Fetch Sentinel's aggregate dashboard bundle, or null when the route is absent (older+ * Sentinel 404s) or the response isn't a real bundle. The bundle always carries an+ * `overview` member — even for an empty range — so its presence distinguishes a genuine+ * response from a stub/`{}`.+ *+ * @return array<string, mixed>|null+ */+ private function fetchDashboard(?string $appKey, string $from, string $to, string $range, int $pathLimit, int $breakdownLimit, int $appsLimit): ?array+ {+ try {+ $decoded = json_decode($this->raw($this->dashboardUrl($appKey, $from, $to, $range, $pathLimit, $breakdownLimit, $appsLimit)), true);+ } catch (\Throwable) {+ return null;+ }++ if (! is_array($decoded) || ! array_key_exists('overview', $decoded)) {+ return null;+ }++ return $decoded;+ }++ /**+ * Decompose the aggregate bundle back into the per-endpoint response cache, so the+ * existing per-call methods (overview/paths/breakdown/series/attribution and each+ * leaderboard app's overview) read it as a cache hit — the whole page from one fetch.+ *+ * @param array<int, string> $dimensions+ * @param array<string, mixed> $bundle+ */+ private function seedFromDashboard(?string $appKey, string $from, string $to, string $range, array $dimensions, int $pathLimit, int $breakdownLimit, array $bundle): void+ {+ $put = fn (string $url, $member) => Cache::put($this->cacheKey($url), json_encode($member), 60);++ $put($this->overviewUrl($appKey, $from, $to), $bundle['overview'] ?? []);+ $put($this->pathsUrl($appKey, $from, $to, $pathLimit), $bundle['paths'] ?? []);+ $put($this->seriesUrl($appKey, $range), $bundle['series'] ?? []);+ $put($this->attributionUrl(), ['attribution' => $bundle['attribution'] ?? null]);++ $breakdowns = $bundle['breakdowns'] ?? [];+ foreach ($dimensions as $dimension) {+ $put($this->breakdownUrl($appKey, $dimension, $from, $to, $breakdownLimit), $breakdowns[$dimension] ?? []);+ }++ foreach ($bundle['apps'] ?? [] as $app) {+ $uuid = is_array($app) ? ($app['uuid'] ?? null) : null;+ if (is_string($uuid) && $uuid !== '' && isset($app['overview'])) {+ $put($this->overviewUrl($uuid, $from, $to), $app['overview']);+ }+ }+ }++ /**+ * Warm the per-app overview cache for the leaderboard in one batched exec.+ *+ * @param array<int, string> $appKeys+ */+ public function prefetchAppOverviews(array $appKeys, string $from, string $to): void+ {+ $urls = array_map(fn ($appKey) => $this->overviewUrl($appKey, $from, $to), $appKeys);++ $this->warm($urls);+ }++ private function overviewUrl(?string $appKey, string $from, string $to): string+ {+ $path = $this->appScopedPath($appKey, 'overview');++ return $this->url($path, ['from' => $from, 'to' => $to]);+ }++ private function pathsUrl(?string $appKey, string $from, string $to, int $limit): string+ {+ $path = $this->appScopedPath($appKey, 'paths');++ return $this->url($path, ['from' => $from, 'to' => $to, 'limit' => (int) $limit]);+ }++ private function breakdownUrl(?string $appKey, string $dimension, string $from, string $to, int $limit): string+ {+ $this->assertSafeDimension($dimension);+ $path = $this->appScopedPath($appKey, "breakdown/{$dimension}");++ return $this->url($path, ['from' => $from, 'to' => $to, 'limit' => (int) $limit]);+ }++ private function seriesUrl(?string $appKey, string $range): string+ {+ $range = in_array($range, ['24h', '7d', '30d'], true) ? $range : '24h';+ $path = $this->appScopedPath($appKey, 'series');++ return $this->url($path, ['range' => $range]);+ }++ private function dashboardUrl(?string $appKey, string $from, string $to, string $range, int $pathLimit, int $breakdownLimit, int $appsLimit): string+ {+ $range = in_array($range, ['24h', '7d', '30d'], true) ? $range : '24h';+ $query = [+ 'from' => $from,+ 'to' => $to,+ 'range' => $range,+ 'paths_limit' => (int) $pathLimit,+ 'breakdown_limit' => (int) $breakdownLimit,+ ];+ if ($appKey === null) {+ // apps_limit only applies to the server-wide leaderboard.+ $query['apps_limit'] = (int) $appsLimit;++ return $this->url('/traffic/dashboard', $query);+ }+ $this->assertSafeKey($appKey);++ return $this->url("/app/{$appKey}/traffic/dashboard", $query);+ }++ private function appsUrl(): string+ {+ return $this->url('/traffic/apps');+ }++ private function attributionUrl(): string+ {+ return $this->url('/traffic/attribution');+ }++ /**+ * Build a traffic path, optionally scoped to a single (validated) app key.+ */+ private function appScopedPath(?string $appKey, string $suffix): string+ {+ if ($appKey === null) {+ return "/traffic/{$suffix}";+ }+ $this->assertSafeKey($appKey);++ return "/app/{$appKey}/traffic/{$suffix}";+ }+/*** Reject anything that isn't a bare CUID2/UUID or hostname before it is* interpolated into a shell-quoted `docker exec ... curl` command- * (see remoteFetch()). No quotes, spaces, slashes, or shell metacharacters.+ * (see remoteFetch()/buildFetchCommand()). No quotes, spaces, slashes, or+ * shell metacharacters.*/private function assertSafeKey(string $value): void{@@ -152,9 +332,68 @@ class SentinelTrafficClientreturn $this->base.$path.$qs;}+ private function cacheKey(string $url): string+ {+ return 'traffic:'.$this->server->uuid.':'.md5($url);+ }++ /**+ * True when warm() may issue its batched exec: either raw() is the base (real transport),+ * or a subclass has explicitly overridden batchRemoteFetch to intercept the batch. A fake+ * that only overrides raw() returns false, so warm() stays off the wire.+ */+ private function usesBatchableTransport(): bool+ {+ if ((new \ReflectionMethod($this, 'raw'))->getDeclaringClass()->getName() === self::class) {+ return true;+ }++ return (new \ReflectionMethod($this, 'batchRemoteFetch'))->getDeclaringClass()->getName() !== self::class;+ }+protected function raw(string $url): string{- return Cache::remember('traffic:'.$this->server->uuid.':'.md5($url), 60, fn () => $this->guard($this->remoteFetch($url)));+ return Cache::remember($this->cacheKey($url), 60, fn () => $this->guard($this->remoteFetch($url)));+ }++ /**+ * Fetch several URLs in one `docker exec` and warm each one's response cache under the+ * same key raw() reads, so the subsequent per-call methods become cache hits. Cache hits+ * are skipped, individual error/invalid responses are left uncached (the per-call fetch+ * surfaces them), and any transport failure is swallowed — warming is an optimization,+ * never a correctness dependency.+ *+ * @param array<int, string> $urls+ */+ protected function warm(array $urls): void+ {+ // Batching only helps when raw() uses the real remote transport. A subclass that+ // overrides raw() to serve canned bodies (a test fake) — but not batchRemoteFetch —+ // would otherwise reach real SSH here; skip and let its raw() answer each call.+ if (! $this->usesBatchableTransport()) {+ return;+ }++ $misses = array_values(array_filter($urls, fn ($url) => ! Cache::has($this->cacheKey($url))));+ if ($misses === []) {+ return;+ }++ try {+ $output = $this->batchRemoteFetch($misses);+ } catch (\Throwable) {+ return;+ }++ $bodies = explode(self::RECORD_SEPARATOR, $output);+ foreach ($misses as $index => $url) {+ $body = $bodies[$index] ?? '';+ try {+ Cache::put($this->cacheKey($url), $this->guard($body), 60);+ } catch (\Throwable) {+ // Invalid/error body: leave uncached so raw() re-fetches and reports it.+ }+ }}protected function remoteFetch(string $url): string@@ -162,12 +401,58 @@ class SentinelTrafficClient$token = $this->server->settings->ensureValidSentinelToken();return instant_remote_process(- ["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$token}\" {$url}'"],+ [$this->buildFetchCommand($token, $url)],+ $this->server,+ false+ );+ }++ /**+ * @param array<int, string> $urls+ */+ protected function batchRemoteFetch(array $urls): string+ {+ $token = $this->server->settings->ensureValidSentinelToken();++ return instant_remote_process(+ [$this->buildBatchCommand($token, $urls)],$this->server,false);}+ /**+ * Build the `docker exec ... curl` command run inside the Sentinel container.+ *+ * The URL is double-quoted inside the inner `sh -c` string so the literal `&`+ * between the `from`/`to` (and `limit`) query params is not interpreted as a+ * shell background operator — which would background curl after `from=...` and+ * truncate every multi-param request. The app key and dimension are validated+ * (assertSafeKey/assertSafeDimension) before reaching here, so the URL cannot+ * contain shell metacharacters that break out of the quoting.+ */+ protected function buildFetchCommand(string $token, string $url): string+ {+ return "docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$token}\" \"{$url}\"'";+ }++ /**+ * Build one `docker exec` that curls every URL in order and separates the responses+ * with a 0x1E record separator, so warm() can split them back apart. escapeshellarg+ * safely wraps the whole script; each URL stays double-quoted so its `&` is literal.+ *+ * @param array<int, string> $urls+ */+ protected function buildBatchCommand(string $token, array $urls): string+ {+ $script = implode(' ; ', array_map(+ fn ($url) => "curl -s -H \"Authorization: Bearer {$token}\" \"{$url}\" ; printf '\\036'",+ $urls+ ));++ return 'docker exec coolify-sentinel sh -c '.escapeshellarg($script);+ }+private function guard(string $response): string{$payload = json_decode($response, true);diff --git a/resources/views/components/skeleton.blade.php b/resources/views/components/skeleton.blade.phpnew file mode 100644index 0000000000..0ac99a8734--- /dev/null+++ b/resources/views/components/skeleton.blade.php@@ -0,0 +1,6 @@+{{--+ Generic shimmer block. Size and shape are passed via `class`, e.g.+ <x-skeleton class="h-6 w-24 rounded-full" />. Composed by the x-skeleton.* helpers+ (tiles, table) and by component placeholder() views for lazy-loaded pages.+--}}+<div aria-hidden="true" {{ $attributes->class(['animate-pulse rounded-md bg-neutral-200/80 dark:bg-white/[0.06]']) }}></div>diff --git a/resources/views/components/skeleton/table.blade.php b/resources/views/components/skeleton/table.blade.phpnew file mode 100644index 0000000000..b37969cbb5--- /dev/null+++ b/resources/views/components/skeleton/table.blade.php@@ -0,0 +1,31 @@+@props([+ 'rows' => 6,+ 'flush' => false,+])++@php+ // Vary the leading-column widths so rows read as content, not a solid block.+ $widths = ['w-3/5', 'w-2/5', 'w-1/2', 'w-3/4', 'w-1/3', 'w-2/3'];+@endphp++@if ($flush)+ {{-- Edge-to-edge list rows with dividers, matching a `flush` settings-section list. --}}+ <div class="flex flex-col">+ @for ($i = 0; $i < (int) $rows; $i++)+ <div class="flex min-h-11 items-center gap-3 border-b border-neutral-200 px-4 py-2 last:border-b-0 dark:border-white/[0.07]">+ <x-skeleton class="h-3 {{ $widths[$i % count($widths)] }} rounded-full" />+ <x-skeleton class="ml-auto h-3 w-10 shrink-0 rounded-full" />+ </div>+ @endfor+ </div>+@else+ {{-- Padded list rows: a label column and a trailing value per row. --}}+ <div class="flex flex-col gap-2.5">+ @for ($i = 0; $i < (int) $rows; $i++)+ <div class="flex items-center justify-between gap-4">+ <x-skeleton class="h-3 {{ $widths[$i % count($widths)] }} rounded-full" />+ <x-skeleton class="h-3 w-10 shrink-0 rounded-full" />+ </div>+ @endfor+ </div>+@endifdiff --git a/resources/views/components/skeleton/tiles.blade.php b/resources/views/components/skeleton/tiles.blade.phpnew file mode 100644index 0000000000..fb14d213be--- /dev/null+++ b/resources/views/components/skeleton/tiles.blade.php@@ -0,0 +1,18 @@+@props([+ 'count' => 5,+ 'grid' => 'grid-cols-2 sm:grid-cols-3 lg:grid-cols-5',+ 'rounded' => 'rounded-lg',+])++{{-- KPI stat-tile grid skeleton, mirroring an analytics Overview tile grid. --}}+<div class="grid {{ $grid }} gap-px overflow-hidden {{ $rounded }} bg-neutral-200 dark:bg-white/[0.07]">+ @for ($i = 0; $i < (int) $count; $i++)+ <div class="flex flex-col bg-white px-4 py-3 dark:bg-base">+ <x-skeleton class="h-2.5 w-16" />+ <x-skeleton class="mt-2 h-6 w-20" />+ <div class="mt-auto pt-3">+ <x-skeleton class="h-8 w-full rounded" />+ </div>+ </div>+ @endfor+</div>diff --git a/resources/views/livewire/analytics-placeholder.blade.php b/resources/views/livewire/analytics-placeholder.blade.phpnew file mode 100644index 0000000000..d22a0c06f6--- /dev/null+++ b/resources/views/livewire/analytics-placeholder.blade.php@@ -0,0 +1,58 @@+<div class="flex w-full min-w-0 flex-col gap-6">+ {{-- Header (real chrome; only the data below is a skeleton) --}}+ <div class="flex flex-col gap-4">+ <div class="flex items-center gap-3">+ <span class="flex size-9 shrink-0 items-center justify-center rounded-lg bg-neutral-100 text-neutral-600 dark:bg-white/[0.06] dark:text-fg-dim">+ <x-reicon name="analytics" class="size-5" />+ </span>+ <div class="min-w-0">+ <h1 class="text-[16px]! leading-5! font-semibold! text-black dark:text-fg">Analytics</h1>+ <p class="mt-0.5 text-[12px] text-neutral-500 dark:text-fg-faint">+ Request traffic across every application and server, reported by Sentinel.+ </p>+ </div>+ </div>++ {{-- Filter bar --}}+ <div class="flex flex-wrap items-center gap-2">+ <x-skeleton class="h-9 w-full rounded-lg sm:w-52" />+ <x-skeleton class="h-9 w-full rounded-lg sm:w-52" />+ <x-skeleton class="h-9 w-44 rounded-lg sm:ml-auto" />+ </div>+ </div>++ <x-application.settings-section id="analytics-overview-section" title="Overview">+ <x-skeleton.tiles :count="5" />+ </x-application.settings-section>++ <x-application.settings-section id="analytics-requests-section" title="Requests">+ <x-skeleton class="h-[220px] w-full rounded-lg" />+ </x-application.settings-section>++ <x-application.settings-section id="analytics-status-codes-section" title="Status codes">+ <x-skeleton class="h-9 w-full rounded-lg" />+ <div class="mt-3 flex flex-wrap gap-2">+ <x-skeleton class="h-4 w-20 rounded-full" />+ <x-skeleton class="h-4 w-16 rounded-full" />+ <x-skeleton class="h-4 w-16 rounded-full" />+ <x-skeleton class="h-4 w-14 rounded-full" />+ </div>+ </x-application.settings-section>++ <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">+ <x-application.settings-section id="analytics-hosts-section" title="Top hosts" flush>+ <x-skeleton.table :rows="6" flush />+ </x-application.settings-section>+ <x-application.settings-section id="analytics-apps-section" title="Top applications" flush>+ <x-skeleton.table :rows="6" flush />+ </x-application.settings-section>+ </div>++ <x-application.settings-section id="analytics-paths-section" title="Top paths" flush>+ <x-skeleton.table :rows="6" flush />+ </x-application.settings-section>++ <x-application.settings-section id="analytics-country-section" title="Countries" flush>+ <x-skeleton class="h-64 w-full" />+ </x-application.settings-section>+</div>diff --git a/resources/views/livewire/dashboard/traffic-analytics-placeholder.blade.php b/resources/views/livewire/dashboard/traffic-analytics-placeholder.blade.phpnew file mode 100644index 0000000000..eb01c43266--- /dev/null+++ b/resources/views/livewire/dashboard/traffic-analytics-placeholder.blade.php@@ -0,0 +1,19 @@+<section class="mb-0! min-w-0">+ {{-- Real section header; only the KPI grid below is a skeleton. --}}+ <div class="mb-3 flex items-end justify-between gap-4">+ <div>+ <h2 class="text-[14px]! leading-5! font-semibold! text-black dark:text-fg">+ Traffic analytics+ </h2>+ <p class="mt-0.5 text-[11px] text-neutral-500 dark:text-fg-faint">+ Team-wide request volume across traffic-enabled servers+ </p>+ </div>+ <div class="flex items-center gap-2">+ <x-skeleton class="h-8 w-40 rounded-lg" />+ <x-skeleton class="h-4 w-24 rounded-full" />+ </div>+ </div>++ <x-skeleton.tiles :count="4" grid="grid-cols-1 sm:grid-cols-2 lg:grid-cols-4" rounded="rounded-xl" />+</section>diff --git a/resources/views/livewire/project/application/analytics-placeholder.blade.php b/resources/views/livewire/project/application/analytics-placeholder.blade.phpnew file mode 100644index 0000000000..1cb6cffc70--- /dev/null+++ b/resources/views/livewire/project/application/analytics-placeholder.blade.php@@ -0,0 +1,42 @@+<div class="flex flex-col gap-6">+ {{-- Real section chrome around skeleton bodies, so the tab has no layout jump on load. --}}+ <x-application.settings-section id="analytics-range-section" title="Analytics">+ <x-slot:actions>+ <x-skeleton class="h-8 w-48 rounded-lg" />+ </x-slot:actions>+ <x-skeleton.tiles :count="5" />+ </x-application.settings-section>++ <x-application.settings-section id="analytics-requests-section" title="Requests">+ <x-skeleton class="h-[220px] w-full rounded-lg" />+ </x-application.settings-section>++ <x-application.settings-section id="analytics-status-codes-section" title="Status codes">+ <x-skeleton class="h-9 w-full rounded-lg" />+ <div class="mt-3 flex flex-wrap gap-2">+ <x-skeleton class="h-4 w-20 rounded-full" />+ <x-skeleton class="h-4 w-16 rounded-full" />+ <x-skeleton class="h-4 w-16 rounded-full" />+ <x-skeleton class="h-4 w-14 rounded-full" />+ </div>+ </x-application.settings-section>++ <x-application.settings-section id="analytics-paths-section" title="Top paths" flush>+ <x-skeleton.table :rows="6" flush />+ </x-application.settings-section>++ <x-application.settings-section id="analytics-country-section" title="Countries" flush>+ <x-skeleton class="h-64 w-full" />+ </x-application.settings-section>++ <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">+ <x-application.settings-section id="analytics-device-section" title="Requests by device type">+ <div class="flex items-center justify-center py-4">+ <x-skeleton class="size-40 rounded-full" />+ </div>+ </x-application.settings-section>+ <x-application.settings-section id="analytics-protocol-section" title="Top HTTP versions">+ <x-skeleton.table :rows="5" />+ </x-application.settings-section>+ </div>+</div>diff --git a/resources/views/livewire/traffic/_requests-chart.blade.php b/resources/views/livewire/traffic/_requests-chart.blade.phpindex c38f5cc460..486d0a1ae6 100644--- a/resources/views/livewire/traffic/_requests-chart.blade.php+++ b/resources/views/livewire/traffic/_requests-chart.blade.php@@ -4,7 +4,20 @@token. Updated via the `refreshChartData-{chartId}-status` event (the `timeSeries.requests`array, aligned with `timeSeries.categories`). Expects `$chartId` in scope.--}}-<div wire:ignore id="{!! $chartId !!}-requests" class="min-h-[220px] w-full"></div>+<div wire:ignore class="relative w-full">+ <div id="{!! $chartId !!}-requests" class="min-h-[220px] w-full"></div>++ {{-- No-data overlay: covers the empty chart frame when no requests fall in the range.+ Uses the shared x-empty component so it matches the other analytics empty states+ (e.g. Status codes). Toggled from the refresh listener below (kept mounted so the+ chart's listener survives live/range re-renders). --}}+ <div id="{!! $chartId !!}-requests-empty" style="display: {{ $this->hasRequestSeries() ? 'none' : 'flex' }}"+ class="absolute inset-0 items-center justify-center bg-white dark:bg-base">+ <x-empty size="sm" title="No requests in this range"+ description="No request traffic was recorded for the selected filters and range. Try a wider range or check back later."+ icon-name="analytics" />+ </div>+</div>@script<script>@@ -12,6 +25,7 @@checkTheme();const el = document.getElementById('{!! $chartId !!}-requests');+ const emptyEl = document.getElementById('{!! $chartId !!}-requests-empty');const cssVar = name => getComputedStyle(document.documentElement).getPropertyValue(name).trim();const accent = () => cssVar('--chart-status-3xx') || '#3b82f6';const gridColor = () => cssVar('--chart-geo-empty') || 'rgba(128,128,128,0.15)';@@ -70,6 +84,10 @@const ts = data.timeSeries;const points = (ts.categories || []).map((c, i) => ({ x: c, y: (ts.requests && ts.requests[i]) || 0 }));+ // Show the no-data overlay when nothing in the range carries request volume.+ const hasData = points.some(p => (p.y || 0) > 0);+ if (emptyEl) { emptyEl.style.display = hasData ? 'none' : 'flex'; }+chart.updateOptions({colors: [accent()],grid: { borderColor: gridColor() },diff --git a/tests/Feature/Server/ServerSettingSentinelRestartTest.php b/tests/Feature/Server/ServerSettingSentinelRestartTest.phpindex 57c256110d..8e2b2b32b0 100644--- a/tests/Feature/Server/ServerSettingSentinelRestartTest.php+++ b/tests/Feature/Server/ServerSettingSentinelRestartTest.php@@ -1,13 +1,20 @@<?php+use App\Actions\Server\StartSentinel;use App\Models\Server;use App\Models\ServerSetting;use App\Models\User;use Illuminate\Foundation\Testing\RefreshDatabase;use Illuminate\Support\Facades\Queue;+use Lorisleiva\Actions\Decorators\JobDecorator;uses(RefreshDatabase::class);+function isStartSentinelJob($job): bool+{+ return $job instanceof JobDecorator && $job->getAction() instanceof StartSentinel;+}+beforeEach(function () {Queue::fake();@@ -147,6 +154,28 @@ it('detects traffic analytics setting changes with wasChanged', function () {expect($changeDetected)->toBeTrue();});+it('does not restart sentinel when a traffic knob changes while sentinel is disabled', function () {+ $settings = $this->server->settings;+ $settings->is_sentinel_enabled = false;+ $settings->save();++ $settings->traffic_topn = 999;+ $settings->save();++ Queue::assertNotPushed(JobDecorator::class, fn ($job) => isStartSentinelJob($job));+});++it('restarts sentinel when a traffic knob changes while sentinel is enabled', function () {+ $settings = $this->server->settings;+ $settings->is_sentinel_enabled = true;+ $settings->save();++ $settings->traffic_topn = 888;+ $settings->save();++ Queue::assertPushed(JobDecorator::class, fn ($job) => isStartSentinelJob($job));+});+it('does not detect changes when sentinel field is set to same value', function () {$changeDetected = false;diff --git a/tests/Feature/TrafficAnalytics/ApplicationAnalyticsTest.php b/tests/Feature/TrafficAnalytics/ApplicationAnalyticsTest.phpindex 547fbcee38..ec7f9b2037 100644--- a/tests/Feature/TrafficAnalytics/ApplicationAnalyticsTest.php+++ b/tests/Feature/TrafficAnalytics/ApplicationAnalyticsTest.php@@ -78,6 +78,11 @@ function fakeAnalyticsResponses(): array}beforeEach(function () {+ // RefreshDatabase resets ids each test; without flushing the model identity map a stale+ // Server (from a prior enabled test) can leak into a later test and be treated as+ // analytics-enabled, mounting the component against an unreachable server.+ Server::flushIdentityMap();+$this->team = Team::factory()->create();$this->user = User::factory()->create();$this->team->members()->attach($this->user->id, ['role' => 'owner']);@@ -116,7 +121,7 @@ it('renders KPIs from a mocked traffic client when analytics is enabled', functi$fake->responses = fakeAnalyticsResponses();app()->bind(SentinelTrafficClient::class, fn () => $fake);- Livewire::test(Analytics::class, ['application' => $application])+ loadLazy(Livewire::test(Analytics::class, ['application' => $application]))->assertOk()->assertSee('Requests')->assertSee('1,000')@@ -134,7 +139,7 @@ it('loads the per-app status time series when Sentinel exposes the series endpoi$fake->responses = fakeAnalyticsResponses();app()->bind(SentinelTrafficClient::class, fn () => $fake);- Livewire::test(Analytics::class, ['application' => $application])+ loadLazy(Livewire::test(Analytics::class, ['application' => $application]))->assertOk()->assertSet('hasSeries', true)->assertSet('series', [@@ -152,7 +157,7 @@ it('decorates per-app paths with the app domain and surfaces AI agents', functio$fake->responses = fakeAnalyticsResponses();app()->bind(SentinelTrafficClient::class, fn () => $fake);- $component = Livewire::test(Analytics::class, ['application' => $application])+ $component = loadLazy(Livewire::test(Analytics::class, ['application' => $application]))->assertOk()->assertSee('api.example.com')->assertSee('AI agents & bots')@@ -175,7 +180,7 @@ it('falls back to the donut for the per-app chart when the series endpoint is ab$fake->responses = $responses;app()->bind(SentinelTrafficClient::class, fn () => $fake);- Livewire::test(Analytics::class, ['application' => $application])+ loadLazy(Livewire::test(Analytics::class, ['application' => $application]))->assertOk()->assertSet('hasSeries', false)->assertSet('series', []);@@ -184,7 +189,7 @@ it('falls back to the donut for the per-app chart when the series endpoint is abit('shows an empty state when traffic analytics is disabled for the server', function () {$application = makeAnalyticsApplication($this->team, $this->privateKey, $this->environment, false);- Livewire::test(Analytics::class, ['application' => $application])+ loadLazy(Livewire::test(Analytics::class, ['application' => $application]))->assertOk()->assertSee('Analytics')->assertDontSee('Unique visitors');@@ -199,7 +204,7 @@ it('renders the disabled empty-state without crashing when the application has nexpect($application->destination)->toBeNull();- Livewire::test(Analytics::class, ['application' => $application])+ loadLazy(Livewire::test(Analytics::class, ['application' => $application]))->assertOk()->assertSee('Analytics')->assertDontSee('Server settings');diff --git a/tests/Feature/TrafficAnalytics/ApplicationTrafficOverviewTest.php b/tests/Feature/TrafficAnalytics/ApplicationTrafficOverviewTest.phpindex 8627234ad2..4c958f1a79 100644--- a/tests/Feature/TrafficAnalytics/ApplicationTrafficOverviewTest.php+++ b/tests/Feature/TrafficAnalytics/ApplicationTrafficOverviewTest.php@@ -12,7 +12,6 @@ use App\Models\User;use App\Services\SentinelTrafficClient;use Illuminate\Foundation\Testing\RefreshDatabase;use Illuminate\Support\Facades\Cache;-use Livewire\Features\SupportTesting\Testable;use Livewire\Livewire;uses(RefreshDatabase::class);@@ -33,15 +32,6 @@ class FakeAppOverviewTrafficClient extends SentinelTrafficClient}}-// #[Lazy] components render a placeholder first; trigger the deferred mount as the-// browser would via the x-intersect __lazyLoad call, then continue asserting.-function loadLazy(Testable $component): Testable-{- preg_match('/__lazyLoad\('([^&]+)'\)/', $component->html(), $matches);-- return $component->call('__lazyLoad', $matches[1]);-}-beforeEach(function () {// Servers are memoized via once()/cache; clear both so DB-id reuse across tests doesn't bleed a stale enabled server.Cache::flush();diff --git a/tests/Feature/TrafficAnalytics/DashboardTrafficAnalyticsTest.php b/tests/Feature/TrafficAnalytics/DashboardTrafficAnalyticsTest.phpindex 3469db4b85..0a095b6cd6 100644--- a/tests/Feature/TrafficAnalytics/DashboardTrafficAnalyticsTest.php+++ b/tests/Feature/TrafficAnalytics/DashboardTrafficAnalyticsTest.php@@ -94,7 +94,7 @@ it('renders the team traffic summary aggregated across servers with an approximareturn $server && $server->is($serverOne) ? $fakeOne : $fakeTwo;});- Livewire::test(TrafficAnalytics::class)+ loadLazy(Livewire::test(TrafficAnalytics::class))->assertOk()->assertSee('Requests')->assertSee('1,500')@@ -129,7 +129,7 @@ it('shows only sparkline KPI cards that link through to the full analytics page'app()->bind(SentinelTrafficClient::class, fn () => $fake);- Livewire::test(TrafficAnalytics::class)+ loadLazy(Livewire::test(TrafficAnalytics::class))->assertOk()// The slimmed dashboard shows only KPI cards + a link to /analytics — no per-app rows.->assertSee('Open analytics')@@ -158,7 +158,7 @@ it('shows a failure empty-state instead of an all-zero KPI panel when every servreturn new FailingDashboardTrafficClient($params['server']);});- Livewire::test(TrafficAnalytics::class)+ loadLazy(Livewire::test(TrafficAnalytics::class))->assertOk()->assertSee('No analytics data yet')->assertDontSee('Unique visitors')@@ -174,7 +174,7 @@ it('shows an empty state when no server in the team has traffic analytics enable$server->settings->is_traffic_analytics_enabled = false;$server->settings->save();- Livewire::test(TrafficAnalytics::class)+ loadLazy(Livewire::test(TrafficAnalytics::class))->assertOk()->assertDontSee('Unique visitors')->assertSee('not enabled');diff --git a/tests/Feature/TrafficAnalytics/GeoVisualizationTest.php b/tests/Feature/TrafficAnalytics/GeoVisualizationTest.phpindex c7309be950..bf239a743c 100644--- a/tests/Feature/TrafficAnalytics/GeoVisualizationTest.php+++ b/tests/Feature/TrafficAnalytics/GeoVisualizationTest.php@@ -75,7 +75,7 @@ it('renders resolved country names and the interactive globe when country data i]);app()->bind(SentinelTrafficClient::class, fn () => $fake);- Livewire::test(Analytics::class)+ loadLazy(Livewire::test(Analytics::class))->assertOk()->assertSee('Countries')->assertSee('United States')@@ -96,7 +96,7 @@ it('collapses unresolvable country codes into a single Unknown row', function ()]);app()->bind(SentinelTrafficClient::class, fn () => $fake);- Livewire::test(Analytics::class)+ loadLazy(Livewire::test(Analytics::class))->assertOk()->assertSee('United States')->assertSee('Unknown');@@ -109,7 +109,7 @@ it('shows a plain no-data state when no country data has been recorded', functio$fake->responses = fakeGeoResponses([]);app()->bind(SentinelTrafficClient::class, fn () => $fake);- Livewire::test(Analytics::class)+ loadLazy(Livewire::test(Analytics::class))->assertOk()->assertSee('Countries')->assertSee('No country data for the selected range');diff --git a/tests/Feature/TrafficAnalytics/GlobalAnalyticsTest.php b/tests/Feature/TrafficAnalytics/GlobalAnalyticsTest.phpindex fc64e4c333..6780f7aebb 100644--- a/tests/Feature/TrafficAnalytics/GlobalAnalyticsTest.php+++ b/tests/Feature/TrafficAnalytics/GlobalAnalyticsTest.php@@ -3,6 +3,7 @@use App\Livewire\Analytics;use App\Models\Application;use App\Models\Environment;+use App\Models\InstanceSettings;use App\Models\PrivateKey;use App\Models\Project;use App\Models\Server;@@ -129,7 +130,7 @@ it('renders a team-wide analytics summary across enabled servers', function () {$fake->responses = fakeGlobalAnalyticsResponses([$application->uuid]);app()->bind(SentinelTrafficClient::class, fn () => $fake);- Livewire::test(Analytics::class)+ loadLazy(Livewire::test(Analytics::class))->assertOk()->assertSee('Analytics')->assertSee('1,000')@@ -151,6 +152,54 @@ it('renders a team-wide analytics summary across enabled servers', function () {->assertSet('appOptions', [$application->uuid => 'Global Leaderboard App']);});+it('shows a no-data state for the requests chart when no traffic falls in the range', function () {+ $server = bootEnabledGlobalServer();++ $responses = fakeGlobalAnalyticsResponses();+ // Zeroed overview + no series buckets: the page still renders, but there is nothing+ // to plot over time, so the Requests chart shows its no-data overlay.+ $responses['/traffic/overview'] = json_encode([+ 'requests' => 0, 'bytes_in' => 0, 'bytes_out' => 0,+ 'status' => ['s2xx' => 0, 's3xx' => 0, 's4xx' => 0, 's5xx' => 0],+ 'latency' => ['p50' => 0, 'p95' => 0, 'p99' => 0], 'unique_visitors' => 0,+ ]);+ $responses['/traffic/series'] = json_encode([]);++ $fake = new FakeGlobalAnalyticsTrafficClient($server);+ $fake->responses = $responses;+ app()->bind(SentinelTrafficClient::class, fn () => $fake);++ loadLazy(Livewire::test(Analytics::class))+ ->assertOk()+ ->assertSee('No requests in this range')+ // Server-rendered as visible (display:flex) before any client-side toggle.+ ->assertSee('global-analytics-requests-empty" style="display: flex', escape: false);+});++it('hides the requests no-data overlay when there is traffic in the range', function () {+ $server = bootEnabledGlobalServer();++ $fake = new FakeGlobalAnalyticsTrafficClient($server);+ $fake->responses = fakeGlobalAnalyticsResponses();+ app()->bind(SentinelTrafficClient::class, fn () => $fake);++ loadLazy(Livewire::test(Analytics::class))+ ->assertOk()+ ->assertSee('global-analytics-requests-empty" style="display: none', escape: false);+});++it('renders the full analytics page with a lazy placeholder before data loads', function () {+ InstanceSettings::forceCreate(['id' => 0]);+ bootEnabledGlobalServer();++ // Full-page #[Lazy]: the initial HTTP response is the skeleton placeholder plus the+ // x-intersect __lazyLoad trigger; the Sentinel round-trips run only on the deferred call.+ $this->get(route('analytics'))+ ->assertOk()+ ->assertSee('Analytics')+ ->assertSee('__lazyLoad', escape: false);+});+it('shows path domains, links top apps to analytics, groups by project, and surfaces AI agents', function () {$server = bootEnabledGlobalServer();@@ -177,7 +226,7 @@ it('shows path domains, links top apps to analytics, groups by project, and surf'application_uuid' => $application->uuid,]);- $component = Livewire::test(Analytics::class)+ $component = loadLazy(Livewire::test(Analytics::class))->assertOk()->assertSee('Top hosts')->assertSee('shop.example.com') // served host shown in Top hosts + top-app row@@ -208,7 +257,7 @@ it('builds a stacked status time series when Sentinel exposes the series endpoin$fake->responses = fakeGlobalAnalyticsResponses();app()->bind(SentinelTrafficClient::class, fn () => $fake);- Livewire::test(Analytics::class)+ loadLazy(Livewire::test(Analytics::class))->assertOk()->assertSet('hasSeries', true)->assertSet('series', [@@ -238,7 +287,7 @@ it('derives KPI sparklines, device-donut data, and top hosts for the chart paylo$fake->responses = fakeGlobalAnalyticsResponses([$application->uuid]);app()->bind(SentinelTrafficClient::class, fn () => $fake);- $instance = Livewire::test(Analytics::class)->assertOk()->instance();+ $instance = loadLazy(Livewire::test(Analytics::class))->assertOk()->instance();// Per-bucket sparkline series derived from Sentinel's enriched buckets.expect($instance->requestsSpark())->toBe([43, 66]);@@ -267,7 +316,7 @@ it('falls back to the donut when Sentinel lacks the series endpoint', function ($fake->responses = $responses;app()->bind(SentinelTrafficClient::class, fn () => $fake);- Livewire::test(Analytics::class)+ loadLazy(Livewire::test(Analytics::class))->assertOk()->assertSet('hasSeries', false)->assertSet('series', []);@@ -293,7 +342,7 @@ it('does not disclose another team application name for a sentinel-reported uuid$fake->responses = fakeGlobalAnalyticsResponses([$otherTeamApplication->uuid]);app()->bind(SentinelTrafficClient::class, fn () => $fake);- Livewire::test(Analytics::class)+ loadLazy(Livewire::test(Analytics::class))->assertOk()->assertDontSee('Secret Other Team App')->assertSee($otherTeamApplication->uuid);@@ -318,7 +367,7 @@ it('scopes the view to a single application and hides the leaderboard when filte$fake->responses = fakeGlobalAnalyticsResponses([$application->uuid]);app()->bind(SentinelTrafficClient::class, fn () => $fake);- Livewire::test(Analytics::class)+ loadLazy(Livewire::test(Analytics::class))->set('appUuid', $application->uuid)->assertOk()->assertSee('1,000')@@ -334,7 +383,7 @@ it('shows the not-enabled empty state when no server has traffic analytics on',$server->settings->is_traffic_analytics_enabled = false;$server->settings->save();- Livewire::test(Analytics::class)+ loadLazy(Livewire::test(Analytics::class))->assertOk()->assertSee('Traffic analytics is not enabled')->assertDontSee('Unique visitors');diff --git a/tests/Feature/TrafficAnalytics/LiveRefreshTest.php b/tests/Feature/TrafficAnalytics/LiveRefreshTest.phpindex 7d47045c25..4ec260dee5 100644--- a/tests/Feature/TrafficAnalytics/LiveRefreshTest.php+++ b/tests/Feature/TrafficAnalytics/LiveRefreshTest.php@@ -55,7 +55,7 @@ function bootLiveServer(): Serverit('is paused by default and does not poll until Live Refresh is turned on', function () {$server = bootLiveServer();- Livewire::test(Analytics::class)+ loadLazy(Livewire::test(Analytics::class))->assertOk()->assertSet('live', false)->assertDontSeeHtml('wire:poll.60s')@@ -65,7 +65,7 @@ it('is paused by default and does not poll until Live Refresh is turned on', funit('starts polling when live is toggled on at the 24h range', function () {$server = bootLiveServer();- Livewire::test(Analytics::class)+ loadLazy(Livewire::test(Analytics::class))->assertDontSeeHtml('wire:poll.60s')->call('toggleLive')->assertSet('live', true)@@ -76,7 +76,7 @@ it('starts polling when live is toggled on at the 24h range', function () {it('hides the Live Refresh control and stops polling for the 7d and 30d ranges', function () {$server = bootLiveServer();- $component = Livewire::test(Analytics::class)+ $component = loadLazy(Livewire::test(Analytics::class))->call('setRange', '7d')->assertDontSeeHtml('wire:poll.60s')->assertDontSee('Live Refresh');@@ -91,7 +91,7 @@ it('hides the Live Refresh control and stops polling for the 7d and 30d ranges',it('re-arms polling when returning to the 24h range after live was turned on', function () {$server = bootLiveServer();- Livewire::test(Analytics::class)+ loadLazy(Livewire::test(Analytics::class))->call('toggleLive') // arm live at 24h->assertSeeHtml('wire:poll.60s')->call('setRange', '7d')diff --git a/tests/Feature/TrafficAnalytics/SentinelTrafficClientTest.php b/tests/Feature/TrafficAnalytics/SentinelTrafficClientTest.phpindex 5e7438ec16..4eb3dbdc60 100644--- a/tests/Feature/TrafficAnalytics/SentinelTrafficClientTest.php+++ b/tests/Feature/TrafficAnalytics/SentinelTrafficClientTest.php@@ -149,3 +149,113 @@ it('rejects a malicious app key for the series endpoint', function () {->toThrow(InvalidArgumentException::class);expect($client->captured)->toBeEmpty();});++it('serves every endpoint from one aggregate dashboard fetch when Sentinel exposes it', function () {+ $server = Server::factory()->create(['team_id' => $this->team->id]);++ $bundle = json_encode([+ 'overview' => ['requests' => 7],+ 'paths' => [['path' => '/', 'requests' => 7]],+ 'breakdowns' => ['country' => [['value' => 'US', 'requests' => 7]], 'browser' => []],+ 'series' => [],+ 'attribution' => 'MaxMind',+ 'apps' => [+ ['uuid' => 'app-a', 'overview' => ['requests' => 4]],+ ['uuid' => 'app-b', 'overview' => ['requests' => 3]],+ ],+ ]);++ // Only the /traffic/dashboard fetch is allowed; any individual/batch fetch means the+ // bundle wasn't decomposed into the per-endpoint cache.+ $client = new class($server, $bundle) extends SentinelTrafficClient+ {+ public function __construct($server, private string $bundle)+ {+ parent::__construct($server);+ }++ protected function remoteFetch(string $url): string+ {+ if (str_contains($url, '/traffic/dashboard')) {+ return $this->bundle;+ }+ throw new RuntimeException("unexpected individual fetch: {$url}");+ }++ protected function batchRemoteFetch(array $urls): string+ {+ throw new RuntimeException('batch fallback should not run when the dashboard is available');+ }+ };++ $apps = $client->prefetchServerWide(null, 'F', 'T', ['country', 'browser'], '24h');+ expect($apps)->toBe(['app-a', 'app-b']);++ // All served from the seeded cache — remoteFetch throws for anything but the dashboard.+ expect($client->overview(null, 'F', 'T')->requests)->toBe(7)+ ->and($client->overview('app-a', 'F', 'T')->requests)->toBe(4)+ ->and($client->attribution())->toBe('MaxMind');+ $client->paths(null, 'F', 'T');+ $client->breakdown(null, 'country', 'F', 'T');+});++it('warms every server-wide endpoint in a single batched exec and per-call methods hit cache', function () {+ $server = Server::factory()->create(['team_id' => $this->team->id]);++ // Batches responses; individual remoteFetch() must never run once the batch has warmed+ // the cache, proving the round-trips collapsed into one exec.+ $client = new class($server) extends SentinelTrafficClient+ {+ public array $batchedCalls = [];++ protected function batchRemoteFetch(array $urls): string+ {+ $this->batchedCalls[] = $urls;++ // One framed body per url, matched by endpoint so ordering stays irrelevant.+ $bodies = array_map(fn ($url) => match (true) {+ str_contains($url, '/traffic/apps') => json_encode(['app-a', 'app-b']),+ str_contains($url, '/attribution') => '{"attribution":"demo"}',+ str_contains($url, '/overview') => '{"requests":1}',+ default => '[]', // paths, series, breakdowns+ }, $urls);++ return implode("\x1e", $bodies)."\x1e";+ }++ protected function remoteFetch(string $url): string+ {+ throw new RuntimeException("individual fetch should not run for: {$url}");+ }+ };++ $apps = $client->prefetchServerWide(null, 'F', 'T', ['country', 'browser'], '24h');++ expect($client->batchedCalls)->toHaveCount(1)+ ->and($apps)->toBe(['app-a', 'app-b']);++ // These now read from the warmed cache; remoteFetch() would throw if they didn't.+ expect($client->overview(null, 'F', 'T')->requests)->toBe(1);+ $client->breakdown(null, 'country', 'F', 'T');+ $client->series(null, '24h');+ $client->attribution();+});++it('double-quotes the url in the remote curl command so & is not a shell background operator', function () {+ $server = Server::factory()->create(['team_id' => $this->team->id]);+ $client = new class($server) extends SentinelTrafficClient+ {+ public function exposeCommand(string $token, string $url): string+ {+ return $this->buildFetchCommand($token, $url);+ }+ };++ // A real overview/paths/breakdown URL carries both from and to, joined by `&`.+ $url = 'http://localhost:8888/api/traffic/overview?from=2026-08-01T00:00:00Z&to=2026-08-02T00:00:00Z';+ $command = $client->exposeCommand('tok-123', $url);++ // The URL must be wrapped in double quotes inside the inner `sh -c`, otherwise the+ // container shell backgrounds curl at the `&` and only `from=...` reaches Sentinel.+ expect($command)->toContain('"'.$url.'"');+});diff --git a/tests/Feature/TrafficAnalytics/TrafficNudgeTest.php b/tests/Feature/TrafficAnalytics/TrafficNudgeTest.phpindex bffc8f2e5f..eb2eb83de9 100644--- a/tests/Feature/TrafficAnalytics/TrafficNudgeTest.php+++ b/tests/Feature/TrafficAnalytics/TrafficNudgeTest.php@@ -36,7 +36,7 @@ function disabledServer(): Serverit('does not show a traffic nudge on the dashboard', function () {disabledServer();- Livewire::test(DashboardTrafficAnalytics::class)+ loadLazy(Livewire::test(DashboardTrafficAnalytics::class))->assertOk()->assertDontSee('can start collecting traffic analytics');});@@ -44,7 +44,7 @@ it('does not show a traffic nudge on the dashboard', function () {it('shows the analytics-page nudge when an eligible server has analytics disabled', function () {disabledServer();- Livewire::test(Analytics::class)+ loadLazy(Livewire::test(Analytics::class))->assertOk()->assertSee('can start collecting traffic analytics');});@@ -58,7 +58,7 @@ it('does not count swarm or build servers in the analytics-page nudge', function$build->settings->is_build_server = true;$build->settings->save();- Livewire::test(Analytics::class)+ loadLazy(Livewire::test(Analytics::class))->assertOk()->assertDontSee('can start collecting traffic analytics');});diff --git a/tests/Pest.php b/tests/Pest.phpindex 25d9440108..ac0b667c19 100644--- a/tests/Pest.php+++ b/tests/Pest.php@@ -2,6 +2,7 @@use App\Models\Server;use Illuminate\Support\Once;+use Livewire\Features\SupportTesting\Testable;use Tests\TestCase;/*@@ -44,6 +45,22 @@ function remoteOutputSource(string $path): stringreturn $source;}+/**+ * Trigger the deferred mount of a #[Lazy] Livewire component the way the browser would+ * via its x-intersect `__lazyLoad(...)` call, so assertions can run against the real+ * (post-mount) render instead of the placeholder.+ */+function loadLazy(Testable $component): Testable+{+ preg_match('/__lazyLoad\('([^&]+)'\)/', $component->html(), $matches);++ if (empty($matches)) {+ return $component;+ }++ return $component->call('__lazyLoad', $matches[1]);+}+/*|--------------------------------------------------------------------------| Test Hooks