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(v5): add server reconciliation and canvas APIs
Andras Bacsai6ae45684f990
diff --git a/.ai/todo.md b/.ai/todo.mdnew file mode 100644index 0000000000..7a0ef59dbf--- /dev/null+++ b/.ai/todo.md@@ -0,0 +1,64 @@+# V5 Architecture Fix Plan++Source: /Users/heyandras/.claude/plans/what-do-you-think-soft-firefly.md++## Wave 1 (parallel) — DONE+- [x] 1. Split DashboardController into domain controllers + Laravel policies (denyAsNotFound), dedupe cluster serializer+- [x] 6. Frontend: extract Dashboard.tsx components, useCallback/memo, unified optimistic rollback, use-pending-ids reuse, mid-drag snap-back fix, types.ts drift, env-scoped merge+- [x] 5. Hot-path index migration (wireguard_management_ip, node_address, host, runtime_container_id, last_seen_at)++## Wave 2 (parallel, after wave 1) — DONE+- [x] 2. Status enums (ApplicationStatus/ServerStatus/IngressStatus/ContainerState) + observed_at ordered ingestion+- [x] 3. Reconcile + prune scheduled jobs (V5ReconcileServersJob every 5m + per-server V5ReconcileServerStateJob, 24h container-status prune)+- [x] 4. Job uniqueness (ShouldBeUnique deploy+bootstrap) + queued broadcasts (ShouldBroadcast, afterCommit, null-safe payloads)+- [x] 7. Laravel↔coold verb handshake: UnsupportedCooldVerb detection (flux 501), graceful ingress degradation, coold_version persisted++## Wave 3 (everything else) — DONE+- [x] Morph map (v5.application alias) + uuid collision retry + drop per-insert Schema::hasColumn + defaults dedup+- [x] v5_servers.uuid non-null; capabilities → indexed has_coold/is_ingress booleans (wire format preserved)+- [x] Firewall vs DB atomicity (DB=desired state, flux converge, compensating rollback; revoke-first destroy)+- [x] Deploy failure compensation (stop+force-remove orphaned container, original error preserved)+- [x] Caddyfile hostname/port validation + ValidHostname newline-bypass fix+- [x] Ambiguous host_id resolution warning++## Wave 4 — DONE+- [x] Full V5 suite: 262 passed (1901 assertions); tsc clean; npm build ok; pint clean++## Wave 5 (deep dives)+- [ ] Clusters.tsx + remaining frontend audit+- [ ] coold/flux Rust internals + security audit+- [ ] V5 test quality/coverage audit++## Skipped (product decisions, documented)+- Soft deletes on infra rows (changes cascade semantics — needs product call)+- TLS in v5 ingress (feature, not fix)+- config coold.php/flux.php merge (cosmetic)++## Wave 5 (deep dives) — DONE+- [x] coold/flux Rust audit → findings reported (NOT fixed — separate repo, see session recap: no-TLS gRPC, wildcard cap profiles, lost status updates on outage, exec exit_code always 0, mount-allowlist gaps, unauthenticated Corrosion gossip)+- [x] Frontend audit → all MUST/SHOULD-FIX applied (stale connections on env switch, deleteCluster shadow null-deref, persistSelection ok-guard, useTeamChannel extraction, apiRequest timeouts in Clusters, echo logging gated)+- [x] Test-quality audit → all applied (shared V5TestSchema helper killed schema drift, DashboardTest 174-test monolith split into 12 files, substring tests quarantined in V5FrontendSourceContractTest, +20 new tests: policies, RemoveBootstrapMarker, broadcast payloads, channel auth)++## Wave 6 (audit fixes) — DONE+- [x] v4/v5 currentTeam session cross-contamination (full Team model, write-on-change only)+- [x] flux_url preflight 422 before bootstrap dispatch+- [x] Bootstrap marker/coold_version ordering+- [x] Enum literals sweep (jobs + StopCaddyIngress)+- [x] ManagesConnectionFirewallRules + SerializesResourceConnections → app/Support/V5 classes++## Final state+289 V5 tests passed (2005 assertions) + 333 v4 unit slice green; tsc clean; npm build ok; pint clean. Nothing committed.++## Wave 7 (security + JWT, cut off by session limit, then recovered) — DONE+- [x] JWT: mint explicit 21-primitive caps (config flux.host_capabilities), NOT the host-agent:default wildcard that flux treats as authorize-all; escape-hatch profile config; jti claim + persisted agent_token_jti; kid header; TTL 24h→1h (config); RevokedAgentToken model + migration + isRevoked API; inbound bearer array (laravel_api_tokens) for rotation+- [x] Authz: V5 policies role-gate mutations via isAdminOfTeam (403), keep denyAsNotFound (404) for cross-team; ClusterController::store authorize+- [x] Input: ValidServerIp rejects private/reserved ranges behind config('coold.allow_private_server_ips'); error-detail leak → generic messages + Log::warning; throttle:v5 limiter (RouteServiceProvider)+- [x] Stability: reconcile+refresh honor/advance status_observed_at (shared StatusObservation); Configured + full podman states in enums; deploy persists runtime_container_id after create; reconcile jobs on v5-reconcile queue; status_message churn fixed+- [x] Team-delete teardown: Team::deleting → V5TeardownTeamJob (best-effort per-server container/ingress/marker teardown, self-contained payload)++## Wave 7 recovery fix (post-cutoff)+- [x] FATAL: V5ReconcileServersJob + V5ReconcileServerStateJob redeclared `public $queue = 'v5-reconcile'` — incompatible with Queueable trait's `public $queue;` on PHP 8.5 → hard fatal crashing BOTH pest suite and `php artisan test` bootstrap (job discovery). Moved queue assignment to onQueue() in constructor.+- [x] Stale test: ResourceConnectionControllerTest asserted old snapshot-fail detail; scenario hits the restore path → updated to "The previous rules were restored." (correct behavior)++## Final state (Wave 7)+322 V5 tests passed (2124 assertions) via BOTH vendor/bin/pest AND php artisan test; v4 slice 308 passed; tsc clean; npm build ok; pint clean.diff --git a/app/Actions/V5/Application/DeployNginxApplication.php b/app/Actions/V5/Application/DeployNginxApplication.phpindex 1974d6be94..6e0e50e064 100644--- a/app/Actions/V5/Application/DeployNginxApplication.php+++ b/app/Actions/V5/Application/DeployNginxApplication.php@@ -2,8 +2,12 @@namespace App\Actions\V5\Application;+use App\Enums\V5\ApplicationStatus;+use App\Enums\V5\ContainerState;+use App\Enums\V5\ServerStatus;use App\Models\V5\Application;use App\Services\Flux\FluxClient;+use Illuminate\Support\Facades\Log;use Lorisleiva\Actions\Concerns\AsAction;class DeployNginxApplication@@ -21,34 +25,91 @@ class DeployNginxApplicationreturn $this->markFailed($application, 'No server is attached to this application.');}- $hostId = $server->wireguard_management_ip ?: $server->node_address ?: $server->host;+ if ($server->status !== ServerStatus::Installed->value || $server->last_bootstrapped_at === null) {+ return $this->markFailed($application, "Bootstrap server {$server->name} before deploying to it.");+ }++ $hostId = $server->fluxHostId();if (! is_string($hostId) || $hostId === '') {return $this->markFailed($application, 'No Flux host ID is available for this server.');}+ $containerId = null;+try {$this->fluxClient->pullImage($hostId, $application->image);$containerId = $this->fluxClient->createContainer($hostId, $this->containerSpec($application));++ // Persist the runtime id the instant the container exists, before+ // start/inspect. A worker SIGKILL at the job timeout would otherwise+ // orphan a created container whose id only lived in this local var,+ // leaving failed()/reconcile unable to find and clean it by id.+ $application->update([+ 'status' => ApplicationStatus::Created->value,+ 'status_message' => 'Container created.',+ 'runtime_container_id' => $containerId,+ ]);+$this->fluxClient->startContainer($hostId, $containerId);$inspect = $this->fluxClient->inspectContainer($hostId, $containerId);if (! $this->isContainerRunning($inspect)) {+ $this->cleanUpContainer($application, $hostId, $containerId);+return $this->markFailed($application, 'Container did not stay running.');}$application->update([- 'status' => 'running',+ 'status' => ApplicationStatus::Running->value,'status_message' => 'Container started.','runtime_container_id' => $containerId,]);return $application->refresh()->load('server');} catch (\Throwable $e) {+ if (is_string($containerId) && $containerId !== '') {+ $this->cleanUpContainer($application, $hostId, $containerId);+ }+return $this->markFailed($application, $e->getMessage());}}+ /**+ * Best-effort compensation for a failed deploy: stop and force-remove the+ * container this run created so it is never left orphaned on the node, then+ * null the runtime id we persisted right after create so a cleaned-up+ * failure never leaves a dangling id that reconcile would try to reap.+ * Cleanup failures only log a warning and never mask the original error.+ */+ private function cleanUpContainer(Application $application, string $hostId, string $containerId): void+ {+ try {+ $this->fluxClient->stopContainer($hostId, $containerId);+ } catch (\Throwable $e) {+ Log::warning('Could not stop the container created by a failed v5 deploy.', [+ 'application_id' => $application->getKey(),+ 'container_id' => $containerId,+ 'error' => $e->getMessage(),+ ]);+ }++ try {+ $this->fluxClient->removeContainer($hostId, $containerId, force: true);+ } catch (\Throwable $e) {+ Log::warning('Could not remove the container created by a failed v5 deploy.', [+ 'application_id' => $application->getKey(),+ 'container_id' => $containerId,+ 'error' => $e->getMessage(),+ ]);+ }++ if ($application->runtime_container_id === $containerId) {+ $application->update(['runtime_container_id' => null]);+ }+ }+/*** @return array<string, mixed>*/@@ -92,13 +153,13 @@ class DeployNginxApplicationreturn true;}- return is_string($inspect['state'] ?? null) && $inspect['state'] === 'running';+ return is_string($inspect['state'] ?? null) && $inspect['state'] === ContainerState::Running->value;}private function markFailed(Application $application, string $message): Application{$application->update([- 'status' => 'failed',+ 'status' => ApplicationStatus::Failed->value,'status_message' => str($message)->limit(10000)->toString(),]);diff --git a/app/Actions/V5/Flux/ApplyFluxResourceStatusUpdate.php b/app/Actions/V5/Flux/ApplyFluxResourceStatusUpdate.phpindex e763ab44fb..5ed35cc5cc 100644--- a/app/Actions/V5/Flux/ApplyFluxResourceStatusUpdate.php+++ b/app/Actions/V5/Flux/ApplyFluxResourceStatusUpdate.php@@ -2,10 +2,18 @@namespace App\Actions\V5\Flux;+use App\Enums\V5\ApplicationStatus;+use App\Enums\V5\ContainerState;+use App\Enums\V5\IngressStatus;+use App\Enums\V5\ServerStatus;use App\Models\V5\Application as V5Application;use App\Models\V5\ContainerStatus;use App\Models\V5\Server as V5Server;+use App\Support\V5\StatusObservation;+use Carbon\CarbonImmutable;+use Carbon\CarbonInterface;use Illuminate\Database\Eloquent\Model;+use Illuminate\Support\Facades\Log;use Lorisleiva\Actions\Concerns\AsAction;class ApplyFluxResourceStatusUpdate@@ -37,7 +45,7 @@ class ApplyFluxResourceStatusUpdate*/private function upsertContainerStatus(array $payload): ?ContainerStatus{- $status = $this->status($payload);+ $status = $this->status($payload, ContainerState::class);$containerId = $this->stringValue($payload, 'container_id') ?? $this->stringValue($payload, 'runtime_container_id');$server = $this->findServer($payload);@@ -45,17 +53,36 @@ class ApplyFluxResourceStatusUpdatereturn null;}- ContainerStatus::query()->updateOrCreate([+ $observedAt = $this->observedAt($payload);+ $existing = ContainerStatus::query()+ ->where('server_id', $server->id)+ ->where('container_id', $containerId)+ ->first();++ if ($this->isStaleObservation($observedAt, $existing?->status_observed_at, 'container status', ['server_id' => $server->id,'container_id' => $containerId,- ], [+ ])) {+ return $existing;+ }++ $attributes = ['team_id' => $server->team_id,'container_name' => $this->stringValue($payload, 'container_name') ?? $this->stringValue($payload, 'name'),'image' => $this->stringValue($payload, 'image'),'status' => $status,'status_message' => $this->statusMessage($payload, 'Container state received from coold.'),'last_seen_at' => now(),- ]);+ ];++ if ($observedAt !== null) {+ $attributes['status_observed_at'] = $observedAt;+ }++ ContainerStatus::query()->updateOrCreate([+ 'server_id' => $server->id,+ 'container_id' => $containerId,+ ], $attributes);return ContainerStatus::query()->where('server_id', $server->id)@@ -68,7 +95,7 @@ class ApplyFluxResourceStatusUpdate*/private function updateApplication(array $payload): ?V5Application{- $status = $this->status($payload);+ $status = $this->status($payload, ApplicationStatus::class);if ($status === null) {return null;@@ -80,13 +107,39 @@ class ApplyFluxResourceStatusUpdatereturn null;}- $application->update([+ $observedAt = $this->observedAt($payload);++ if ($this->isStaleObservation($observedAt, $application->status_observed_at, 'application status', [+ 'application_id' => $application->id,+ ])) {+ return $application;+ }++ $payloadContainerId = $this->stringValue($payload, 'runtime_container_id')+ ?? $this->stringValue($payload, 'container_id');++ // Payloads may carry no timestamp, so the container id remains an+ // ordering signal as a second layer: an update for a superseded+ // container is stale and must not overwrite the current one's state.+ if (+ $payloadContainerId !== null+ && $application->runtime_container_id !== null+ && $payloadContainerId !== $application->runtime_container_id+ ) {+ return $application;+ }++ $attributes = ['status' => $status,'status_message' => $this->statusMessage($payload, 'Status updated by flux.'),- 'runtime_container_id' => $this->stringValue($payload, 'runtime_container_id')- ?? $this->stringValue($payload, 'container_id')- ?? $application->runtime_container_id,- ]);+ 'runtime_container_id' => $payloadContainerId ?? $application->runtime_container_id,+ ];++ if ($observedAt !== null) {+ $attributes['status_observed_at'] = $observedAt;+ }++ $application->update($attributes);return $application->refresh();}@@ -96,7 +149,7 @@ class ApplyFluxResourceStatusUpdate*/private function updateServer(array $payload): ?V5Server{- $status = $this->status($payload);+ $status = $this->status($payload, ServerStatus::class);if ($status === null) {return null;@@ -108,22 +161,40 @@ class ApplyFluxResourceStatusUpdatereturn null;}- $server->update([+ $observedAt = $this->observedAt($payload);++ if ($this->isStaleObservation($observedAt, $server->status_observed_at, 'server status', [+ 'server_id' => $server->id,+ ])) {+ return $server;+ }++ $attributes = ['status' => $status,'last_status_check' => 'flux','last_status_output' => $this->statusMessage($payload, 'Status updated by flux.'),'last_status_checked_at' => now(),- ]);+ ];++ if ($observedAt !== null) {+ $attributes['status_observed_at'] = $observedAt;+ }++ $server->update($attributes);return $server->refresh();}/**+ * The ingress state shares the server row but describes a different+ * resource, so it deliberately does not read or write the server's+ * `status_observed_at` watermark.+ ** @param array<string, mixed> $payload*/private function updateCaddyIngress(array $payload): ?V5Server{- $status = $this->status($payload);+ $status = $this->status($payload, IngressStatus::class);if ($status === null) {return null;@@ -151,13 +222,17 @@ class ApplyFluxResourceStatusUpdate*/private function findApplication(array $payload): ?V5Application{- $query = V5Application::query()->with('server');$server = $this->findServer($payload);- if ($server instanceof V5Server) {- $query->where('server_id', $server->id);+ if (! $server instanceof V5Server) {+ return null;}+ $query = V5Application::query()+ ->with('server')+ ->where('server_id', $server->id)+ ->where('team_id', $server->team_id);+$applicationUuid = $this->stringValue($payload, 'application_uuid') ?? $this->stringValue($payload, 'resource_uuid');if ($applicationUuid !== null) {@@ -211,54 +286,81 @@ class ApplyFluxResourceStatusUpdatereturn null;}- return V5Server::query()- ->where('wireguard_management_ip', $hostId)- ->orWhere('node_address', $hostId)- ->orWhere('host', $hostId)- ->first();+ $matches = V5Server::query()+ ->where('uuid', $hostId)+ ->limit(2)+ ->get();++ if ($matches->count() > 1) {+ Log::warning('Dropping flux resource status update: host id matches multiple v5 servers.', [+ 'host_id' => $hostId,+ 'server_ids' => $matches->pluck('id')->all(),+ ]);++ return null;+ }++ return $matches->first();}/**+ * Map the raw payload status onto the given status enum. Unknown values+ * are never written to the database: they fall back to the enum's+ * Unknown case and are logged.+ ** @param array<string, mixed> $payload+ * @param class-string<ApplicationStatus|ContainerState|IngressStatus|ServerStatus> $enumClass*/- private function status(array $payload): ?string+ private function status(array $payload, string $enumClass): ?string{- $status = $this->stringValue($payload, 'status') ?? $this->stringValue($payload, 'state');+ $raw = $this->stringValue($payload, 'status') ?? $this->stringValue($payload, 'state');- return $status === null ? null : strtolower($status);+ return StatusObservation::normalize($raw, $enumClass);}/*** @param array<string, mixed> $payload*/- private function statusMessage(array $payload, string $fallback): string+ private function observedAt(array $payload): ?CarbonInterface{- return $this->stringValue($payload, 'status_message')- ?? $this->stringValue($payload, 'message')- ?? $fallback;+ $observedAt = $this->stringValue($payload, 'observed_at');++ if ($observedAt === null) {+ return null;+ }++ return rescue(fn (): CarbonImmutable => CarbonImmutable::parse($observedAt), null, false);}/**- * @param array<string, mixed> $payload+ * A payload that carries an observation timestamp older than the one+ * already persisted is stale (delivered out of order) and must not+ * clobber the newer state.+ *+ * @param array<string, mixed> $logContext*/- private function stringValue(array $payload, string $key): ?string+ private function isStaleObservation(?CarbonInterface $observedAt, ?CarbonInterface $currentObservedAt, string $context, array $logContext): bool{- $value = data_get($payload, $key);+ return StatusObservation::isStale($observedAt, $currentObservedAt, $context, $logContext);+ }- return is_string($value) && $value !== '' ? $value : null;+ /**+ * @param array<string, mixed> $payload+ */+ private function statusMessage(array $payload, string $fallback): string+ {+ return $this->stringValue($payload, 'status_message')+ ?? $this->stringValue($payload, 'message')+ ?? $fallback;}/*** @param array<string, mixed> $payload*/- private function intValue(array $payload, string $key): ?int+ private function stringValue(array $payload, string $key): ?string{$value = data_get($payload, $key);- if (is_int($value)) {- return $value;- }-- return is_string($value) && ctype_digit($value) ? (int) $value : null;+ return is_string($value) && $value !== '' ? $value : null;}}diff --git a/app/Actions/V5/Proxy/GenerateCaddyIngressConfiguration.php b/app/Actions/V5/Proxy/GenerateCaddyIngressConfiguration.phpindex aeb3768db7..2c17f89b03 100644--- a/app/Actions/V5/Proxy/GenerateCaddyIngressConfiguration.php+++ b/app/Actions/V5/Proxy/GenerateCaddyIngressConfiguration.php@@ -5,6 +5,7 @@ namespace App\Actions\V5\Proxy;use App\Models\V5\Application;use App\Models\V5\ApplicationDomain;use Illuminate\Support\Collection;+use Illuminate\Support\Facades\Log;use Lorisleiva\Actions\Concerns\AsAction;use Symfony\Component\Yaml\Yaml;@@ -12,6 +13,14 @@ class GenerateCaddyIngressConfiguration{use AsAction;+ /**+ * Strict RFC 1123 hostname: dot-separated alphanumeric labels with inner+ * hyphens, max 253 characters. Anchored with \A/\z (never $) so values+ * containing newlines, braces, quotes, whitespace, or control characters+ * can never inject extra directives into the generated Caddyfile.+ */+ private const HOSTNAME_PATTERN = '/\A(?=.{1,253}\z)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\z/i';+/*** @param Collection<int, Application>|null $applications* @return array{compose: string, caddyfile: string, apps: array<int, array{name: string, caddyfile: string}>}@@ -92,12 +101,42 @@ CADDY;private function applicationRoute(Application $application, ApplicationDomain $domain): ?string{- if ($domain->domain === '') {+ if ($domain->domain === null || $domain->domain === '') {return null;}$namespace = $application->mesh_namespace ?: 'default';- $upstream = "{$application->container_name}.{$namespace}.coolify.internal:{$application->internal_port}";+ $internalPort = (int) $application->internal_port;++ if (! $this->isSafeHostname($domain->domain)) {+ Log::warning('Skipping a caddy ingress route with an unsafe domain.', [+ 'application_id' => $application->getKey(),+ 'domain' => $domain->domain,+ ]);++ return null;+ }++ if (! $this->isSafeHostname($application->container_name) || ! $this->isSafeHostname($namespace)) {+ Log::warning('Skipping a caddy ingress route with an unsafe container name or namespace.', [+ 'application_id' => $application->getKey(),+ 'container_name' => $application->container_name,+ 'namespace' => $namespace,+ ]);++ return null;+ }++ if ($internalPort < 1 || $internalPort > 65535) {+ Log::warning('Skipping a caddy ingress route with an out-of-range internal port.', [+ 'application_id' => $application->getKey(),+ 'internal_port' => $application->internal_port,+ ]);++ return null;+ }++ $upstream = "{$application->container_name}.{$namespace}.coolify.internal:{$internalPort}";return implode("\n", ["http://{$domain->domain} {",@@ -106,6 +145,11 @@ CADDY;]);}+ private function isSafeHostname(mixed $value): bool+ {+ return is_string($value) && preg_match(self::HOSTNAME_PATTERN, $value) === 1;+ }+private function appFileName(Application $application): string{return 'app_'.$application->getKey();diff --git a/app/Actions/V5/Proxy/StartCaddyIngress.php b/app/Actions/V5/Proxy/StartCaddyIngress.phpindex 778ccf3c18..127c00bd63 100644--- a/app/Actions/V5/Proxy/StartCaddyIngress.php+++ b/app/Actions/V5/Proxy/StartCaddyIngress.php@@ -2,17 +2,19 @@namespace App\Actions\V5\Proxy;+use App\Exceptions\V5\UnsupportedCooldVerb;use App\Models\V5\Application;use App\Models\V5\Server;use App\Services\Flux\FluxClient;use Illuminate\Support\Collection;+use Illuminate\Support\Facades\Log;use Lorisleiva\Actions\Concerns\AsAction;class StartCaddyIngress{use AsAction;- private const FIREWALL_PORTS = [80, 443];+ private const FIREWALL_PORTS = [80];public function __construct(private readonly FluxClient $fluxClient) {}@@ -22,30 +24,48 @@ class StartCaddyIngressreturn 'Server is not an ingress server.';}- $hostId = $server->wireguard_management_ip ?: $server->node_address;+ $hostId = $server->fluxHostId();if (! is_string($hostId) || $hostId === '') {- return 'Server is missing its Flux host id.';+ throw new \RuntimeException('Server is missing its Flux host id.');}$configuration = GenerateCaddyIngressConfiguration::run($this->applications($server));$output = $this->fluxClient->applyIngress($hostId, 'caddy', $configuration['caddyfile'], $this->ingressApps($configuration['apps']));+ $firewallWarning = null;+foreach (self::FIREWALL_PORTS as $port) {- $this->fluxClient->applyFirewallRule($hostId, [- 'id' => "v5-caddy-ingress:{$port}",- 'namespace' => 'default',- 'src' => '0.0.0.0/0',- 'dst' => 'coolify-v5-caddy',- 'proto' => 'tcp',- 'port' => $port,- ]);+ try {+ $this->fluxClient->applyFirewallRule($hostId, [+ 'id' => "v5-caddy-ingress:{$port}",+ 'namespace' => 'default',+ 'src' => '0.0.0.0/0',+ 'dst' => 'coolify-v5-caddy',+ 'proto' => 'tcp',+ 'port' => $port,+ ]);+ } catch (UnsupportedCooldVerb $exception) {+ $firewallWarning = "Caddy ingress is running, but this node's coold does not support {$exception->verb}, so the managed firewall was not updated for port {$port}.";+ Log::warning('V5 caddy ingress firewall rule skipped: coold verb unsupported', [+ 'server_id' => $server->id,+ 'port' => $port,+ 'verb' => $exception->verb,+ 'message' => $exception->getMessage(),+ ]);++ break;+ }}if ($server->exists) {$server->update(['ingress_type' => 'caddy','ingress_status' => 'running',+ ...($firewallWarning === null ? [] : [+ 'last_status_check' => 'flux',+ 'last_status_output' => $firewallWarning,+ ]),]);}diff --git a/app/Actions/V5/Proxy/StopCaddyIngress.php b/app/Actions/V5/Proxy/StopCaddyIngress.phpindex 2b3e27442e..105d075237 100644--- a/app/Actions/V5/Proxy/StopCaddyIngress.php+++ b/app/Actions/V5/Proxy/StopCaddyIngress.php@@ -2,36 +2,64 @@namespace App\Actions\V5\Proxy;+use App\Enums\V5\IngressStatus;+use App\Exceptions\V5\UnsupportedCooldVerb;use App\Models\V5\Server;use App\Services\Flux\FluxClient;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Str;use Lorisleiva\Actions\Concerns\AsAction;class StopCaddyIngress{use AsAction;- private const FIREWALL_PORTS = [80, 443];+ private const FIREWALL_PORTS = [80];public function __construct(private readonly FluxClient $fluxClient) {}public function handle(Server $server): string{- $hostId = $server->wireguard_management_ip ?: $server->node_address;+ if (! $server->isIngress() && $server->ingress_type === null) {+ return 'Server is not an ingress server.';+ }++ $hostId = $server->fluxHostId();if (! is_string($hostId) || $hostId === '') {- return 'Server is missing its Flux host id.';+ throw new \RuntimeException('Server is missing its Flux host id.');}- $output = $this->fluxClient->stopIngress($hostId, 'caddy');-+ // Revoke first: if stopping the container fails the allow rules must not+ // stay orphaned on the host.foreach (self::FIREWALL_PORTS as $port) {- $this->fluxClient->revokeFirewallRule($hostId, "v5-caddy-ingress:{$port}");+ $this->revokeFirewallRuleIfPresent($hostId, "v5-caddy-ingress:{$port}");}+ $output = $this->fluxClient->stopIngress($hostId, 'caddy');+if ($server->exists) {- $server->update(['ingress_status' => 'exited']);+ $server->update(['ingress_status' => IngressStatus::Exited->value]);}return $output;}++ private function revokeFirewallRuleIfPresent(string $hostId, string $ruleId): void+ {+ try {+ $this->fluxClient->revokeFirewallRule($hostId, $ruleId);+ } catch (UnsupportedCooldVerb $exception) {+ Log::warning('V5 caddy ingress firewall revoke skipped: coold verb unsupported', [+ 'host_id' => $hostId,+ 'rule_id' => $ruleId,+ 'verb' => $exception->verb,+ 'message' => $exception->getMessage(),+ ]);+ } catch (\RuntimeException $exception) {+ if (! str_contains(Str::lower($exception->getMessage()), 'not found')) {+ throw $exception;+ }+ }+ }}diff --git a/app/Actions/V5/Server/PushHostAgentToken.php b/app/Actions/V5/Server/PushHostAgentToken.phpnew file mode 100644index 0000000000..a6e87d737a--- /dev/null+++ b/app/Actions/V5/Server/PushHostAgentToken.php@@ -0,0 +1,101 @@+<?php++namespace App\Actions\V5\Server;++use App\Models\PrivateKey;+use App\Models\V5\Server;+use Illuminate\Support\Facades\Process;+use Lorisleiva\Actions\Concerns\AsAction;++class PushHostAgentToken+{+ use AsAction;++ /**+ * Best-effort SSH push of a freshly minted host JWT to the on-host jwt path.+ *+ * coold re-reads the JWT file on every reconnect and flux drops the stream+ * at the token's exp, so overwriting the file in place is enough for the+ * next reconnect to pick up the new token — coold is intentionally NOT+ * restarted here (a restart would force an unnecessary disconnect of a+ * stream that is still valid on the current token).+ *+ * Mirrors V5BootstrapServerJob::enrollCooldIntoFlux for the write mechanics+ * (printf %s <token> | sudo tee <path>; chmod 600) and RemoveBootstrapMarker+ * for the SSH/temp-key mechanics. Returns whether the write succeeded;+ * every failure path (missing key, SSH error, exception) resolves to false+ * and always cleans up the temporary key file.+ */+ public function handle(Server $server, string $token): bool+ {+ $server->loadMissing('privateKey');++ if (! $server->privateKey instanceof PrivateKey) {+ return false;+ }++ $jwtPath = trim((string) config('coold.flux_host_jwt_path', '/etc/coolify/host-jwt'));++ if ($jwtPath === '') {+ $jwtPath = '/etc/coolify/host-jwt';+ }++ $jwtPath = str_replace(["\r", "\n"], '', $jwtPath);+ $token = str_replace(["\r", "\n"], '', $token);++ $keyDirectory = storage_path('app/ssh/keys');+ if (! is_dir($keyDirectory)) {+ mkdir($keyDirectory, 0700, true);+ }++ $keyLocation = tempnam($keyDirectory, 'v5_ssh_key_');+ if ($keyLocation === false) {+ return false;+ }++ file_put_contents($keyLocation, $server->privateKey->private_key);+ chmod($keyLocation, 0600);++ $tokenArgument = escapeshellarg($token);+ $jwtPathArgument = $this->shellPathArg($jwtPath);+ $script = <<<SH+set -e+SUDO=''+if [ "\$(id -u)" != "0" ]; then SUDO='sudo'; fi+\$SUDO mkdir -p /etc/coolify+printf %s {$tokenArgument} | \$SUDO tee {$jwtPathArgument} >/dev/null+\$SUDO chmod 600 {$jwtPathArgument}+SH;++ try {+ $result = Process::timeout(30)->run([+ 'ssh',+ '-o', 'BatchMode=yes',+ '-o', 'LogLevel=ERROR',+ '-o', 'StrictHostKeyChecking=no',+ '-o', 'UserKnownHostsFile=/dev/null',+ '-o', 'ConnectTimeout=10',+ '-o', 'IdentitiesOnly=yes',+ '-i', $keyLocation,+ '-p', (string) $server->ssh_port,+ "{$server->ssh_user}@{$server->host}",+ $script,+ ]);++ return $result->successful();+ } catch (\Throwable) {+ return false;+ } finally {+ @unlink($keyLocation);+ }+ }++ private function shellPathArg(string $value): string+ {+ if (preg_match('/^[A-Za-z0-9_\/:.,@%+=-]+$/', $value) === 1) {+ return $value;+ }++ return escapeshellarg($value);+ }+}diff --git a/app/Actions/V5/Server/RemoveBootstrapMarker.php b/app/Actions/V5/Server/RemoveBootstrapMarker.phpnew file mode 100644index 0000000000..ba1a6e7e25--- /dev/null+++ b/app/Actions/V5/Server/RemoveBootstrapMarker.php@@ -0,0 +1,75 @@+<?php++namespace App\Actions\V5\Server;++use App\Models\PrivateKey;+use App\Models\V5\Server;+use App\Services\Flux\AgentTokenIssuer;+use Illuminate\Support\Facades\Process;+use Lorisleiva\Actions\Concerns\AsAction;++class RemoveBootstrapMarker+{+ use AsAction;++ /**+ * Best-effort removal of the on-host bootstrap identity (marker, host JWT and+ * Flux drop-in) so a re-added server can never silently adopt stale state.+ *+ * The host token jti is revoked first (a local DB write plus a best-effort+ * push to the flux revocation store) so a captured or pre-copied token is+ * recorded revoked even when the host is unreachable — see+ * AgentTokenIssuer::revoke.+ */+ public function handle(Server $server): bool+ {+ app(AgentTokenIssuer::class)->revoke($server);++ $server->loadMissing('privateKey');++ if (! $server->privateKey instanceof PrivateKey) {+ return false;+ }++ $keyDirectory = storage_path('app/ssh/keys');+ if (! is_dir($keyDirectory)) {+ mkdir($keyDirectory, 0700, true);+ }++ $keyLocation = tempnam($keyDirectory, 'v5_ssh_key_');+ if ($keyLocation === false) {+ return false;+ }++ file_put_contents($keyLocation, $server->privateKey->private_key);+ chmod($keyLocation, 0600);++ $script = implode("\n", [+ "SUDO=''",+ 'if [ "$(id -u)" != "0" ]; then SUDO=\'sudo\'; fi',+ '$SUDO rm -f /etc/coolify/v5-node.json /etc/coolify/host-jwt /etc/systemd/system/coold.service.d/10-flux.conf',+ ]);++ try {+ $result = Process::timeout(15)->run([+ 'ssh',+ '-o', 'BatchMode=yes',+ '-o', 'LogLevel=ERROR',+ '-o', 'StrictHostKeyChecking=no',+ '-o', 'UserKnownHostsFile=/dev/null',+ '-o', 'ConnectTimeout=10',+ '-o', 'IdentitiesOnly=yes',+ '-i', $keyLocation,+ '-p', (string) $server->ssh_port,+ "{$server->ssh_user}@{$server->host}",+ $script,+ ]);++ return $result->successful();+ } catch (\Throwable) {+ return false;+ } finally {+ @unlink($keyLocation);+ }+ }+}diff --git a/app/Actions/V5/Server/SyncDevLimaServers.php b/app/Actions/V5/Server/SyncDevLimaServers.phpindex 8bf98b2f05..1eb68feb14 100644--- a/app/Actions/V5/Server/SyncDevLimaServers.php+++ b/app/Actions/V5/Server/SyncDevLimaServers.php@@ -2,6 +2,7 @@namespace App\Actions\V5\Server;+use App\Enums\V5\ServerStatus;use App\Models\PrivateKey;use App\Models\Team;use App\Models\User;@@ -9,6 +10,14 @@ use App\Models\V5\Cluster;use App\Models\V5\Server;use Lorisleiva\Actions\Concerns\AsAction;+/**+ * Registers local Lima development VMs (provisioned by scripts/dev.sh) as+ * cluster servers. They are intentionally seeded as Installed with+ * last_bootstrapped_at already set but has_coold=false, so they skip the real+ * bootstrap flow by design: V5BootstrapServerJob early-returns on a non-null+ * last_bootstrapped_at, and V5ReconcileServersJob ignores them until+ * something marks has_coold=true.+ */class SyncDevLimaServers{use AsAction;@@ -39,8 +48,6 @@ class SyncDevLimaServers'description' => 'Local Lima development cluster managed by scripts/dev.sh.',]);- $capabilities = [];-foreach ($servers as $server) {$wireguardManagementIp = $server['wireguard_management_ip'] ?? null;$values = [@@ -49,8 +56,9 @@ class SyncDevLimaServers'host' => $server['host'],'ssh_user' => $server['ssh_user'],'ssh_port' => $server['ssh_port'],- 'status' => 'installed',- 'capabilities' => $capabilities,+ 'status' => ServerStatus::Installed->value,+ 'has_coold' => false,+ 'is_ingress' => false,'builder_enabled' => false,'builder_capacity' => 0,'node_address' => $wireguardManagementIp ?: $server['host'],diff --git a/app/Console/Commands/V5FluxGenerateKeys.php b/app/Console/Commands/V5FluxGenerateKeys.phpnew file mode 100644index 0000000000..6f459ad59c--- /dev/null+++ b/app/Console/Commands/V5FluxGenerateKeys.php@@ -0,0 +1,135 @@+<?php++namespace App\Console\Commands;++use App\Services\Flux\AgentTokenIssuer;+use Illuminate\Console\Command;+use Illuminate\Support\Facades\File;++/**+ * Generates the ES256 (EC P-256) keypair used to authorize coold host agents+ * against flux. Laravel signs the per-host JWT with the private key+ * (config('flux.jwt_private_key_path')); flux verifies it with the matching+ * public key (config('flux.jwt_public_key_path')). Without this keypair a fresh+ * install cannot mint host tokens, so this command is a bootstrap prerequisite.+ *+ * @see AgentTokenIssuer+ */+class V5FluxGenerateKeys extends Command+{+ protected $signature = 'v5:flux-generate-keys+ {--force : Overwrite an existing private key instead of refusing}+ {--show-public : Print the generated public key PEM so it can be provisioned to flux}';++ protected $description = 'Generate the ES256 keypair Flux uses to sign and verify coold host agent JWTs.';++ public function handle(AgentTokenIssuer $agentTokenIssuer): int+ {+ $privateKeyPath = (string) config('flux.jwt_private_key_path');+ $publicKeyPath = (string) config('flux.jwt_public_key_path');++ if ($privateKeyPath === '' || $publicKeyPath === '') {+ $this->error('Flux JWT key paths are not configured (flux.jwt_private_key_path / flux.jwt_public_key_path).');++ return self::FAILURE;+ }++ // Idempotent by default: re-running during provisioning must not clobber+ // a live key (which would instantly invalidate every host token on+ // disk). Refuse unless --force is passed, and exit SUCCESS so a+ // provisioning script can call this unconditionally on every deploy.+ if (File::exists($privateKeyPath) && ! $this->option('force')) {+ $this->warn("A Flux JWT private key already exists at {$privateKeyPath}.");+ $this->line('Refusing to overwrite it. Re-run with --force to replace it (this invalidates every host token currently on disk).');++ return self::SUCCESS;+ }++ // curve_name drives the actual EC key (P-256). private_key_bits is+ // still validated by PHP's generic length check (>= 384) even though it+ // is irrelevant to EC, so it must be present or openssl_pkey_new fails+ // with "Private key length must be at least 384 bits, configured to 0".+ $keyPair = openssl_pkey_new([+ 'private_key_type' => OPENSSL_KEYTYPE_EC,+ 'curve_name' => 'prime256v1',+ 'private_key_bits' => 384,+ ]);++ if ($keyPair === false) {+ $this->error('Failed to generate an EC P-256 keypair: '.openssl_error_string());++ return self::FAILURE;+ }++ $privatePem = '';++ if (! openssl_pkey_export($keyPair, $privatePem)) {+ $this->error('Failed to export the private key PEM: '.openssl_error_string());++ return self::FAILURE;+ }++ $details = openssl_pkey_get_details($keyPair);++ if ($details === false || ! isset($details['key'])) {+ $this->error('Failed to read the generated public key PEM.');++ return self::FAILURE;+ }++ $publicPem = (string) $details['key'];++ $this->writeKeyFile($privateKeyPath, $privatePem, 0600);+ $this->writeKeyFile($publicKeyPath, $publicPem, 0644);++ // Self-check: the whole point of this command is that AgentTokenIssuer+ // can mint with the key we just wrote. If the format were wrong (e.g.+ // not a PEM EC private key Firebase\JWT accepts for ES256) this fails+ // loudly here instead of silently at the first real host bootstrap.+ try {+ $token = $agentTokenIssuer->issue('flux-keygen-selfcheck');+ } catch (\Throwable $exception) {+ $this->error('Generated a keypair but AgentTokenIssuer could not mint a token with it: '.$exception->getMessage());++ return self::FAILURE;+ }++ if (substr_count($token, '.') !== 2) {+ $this->error('Generated key produced a malformed JWT (expected 3 segments).');++ return self::FAILURE;+ }++ $this->info('Generated a fresh ES256 (EC P-256) Flux keypair.');+ $this->line(" Private key (0600): {$privateKeyPath}");+ $this->line(" Public key (0644): {$publicKeyPath}");+ $this->newLine();+ $this->line('Provision the PUBLIC key to flux — flux verifies every host JWT with it.');+ $this->line('Keep the PRIVATE key secret and on the Laravel host only.');++ if ($this->option('show-public')) {+ $this->newLine();+ $this->line(rtrim($publicPem));+ }++ return self::SUCCESS;+ }++ /**+ * Write a key file with exact permissions, creating the parent directory at+ * 0700 if missing. chmod is applied after the write because umask can+ * loosen both the mkdir mode and the created file mode.+ */+ private function writeKeyFile(string $path, string $contents, int $mode): void+ {+ $directory = dirname($path);++ if (! is_dir($directory)) {+ File::makeDirectory($directory, 0700, true);+ @chmod($directory, 0700);+ }++ File::put($path, $contents);+ @chmod($path, $mode);+ }+}diff --git a/app/Console/Kernel.php b/app/Console/Kernel.phpindex e6dc323838..f06bec45c2 100644--- a/app/Console/Kernel.php+++ b/app/Console/Kernel.php@@ -15,6 +15,8 @@ use App\Jobs\RegenerateSslCertJob;use App\Jobs\ScheduledJobManager;use App\Jobs\ServerManagerJob;use App\Jobs\UpdateCoolifyJob;+use App\Jobs\V5ReconcileServersJob;+use App\Jobs\V5RotateAgentTokensJob;use App\Models\InstanceSettings;use Illuminate\Console\Scheduling\Schedule;use Illuminate\Foundation\Console\Kernel as ConsoleKernel;@@ -49,6 +51,14 @@ class Kernel extends ConsoleKernel$this->scheduleInstance->command('sanctum:prune-expired --hours=1')->hourly()->onOneServer();$this->scheduleInstance->job(new ApiTokenExpirationWarningJob)->hourly()->onOneServer();+ // V5 reconciliation loop: pull-based safety net for the push-only+ // coold -> flux -> webhook status pipeline, plus container status pruning.+ $this->scheduleInstance->job(new V5ReconcileServersJob)->everyFiveMinutes()->withoutOverlapping()->onOneServer();++ // V5 host JWT rotation: re-mints and SSH-pushes a fresh host token+ // before the on-disk token expires so coold reconnects stay authorized.+ $this->scheduleInstance->job(new V5RotateAgentTokensJob)->hourly()->withoutOverlapping()->onOneServer();+if (isDev()) {// Instance Jobs$this->scheduleInstance->command('horizon:snapshot')->everyMinute();diff --git a/app/Enums/V5/ApplicationStatus.php b/app/Enums/V5/ApplicationStatus.phpnew file mode 100644index 0000000000..66fafa5556--- /dev/null+++ b/app/Enums/V5/ApplicationStatus.php@@ -0,0 +1,28 @@+<?php++namespace App\Enums\V5;++/**+ * Lifecycle states persisted on `v5_applications.status`.+ *+ * Besides Coolify's own states (creating, failed, unknown), the column also+ * receives raw container runtime states reported by coold, so the Docker and+ * Podman container states are part of the catalog.+ */+enum ApplicationStatus: string+{+ case Creating = 'creating';+ case Configured = 'configured';+ case Created = 'created';+ case Starting = 'starting';+ case Running = 'running';+ case Restarting = 'restarting';+ case Paused = 'paused';+ case Removing = 'removing';+ case Stopping = 'stopping';+ case Stopped = 'stopped';+ case Exited = 'exited';+ case Dead = 'dead';+ case Failed = 'failed';+ case Unknown = 'unknown';+}diff --git a/app/Enums/V5/ContainerState.php b/app/Enums/V5/ContainerState.phpnew file mode 100644index 0000000000..6fc17b7503--- /dev/null+++ b/app/Enums/V5/ContainerState.php@@ -0,0 +1,26 @@+<?php++namespace App\Enums\V5;++/**+ * Runtime states persisted on `v5_container_statuses.status`.+ *+ * Named ContainerState (not ContainerStatus) to avoid clashing with the+ * App\Models\V5\ContainerStatus Eloquent model. Covers the Docker and Podman+ * container states reported by coold.+ */+enum ContainerState: string+{+ case Configured = 'configured';+ case Created = 'created';+ case Starting = 'starting';+ case Running = 'running';+ case Restarting = 'restarting';+ case Paused = 'paused';+ case Removing = 'removing';+ case Stopping = 'stopping';+ case Stopped = 'stopped';+ case Exited = 'exited';+ case Dead = 'dead';+ case Unknown = 'unknown';+}diff --git a/app/Enums/V5/IngressStatus.php b/app/Enums/V5/IngressStatus.phpnew file mode 100644index 0000000000..af647637ed--- /dev/null+++ b/app/Enums/V5/IngressStatus.php@@ -0,0 +1,25 @@+<?php++namespace App\Enums\V5;++/**+ * States persisted on `v5_servers.ingress_status`.+ *+ * The value mirrors the ingress proxy container's runtime state as reported+ * by coold, so the Docker and Podman container states are part of the catalog.+ */+enum IngressStatus: string+{+ case Configured = 'configured';+ case Created = 'created';+ case Starting = 'starting';+ case Running = 'running';+ case Restarting = 'restarting';+ case Paused = 'paused';+ case Removing = 'removing';+ case Stopping = 'stopping';+ case Stopped = 'stopped';+ case Exited = 'exited';+ case Dead = 'dead';+ case Unknown = 'unknown';+}diff --git a/app/Enums/V5/ServerStatus.php b/app/Enums/V5/ServerStatus.phpnew file mode 100644index 0000000000..16385bfd64--- /dev/null+++ b/app/Enums/V5/ServerStatus.php@@ -0,0 +1,15 @@+<?php++namespace App\Enums\V5;++/**+ * Lifecycle states persisted on `v5_servers.status`.+ */+enum ServerStatus: string+{+ case Added = 'added';+ case Installed = 'installed';+ case Failed = 'failed';+ case Unreachable = 'unreachable';+ case Unknown = 'unknown';+}diff --git a/app/Events/V5CanvasResourceUpdated.php b/app/Events/V5CanvasResourceUpdated.phpindex ac8cef3072..04615f42ec 100644--- a/app/Events/V5CanvasResourceUpdated.php+++ b/app/Events/V5CanvasResourceUpdated.php@@ -4,16 +4,23 @@ namespace App\Events;use App\Models\V5\Application as V5Application;use App\Models\V5\Server as V5Server;+use App\Support\V5\CanvasResourceSerializer;use Illuminate\Broadcasting\InteractsWithSockets;use Illuminate\Broadcasting\PrivateChannel;-use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;+use Illuminate\Contracts\Broadcasting\ShouldBroadcast;use Illuminate\Foundation\Events\Dispatchable;use Illuminate\Queue\SerializesModels;-class V5CanvasResourceUpdated implements ShouldBroadcastNow+class V5CanvasResourceUpdated implements ShouldBroadcast{use Dispatchable, InteractsWithSockets, SerializesModels;+ /**+ * Push the queued broadcast job only after the dispatching database+ * transaction commits, so workers never serialize pre-commit state.+ */+ public bool $afterCommit = true;+public function __construct(public int $teamId,public ?int $applicationId = null,@@ -38,6 +45,7 @@ class V5CanvasResourceUpdated implements ShouldBroadcastNow*/public function broadcastWith(): array{+ $serializer = app(CanvasResourceSerializer::class);$application = $this->applicationId !== null? V5Application::query()->with(['server', 'domains'])->find($this->applicationId): null;@@ -52,78 +60,14 @@ class V5CanvasResourceUpdated implements ShouldBroadcastNow: null;return [- 'application' => $application instanceof V5Application ? $this->serializeApplication($application) : null,+ 'application' => $application instanceof V5Application ? $serializer->serializeApplication($application) : null,'applications' => $applications- ->map(fn (V5Application $application) => $this->serializeApplication($application))+ ->map(fn (V5Application $application) => $serializer->serializeApplication($application))->values()->all(),'caddyIngress' => $caddyIngress instanceof V5Server && $caddyIngress->isIngress()- ? $this->serializeCaddyIngress($caddyIngress)+ ? $serializer->serializeCaddyIngress($caddyIngress): null,];}-- /**- * @return array<string, mixed>- */- private function serializeApplication(V5Application $application): array- {- $server = $application->server;- $isServerReachable = ! $server instanceof V5Server || $this->isServerReachable($server);-- return [- 'id' => (string) $application->id,- 'name' => $application->name,- 'image' => $application->image,- 'containerName' => $application->container_name,- 'status' => $application->status,- 'statusMessage' => $application->status_message,- 'effectiveStatus' => $isServerReachable ? $application->status : 'unknown',- 'effectiveStatusMessage' => $isServerReachable- ? $application->status_message- : $this->serverStatusMessage($server),- 'runtimeContainerId' => $application->runtime_container_id,- 'serverName' => $server?->name,- 'serverStatus' => $server?->status,- 'serverStatusMessage' => $server instanceof V5Server ? $this->serverStatusMessage($server) : null,- 'isServerReachable' => $isServerReachable,- 'serverIngressEnabled' => (bool) $server?->isIngress(),- 'meshNamespace' => $application->mesh_namespace,- 'ingressEnabled' => $application->ingress_enabled,- 'internalPort' => $application->internal_port,- 'domains' => $application->domains->pluck('domain')->values()->all(),- 'meshFqdn' => $application->container_name.'.'.($application->mesh_namespace ?: 'default').'.coolify.internal',- 'canvasX' => $application->canvas_x,- 'canvasY' => $application->canvas_y,- ];- }-- private function isServerReachable(V5Server $server): bool- {- return $server->status !== 'unreachable';- }-- private function serverStatusMessage(?V5Server $server): ?string- {- return $server?->last_status_output ?: null;- }-- /**- * @return array<string, mixed>- */- private function serializeCaddyIngress(V5Server $server): array- {- $isServerReachable = $this->isServerReachable($server);-- return [- 'id' => (string) $server->id,- 'name' => $server->name,- 'host' => $server->host,- 'type' => $server->ingressType(),- 'status' => $isServerReachable ? $server->ingressStatus() : 'unreachable',- 'statusMessage' => $isServerReachable ? null : $this->serverStatusMessage($server),- 'canvasX' => $server->canvas_x ?? -352,- 'canvasY' => $server->canvas_y ?? 0,- ];- }}diff --git a/app/Events/V5ClusterUpdated.php b/app/Events/V5ClusterUpdated.phpindex a820ba6d40..a5c863cbbc 100644--- a/app/Events/V5ClusterUpdated.php+++ b/app/Events/V5ClusterUpdated.php@@ -3,17 +3,23 @@namespace App\Events;use App\Models\V5\Cluster as V5Cluster;-use App\Models\V5\Server as V5Server;+use App\Support\V5\ClusterSerializer;use Illuminate\Broadcasting\InteractsWithSockets;use Illuminate\Broadcasting\PrivateChannel;-use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;+use Illuminate\Contracts\Broadcasting\ShouldBroadcast;use Illuminate\Foundation\Events\Dispatchable;use Illuminate\Queue\SerializesModels;-class V5ClusterUpdated implements ShouldBroadcastNow+class V5ClusterUpdated implements ShouldBroadcast{use Dispatchable, InteractsWithSockets, SerializesModels;+ /**+ * Push the queued broadcast job only after the dispatching database+ * transaction commits, so workers never serialize pre-commit state.+ */+ public bool $afterCommit = true;+public function __construct(public int $teamId, public int $clusterId) {}public function broadcastOn(): array@@ -42,63 +48,7 @@ class V5ClusterUpdated implements ShouldBroadcastNow->find($this->clusterId);return [- 'cluster' => $cluster instanceof V5Cluster ? $this->serializeCluster($cluster) : null,- ];- }-- /**- * @return array<string, mixed>- */- private function serializeCluster(V5Cluster $cluster): array- {- return [- 'id' => (string) $cluster->id,- 'name' => $cluster->name,- 'description' => $cluster->description,- 'wireguardInterface' => $cluster->wireguard_interface,- 'wireguardManagementPool' => $cluster->wireguard_management_pool,- 'wireguardListenPort' => $cluster->wireguard_listen_port,- 'containerNetworkPool' => $cluster->container_network_pool,- 'containerNetworkPrefix' => $cluster->container_network_prefix,- 'namespaces' => $cluster->namespaces ?? V5Cluster::DEFAULT_NAMESPACES,- 'defaultDenyContainers' => $cluster->default_deny_containers,- 'cooldVersion' => $cluster->coold_version,- 'corrosionVersion' => $cluster->corrosion_version,- 'corrosionGossipPort' => $cluster->corrosion_gossip_port,- 'corrosionApiPort' => $cluster->corrosion_api_port,- 'builderEnabled' => $cluster->builder_enabled,- 'builderCapacity' => $cluster->builder_capacity,- 'builderCpuQuota' => $cluster->builder_cpu_quota,- 'builderMemoryMax' => $cluster->builder_memory_max,- 'builderTimeoutSecs' => $cluster->builder_timeout_secs,- 'lastCliAction' => $cluster->last_cli_action,- 'lastCliStatus' => $cluster->last_cli_status,- 'lastCliSummary' => $cluster->last_cli_summary,- 'lastCliRanAt' => $cluster->last_cli_ran_at?->toJSON(),- 'serversCount' => $cluster->servers_count ?? $cluster->servers->count(),- 'servers' => $cluster->servers->map(fn (V5Server $server) => [- 'id' => (string) $server->id,- 'name' => $server->name,- 'host' => $server->host,- 'status' => $server->status,- 'capabilities' => $server->capabilities ?? [],- 'builderEnabled' => $server->builder_enabled,- 'builderCapacity' => $server->builder_capacity,- 'builderCpuQuota' => $server->builder_cpu_quota,- 'uuid' => $server->uuid,- 'nodeAddress' => $server->node_address,- 'wireguardListenPortOverride' => $server->wireguard_listen_port_override,- 'wireguardEndpointOverride' => $server->wireguard_endpoint_override,- 'wireguardManagementIp' => $server->wireguard_management_ip,- 'wireguardPublicKey' => $server->wireguard_public_key,- 'containerSubnets' => $server->container_subnets ?? [],- 'privateKeyName' => $server->privateKey?->name,- 'lastBootstrappedAt' => $server->last_bootstrapped_at?->toJSON(),- 'lastBootstrapAction' => $server->last_bootstrap_action,- 'lastBootstrapStatus' => $server->last_bootstrap_status,- 'lastBootstrapOutput' => $server->last_bootstrap_output,- 'lastBootstrapRanAt' => $server->last_bootstrap_ran_at?->toJSON(),- ])->all(),+ 'cluster' => $cluster instanceof V5Cluster ? app(ClusterSerializer::class)->serialize($cluster) : null,];}}diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.phpindex 58f21c7933..4b4df49711 100644--- a/app/Exceptions/Handler.php+++ b/app/Exceptions/Handler.php@@ -69,8 +69,9 @@ class Handler extends ExceptionHandler*/public function render($request, Throwable $e){- // Handle authorization exceptions for API routes- if ($e instanceof AuthorizationException) {+ // Handle authorization exceptions for API routes. Exceptions carrying+ // an explicit status (e.g. denyAsNotFound) keep it via parent::render.+ if ($e instanceof AuthorizationException && ! $e->hasStatus()) {if ($request->is('api/*') || $request->expectsJson()) {if ($request->is('api/*')) {auditLog('api.auth.policy_denied', [diff --git a/app/Exceptions/V5/UnsupportedCooldVerb.php b/app/Exceptions/V5/UnsupportedCooldVerb.phpnew file mode 100644index 0000000000..57a86dec51--- /dev/null+++ b/app/Exceptions/V5/UnsupportedCooldVerb.php@@ -0,0 +1,18 @@+<?php++namespace App\Exceptions\V5;++use RuntimeException;++/**+ * The per-node coold agent does not implement the dispatched verb. Flux+ * rejects these before they reach the node, so callers can degrade+ * gracefully instead of treating the miss as an operational failure.+ */+class UnsupportedCooldVerb extends RuntimeException+{+ public function __construct(public readonly string $verb, string $message = '')+ {+ parent::__construct($message !== '' ? $message : "The node's coold agent does not support the {$verb} verb.");+ }+}diff --git a/app/Http/Controllers/Api/Internal/FluxResourceStatusController.php b/app/Http/Controllers/Api/Internal/FluxResourceStatusController.phpindex 6828049578..1a6133e641 100644--- a/app/Http/Controllers/Api/Internal/FluxResourceStatusController.php+++ b/app/Http/Controllers/Api/Internal/FluxResourceStatusController.php@@ -12,9 +12,7 @@ class FluxResourceStatusController extends Controller{public function __invoke(Request $request): JsonResponse{- $token = config('flux.laravel_api_token');-- if (! is_string($token) || $token === '' || ! hash_equals($token, (string) $request->bearerToken())) {+ if (! $this->authorizedBearer($request)) {abort(401);}@@ -40,6 +38,7 @@ class FluxResourceStatusController extends Controller'state' => ['required_without:status', 'string', 'max:64'],'status_message' => ['nullable', 'string', 'max:1000'],'message' => ['nullable', 'string', 'max:1000'],+ 'observed_at' => ['nullable', 'string', 'date'],])->validate();$resource = ApplyFluxResourceStatusUpdate::run($validated);@@ -60,4 +59,53 @@ class FluxResourceStatusController extends Controller'message' => 'Resource status updated.',]);}++ /**+ * Constant-time match the presented bearer token against every accepted+ * inbound token. Accepting an array (config('flux.laravel_api_tokens'),+ * falling back to the single config('flux.laravel_api_token')) lets an+ * operator rotate by serving old+new tokens simultaneously.+ *+ * SECURITY: this is still a shared global secret — every flux instance+ * presents the same token, so it cannot be scoped or revoked per-flux, and+ * a leak forces a fleet-wide rotation. The target design is per-flux,+ * individually rotatable tokens; until then the array support above is the+ * mitigation that makes rotation possible without downtime.+ */+ private function authorizedBearer(Request $request): bool+ {+ $presented = (string) $request->bearerToken();++ if ($presented === '') {+ return false;+ }++ foreach ($this->acceptedTokens() as $token) {+ if (hash_equals($token, $presented)) {+ return true;+ }+ }++ return false;+ }++ /**+ * @return array<int, string>+ */+ private function acceptedTokens(): array+ {+ $tokens = config('flux.laravel_api_tokens', []);+ $tokens = is_array($tokens) ? $tokens : [];++ $single = config('flux.laravel_api_token');++ if (is_string($single) && $single !== '') {+ $tokens[] = $single;+ }++ return array_values(array_filter(+ array_map(fn ($token): string => is_string($token) ? $token : '', $tokens),+ fn (string $token): bool => $token !== ''+ ));+ }}diff --git a/app/Http/Controllers/V5/ApplicationController.php b/app/Http/Controllers/V5/ApplicationController.phpnew file mode 100644index 0000000000..8d11cd6b68--- /dev/null+++ b/app/Http/Controllers/V5/ApplicationController.php@@ -0,0 +1,635 @@+<?php++namespace App\Http\Controllers\V5;++use App\Actions\V5\Application\DestroyNginxApplication;+use App\Actions\V5\Proxy\StartCaddyIngress;+use App\Enums\V5\ApplicationStatus;+use App\Enums\V5\IngressStatus;+use App\Enums\V5\ServerStatus;+use App\Exceptions\V5\UnsupportedCooldVerb;+use App\Http\Controllers\Controller;+use App\Http\Controllers\V5\Concerns\HandlesIngressSyncErrors;+use App\Http\Controllers\V5\Concerns\ResolvesCurrentTeam;+use App\Http\Controllers\V5\Concerns\ResolvesProjectSelection;+use App\Http\Controllers\V5\Concerns\SerializesCanvasResources;+use App\Jobs\V5DeployApplicationJob;+use App\Models\Environment;+use App\Models\Project;+use App\Models\Team;+use App\Models\V5\Application as V5Application;+use App\Models\V5\ApplicationDomain as V5ApplicationDomain;+use App\Models\V5\ResourceConnection;+use App\Models\V5\Server as V5Server;+use App\Rules\ValidHostname;+use App\Services\Flux\FluxClient;+use App\Support\V5\CanvasResourceSerializer;+use App\Support\V5\ConnectionFirewallSync;+use App\Support\V5\StatusObservation;+use Carbon\CarbonImmutable;+use Illuminate\Database\Eloquent\Builder;+use Illuminate\Http\JsonResponse;+use Illuminate\Http\Request;+use Illuminate\Http\Response;+use Illuminate\Support\Collection;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Str;+use Illuminate\Validation\Rule;++class ApplicationController extends Controller+{+ use HandlesIngressSyncErrors;+ use ResolvesCurrentTeam;+ use ResolvesProjectSelection;+ use SerializesCanvasResources;++ private const DEFAULT_NGINX_IMAGE = 'docker.io/library/nginx:alpine';++ public function __construct(private readonly ConnectionFirewallSync $firewallSync) {}++ public function store(Request $request): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $projects = $this->projects($currentTeam);+ [$selectedProject, $selectedEnvironment] = $this->selectedProjectAndEnvironment($request, $projects);++ if ($selectedProject === null || $selectedEnvironment === null) {+ return response()->json([+ 'message' => 'Select a project and environment before deploying nginx.',+ ], 422);+ }++ $project = $this->projectQuery($currentTeam)+ ->where('uuid', $selectedProject['uuid'])+ ->first();++ if (! $project instanceof Project) {+ abort(403);+ }++ $environment = $this->selectedEnvironment($project, $selectedEnvironment['uuid']);++ if (! $environment instanceof Environment) {+ abort(403);+ }++ $validated = $request->validate([+ 'server_uuid' => ['nullable', 'string', 'max:255'],+ 'image' => ['nullable', 'string', 'max:255', 'regex:/^[a-zA-Z0-9][a-zA-Z0-9._\/:@-]*$/'],+ ]);+ $image = trim($validated['image'] ?? '') ?: self::DEFAULT_NGINX_IMAGE;++ $server = V5Server::query()+ ->where('team_id', $currentTeam->id)+ ->when(+ isset($validated['server_uuid']),+ fn (Builder $query) => $query->where('uuid', $validated['server_uuid']),+ fn (Builder $query) => $query+ ->orderByRaw('last_bootstrapped_at is null')+ ->orderBy('name')+ )+ ->first();++ if (! $server instanceof V5Server) {+ return response()->json([+ 'message' => 'Add a v5 server before deploying nginx.',+ ], 422);+ }++ if ($server->status !== ServerStatus::Installed->value || $server->last_bootstrapped_at === null) {+ return response()->json([+ 'message' => "Bootstrap server {$server->name} before deploying to it.",+ ], 422);+ }++ $canvasPosition = $this->nextApplicationCanvasPosition($currentTeam, $project, $environment);++ $application = V5Application::query()->create([+ 'team_id' => $currentTeam->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $request->user()->id,+ 'name' => 'nginx-test',+ 'image' => $image,+ 'container_name' => 'coolify-v5-nginx-'.strtolower((string) Str::ulid()),+ 'status' => ApplicationStatus::Creating->value,+ 'status_message' => 'Starting nginx container.',+ 'mesh_namespace' => 'default',+ 'canvas_x' => $canvasPosition['canvas_x'],+ 'canvas_y' => $canvasPosition['canvas_y'],+ ]);++ V5DeployApplicationJob::dispatch($application->id);++ return response()->json([+ 'application' => $this->serializeApplication($application),+ ], 202);+ }++ public function refresh(Request $request, FluxClient $fluxClient): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $projects = $this->projects($currentTeam);+ [$selectedProject, $selectedEnvironment] = $this->selectedProjectAndEnvironment($request, $projects);++ if ($selectedProject === null || $selectedEnvironment === null) {+ return response()->json([+ 'message' => 'Select a project and environment before refreshing applications.',+ ], 422);+ }++ $applications = $this->applicationQuery($currentTeam, $selectedProject, $selectedEnvironment)+ ->with('server')+ ->get();+ $errors = [];++ $applications+ ->groupBy('server_id')+ ->each(function (Collection $serverApplications) use ($fluxClient, &$errors): void {+ /** @var V5Application|null $firstApplication */+ $firstApplication = $serverApplications->first();+ $server = $firstApplication?->server;+ $hostId = $server?->fluxHostId();++ if (! $server instanceof V5Server || ! is_string($hostId) || $hostId === '') {+ $errors[] = 'A server is missing its Flux host id.';++ return;+ }++ // The moment we query coold is the observation time for the rows+ // this refresh writes, so a fresher webhook always wins the+ // status_observed_at watermark and is never clobbered.+ $observedAt = CarbonImmutable::now();++ try {+ $containers = collect($fluxClient->listContainers($hostId));+ } catch (\Throwable $e) {+ $errors[] = $e->getMessage();++ return;+ }++ $serverApplications->each(function (V5Application $application) use ($containers, $observedAt): void {+ $container = $containers->first(function (array $container) use ($application): bool {+ return ($application->runtime_container_id !== null && ($container['id'] ?? null) === $application->runtime_container_id)+ || ($container['name'] ?? null) === $application->container_name;+ });++ if (! is_array($container)) {+ // A creating application without a container id simply has+ // not materialized yet; the deploy job will settle it.+ if ($application->status === ApplicationStatus::Creating->value && $application->runtime_container_id === null) {+ return;+ }++ if (StatusObservation::isStale($observedAt, $application->status_observed_at, 'application status', ['application_id' => $application->id])) {+ return;+ }++ $application->update([+ 'status' => ApplicationStatus::Exited->value,+ 'status_message' => 'Container not found on server.',+ 'status_observed_at' => $observedAt,+ ]);++ return;+ }++ if (StatusObservation::isStale($observedAt, $application->status_observed_at, 'application status', ['application_id' => $application->id])) {+ return;+ }++ $rawState = is_string($container['state'] ?? null) && $container['state'] !== '' ? $container['state'] : null;++ $application->update([+ 'status' => StatusObservation::normalize($rawState, ApplicationStatus::class) ?? ApplicationStatus::Unknown->value,+ 'status_message' => 'Container state refreshed from coold.',+ 'status_observed_at' => $observedAt,+ 'runtime_container_id' => is_string($container['id'] ?? null) ? $container['id'] : $application->runtime_container_id,+ ]);+ });+ });++ V5Server::query()+ ->where('team_id', $currentTeam->id)+ ->orderBy('name')+ ->get()+ ->filter(fn (V5Server $server) => $server->isIngress())+ ->each(function (V5Server $server) use ($fluxClient, &$errors): void {+ $hostId = $server->fluxHostId();++ if (! is_string($hostId) || $hostId === '') {+ $errors[] = "Caddy ingress server {$server->name} is missing its Flux host id.";++ return;+ }++ try {+ $containers = collect($fluxClient->listContainers($hostId));+ } catch (\Throwable $e) {+ $errors[] = $e->getMessage();++ return;+ }++ $container = $containers->first(fn (array $container) => ($container['name'] ?? null) === 'coolify-v5-caddy');+ $rawState = is_array($container) && is_string($container['state'] ?? null) && $container['state'] !== '' ? $container['state'] : null;+ $state = $rawState !== null+ ? (StatusObservation::normalize($rawState, IngressStatus::class) ?? IngressStatus::Unknown->value)+ : IngressStatus::Exited->value;++ $server->update([+ 'ingress_type' => 'caddy',+ 'ingress_status' => $state,+ 'last_status_check' => 'flux',+ 'last_status_output' => 'Caddy ingress state refreshed from coold.',+ 'last_status_checked_at' => now(),+ ]);+ });++ return response()->json([+ 'applications' => $this->applicationQuery($currentTeam, $selectedProject, $selectedEnvironment)+ ->with('server')+ ->orderBy('created_at')+ ->get()+ ->map(fn (V5Application $application) => $this->serializeApplication($application))+ ->all(),+ 'caddyIngresses' => $this->caddyIngresses($currentTeam),+ 'errors' => $errors,+ ]);+ }++ public function logs(Request $request, V5Application $application): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('view', [$application, $currentTeam]);++ $application->loadMissing('server');+ $server = $application->server;+ $hostId = $server?->fluxHostId();+ $containerId = $application->runtime_container_id;++ $logs = null;+ $logsError = null;++ // A container id only appears once the deploy actually created one; a+ // deploy that failed before that (e.g. host not connected) has none, so+ // there is nothing to fetch and the frontend just shows the status.+ if (is_string($containerId) && $containerId !== '' && $server instanceof V5Server && $server->status !== ServerStatus::Unreachable->value && is_string($hostId) && $hostId !== '') {+ try {+ $logs = app(FluxClient::class)->containerLogs($hostId, $containerId);+ } catch (UnsupportedCooldVerb $exception) {+ $logsError = "This node's coold does not support container logs.";+ } catch (\RuntimeException $exception) {+ Log::warning('V5 application container logs request failed', [+ 'application_id' => $application->id,+ 'message' => $exception->getMessage(),+ ]);+ $logsError = 'Could not fetch container logs through Flux. Check the Flux and coold status, then try again.';+ }+ }++ return response()->json([+ 'status' => $application->status,+ 'statusMessage' => $application->status_message,+ 'containerId' => $containerId,+ 'logs' => $logs,+ 'logsError' => $logsError,+ ]);+ }++ public function updatePosition(Request $request, V5Application $application): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('update', [$application, $currentTeam]);++ $validated = $request->validate([+ 'canvas_x' => ['required', 'integer', 'min:-100000', 'max:100000'],+ 'canvas_y' => ['required', 'integer', 'min:-100000', 'max:100000'],+ ]);++ $application->update([+ 'canvas_x' => $validated['canvas_x'],+ 'canvas_y' => $validated['canvas_y'],+ ]);++ return response()->json([+ 'application' => $this->serializeApplication($application->refresh()->load('server')),+ ]);+ }++ public function updateIngress(Request $request, V5Application $application): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('updateIngress', [$application, $currentTeam]);++ $validated = $request->validate([+ 'ingress_enabled' => ['required', 'boolean'],+ 'internal_port' => ['nullable', 'integer', 'min:1', 'max:65535'],+ 'domains' => [Rule::requiredIf(fn () => $request->boolean('ingress_enabled')), 'array', 'min:1'],+ 'domains.*' => ['required', 'string', 'max:255', 'distinct:ignore_case', new ValidHostname],+ ]);++ $application->loadMissing('server');++ if ($validated['ingress_enabled'] && ! $application->server?->isIngress()) {+ return response()->json([+ 'message' => 'Enable ingress on the server before enabling app ingress.',+ ], 422);+ }++ if ($validated['ingress_enabled'] && array_key_exists('domains', $validated)) {+ $conflict = $this->conflictingApplicationDomain($application, $validated['domains']);++ if ($conflict instanceof V5ApplicationDomain) {+ return response()->json([+ 'message' => "The domain {$conflict->domain} is already used by application \"{$conflict->application?->name}\" on this server.",+ ], 422);+ }+ }++ $originalAttributes = $application->only(['ingress_enabled', 'internal_port']);+ $originalDomains = $application->domains()->pluck('domain')->all();++ DB::transaction(function () use ($application, $validated): void {+ $application->update([+ 'ingress_enabled' => $validated['ingress_enabled'],+ 'internal_port' => $validated['internal_port'] ?? null,+ ]);++ if (array_key_exists('domains', $validated)) {+ $application->domains()->delete();++ collect($validated['domains'])+ ->map(fn (string $domain) => trim($domain))+ ->filter()+ ->unique()+ ->each(fn (string $domain) => V5ApplicationDomain::query()->create([+ 'application_id' => $application->id,+ 'domain' => $domain,+ ]));+ }+ });++ $application->refresh()->load(['server', 'domains']);++ if ($application->server?->isIngress() && $application->server->status === ServerStatus::Installed->value) {+ try {+ StartCaddyIngress::run($application->server);+ } catch (\RuntimeException $exception) {+ $this->restoreApplicationIngress($application, $originalAttributes, $originalDomains);++ return $this->ingressSyncErrorResponse($exception);+ }+ }++ return response()->json([+ 'application' => $this->serializeApplication($application),+ ]);+ }++ public function updateCaddyIngressPosition(Request $request, V5Server $server): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('updateCanvasPosition', [$server, $currentTeam]);++ $validated = $request->validate([+ 'canvas_x' => ['required', 'integer', 'min:-100000', 'max:100000'],+ 'canvas_y' => ['required', 'integer', 'min:-100000', 'max:100000'],+ ]);++ $server->update([+ 'canvas_x' => $validated['canvas_x'],+ 'canvas_y' => $validated['canvas_y'],+ ]);++ return response()->json([+ 'caddyIngress' => $this->serializeCaddyIngress($server->refresh()),+ ]);+ }++ public function destroy(Request $request, V5Application $application, FluxClient $fluxClient): Response|JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('delete', [$application, $currentTeam]);++ $application->loadMissing(['server', 'domains']);+ $server = $application->server;+ $connections = $this->applicationResourceConnections($application);++ if ($request->boolean('delete_locally')) {+ $this->deleteApplicationLocally($application, $connections);++ return response()->noContent();+ }+ $oldFirewallRules = $connections+ ->flatMap(function (ResourceConnection $connection): Collection {+ // Deletion must never be blocked by an endpoint that already lost+ // its server; those rules can no longer be revoked anyway.+ try {+ return $this->firewallSync->rulesFor($connection->load('rules'));+ } catch (\RuntimeException $exception) {+ report($exception);++ return collect();+ }+ });+ $originalIngressAttributes = null;+ $originalIngressDomains = [];+ $ingressConfigurationChanged = false;++ try {+ $this->firewallSync->sync($fluxClient, $oldFirewallRules, collect());+ } catch (\RuntimeException $exception) {+ report($exception);++ return response()->json([+ 'message' => 'Could not sync firewall rules through Flux.',+ 'detail' => $exception->getMessage(),+ ], 502);+ }++ if ($server instanceof V5Server && $server->isIngress() && $server->status === ServerStatus::Installed->value && $application->ingress_enabled) {+ $originalIngressAttributes = $application->only(['ingress_enabled', 'internal_port']);+ $originalIngressDomains = $application->domains()->pluck('domain')->all();++ DB::transaction(function () use ($application): void {+ $application->update([+ 'ingress_enabled' => false,+ 'internal_port' => null,+ ]);+ $application->domains()->delete();+ });++ try {+ StartCaddyIngress::run($server);+ $ingressConfigurationChanged = true;+ } catch (\RuntimeException $exception) {+ $this->restoreApplicationIngress($application, $originalIngressAttributes, $originalIngressDomains);++ return $this->ingressSyncErrorResponse($exception);+ }+ }++ $error = DestroyNginxApplication::run($application);++ if ($error !== null) {+ if ($originalIngressAttributes !== null) {+ $this->restoreApplicationIngress($application, $originalIngressAttributes, $originalIngressDomains);++ if ($ingressConfigurationChanged && $server instanceof V5Server) {+ try {+ StartCaddyIngress::run($server);+ } catch (\RuntimeException $exception) {+ report($exception);+ }+ }+ }++ try {+ $this->firewallSync->sync($fluxClient, collect(), $oldFirewallRules);+ } catch (\RuntimeException $exception) {+ report($exception);+ }++ return response()->json([+ 'message' => $error,+ 'can_delete_locally' => true,+ ], 422);+ }++ $this->deleteApplicationLocally($application, $connections);++ return response()->noContent();+ }++ /**+ * @param Collection<int, ResourceConnection> $connections+ */+ private function deleteApplicationLocally(V5Application $application, Collection $connections): void+ {+ DB::transaction(function () use ($application, $connections): void {+ $connections->each(function (ResourceConnection $connection): void {+ $connection->rules()->delete();+ $connection->delete();+ });++ $application->delete();+ });+ }++ /**+ * @return Collection<int, ResourceConnection>+ */+ private function applicationResourceConnections(V5Application $application): Collection+ {+ return ResourceConnection::query()+ ->where('team_id', $application->team_id)+ ->where(function (Builder $query) use ($application): void {+ $query+ ->where(function (Builder $query) use ($application): void {+ $query+ ->where('resource_one_type', $application->getMorphClass())+ ->where('resource_one_id', $application->id);+ })+ ->orWhere(function (Builder $query) use ($application): void {+ $query+ ->where('resource_two_type', $application->getMorphClass())+ ->where('resource_two_id', $application->id);+ });+ })+ ->with('rules')+ ->get();+ }++ /**+ * @return array{canvas_x: int, canvas_y: int}+ */+ private function nextApplicationCanvasPosition(Team $currentTeam, Project $project, Environment $environment): array+ {+ $existingApplications = V5Application::query()+ ->where('team_id', $currentTeam->id)+ ->where('project_id', $project->id)+ ->where('environment_id', $environment->id)+ ->get(['canvas_x', 'canvas_y']);++ $horizontalStep = CanvasResourceSerializer::CARD_WIDTH + CanvasResourceSerializer::CARD_GAP;+ $verticalStep = CanvasResourceSerializer::CARD_HEIGHT + CanvasResourceSerializer::CARD_GAP;++ for ($row = 0; $row < 100; $row++) {+ for ($column = 0; $column < 100; $column++) {+ $candidate = [+ 'canvas_x' => $column * $horizontalStep,+ 'canvas_y' => $row * $verticalStep,+ ];++ if (! $this->canvasPositionCollides($candidate, $existingApplications)) {+ return $candidate;+ }+ }+ }++ return [+ 'canvas_x' => $existingApplications->max('canvas_x') + $horizontalStep,+ 'canvas_y' => 0,+ ];+ }++ /**+ * @param array{canvas_x: int, canvas_y: int} $candidate+ * @param Collection<int, V5Application> $existingApplications+ */+ private function canvasPositionCollides(array $candidate, Collection $existingApplications): bool+ {+ return $existingApplications->contains(function (V5Application $application) use ($candidate) {+ return abs($candidate['canvas_x'] - $application->canvas_x) < CanvasResourceSerializer::CARD_WIDTH + CanvasResourceSerializer::CARD_GAP+ && abs($candidate['canvas_y'] - $application->canvas_y) < CanvasResourceSerializer::CARD_HEIGHT + CanvasResourceSerializer::CARD_GAP;+ });+ }++ /**+ * @param array<int, string> $domains+ */+ private function conflictingApplicationDomain(V5Application $application, array $domains): ?V5ApplicationDomain+ {+ $normalizedDomains = collect($domains)+ ->map(fn (string $domain) => Str::lower(trim($domain)))+ ->filter()+ ->values();++ if ($normalizedDomains->isEmpty()) {+ return null;+ }++ return V5ApplicationDomain::query()+ ->whereIn(DB::raw('LOWER(domain)'), $normalizedDomains->all())+ ->whereHas('application', fn (Builder $query) => $query+ ->where('server_id', $application->server_id)+ ->whereKeyNot($application->id)+ ->where('ingress_enabled', true))+ ->with('application:id,name')+ ->first();+ }++ /**+ * @param array<string, mixed> $attributes+ * @param array<int, string> $domains+ */+ private function restoreApplicationIngress(V5Application $application, array $attributes, array $domains): void+ {+ DB::transaction(function () use ($application, $attributes, $domains): void {+ $application->update($attributes);+ $application->domains()->delete();++ foreach ($domains as $domain) {+ V5ApplicationDomain::query()->create([+ 'application_id' => $application->id,+ 'domain' => $domain,+ ]);+ }+ });+ }+}diff --git a/app/Http/Controllers/V5/ClusterController.php b/app/Http/Controllers/V5/ClusterController.phpnew file mode 100644index 0000000000..5477a893cd--- /dev/null+++ b/app/Http/Controllers/V5/ClusterController.php@@ -0,0 +1,207 @@+<?php++namespace App\Http\Controllers\V5;++use App\Http\Controllers\Controller;+use App\Http\Controllers\V5\Concerns\ResolvesCurrentTeam;+use App\Http\Controllers\V5\Concerns\ResolvesProjectSelection;+use App\Http\Controllers\V5\Concerns\ValidatesBuilderConfiguration;+use App\Models\PrivateKey;+use App\Models\Team;+use App\Models\V5\Cluster as V5Cluster;+use App\Services\Flux\FluxHealth;+use App\Support\V5\ClusterSerializer;+use Illuminate\Http\JsonResponse;+use Illuminate\Http\Request;+use Illuminate\Validation\Rule;+use Inertia\Inertia;+use Inertia\Response;++class ClusterController extends Controller+{+ use ResolvesCurrentTeam;+ use ResolvesProjectSelection;+ use ValidatesBuilderConfiguration;++ public function index(Request $request, FluxHealth $fluxHealth): Response+ {+ $currentTeam = $request->attributes->get('v5.currentTeam');+ $projects = $this->projects($currentTeam);+ [$selectedProject, $selectedEnvironment] = $this->selectedProjectAndEnvironment($request, $projects);++ return Inertia::render('Clusters', [+ 'currentTeam' => $this->serializeCurrentTeam($currentTeam),+ 'flux' => $fluxHealth->check(),+ 'clusters' => $this->clusters($currentTeam),+ 'privateKeys' => $this->privateKeys($currentTeam),+ 'projects' => $projects,+ 'selectedProjectUuid' => $selectedProject['uuid'] ?? null,+ 'selectedEnvironmentUuid' => $selectedEnvironment['uuid'] ?? null,+ ]);+ }++ public function show(Request $request, V5Cluster $cluster): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('view', [$cluster, $currentTeam]);++ return response()->json([+ 'cluster' => app(ClusterSerializer::class)->serializeFresh($cluster),+ ]);+ }++ public function store(Request $request): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('create', [V5Cluster::class, $currentTeam]);++ $validated = $request->validate([+ 'name' => [+ 'required',+ 'string',+ 'max:255',+ Rule::unique('v5_clusters', 'name')->where('team_id', $currentTeam->id),+ ],+ 'description' => ['nullable', 'string', 'max:1000'],+ 'wireguard_interface' => ['sometimes', 'string', 'max:32', 'regex:/^[a-zA-Z0-9_.-]+$/'],+ 'wireguard_management_pool' => ['sometimes', 'string', 'max:64', $this->ipv4CidrRule()],+ 'wireguard_listen_port' => ['sometimes', 'integer', 'min:1', 'max:65535'],+ 'container_network_pool' => ['sometimes', 'string', 'max:64', $this->ipv4CidrRule()],+ 'container_network_prefix' => ['sometimes', 'integer', 'min:1', 'max:32'],+ 'namespaces' => ['sometimes', 'array', 'min:1'],+ 'namespaces.*' => ['string', 'distinct', 'regex:/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/'],+ 'default_deny_containers' => ['sometimes', 'boolean'],+ 'coold_version' => ['sometimes', 'string', 'max:64'],+ 'corrosion_version' => ['sometimes', 'string', 'max:64'],+ 'corrosion_gossip_port' => ['sometimes', 'integer', 'min:1', 'max:65535'],+ 'corrosion_api_port' => ['sometimes', 'integer', 'min:1', 'max:65535'],+ 'builder_enabled' => ['sometimes', 'boolean'],+ 'builder_capacity' => $this->builderCapacityRules(+ $this->requestedBuilderEnabled($request, true)+ ),+ 'builder_cpu_quota' => ['sometimes', 'string', 'max:32'],+ 'builder_memory_max' => ['sometimes', 'string', 'max:32'],+ 'builder_timeout_secs' => ['sometimes', 'integer', 'min:1', 'max:86400'],+ ]);++ $cluster = V5Cluster::query()->create([+ ...$this->defaultClusterConfiguration(),+ ...collect($validated)->except(['name', 'description'])->all(),+ 'team_id' => $currentTeam->id,+ 'created_by_user_id' => $request->user()->id,+ 'name' => $validated['name'],+ 'description' => $validated['description'] ?? null,+ ]);++ return response()->json([+ 'cluster' => app(ClusterSerializer::class)->serializeFresh($cluster),+ ], 201);+ }++ public function destroy(Request $request, V5Cluster $cluster): \Illuminate\Http\Response|JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('delete', [$cluster, $currentTeam]);++ if ($cluster->servers()->exists()) {+ return response()->json([+ 'message' => 'Only empty clusters can be deleted.',+ ], 422);+ }++ $cluster->delete();++ return response()->noContent();+ }++ /**+ * @return array<int, array<string, mixed>>+ */+ private function clusters(mixed $currentTeam): array+ {+ if (! $currentTeam instanceof Team) {+ return [];+ }++ $serializer = app(ClusterSerializer::class);++ return V5Cluster::query()+ ->where('team_id', $currentTeam->id)+ ->with(['servers' => fn ($query) => $query+ ->with('privateKey')+ ->orderBy('name')])+ ->withCount('servers')+ ->orderBy('name')+ ->get()+ ->map(fn (V5Cluster $cluster) => $serializer->serialize($cluster))+ ->all();+ }++ /**+ * @return array<int, array{id: string, name: string}>+ */+ private function privateKeys(mixed $currentTeam): array+ {+ if (! $currentTeam instanceof Team) {+ return [];+ }++ return PrivateKey::query()+ ->where('team_id', $currentTeam->id)+ ->where('is_git_related', false)+ ->orderBy('name')+ ->get(['id', 'uuid', 'name'])+ ->map(fn (PrivateKey $privateKey) => [+ 'id' => $privateKey->uuid,+ 'name' => $privateKey->name,+ ])+ ->all();+ }++ /**+ * @return array<string, mixed>+ */+ private function defaultClusterConfiguration(): array+ {+ return [+ 'wireguard_interface' => V5Cluster::DEFAULT_WIREGUARD_INTERFACE,+ 'wireguard_management_pool' => V5Cluster::DEFAULT_WIREGUARD_MANAGEMENT_POOL,+ 'wireguard_listen_port' => V5Cluster::DEFAULT_WIREGUARD_LISTEN_PORT,+ 'container_network_pool' => V5Cluster::DEFAULT_CONTAINER_NETWORK_POOL,+ 'container_network_prefix' => V5Cluster::DEFAULT_CONTAINER_NETWORK_PREFIX,+ 'namespaces' => V5Cluster::DEFAULT_NAMESPACES,+ 'default_deny_containers' => true,+ 'coold_version' => V5Cluster::DEFAULT_COOLD_VERSION,+ 'corrosion_version' => V5Cluster::DEFAULT_CORROSION_VERSION,+ 'corrosion_gossip_port' => V5Cluster::DEFAULT_CORROSION_GOSSIP_PORT,+ 'corrosion_api_port' => V5Cluster::DEFAULT_CORROSION_API_PORT,+ 'builder_enabled' => true,+ 'builder_capacity' => V5Cluster::DEFAULT_BUILDER_CAPACITY,+ 'builder_cpu_quota' => V5Cluster::DEFAULT_BUILDER_CPU_QUOTA,+ 'builder_memory_max' => V5Cluster::DEFAULT_BUILDER_MEMORY_MAX,+ 'builder_timeout_secs' => V5Cluster::DEFAULT_BUILDER_TIMEOUT_SECS,+ ];+ }++ private function ipv4CidrRule(): \Closure+ {+ return function (string $attribute, mixed $value, \Closure $fail): void {+ if (! is_string($value) || ! str_contains($value, '/')) {+ $fail('The :attribute must be a valid IPv4 CIDR range.');++ return;+ }++ [$ip, $prefix] = explode('/', $value, 2);++ if (+ filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false+ || ! ctype_digit($prefix)+ || (int) $prefix < 0+ || (int) $prefix > 32+ ) {+ $fail('The :attribute must be a valid IPv4 CIDR range.');+ }+ };+ }+}diff --git a/app/Http/Controllers/V5/Concerns/HandlesIngressSyncErrors.php b/app/Http/Controllers/V5/Concerns/HandlesIngressSyncErrors.phpnew file mode 100644index 0000000000..94ccc1b52d--- /dev/null+++ b/app/Http/Controllers/V5/Concerns/HandlesIngressSyncErrors.php@@ -0,0 +1,40 @@+<?php++namespace App\Http\Controllers\V5\Concerns;++use Illuminate\Http\JsonResponse;+use Illuminate\Support\Str;++trait HandlesIngressSyncErrors+{+ protected function ingressSyncErrorResponse(\RuntimeException $exception): JsonResponse+ {+ return response()->json([+ 'message' => $this->friendlyIngressSyncError($exception->getMessage()),+ 'detail' => $exception->getMessage(),+ ], 502);+ }++ protected function friendlyIngressSyncError(string $message): string+ {+ $normalized = Str::lower($message);++ if (str_contains($normalized, 'invalid http response') || str_contains($normalized, 'could not talk to flux')) {+ return 'Could not reach Flux. Check that Flux is running in the Coolify container and try again.';+ }++ if (str_contains($normalized, 'dispatch timeout') || str_contains($normalized, 'timed out')) {+ return 'coold did not respond in time. Check that the server agent is running and connected to Flux.';+ }++ if (str_contains($normalized, 'validate caddyfile')) {+ return 'Caddy rejected the generated ingress configuration. Check the domains and internal port, then try again.';+ }++ if (str_contains($normalized, 'start caddy ingress') || str_contains($normalized, 'reload caddy ingress')) {+ return 'Could not start Caddy ingress on the server. Check that Podman is running and port 80 is available.';+ }++ return 'Could not update ingress. Check Flux and coold logs, then try again.';+ }+}diff --git a/app/Http/Controllers/V5/Concerns/ResolvesCurrentTeam.php b/app/Http/Controllers/V5/Concerns/ResolvesCurrentTeam.phpnew file mode 100644index 0000000000..915cf373b3--- /dev/null+++ b/app/Http/Controllers/V5/Concerns/ResolvesCurrentTeam.php@@ -0,0 +1,22 @@+<?php++namespace App\Http\Controllers\V5\Concerns;++use App\Models\Team;+use Illuminate\Http\Request;++trait ResolvesCurrentTeam+{+ /**+ * Resolve the current team set by the EnsureCurrentTeam middleware, or+ * abort with a 404 so resources outside the team stay invisible.+ */+ protected function currentTeamOrFail(Request $request): Team+ {+ $currentTeam = $request->attributes->get('v5.currentTeam');++ abort_unless($currentTeam instanceof Team, 404);++ return $currentTeam;+ }+}diff --git a/app/Http/Controllers/V5/Concerns/ResolvesProjectSelection.php b/app/Http/Controllers/V5/Concerns/ResolvesProjectSelection.phpnew file mode 100644index 0000000000..1d48eff33e--- /dev/null+++ b/app/Http/Controllers/V5/Concerns/ResolvesProjectSelection.php@@ -0,0 +1,115 @@+<?php++namespace App\Http\Controllers\V5\Concerns;++use App\Models\Environment;+use App\Models\Project;+use App\Models\Team;+use Illuminate\Database\Eloquent\Builder;+use Illuminate\Http\Request;++trait ResolvesProjectSelection+{+ protected const SELECTED_PROJECT_SESSION_KEY = 'v5.selectedProjectUuid';++ protected const SELECTED_ENVIRONMENT_SESSION_KEY = 'v5.selectedEnvironmentUuid';++ /**+ * @return array{id: int}|null+ */+ protected function serializeCurrentTeam(mixed $currentTeam): ?array+ {+ if (! $currentTeam instanceof Team) {+ return null;+ }++ return [+ 'id' => $currentTeam->id,+ ];+ }++ /**+ * @param array<int, array{uuid: string, name: string, environments: array<int, array{uuid: string, name: string}>}> $projects+ * @return array{0: array{uuid: string, name: string, environments: array<int, array{uuid: string, name: string}>}|null, 1: array{uuid: string, name: string}|null}+ */+ protected function selectedProjectAndEnvironment(Request $request, array $projects): array+ {+ $selectedProjectUuid = $request->session()->get(self::SELECTED_PROJECT_SESSION_KEY);+ $selectedEnvironmentUuid = $request->session()->get(self::SELECTED_ENVIRONMENT_SESSION_KEY);+ $selectedProject = null;++ foreach ($projects as $project) {+ if ($project['uuid'] === $selectedProjectUuid) {+ $selectedProject = $project;++ break;+ }+ }++ $selectedProject ??= $projects[0] ?? null;+ $selectedEnvironment = null;++ foreach ($selectedProject['environments'] ?? [] as $environment) {+ if ($environment['uuid'] === $selectedEnvironmentUuid) {+ $selectedEnvironment = $environment;++ break;+ }+ }++ $selectedEnvironment ??= $selectedProject['environments'][0] ?? null;++ return [$selectedProject, $selectedEnvironment];+ }++ protected function selectedEnvironment(Project $project, ?string $environmentUuid): ?Environment+ {+ if ($environmentUuid === null) {+ return $project->environments->first();+ }++ $environment = $project->environments->firstWhere('uuid', $environmentUuid);++ if (! $environment instanceof Environment) {+ abort(422, 'The selected environment is not available for the selected project.');+ }++ return $environment;+ }++ /**+ * @return array<int, array{uuid: string, name: string, environments: array<int, array{uuid: string, name: string}>}>+ */+ protected function projects(mixed $currentTeam): array+ {+ if (! $currentTeam instanceof Team) {+ return [];+ }++ return $this->projectQuery($currentTeam)+ ->get()+ ->map(fn (Project $project) => [+ 'uuid' => $project->uuid,+ 'name' => $project->name,+ 'environments' => $project->environments+ ->map(fn ($environment) => [+ 'uuid' => $environment->uuid,+ 'name' => $environment->name,+ ])+ ->all(),+ ])+ ->all();+ }++ protected function projectQuery(Team $currentTeam): Builder+ {+ return Project::query()+ ->select(['id', 'uuid', 'name', 'team_id'])+ ->where('team_id', $currentTeam->id)+ ->with(['environments' => fn ($query) => $query+ ->select(['id', 'uuid', 'name', 'project_id'])+ ->orderByRaw("CASE WHEN LOWER(name) = 'production' THEN 0 ELSE 1 END")+ ->orderByRaw('LOWER(name)')])+ ->orderByRaw('LOWER(name)');+ }+}diff --git a/app/Http/Controllers/V5/Concerns/SerializesCanvasResources.php b/app/Http/Controllers/V5/Concerns/SerializesCanvasResources.phpnew file mode 100644index 0000000000..5dc02e8009--- /dev/null+++ b/app/Http/Controllers/V5/Concerns/SerializesCanvasResources.php@@ -0,0 +1,63 @@+<?php++namespace App\Http\Controllers\V5\Concerns;++use App\Models\Team;+use App\Models\V5\Application as V5Application;+use App\Models\V5\Server as V5Server;+use App\Support\V5\CanvasResourceSerializer;+use Illuminate\Database\Eloquent\Builder;++trait SerializesCanvasResources+{+ /**+ * @return array<string, mixed>+ */+ protected function serializeApplication(V5Application $application): array+ {+ return app(CanvasResourceSerializer::class)->serializeApplication($application);+ }++ /**+ * @return array<string, mixed>+ */+ protected function serializeCaddyIngress(V5Server $server, int $index = 0): array+ {+ return app(CanvasResourceSerializer::class)->serializeCaddyIngress($server, $index);+ }++ /**+ * @return array<int, array<string, mixed>>+ */+ protected function caddyIngresses(mixed $currentTeam): array+ {+ if (! $currentTeam instanceof Team) {+ return [];+ }++ return V5Server::query()+ ->where('team_id', $currentTeam->id)+ ->orderBy('name')+ ->get()+ ->filter(fn (V5Server $server) => $server->isIngress())+ ->values()+ ->map(fn (V5Server $server, int $index) => $this->serializeCaddyIngress($server, $index))+ ->all();+ }++ /**+ * @param array{uuid: string} $selectedProject+ * @param array{uuid: string} $selectedEnvironment+ * @return Builder<V5Application>+ */+ protected function applicationQuery(Team $currentTeam, array $selectedProject, array $selectedEnvironment): Builder+ {+ return V5Application::query()+ ->where('team_id', $currentTeam->id)+ ->whereHas('project', fn (Builder $query) => $query+ ->where('team_id', $currentTeam->id)+ ->where('uuid', $selectedProject['uuid']))+ ->whereHas('environment', fn (Builder $query) => $query+ ->where('uuid', $selectedEnvironment['uuid']));+ }+}diff --git a/app/Http/Controllers/V5/Concerns/ValidatesBuilderConfiguration.php b/app/Http/Controllers/V5/Concerns/ValidatesBuilderConfiguration.phpnew file mode 100644index 0000000000..ff97c272f8--- /dev/null+++ b/app/Http/Controllers/V5/Concerns/ValidatesBuilderConfiguration.php@@ -0,0 +1,30 @@+<?php++namespace App\Http\Controllers\V5\Concerns;++use Illuminate\Http\Request;++trait ValidatesBuilderConfiguration+{+ /**+ * @return array<int, string>+ */+ protected function builderCapacityRules(bool $builderEnabled, bool $required = false): array+ {+ return [+ $required ? 'required' : 'sometimes',+ 'integer',+ $builderEnabled ? 'min:1' : 'min:0',+ 'max:1000',+ ];+ }++ protected function requestedBuilderEnabled(Request $request, bool $default): bool+ {+ if (! $request->has('builder_enabled')) {+ return $default;+ }++ return $request->boolean('builder_enabled');+ }+}diff --git a/app/Http/Controllers/V5/DashboardController.php b/app/Http/Controllers/V5/DashboardController.phpindex d46a2ad046..9f5e267368 100644--- a/app/Http/Controllers/V5/DashboardController.php+++ b/app/Http/Controllers/V5/DashboardController.php@@ -2,51 +2,31 @@namespace App\Http\Controllers\V5;-use App\Actions\V5\Application\DeployNginxApplication;-use App\Actions\V5\Application\DestroyNginxApplication;-use App\Actions\V5\Proxy\StartCaddyIngress;-use App\Actions\V5\Proxy\StopCaddyIngress;-use App\Events\V5ClusterUpdated;use App\Events\V5RealtimeTestEvent;use App\Http\Controllers\Controller;-use App\Jobs\V5BootstrapServerJob;-use App\Models\Environment;-use App\Models\PrivateKey;+use App\Http\Controllers\V5\Concerns\ResolvesCurrentTeam;+use App\Http\Controllers\V5\Concerns\ResolvesProjectSelection;+use App\Http\Controllers\V5\Concerns\SerializesCanvasResources;use App\Models\Project;use App\Models\Team;use App\Models\V5\Application as V5Application;-use App\Models\V5\ApplicationDomain as V5ApplicationDomain;-use App\Models\V5\Cluster as V5Cluster;use App\Models\V5\ResourceConnection;use App\Models\V5\Server as V5Server;-use App\Rules\ValidHostname;-use App\Services\Flux\FluxClient;use App\Services\Flux\FluxHealth;+use App\Support\V5\ResourceConnectionSerializer;use Illuminate\Database\Eloquent\Builder;-use Illuminate\Database\Eloquent\Model;use Illuminate\Http\JsonResponse;use Illuminate\Http\Request;-use Illuminate\Support\Collection;-use Illuminate\Support\Facades\DB;-use Illuminate\Support\Facades\Process;-use Illuminate\Support\Str;-use Illuminate\Validation\Rule;use Inertia\Inertia;use Inertia\Response;class DashboardController extends Controller{- private const DEFAULT_NGINX_IMAGE = 'docker.io/library/nginx:alpine';+ use ResolvesCurrentTeam;+ use ResolvesProjectSelection;+ use SerializesCanvasResources;- private const CANVAS_CARD_WIDTH = 320;-- private const CANVAS_CARD_HEIGHT = 144;-- private const CANVAS_CARD_GAP = 32;-- private const SELECTED_PROJECT_SESSION_KEY = 'v5.selectedProjectUuid';-- private const SELECTED_ENVIRONMENT_SESSION_KEY = 'v5.selectedEnvironmentUuid';+ public function __construct(private readonly ResourceConnectionSerializer $connectionSerializer) {}public function __invoke(Request $request, FluxHealth $fluxHealth): Response{@@ -67,43 +47,9 @@ class DashboardController extends Controller]);}- public function clustersIndex(Request $request, FluxHealth $fluxHealth): Response- {- $currentTeam = $request->attributes->get('v5.currentTeam');- $projects = $this->projects($currentTeam);- [$selectedProject, $selectedEnvironment] = $this->selectedProjectAndEnvironment($request, $projects);-- return Inertia::render('Clusters', [- 'currentTeam' => $this->serializeCurrentTeam($currentTeam),- 'flux' => $fluxHealth->check(),- 'clusters' => $this->clusters($currentTeam),- 'privateKeys' => $this->privateKeys($currentTeam),- 'projects' => $projects,- 'selectedProjectUuid' => $selectedProject['uuid'] ?? null,- 'selectedEnvironmentUuid' => $selectedEnvironment['uuid'] ?? null,- ]);- }-- public function showCluster(Request $request, V5Cluster $cluster): JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (! $currentTeam instanceof Team || $cluster->team_id !== $currentTeam->id) {- abort(404);- }-- return response()->json([- 'cluster' => $this->freshSerializedCluster($cluster),- ]);- }-public function realtimeTest(Request $request): Response{- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (! $currentTeam instanceof Team) {- abort(403);- }+ $currentTeam = $this->currentTeamOrFail($request);return Inertia::render('RealtimeTest', ['currentTeam' => [@@ -114,11 +60,7 @@ class DashboardController extends Controllerpublic function broadcastRealtimeTest(Request $request): JsonResponse{- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (! $currentTeam instanceof Team) {- abort(403);- }+ $currentTeam = $this->currentTeamOrFail($request);$validated = $request->validate(['message' => ['nullable', 'string', 'max:255'],@@ -136,11 +78,7 @@ class DashboardController extends Controllerpublic function updateSelection(Request $request): \Illuminate\Http\Response{- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (! $currentTeam instanceof Team) {- abort(403);- }+ $currentTeam = $this->currentTeamOrFail($request);$validated = $request->validate(['project_uuid' => ['required', 'string'],@@ -165,1924 +103,63 @@ class DashboardController extends Controllerreturn response()->noContent();}- public function storeNginxApplication(Request $request): JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (! $currentTeam instanceof Team) {- abort(403);- }-- $projects = $this->projects($currentTeam);- [$selectedProject, $selectedEnvironment] = $this->selectedProjectAndEnvironment($request, $projects);-- if ($selectedProject === null || $selectedEnvironment === null) {- return response()->json([- 'message' => 'Select a project and environment before deploying nginx.',- ], 422);- }-- $project = $this->projectQuery($currentTeam)- ->where('uuid', $selectedProject['uuid'])- ->first();-- if (! $project instanceof Project) {- abort(403);- }-- $environment = $this->selectedEnvironment($project, $selectedEnvironment['uuid']);-- if (! $environment instanceof Environment) {- abort(403);- }-- $validated = $request->validate([- 'server_uuid' => ['nullable', 'string', 'max:255'],- 'image' => ['nullable', 'string', 'max:255', 'regex:/^[a-zA-Z0-9][a-zA-Z0-9._\/:@-]*$/'],- ]);- $image = trim($validated['image'] ?? '') ?: self::DEFAULT_NGINX_IMAGE;-- $server = V5Server::query()- ->where('team_id', $currentTeam->id)- ->when(- isset($validated['server_uuid']),- fn (Builder $query) => $query->where('uuid', $validated['server_uuid']),- fn (Builder $query) => $query- ->orderByRaw('last_bootstrapped_at is null')- ->orderBy('name')- )- ->first();-- if (! $server instanceof V5Server) {- return response()->json([- 'message' => 'Add a v5 server before deploying nginx.',- ], 422);- }-- $canvasPosition = $this->nextApplicationCanvasPosition($currentTeam, $project, $environment);-- $application = V5Application::query()->create([- 'team_id' => $currentTeam->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $request->user()->id,- 'name' => 'nginx-test',- 'image' => $image,- 'container_name' => 'coolify-v5-nginx-'.strtolower((string) Str::ulid()),- 'status' => 'creating',- 'status_message' => 'Starting nginx container.',- 'mesh_namespace' => 'default',- 'canvas_x' => $canvasPosition['canvas_x'],- 'canvas_y' => $canvasPosition['canvas_y'],- ]);-- $application = DeployNginxApplication::run($application);-- return response()->json([- 'application' => $this->serializeApplication($application),- ], $application->status === 'running' ? 201 : 422);- }-- public function refreshApplications(Request $request, FluxClient $fluxClient): JsonResponse+ /**+ * @return array<int, array<string, mixed>>+ */+ private function applications(mixed $currentTeam, ?array $selectedProject, ?array $selectedEnvironment): array{- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (! $currentTeam instanceof Team) {- abort(403);- }-- $projects = $this->projects($currentTeam);- [$selectedProject, $selectedEnvironment] = $this->selectedProjectAndEnvironment($request, $projects);-- if ($selectedProject === null || $selectedEnvironment === null) {- return response()->json([- 'message' => 'Select a project and environment before refreshing applications.',- ], 422);+ if (! $currentTeam instanceof Team || $selectedProject === null || $selectedEnvironment === null) {+ return [];}- $applications = $this->applicationQuery($currentTeam, $selectedProject, $selectedEnvironment)+ return $this->applicationQuery($currentTeam, $selectedProject, $selectedEnvironment)->with('server')- ->get();- $errors = [];-- $applications- ->groupBy('server_id')- ->each(function (Collection $serverApplications) use ($fluxClient, &$errors): void {- /** @var V5Application|null $firstApplication */- $firstApplication = $serverApplications->first();- $server = $firstApplication?->server;- $hostId = $server?->wireguard_management_ip ?: $server?->node_address;-- if (! $server instanceof V5Server || ! is_string($hostId) || $hostId === '') {- $errors[] = 'A server is missing its Flux host id.';-- return;- }-- try {- $containers = collect($fluxClient->listContainers($hostId));- } catch (\Throwable $e) {- $errors[] = $e->getMessage();-- return;- }-- $serverApplications->each(function (V5Application $application) use ($containers): void {- $container = $containers->first(function (array $container) use ($application): bool {- return ($application->runtime_container_id !== null && ($container['id'] ?? null) === $application->runtime_container_id)- || ($container['name'] ?? null) === $application->container_name;- });-- if (! is_array($container)) {- $application->update([- 'status' => 'exited',- 'status_message' => 'Container not found on server.',- ]);-- return;- }-- $state = is_string($container['state'] ?? null) && $container['state'] !== '' ? $container['state'] : 'unknown';-- $application->update([- 'status' => strtolower($state),- 'status_message' => 'Container state refreshed from coold.',- 'runtime_container_id' => is_string($container['id'] ?? null) ? $container['id'] : $application->runtime_container_id,- ]);- });- });-- V5Server::query()- ->where('team_id', $currentTeam->id)- ->orderBy('name')+ ->orderBy('created_at')->get()- ->filter(fn (V5Server $server) => $server->isIngress())- ->each(function (V5Server $server) use ($fluxClient, &$errors): void {- $hostId = $server->wireguard_management_ip ?: $server->node_address;-- if (! is_string($hostId) || $hostId === '') {- $errors[] = "Caddy ingress server {$server->name} is missing its Flux host id.";-- return;- }-- try {- $containers = collect($fluxClient->listContainers($hostId));- } catch (\Throwable $e) {- $errors[] = $e->getMessage();-- return;- }-- $container = $containers->first(fn (array $container) => ($container['name'] ?? null) === 'coolify-v5-caddy');- $state = is_array($container) && is_string($container['state'] ?? null) && $container['state'] !== ''- ? strtolower($container['state'])- : 'exited';-- $server->update([- 'ingress_type' => 'caddy',- 'ingress_status' => $state,- 'last_status_check' => 'flux',- 'last_status_output' => 'Caddy ingress state refreshed from coold.',- 'last_status_checked_at' => now(),- ]);- });-- return response()->json([- 'applications' => $this->applicationQuery($currentTeam, $selectedProject, $selectedEnvironment)- ->with('server')- ->orderBy('created_at')- ->get()- ->map(fn (V5Application $application) => $this->serializeApplication($application))- ->all(),- 'caddyIngresses' => $this->caddyIngresses($currentTeam),- 'errors' => $errors,- ]);- }-- public function updateApplicationPosition(Request $request, V5Application $application): JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (! $currentTeam instanceof Team || $application->team_id !== $currentTeam->id) {- abort(404);- }-- $validated = $request->validate([- 'canvas_x' => ['required', 'integer', 'min:-100000', 'max:100000'],- 'canvas_y' => ['required', 'integer', 'min:-100000', 'max:100000'],- ]);-- $application->update([- 'canvas_x' => $validated['canvas_x'],- 'canvas_y' => $validated['canvas_y'],- ]);-- return response()->json([- 'application' => $this->serializeApplication($application->refresh()->load('server')),- ]);- }-- public function updateApplicationIngress(Request $request, V5Application $application): JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (! $currentTeam instanceof Team || $application->team_id !== $currentTeam->id) {- abort(404);- }-- $validated = $request->validate([- 'ingress_enabled' => ['required', 'boolean'],- 'internal_port' => ['nullable', 'integer', 'min:1', 'max:65535'],- 'domains' => [Rule::requiredIf(fn () => $request->boolean('ingress_enabled')), 'array', 'min:1'],- 'domains.*' => ['required', 'string', 'max:255', 'distinct:ignore_case', new ValidHostname],- ]);-- $application->loadMissing('server');-- if ($validated['ingress_enabled'] && ! $application->server?->isIngress()) {- return response()->json([- 'message' => 'Enable ingress on the server before enabling app ingress.',- ], 422);- }-- DB::transaction(function () use ($application, $validated): void {- $application->update([- 'ingress_enabled' => $validated['ingress_enabled'],- 'internal_port' => $validated['internal_port'] ?? null,- ]);-- if (array_key_exists('domains', $validated)) {- $application->domains()->delete();-- collect($validated['domains'])- ->map(fn (string $domain) => trim($domain))- ->filter()- ->unique()- ->each(fn (string $domain) => V5ApplicationDomain::query()->create([- 'application_id' => $application->id,- 'domain' => $domain,- ]));- }- });-- $application->refresh()->load(['server', 'domains']);-- if ($application->server?->isIngress() && $application->server->status === 'installed') {- try {- StartCaddyIngress::run($application->server);- } catch (\RuntimeException $exception) {- return $this->ingressSyncErrorResponse($exception);- }- }-- return response()->json([- 'application' => $this->serializeApplication($application),- ]);- }-- public function updateCaddyIngressPosition(Request $request, V5Server $server): JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (! $currentTeam instanceof Team || $server->team_id !== $currentTeam->id || ! $server->isIngress()) {- abort(404);- }-- $validated = $request->validate([- 'canvas_x' => ['required', 'integer', 'min:-100000', 'max:100000'],- 'canvas_y' => ['required', 'integer', 'min:-100000', 'max:100000'],- ]);-- $server->update([- 'canvas_x' => $validated['canvas_x'],- 'canvas_y' => $validated['canvas_y'],- ]);-- return response()->json([- 'caddyIngress' => $this->serializeCaddyIngress($server->refresh()),- ]);+ ->map(fn (V5Application $application) => $this->serializeApplication($application))+ ->all();}- public function destroyApplication(Request $request, V5Application $application): \Illuminate\Http\Response|JsonResponse+ /**+ * @return array<int, array<string, mixed>>+ */+ private function resourceConnections(mixed $currentTeam, ?array $selectedProject, ?array $selectedEnvironment): array{- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (! $currentTeam instanceof Team || $application->team_id !== $currentTeam->id) {- abort(404);- }-- $error = DestroyNginxApplication::run($application);-- if ($error !== null) {- return response()->json([- 'message' => $error,- ], 422);+ if (! $currentTeam instanceof Team || $selectedProject === null || $selectedEnvironment === null) {+ return [];}- $application->delete();-- return response()->noContent();+ return ResourceConnection::query()+ ->where('team_id', $currentTeam->id)+ ->whereHas('project', fn (Builder $query) => $query+ ->where('team_id', $currentTeam->id)+ ->where('uuid', $selectedProject['uuid']))+ ->whereHas('environment', fn (Builder $query) => $query+ ->where('uuid', $selectedEnvironment['uuid']))+ ->with('rules')+ ->orderBy('id')+ ->get()+ ->map(fn (ResourceConnection $connection) => $this->connectionSerializer->serialize($connection))+ ->all();}- public function storeResourceConnection(Request $request): JsonResponse+ private function nginxServers(mixed $currentTeam): array{- $currentTeam = $request->attributes->get('v5.currentTeam');-if (! $currentTeam instanceof Team) {- abort(403);- }-- $projects = $this->projects($currentTeam);- [$selectedProject, $selectedEnvironment] = $this->selectedProjectAndEnvironment($request, $projects);-- if ($selectedProject === null || $selectedEnvironment === null) {- return response()->json([- 'message' => 'Select a project and environment before connecting resources.',- ], 422);- }-- $project = $this->projectQuery($currentTeam)- ->where('uuid', $selectedProject['uuid'])- ->first();-- if (! $project instanceof Project) {- abort(403);- }-- $environment = $this->selectedEnvironment($project, $selectedEnvironment['uuid']);-- if (! $environment instanceof Environment) {- abort(403);- }-- $validated = $request->validate([- 'resource_one' => ['required', 'array'],- 'resource_one.type' => ['required', 'string', Rule::in(['application'])],- 'resource_one.uuid' => ['required', 'string', 'max:255'],- 'resource_two' => ['required', 'array'],- 'resource_two.type' => ['required', 'string', Rule::in(['application'])],- 'resource_two.uuid' => ['required', 'string', 'max:255'],- ]);-- $resourceOne = $this->resolveConnectableResource($currentTeam, $project, $environment, $validated['resource_one']);- $resourceTwo = $this->resolveConnectableResource($currentTeam, $project, $environment, $validated['resource_two']);-- if ($this->resourceIdentity($resourceOne) === $this->resourceIdentity($resourceTwo)) {- return response()->json([- 'message' => 'A resource cannot connect to itself.',- ], 422);- }-- $connection = ResourceConnection::query()->firstOrCreate(- [- 'team_id' => $currentTeam->id,- 'resource_pair_key' => $this->resourcePairKey($resourceOne, $resourceTwo),- ],- [- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'resource_one_type' => $resourceOne->getMorphClass(),- 'resource_one_id' => $resourceOne->getKey(),- 'resource_two_type' => $resourceTwo->getMorphClass(),- 'resource_two_id' => $resourceTwo->getKey(),- 'created_by_user_id' => $request->user()->id,- ],- );-- return response()->json([- 'connection' => $this->serializeResourceConnection($connection->load('rules')),- ], $connection->wasRecentlyCreated ? 201 : 200);- }-- public function updateResourceConnection(Request $request, ResourceConnection $connection, FluxClient $fluxClient): JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (! $currentTeam instanceof Team || $connection->team_id !== $currentTeam->id) {- abort(404);- }-- $validated = $request->validate([- 'ports_by_direction' => ['present', 'array'],- 'ports_by_direction.*' => ['array'],- 'ports_by_direction.*.*' => ['integer', 'min:1', 'max:65535', 'distinct'],- ]);-- $oldFirewallRules = $this->connectionFirewallRules($connection->load('rules'));-- DB::transaction(function () use ($connection, $validated): void {- $connection->rules()->delete();- $resourcesByUuid = $this->connectionApplicationsByUuid($connection);-- foreach ($validated['ports_by_direction'] as $direction => $ports) {- [$sourceResourceUuid, $targetResourceUuid] = array_pad(explode('->', (string) $direction, 2), 2, null);- $sourceResource = is_string($sourceResourceUuid) ? $resourcesByUuid->get($sourceResourceUuid) : null;- $targetResource = is_string($targetResourceUuid) ? $resourcesByUuid->get($targetResourceUuid) : null;-- if (! $sourceResource instanceof V5Application || ! $targetResource instanceof V5Application) {- continue;- }-- foreach (array_unique($ports) as $port) {- $connection->rules()->create([- 'source_resource_type' => $this->resourceTypeForConnectionUuid($connection, $sourceResource->uuid),- 'source_resource_id' => $sourceResource->id,- 'target_resource_type' => $this->resourceTypeForConnectionUuid($connection, $targetResource->uuid),- 'target_resource_id' => $targetResource->id,- 'protocol' => 'tcp',- 'port' => (int) $port,- ]);- }- }- });-- $connection->refresh()->load('rules');- $newFirewallRules = $this->connectionFirewallRules($connection);-- try {- $this->syncConnectionFirewallRules($fluxClient, $oldFirewallRules, $newFirewallRules);- } catch (\RuntimeException $exception) {- report($exception);-- return response()->json([- 'message' => 'Could not sync firewall rules through Flux.',- 'detail' => $exception->getMessage(),- ], 502);- }-- return response()->json([- 'connection' => $this->serializeResourceConnection($connection),- ]);- }-- public function destroyResourceConnection(Request $request, ResourceConnection $connection, FluxClient $fluxClient): \Illuminate\Http\Response|JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (! $currentTeam instanceof Team || $connection->team_id !== $currentTeam->id) {- abort(404);+ return [];}- $oldFirewallRules = $this->connectionFirewallRules($connection->load('rules'));-- try {- $this->syncConnectionFirewallRules($fluxClient, $oldFirewallRules, collect());- } catch (\RuntimeException $exception) {- report($exception);-- return response()->json([- 'message' => 'Could not sync firewall rules through Flux.',- 'detail' => $exception->getMessage(),- ], 502);- }-- $connection->delete();-- return response()->noContent();- }-- public function storeCluster(Request $request): JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (! $currentTeam instanceof Team) {- abort(403);- }-- $validated = $request->validate([- 'name' => [- 'required',- 'string',- 'max:255',- Rule::unique('v5_clusters', 'name')->where('team_id', $currentTeam->id),- ],- 'description' => ['nullable', 'string', 'max:1000'],- 'wireguard_interface' => ['sometimes', 'string', 'max:32', 'regex:/^[a-zA-Z0-9_.-]+$/'],- 'wireguard_management_pool' => ['sometimes', 'string', 'max:64', $this->ipv4CidrRule()],- 'wireguard_listen_port' => ['sometimes', 'integer', 'min:1', 'max:65535'],- 'container_network_pool' => ['sometimes', 'string', 'max:64', $this->ipv4CidrRule()],- 'container_network_prefix' => ['sometimes', 'integer', 'min:1', 'max:32'],- 'namespaces' => ['sometimes', 'array', 'min:1'],- 'namespaces.*' => ['string', 'distinct', 'regex:/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/'],- 'default_deny_containers' => ['sometimes', 'boolean'],- 'coold_version' => ['sometimes', 'string', 'max:64'],- 'corrosion_version' => ['sometimes', 'string', 'max:64'],- 'corrosion_gossip_port' => ['sometimes', 'integer', 'min:1', 'max:65535'],- 'corrosion_api_port' => ['sometimes', 'integer', 'min:1', 'max:65535'],- 'builder_enabled' => ['sometimes', 'boolean'],- 'builder_capacity' => $this->builderCapacityRules(- $this->requestedBuilderEnabled($request, true)- ),- 'builder_cpu_quota' => ['sometimes', 'string', 'max:32'],- 'builder_memory_max' => ['sometimes', 'string', 'max:32'],- 'builder_timeout_secs' => ['sometimes', 'integer', 'min:1', 'max:86400'],- ]);-- $cluster = V5Cluster::query()->create([- ...$this->defaultClusterConfiguration(),- ...collect($validated)->except(['name', 'description'])->all(),- 'team_id' => $currentTeam->id,- 'created_by_user_id' => $request->user()->id,- 'name' => $validated['name'],- 'description' => $validated['description'] ?? null,- ]);-- $cluster->load(['servers' => fn ($query) => $query- ->with('privateKey')- ->orderBy('name')]);- $cluster->loadCount('servers');-- return response()->json([- 'cluster' => $this->serializeCluster($cluster),- ], 201);- }-- public function bootstrapServer(Request $request, V5Cluster $cluster, V5Server $server): JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (- ! $currentTeam instanceof Team- || $cluster->team_id !== $currentTeam->id- || $server->team_id !== $currentTeam->id- || $server->cluster_id !== $cluster->id- ) {- abort(404);- }-- if ($server->last_bootstrapped_at !== null) {- return response()->json([- 'message' => 'This server is already bootstrapped.',- ], 409);- }-- if (in_array($server->last_bootstrap_status, ['queued', 'running'], true)) {- return response()->json([- 'cluster' => $this->freshSerializedCluster($cluster),- 'message' => 'Bootstrap is already queued or running for this server.',- ], 409);- }-- $installedServers = $cluster->servers()- ->with('privateKey')- ->whereNotNull('last_bootstrapped_at')- ->orderBy('name')- ->get();- $server->load('privateKey');- $servers = $installedServers->toBase()- ->push($server)- ->unique('id')- ->values();-- if ($servers->contains(fn (V5Server $server) => ! $server->privateKey instanceof PrivateKey)) {- return response()->json([- 'message' => 'The new server and every already-bootstrapped server in this cluster must have a private key before extending the cluster.',- ], 422);- }-- $server->update([- 'last_bootstrap_action' => $installedServers->isEmpty() ? 'bootstrap' : 'extend',- 'last_bootstrap_status' => 'queued',- 'last_bootstrap_output' => "Queued Coolify bootstrap for {$server->name}.",- 'last_bootstrap_ran_at' => now(),- ]);-- V5ClusterUpdated::dispatch($currentTeam->id, $cluster->id);- V5BootstrapServerJob::dispatch($cluster->id, $server->id);-- return response()->json([- 'cluster' => $this->freshSerializedCluster($cluster),- 'message' => 'Bootstrap queued.',- ], 202);- }-- public function storeServer(Request $request, V5Cluster $cluster): JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (! $currentTeam instanceof Team || $cluster->team_id !== $currentTeam->id) {- abort(403);- }-- $validated = $request->validate([- 'name' => ['required', 'string', 'max:255'],- 'host' => [- 'required',- 'string',- 'max:255',- Rule::unique('v5_servers', 'host')- ->where('team_id', $currentTeam->id)- ->where('ssh_port', (int) $request->input('ssh_port', 22)),- ],- 'ssh_user' => ['required', 'string', 'max:255'],- 'ssh_port' => ['required', 'integer', 'min:1', 'max:65535'],- 'private_key_uuid' => [- 'required',- 'string',- Rule::exists('private_keys', 'uuid')->where('team_id', $currentTeam->id),- ],- 'node_address' => ['nullable', 'string', 'max:255'],- 'builder_enabled' => ['sometimes', 'boolean'],- 'builder_capacity' => $this->builderCapacityRules(- $this->requestedBuilderEnabled($request, $cluster->builder_enabled)- ),- 'builder_cpu_quota' => ['sometimes', 'string', 'max:32'],- 'wireguard_listen_port_override' => ['nullable', 'integer', 'min:1', 'max:65535'],- 'wireguard_endpoint_override' => ['nullable', 'string', 'max:255'],- 'ingress_enabled' => ['sometimes', 'boolean'],- 'ingress_type' => [- Rule::requiredIf(fn () => $request->boolean('ingress_enabled')),- 'nullable',- 'string',- Rule::in(['caddy']),- ],- ]);-- $builderEnabled = (bool) ($validated['builder_enabled'] ?? $cluster->builder_enabled);- $ingressEnabled = (bool) ($validated['ingress_enabled'] ?? false);- $ingressType = $ingressEnabled ? $validated['ingress_type'] : null;- $builderCapacity = (int) ($validated['builder_capacity'] ?? $cluster->builder_capacity);- $builderCpuQuota = $validated['builder_cpu_quota'] ?? $cluster->builder_cpu_quota;- $devWireguardOverrides = $this->devLimaWireguardOverrides($validated['host'], (int) $validated['ssh_port']);- $privateKey = PrivateKey::query()- ->where('team_id', $currentTeam->id)- ->where('uuid', $validated['private_key_uuid'])- ->firstOrFail();-- V5Server::query()->create([- 'team_id' => $currentTeam->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $request->user()->id,- 'name' => $validated['name'],- 'host' => $validated['host'],- 'ssh_user' => $validated['ssh_user'],- 'ssh_port' => $validated['ssh_port'],- 'private_key_id' => $privateKey->id,- 'status' => 'added',- 'ingress_type' => $ingressType,- 'capabilities' => $this->serverCapabilities($builderEnabled, $ingressEnabled),- 'builder_enabled' => $builderEnabled,- 'builder_capacity' => $builderCapacity,- 'builder_cpu_quota' => $builderCpuQuota,- 'node_address' => $validated['node_address'] ?? $validated['host'],- 'wireguard_listen_port_override' => $validated['wireguard_listen_port_override'] ?? $devWireguardOverrides['listen_port'],- 'wireguard_endpoint_override' => $validated['wireguard_endpoint_override'] ?? $devWireguardOverrides['endpoint'],- ]);-- $cluster->load(['servers' => fn ($query) => $query- ->with('privateKey')- ->orderBy('name')]);- $cluster->loadCount('servers');-- return response()->json([- 'cluster' => $this->serializeCluster($cluster),- ], 201);- }-- public function updateServer(Request $request, V5Cluster $cluster, V5Server $server): JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (- ! $currentTeam instanceof Team- || $cluster->team_id !== $currentTeam->id- || $server->team_id !== $currentTeam->id- || $server->cluster_id !== $cluster->id- ) {- abort(404);- }-- $validated = $request->validate([- 'builder_enabled' => ['required', 'boolean'],- 'builder_capacity' => $this->builderCapacityRules(- $request->boolean('builder_enabled'),- required: true- ),- 'builder_cpu_quota' => ['required', 'string', 'max:32'],- 'ingress_enabled' => ['sometimes', 'boolean'],- 'ingress_type' => [- Rule::requiredIf(fn () => $request->boolean('ingress_enabled')),- 'nullable',- 'string',- Rule::in(['caddy']),- ],- ]);-- $wasIngress = $server->isIngress();- $builderEnabled = (bool) $validated['builder_enabled'];- $ingressEnabled = (bool) ($validated['ingress_enabled'] ?? $wasIngress);- $ingressType = $ingressEnabled ? ($validated['ingress_type'] ?? $server->ingress_type ?? 'caddy') : null;- $capabilities = $this->serverCapabilities($builderEnabled, $ingressEnabled);-- $server->update([- 'capabilities' => $capabilities,- 'ingress_type' => $ingressType,- 'builder_enabled' => $builderEnabled,- 'builder_capacity' => (int) $validated['builder_capacity'],- 'builder_cpu_quota' => $validated['builder_cpu_quota'],- ]);-- $server->refresh();-- try {- $this->reconcileCaddyIngress($server, $wasIngress, $ingressEnabled);- } catch (\RuntimeException $exception) {- return $this->ingressSyncErrorResponse($exception);- }-- $cluster->load(['servers' => fn ($query) => $query- ->with('privateKey')- ->orderBy('name')]);- $cluster->loadCount('servers');-- return response()->json([- 'cluster' => $this->serializeCluster($cluster),- ]);- }-- public function checkServer(Request $request, V5Cluster $cluster, V5Server $server): JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (- ! $currentTeam instanceof Team- || $cluster->team_id !== $currentTeam->id- || $server->team_id !== $currentTeam->id- || $server->cluster_id !== $cluster->id- ) {- abort(404);- }-- if (! $server->privateKey instanceof PrivateKey) {- return response()->json([- 'status' => 'failed',- 'output' => 'No private key is attached to this server.',- 'checkedAt' => now()->toJSON(),- ]);- }-- $keyDirectory = storage_path('app/ssh/keys');- if (! is_dir($keyDirectory)) {- mkdir($keyDirectory, 0700, true);- }-- $keyLocation = tempnam($keyDirectory, 'v5_ssh_key_');- if ($keyLocation === false) {- return response()->json([- 'status' => 'failed',- 'output' => 'Could not create a temporary SSH key file.',- 'checkedAt' => now()->toJSON(),- ]);- }-- file_put_contents($keyLocation, $server->privateKey->private_key);- chmod($keyLocation, 0600);-- $target = "{$server->ssh_user}@{$server->host}";- $command = [- 'ssh',- '-o',- 'BatchMode=yes',- '-o',- 'LogLevel=ERROR',- '-o',- 'StrictHostKeyChecking=no',- '-o',- 'UserKnownHostsFile=/dev/null',- '-o',- 'ConnectTimeout=10',- '-o',- 'IdentitiesOnly=yes',- '-i',- $keyLocation,- '-p',- (string) $server->ssh_port,- $target,- "printf 'SSH connection OK\n'; hostname; uname -srm; command -v docker || true; command -v podman || true",- ];-- try {- $result = Process::timeout(15)->run($command);- $output = trim($result->output()."\n".$result->errorOutput());- $status = $result->successful() ? 'reachable' : 'failed';- } catch (\Throwable $e) {- $output = $e->getMessage();- $status = 'failed';- } finally {- @unlink($keyLocation);- }-- return response()->json([- 'status' => $status,- 'output' => str($output !== '' ? $output : 'No output returned.')->limit(10000)->toString(),- 'checkedAt' => now()->toJSON(),- ]);- }-- public function serverCooldLogs(Request $request, V5Cluster $cluster, V5Server $server, FluxClient $fluxClient): JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (- ! $currentTeam instanceof Team- || $cluster->team_id !== $currentTeam->id- || $server->team_id !== $currentTeam->id- || $server->cluster_id !== $cluster->id- ) {- abort(404);- }-- $validated = $request->validate([- 'tail' => ['sometimes', 'integer', 'min:1', 'max:1000'],- ]);-- $hostId = $server->wireguard_management_ip ?: $server->node_address;-- if (! is_string($hostId) || $hostId === '') {- return response()->json([- 'message' => 'This server is missing its Flux host id.',- ], 422);- }-- try {- $output = $fluxClient->cooldLogs($hostId, (int) ($validated['tail'] ?? 200));- } catch (\Throwable $e) {- return response()->json([- 'message' => $e->getMessage(),- ], 502);- }-- return response()->json([- 'output' => $output,- 'source' => 'flux',- 'fetchedAt' => now()->toJSON(),- ]);- }-- public function serverCorrosionTables(Request $request, V5Cluster $cluster, V5Server $server, FluxClient $fluxClient): JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (- ! $currentTeam instanceof Team- || $cluster->team_id !== $currentTeam->id- || $server->team_id !== $currentTeam->id- || $server->cluster_id !== $cluster->id- ) {- abort(404);- }-- $validated = $request->validate([- 'limit' => ['sometimes', 'integer', 'min:1', 'max:1000'],- ]);-- $hostId = $server->wireguard_management_ip ?: $server->node_address;-- if (! is_string($hostId) || $hostId === '') {- return response()->json([- 'message' => 'This server is missing its Flux host id.',- ], 422);- }-- try {- $output = $fluxClient->corrosionTables($hostId, (int) ($validated['limit'] ?? 200));- } catch (\Throwable $e) {- return response()->json([- 'message' => $e->getMessage(),- ], 502);- }-- return response()->json([- 'output' => $output,- 'source' => 'flux',- 'fetchedAt' => now()->toJSON(),- ]);- }-- public function serverFirewallRules(Request $request, V5Cluster $cluster, V5Server $server, FluxClient $fluxClient): JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (- ! $currentTeam instanceof Team- || $cluster->team_id !== $currentTeam->id- || $server->team_id !== $currentTeam->id- || $server->cluster_id !== $cluster->id- ) {- abort(404);- }-- $validated = $request->validate([- 'namespace' => ['sometimes', 'string', 'max:63'],- ]);-- $hostId = $server->wireguard_management_ip ?: $server->node_address;-- if (! is_string($hostId) || $hostId === '') {- return response()->json([- 'message' => 'This server is missing its Flux host id.',- ], 422);- }-- try {- $rules = $fluxClient->listFirewallRules($hostId, (string) ($validated['namespace'] ?? ''));- } catch (\Throwable $e) {- return response()->json([- 'message' => $e->getMessage(),- ], 502);- }-- return response()->json([- 'rules' => $rules,- 'source' => 'flux',- 'fetchedAt' => now()->toJSON(),- ]);- }-- public function destroyServer(Request $request, V5Cluster $cluster, V5Server $server): \Illuminate\Http\Response|JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (- ! $currentTeam instanceof Team- || $cluster->team_id !== $currentTeam->id- || $server->team_id !== $currentTeam->id- || $server->cluster_id !== $cluster->id- ) {- abort(404);- }-- $server->delete();-- return response()->json([- 'cluster' => $this->freshSerializedCluster($cluster),- ]);- }-- public function destroyCluster(Request $request, V5Cluster $cluster): \Illuminate\Http\Response|JsonResponse- {- $currentTeam = $request->attributes->get('v5.currentTeam');-- if (! $currentTeam instanceof Team || $cluster->team_id !== $currentTeam->id) {- abort(404);- }-- if ($cluster->servers()->exists()) {- return response()->json([- 'message' => 'Only empty clusters can be deleted.',- ], 422);- }-- $cluster->delete();-- return response()->noContent();- }-- /**- * @param Collection<int, V5Server> $servers- * @return array<int, string>- */- /**- * @return array{listen_port: int|null, endpoint: string|null}- */- private function devLimaWireguardOverrides(string $host, int $sshPort): array- {- if (! app()->environment(['local', 'development', 'testing']) || $host !== 'host.docker.internal') {- return ['listen_port' => null, 'endpoint' => null];- }-- if ($sshPort < 60001 || $sshPort > 60009) {- return ['listen_port' => null, 'endpoint' => null];- }-- $wireguardPort = $sshPort - 8180;-- return [- 'listen_port' => $wireguardPort,- 'endpoint' => "host.lima.internal:{$wireguardPort}",- ];- }-- private function bootstrapCommand(V5Cluster $cluster, Collection $servers, V5Server $newServer, string $sshConfigLocation, string $action): array- {- $command = [- $this->coolifyCliBin(),- 'init',- $action,- '--format',- 'table',- '--nodes',- $servers->map(fn (V5Server $server) => $this->bootstrapNode($server))->implode(','),- '--ssh-config',- $sshConfigLocation,- '--namespaces',- implode(',', $cluster->namespaces ?? V5Cluster::DEFAULT_NAMESPACES),- '--container-pool',- $cluster->container_network_pool,- '--container-prefix',- (string) $cluster->container_network_prefix,- '--wg-mgmt-pool',- $cluster->wireguard_management_pool,- '--wg-interface',- $cluster->wireguard_interface,- '--wg-listen-port',- (string) $cluster->wireguard_listen_port,- '--coold-version',- $cluster->coold_version,- '--corrosion-version',- $cluster->corrosion_version,- '--corrosion-gossip-port',- (string) $cluster->corrosion_gossip_port,- '--corrosion-api-port',- (string) $cluster->corrosion_api_port,- ];-- if ($action === 'extend') {- array_push($command, '--new-nodes', $this->bootstrapNode($newServer));- }-- $listenOverrides = $this->wireguardListenPortOverrides($servers);- if ($listenOverrides !== '') {- array_push($command, '--wg-listen-port-overrides', $listenOverrides);- }-- $endpointOverrides = $this->wireguardEndpointOverrides($servers);- if ($endpointOverrides !== '') {- array_push($command, '--wg-endpoint-overrides', $endpointOverrides);- }-- if (! $cluster->default_deny_containers) {- $command[] = '--skip-default-deny';- }-- $command[] = '--yes';-- return $command;- }-- private function coolifyCliBin(): string- {- $configuredBinary = (string) config('coold.coolify_cli_bin', '/usr/local/bin/coolify');- $devBinary = base_path('.dev/bin/coolify');-- if ($configuredBinary === '/usr/local/bin/coolify' && $this->isRunnableDevelopmentCliBinary($devBinary)) {- return $devBinary;- }-- return $configuredBinary;- }-- private function isRunnableDevelopmentCliBinary(string $binary): bool- {- if (! is_file($binary)) {- return false;- }-- $header = file_get_contents($binary, false, null, 0, 4);-- if ($header === false) {- return false;- }-- if (str_starts_with($header, '#!')) {- return true;- }-- if ($header === "\x7FELF") {- return true;- }-- return false;- }-- private function bootstrapNode(V5Server $server): string- {- return "v5-server-{$server->id}";- }-- /**- * @param Collection<int, V5Server> $servers- */- private function writeBootstrapSshConfig(Collection $servers, string $tempDirectory): string- {- $config = '';-- $servers->each(function (V5Server $server) use (&$config, $tempDirectory): void {- $keyLocation = "{$tempDirectory}/server-{$server->id}.key";- file_put_contents($keyLocation, $server->privateKey->private_key);- chmod($keyLocation, 0600);-- $config .= implode("\n", [- 'Host '.$this->bootstrapNode($server),- ' HostName '.$server->host,- ' Port '.$server->ssh_port,- ' User '.$server->ssh_user,- ' IdentityFile '.$keyLocation,- ' IdentitiesOnly yes',- ' LogLevel ERROR',- ' StrictHostKeyChecking no',- ' UserKnownHostsFile /dev/null',- ' BatchMode yes',- '',- ]);- });-- $sshConfigLocation = "{$tempDirectory}/ssh.config";- file_put_contents($sshConfigLocation, $config);- chmod($sshConfigLocation, 0600);-- return $sshConfigLocation;- }-- private function deleteDirectory(string $directory): void- {- if (! is_dir($directory)) {- return;- }-- foreach (scandir($directory) ?: [] as $file) {- if ($file === '.' || $file === '..') {- continue;- }-- $path = "{$directory}/{$file}";-- if (is_dir($path)) {- $this->deleteDirectory($path);-- continue;- }-- @unlink($path);- }-- @rmdir($directory);- }-- /**- * @param Collection<int, V5Server> $servers- */- private function wireguardListenPortOverrides(Collection $servers): string- {- return $servers- ->filter(fn (V5Server $server) => $server->wireguard_listen_port_override !== null)- ->map(fn (V5Server $server) => $this->bootstrapNode($server).'='.$server->wireguard_listen_port_override)- ->implode(',');- }-- /**- * @param Collection<int, V5Server> $servers- */- private function wireguardEndpointOverrides(Collection $servers): string- {- return $servers- ->filter(fn (V5Server $server) => $server->wireguard_endpoint_override !== null)- ->map(fn (V5Server $server) => $this->bootstrapNode($server).'='.$server->wireguard_endpoint_override)- ->implode(',');- }-- /**- * @return array<int, array{id: string, name: string, host: string, status: string}>- */- /**- * @return array{id: int}|null- */- private function serializeCurrentTeam(mixed $currentTeam): ?array- {- if (! $currentTeam instanceof Team) {- return null;- }-- return [- 'id' => $currentTeam->id,- ];- }-- private function nginxServers(mixed $currentTeam): array- {- if (! $currentTeam instanceof Team) {- return [];- }-- return V5Server::query()- ->where('team_id', $currentTeam->id)- ->orderByRaw('last_bootstrapped_at is null')- ->orderBy('name')- ->get(['id', 'uuid', 'name', 'host', 'status'])- ->map(fn (V5Server $server) => [- 'id' => $server->uuid,- 'name' => $server->name,- 'host' => $server->host,- 'status' => $server->status,- ])- ->all();- }-- /**- * @return array<int, array<string, mixed>>- */- private function applications(mixed $currentTeam, ?array $selectedProject, ?array $selectedEnvironment): array- {- if (! $currentTeam instanceof Team || $selectedProject === null || $selectedEnvironment === null) {- return [];- }-- return $this->applicationQuery($currentTeam, $selectedProject, $selectedEnvironment)- ->with('server')- ->orderBy('created_at')- ->get()- ->map(fn (V5Application $application) => $this->serializeApplication($application))- ->all();- }-- /**- * @return array<int, array<string, mixed>>- */- private function caddyIngresses(mixed $currentTeam): array- {- if (! $currentTeam instanceof Team) {- return [];- }-- return V5Server::query()- ->where('team_id', $currentTeam->id)- ->orderBy('name')- ->get()- ->filter(fn (V5Server $server) => $server->isIngress())- ->values()- ->map(fn (V5Server $server, int $index) => $this->serializeCaddyIngress($server, $index))- ->all();- }-- /**- * @return array<int, array<string, mixed>>- */- private function resourceConnections(mixed $currentTeam, ?array $selectedProject, ?array $selectedEnvironment): array- {- if (! $currentTeam instanceof Team || $selectedProject === null || $selectedEnvironment === null) {- return [];- }-- return ResourceConnection::query()- ->where('team_id', $currentTeam->id)- ->whereHas('project', fn (Builder $query) => $query- ->where('team_id', $currentTeam->id)- ->where('uuid', $selectedProject['uuid']))- ->whereHas('environment', fn (Builder $query) => $query- ->where('uuid', $selectedEnvironment['uuid']))- ->with('rules')- ->orderBy('id')- ->get()- ->map(fn (ResourceConnection $connection) => $this->serializeResourceConnection($connection))- ->all();- }-- /**- * @return array<string, mixed>- */- private function serializeCaddyIngress(V5Server $server, int $index = 0): array- {- $isServerReachable = $this->isServerReachable($server);-- return [- 'id' => $server->uuid,- 'name' => $server->name,- 'host' => $server->host,- 'type' => $server->ingressType(),- 'status' => $isServerReachable ? $server->ingressStatus() : 'unreachable',- 'statusMessage' => $isServerReachable ? null : $this->serverStatusMessage($server),- 'canvasX' => $server->canvas_x ?? -self::CANVAS_CARD_WIDTH - self::CANVAS_CARD_GAP,- 'canvasY' => $server->canvas_y ?? $index * (self::CANVAS_CARD_HEIGHT + self::CANVAS_CARD_GAP),- ];- }-- /**- * @return array<string, mixed>- */- private function serializeResourceConnection(ResourceConnection $connection): array- {- $applications = $this->connectionApplicationsById($connection);- $resourceOneUuid = $applications->get($connection->resource_one_id)?->uuid;- $resourceTwoUuid = $applications->get($connection->resource_two_id)?->uuid;- $applicationsById = $applications;-- return [- 'id' => $connection->uuid,- 'applicationIds' => array_values(array_filter([- $resourceOneUuid,- $resourceTwoUuid,- ])),- 'fromApplicationId' => $resourceOneUuid,- 'toApplicationId' => $resourceTwoUuid,- 'portsByDirection' => $connection->rules- ->groupBy(function ($rule) use ($applicationsById): string {- $sourceUuid = $applicationsById->get($rule->source_resource_id)?->uuid;- $targetUuid = $applicationsById->get($rule->target_resource_id)?->uuid;-- return "{$sourceUuid}->{$targetUuid}";- })- ->filter(fn (Collection $rules, string $direction): bool => ! str_starts_with($direction, '->') && ! str_ends_with($direction, '->'))- ->map(fn (Collection $rules) => $rules- ->sortBy('port')- ->pluck('port')- ->map(fn ($port) => (string) $port)- ->values()- ->all())- ->all(),- ];- }-- /**- * @param array{type: string, uuid: string} $resource- */- private function resolveConnectableResource(Team $team, Project $project, Environment $environment, array $resource): Model- {- return match ($resource['type']) {- 'application' => V5Application::query()- ->where('team_id', $team->id)- ->where('project_id', $project->id)- ->where('environment_id', $environment->id)- ->where('uuid', $resource['uuid'])- ->firstOrFail(),- };- }-- private function resourcePairKey(Model $resourceOne, Model $resourceTwo): string- {- return collect([- $this->resourceIdentity($resourceOne),- $this->resourceIdentity($resourceTwo),- ])->sort()->implode('|');- }-- private function resourceIdentity(Model $resource): string- {- return $resource->getMorphClass().':'.$resource->getKey();- }-- /**- * @return Collection<string, V5Application>- */- private function connectionApplicationsByUuid(ResourceConnection $connection): Collection- {- return $this->connectionApplicationsById($connection)->keyBy('uuid');- }-- /**- * @return Collection<int, V5Application>- */- private function connectionApplicationsById(ResourceConnection $connection): Collection- {- return V5Application::query()- ->whereIn('id', [- (int) $connection->resource_one_id,- (int) $connection->resource_two_id,- ])- ->get()- ->keyBy('id');- }-- private function resourceTypeForConnectionUuid(ResourceConnection $connection, string $resourceUuid): string- {- $resourcesByUuid = $this->connectionApplicationsByUuid($connection);- $resource = $resourcesByUuid->get($resourceUuid);-- return $resource instanceof V5Application && (int) $connection->resource_one_id === $resource->id- ? $connection->resource_one_type- : $connection->resource_two_type;- }-- /**- * @return Collection<int, array{id: string, hostId: string, rule: array{id: string, namespace: string, src: string, dst: string, proto: string, port: int}}>- */- private function connectionFirewallRules(ResourceConnection $connection): Collection- {- $applicationIds = $connection->rules- ->flatMap(fn ($rule) => [$rule->source_resource_id, $rule->target_resource_id])- ->unique()- ->values();-- $applications = V5Application::query()- ->whereIn('id', $applicationIds)- ->with('server')- ->get()- ->keyBy('id');-- return $connection->rules- ->flatMap(function ($rule) use ($applications, $connection): Collection {- $source = $applications->get($rule->source_resource_id);- $target = $applications->get($rule->target_resource_id);-- if (- ! $source instanceof V5Application- || ! $target instanceof V5Application- || ! $source->server instanceof V5Server- || ! $target->server instanceof V5Server- ) {- return collect();- }-- $hostIds = collect([$source->server, $target->server])- ->map(fn (V5Server $server) => $server->wireguard_management_ip ?: $server->node_address)- ->filter(fn (mixed $hostId): bool => is_string($hostId) && $hostId !== '')- ->unique()- ->values();-- if ($hostIds->isEmpty()) {- return collect();- }-- $firewallRule = [- 'id' => $this->connectionFirewallRuleId($connection, $rule),- 'namespace' => $target->mesh_namespace ?: 'default',- 'src' => $source->container_name,- 'dst' => $target->container_name,- 'proto' => $rule->protocol ?: 'tcp',- 'port' => (int) $rule->port,- ];-- return $hostIds->map(fn (string $hostId): array => [- 'id' => $firewallRule['id'],- 'hostId' => $hostId,- 'rule' => $firewallRule,- ]);- })- ->values();- }-- /**- * @param Collection<int, array{id: string, hostId: string, rule: array{id: string, namespace: string, src: string, dst: string, proto: string, port: int}}> $oldRules- * @param Collection<int, array{id: string, hostId: string, rule: array{id: string, namespace: string, src: string, dst: string, proto: string, port: int}}> $newRules- */- private function syncConnectionFirewallRules(FluxClient $fluxClient, Collection $oldRules, Collection $newRules): void- {- $newRuleKeys = $newRules->map(fn (array $rule): string => $this->firewallRuleSyncKey($rule))->all();- $oldRuleKeys = $oldRules->map(fn (array $rule): string => $this->firewallRuleSyncKey($rule))->all();-- $oldRules- ->reject(fn (array $oldRule): bool => in_array($this->firewallRuleSyncKey($oldRule), $newRuleKeys, true))- ->each(fn (array $oldRule): string => $fluxClient->revokeFirewallRule($oldRule['hostId'], $oldRule['id']));-- $newRules- ->reject(fn (array $newRule): bool => in_array($this->firewallRuleSyncKey($newRule), $oldRuleKeys, true))- ->each(fn (array $newRule): string => $fluxClient->applyFirewallRule($newRule['hostId'], $newRule['rule']));- }-- /**- * @param array{id: string, hostId: string, rule: array{id: string, namespace: string, src: string, dst: string, proto: string, port: int}} $rule- */- private function firewallRuleSyncKey(array $rule): string- {- return $rule['hostId'].'|'.$rule['id'];- }-- private function connectionFirewallRuleId(ResourceConnection $connection, mixed $rule): string- {- return implode(':', [- 'v5-resource-connection',- $connection->id,- $rule->source_resource_id,- $rule->target_resource_id,- $rule->protocol ?: 'tcp',- (int) $rule->port,- ]);- }-- /**- * @param array{uuid: string} $selectedProject- * @param array{uuid: string} $selectedEnvironment- * @return Builder<V5Application>- */- private function applicationQuery(Team $currentTeam, array $selectedProject, array $selectedEnvironment): Builder- {- return V5Application::query()- ->where('team_id', $currentTeam->id)- ->whereHas('project', fn (Builder $query) => $query- ->where('team_id', $currentTeam->id)- ->where('uuid', $selectedProject['uuid']))- ->whereHas('environment', fn (Builder $query) => $query- ->where('uuid', $selectedEnvironment['uuid']));- }-- /**- * @return array{canvas_x: int, canvas_y: int}- */- private function nextApplicationCanvasPosition(Team $currentTeam, Project $project, Environment $environment): array- {- $existingApplications = V5Application::query()- ->where('team_id', $currentTeam->id)- ->where('project_id', $project->id)- ->where('environment_id', $environment->id)- ->get(['canvas_x', 'canvas_y']);-- $horizontalStep = self::CANVAS_CARD_WIDTH + self::CANVAS_CARD_GAP;- $verticalStep = self::CANVAS_CARD_HEIGHT + self::CANVAS_CARD_GAP;-- for ($row = 0; $row < 100; $row++) {- for ($column = 0; $column < 100; $column++) {- $candidate = [- 'canvas_x' => $column * $horizontalStep,- 'canvas_y' => $row * $verticalStep,- ];-- if (! $this->canvasPositionCollides($candidate, $existingApplications)) {- return $candidate;- }- }- }-- return [- 'canvas_x' => $existingApplications->max('canvas_x') + $horizontalStep,- 'canvas_y' => 0,- ];- }-- /**- * @param array{canvas_x: int, canvas_y: int} $candidate- * @param Collection<int, V5Application> $existingApplications- */- private function canvasPositionCollides(array $candidate, Collection $existingApplications): bool- {- return $existingApplications->contains(function (V5Application $application) use ($candidate) {- return abs($candidate['canvas_x'] - $application->canvas_x) < self::CANVAS_CARD_WIDTH + self::CANVAS_CARD_GAP- && abs($candidate['canvas_y'] - $application->canvas_y) < self::CANVAS_CARD_HEIGHT + self::CANVAS_CARD_GAP;- });- }-- /**- * @return array<string, mixed>- */- private function serializeApplication(V5Application $application): array- {- $application->loadMissing(['server', 'domains']);- $server = $application->server;- $isServerReachable = ! $server instanceof V5Server || $this->isServerReachable($server);-- return [- 'id' => $application->uuid,- 'name' => $application->name,- 'image' => $application->image,- 'containerName' => $application->container_name,- 'status' => $application->status,- 'statusMessage' => $application->status_message,- 'effectiveStatus' => $isServerReachable ? $application->status : 'unknown',- 'effectiveStatusMessage' => $isServerReachable- ? $application->status_message- : $this->serverStatusMessage($server),- 'runtimeContainerId' => $application->runtime_container_id,- 'serverName' => $server?->name,- 'serverStatus' => $server?->status,- 'serverStatusMessage' => $server instanceof V5Server ? $this->serverStatusMessage($server) : null,- 'isServerReachable' => $isServerReachable,- 'serverIngressEnabled' => (bool) $server?->isIngress(),- 'meshNamespace' => $application->mesh_namespace,- 'ingressEnabled' => $application->ingress_enabled,- 'internalPort' => $application->internal_port,- 'domains' => $application->domains->pluck('domain')->values()->all(),- 'meshFqdn' => $application->container_name.'.'.($application->mesh_namespace ?: 'default').'.coolify.internal',- 'canvasX' => $application->canvas_x,- 'canvasY' => $application->canvas_y,- ];- }-- private function isServerReachable(V5Server $server): bool- {- return $server->status !== 'unreachable';- }-- private function serverStatusMessage(V5Server $server): ?string- {- return $server->last_status_output ?: null;- }-- /**- * @return array<int, array<string, mixed>>- */- private function clusters(mixed $currentTeam): array- {- if (! $currentTeam instanceof Team) {- return [];- }-- return V5Cluster::query()- ->where('team_id', $currentTeam->id)- ->with(['servers' => fn ($query) => $query- ->with('privateKey')- ->orderBy('name')])- ->withCount('servers')- ->orderBy('name')- ->get()- ->map(fn (V5Cluster $cluster) => $this->serializeCluster($cluster))- ->all();- }-- /**- * @return array<int, array{id: string, name: string}>- */- private function privateKeys(mixed $currentTeam): array- {- if (! $currentTeam instanceof Team) {- return [];- }-- return PrivateKey::query()+ return V5Server::query()->where('team_id', $currentTeam->id)- ->where('is_git_related', false)+ ->orderByRaw('last_bootstrapped_at is null')->orderBy('name')- ->get(['id', 'uuid', 'name'])- ->map(fn (PrivateKey $privateKey) => [- 'id' => $privateKey->uuid,- 'name' => $privateKey->name,- ])- ->all();- }-- /**- * @return array<int, string>- */- private function serverCapabilities(bool $builderEnabled, bool $ingressEnabled): array- {- return collect()- ->when($ingressEnabled, fn ($capabilities) => $capabilities->push('ingress'))- ->unique()- ->values()- ->all();- }-- private function reconcileCaddyIngress(V5Server $server, bool $wasIngress, bool $isIngress): void- {- if ($server->status !== 'installed') {- return;- }-- if (! $wasIngress && $isIngress) {- StartCaddyIngress::run($server);-- return;- }-- if ($wasIngress && ! $isIngress) {- StopCaddyIngress::run($server);- }- }-- private function ingressSyncErrorResponse(\RuntimeException $exception): JsonResponse- {- return response()->json([- 'message' => $this->friendlyIngressSyncError($exception->getMessage()),- 'detail' => $exception->getMessage(),- ], 502);- }-- private function friendlyIngressSyncError(string $message): string- {- $normalized = Str::lower($message);-- if (str_contains($normalized, 'invalid http response') || str_contains($normalized, 'could not talk to flux')) {- return 'Could not reach Flux. Check that Flux is running in the Coolify container and try again.';- }-- if (str_contains($normalized, 'dispatch timeout') || str_contains($normalized, 'timed out')) {- return 'coold did not respond in time. Check that the server agent is running and connected to Flux.';- }-- if (str_contains($normalized, 'validate caddyfile')) {- return 'Caddy rejected the generated ingress configuration. Check the domains and internal port, then try again.';- }-- if (str_contains($normalized, 'start caddy ingress') || str_contains($normalized, 'reload caddy ingress')) {- return 'Could not start Caddy ingress on the server. Check that Podman is running and port 80 is available.';- }-- return 'Could not update ingress. Check Flux and coold logs, then try again.';- }-- /**- * @return array<string, mixed>- */- private function serializeCluster(V5Cluster $cluster): array- {- return [- 'id' => $cluster->uuid,- 'name' => $cluster->name,- 'description' => $cluster->description,- 'wireguardInterface' => $cluster->wireguard_interface,- 'wireguardManagementPool' => $cluster->wireguard_management_pool,- 'wireguardListenPort' => $cluster->wireguard_listen_port,- 'containerNetworkPool' => $cluster->container_network_pool,- 'containerNetworkPrefix' => $cluster->container_network_prefix,- 'namespaces' => $cluster->namespaces ?? V5Cluster::DEFAULT_NAMESPACES,- 'defaultDenyContainers' => $cluster->default_deny_containers,- 'cooldVersion' => $cluster->coold_version,- 'corrosionVersion' => $cluster->corrosion_version,- 'corrosionGossipPort' => $cluster->corrosion_gossip_port,- 'corrosionApiPort' => $cluster->corrosion_api_port,- 'builderEnabled' => $cluster->builder_enabled,- 'builderCapacity' => $cluster->builder_capacity,- 'builderCpuQuota' => $cluster->builder_cpu_quota,- 'builderMemoryMax' => $cluster->builder_memory_max,- 'builderTimeoutSecs' => $cluster->builder_timeout_secs,- 'lastCliAction' => $cluster->last_cli_action,- 'lastCliStatus' => $cluster->last_cli_status,- 'lastCliSummary' => $cluster->last_cli_summary,- 'lastCliRanAt' => $cluster->last_cli_ran_at?->toJSON(),- 'serversCount' => $cluster->servers_count ?? $cluster->servers->count(),- 'servers' => $cluster->servers->map(fn (V5Server $server) => [+ ->get(['id', 'uuid', 'name', 'host', 'status'])+ ->map(fn (V5Server $server) => ['id' => $server->uuid,'name' => $server->name,'host' => $server->host,'status' => $server->status,- 'capabilities' => $server->capabilities ?? [],- 'builderEnabled' => $server->builder_enabled,- 'builderCapacity' => $server->builder_capacity,- 'builderCpuQuota' => $server->builder_cpu_quota,- 'ingressEnabled' => $server->isIngress(),- 'ingressType' => $server->ingress_type,- 'uuid' => $server->uuid,- 'nodeAddress' => $server->node_address,- 'wireguardListenPortOverride' => $server->wireguard_listen_port_override,- 'wireguardEndpointOverride' => $server->wireguard_endpoint_override,- 'wireguardManagementIp' => $server->wireguard_management_ip,- 'wireguardPublicKey' => $server->wireguard_public_key,- 'containerSubnets' => $server->container_subnets ?? [],- 'privateKeyName' => $server->privateKey?->name,- 'lastBootstrappedAt' => $server->last_bootstrapped_at?->toJSON(),- 'lastBootstrapAction' => $server->last_bootstrap_action,- 'lastBootstrapStatus' => $server->last_bootstrap_status,- 'lastBootstrapOutput' => $server->last_bootstrap_output,- 'lastBootstrapRanAt' => $server->last_bootstrap_ran_at?->toJSON(),- 'lastStatusOutput' => $server->last_status_output,- 'lastStatusCheckedAt' => $server->last_status_checked_at?->toJSON(),- ])->all(),- ];- }-- /**- * @return array<string, mixed>- */- private function freshSerializedCluster(V5Cluster $cluster): array- {- $cluster->load(['servers' => fn ($query) => $query- ->with('privateKey')- ->orderBy('name')]);- $cluster->loadCount('servers');-- return $this->serializeCluster($cluster);- }-- /**- * @return array<string, mixed>- */- private function defaultClusterConfiguration(): array- {- return [- 'wireguard_interface' => V5Cluster::DEFAULT_WIREGUARD_INTERFACE,- 'wireguard_management_pool' => V5Cluster::DEFAULT_WIREGUARD_MANAGEMENT_POOL,- 'wireguard_listen_port' => V5Cluster::DEFAULT_WIREGUARD_LISTEN_PORT,- 'container_network_pool' => V5Cluster::DEFAULT_CONTAINER_NETWORK_POOL,- 'container_network_prefix' => V5Cluster::DEFAULT_CONTAINER_NETWORK_PREFIX,- 'namespaces' => V5Cluster::DEFAULT_NAMESPACES,- 'default_deny_containers' => true,- 'coold_version' => V5Cluster::DEFAULT_COOLD_VERSION,- 'corrosion_version' => V5Cluster::DEFAULT_CORROSION_VERSION,- 'corrosion_gossip_port' => V5Cluster::DEFAULT_CORROSION_GOSSIP_PORT,- 'corrosion_api_port' => V5Cluster::DEFAULT_CORROSION_API_PORT,- 'builder_enabled' => true,- 'builder_capacity' => V5Cluster::DEFAULT_BUILDER_CAPACITY,- 'builder_cpu_quota' => V5Cluster::DEFAULT_BUILDER_CPU_QUOTA,- 'builder_memory_max' => V5Cluster::DEFAULT_BUILDER_MEMORY_MAX,- 'builder_timeout_secs' => V5Cluster::DEFAULT_BUILDER_TIMEOUT_SECS,- ];- }-- private function ipv4CidrRule(): \Closure- {- return function (string $attribute, mixed $value, \Closure $fail): void {- if (! is_string($value) || ! str_contains($value, '/')) {- $fail('The :attribute must be a valid IPv4 CIDR range.');-- return;- }-- [$ip, $prefix] = explode('/', $value, 2);-- if (- filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false- || ! ctype_digit($prefix)- || (int) $prefix < 0- || (int) $prefix > 32- ) {- $fail('The :attribute must be a valid IPv4 CIDR range.');- }- };- }-- /**- * @return array<int, string>- */- private function builderCapacityRules(bool $builderEnabled, bool $required = false): array- {- return [- $required ? 'required' : 'sometimes',- 'integer',- $builderEnabled ? 'min:1' : 'min:0',- 'max:1000',- ];- }-- private function requestedBuilderEnabled(Request $request, bool $default): bool- {- if (! $request->has('builder_enabled')) {- return $default;- }-- return $request->boolean('builder_enabled');- }-- /**- * @param array<int, array{uuid: string, name: string, environments: array<int, array{uuid: string, name: string}>}> $projects- * @return array{0: array{uuid: string, name: string, environments: array<int, array{uuid: string, name: string}>}|null, 1: array{uuid: string, name: string}|null}- */- private function selectedProjectAndEnvironment(Request $request, array $projects): array- {- $selectedProjectUuid = $request->session()->get(self::SELECTED_PROJECT_SESSION_KEY);- $selectedEnvironmentUuid = $request->session()->get(self::SELECTED_ENVIRONMENT_SESSION_KEY);- $selectedProject = null;-- foreach ($projects as $project) {- if ($project['uuid'] === $selectedProjectUuid) {- $selectedProject = $project;-- break;- }- }-- $selectedProject ??= $projects[0] ?? null;- $selectedEnvironment = null;-- foreach ($selectedProject['environments'] ?? [] as $environment) {- if ($environment['uuid'] === $selectedEnvironmentUuid) {- $selectedEnvironment = $environment;-- break;- }- }-- $selectedEnvironment ??= $selectedProject['environments'][0] ?? null;-- return [$selectedProject, $selectedEnvironment];- }-- private function selectedEnvironment(Project $project, ?string $environmentUuid): ?Environment- {- if ($environmentUuid === null) {- return $project->environments->first();- }-- $environment = $project->environments->firstWhere('uuid', $environmentUuid);-- if (! $environment instanceof Environment) {- abort(422, 'The selected environment is not available for the selected project.');- }-- return $environment;- }-- /**- * @return array<int, array{uuid: string, name: string, environments: array<int, array{uuid: string, name: string}>}>- */- private function projects(mixed $currentTeam): array- {- if (! $currentTeam instanceof Team) {- return [];- }-- return $this->projectQuery($currentTeam)- ->get()- ->map(fn (Project $project) => [- 'uuid' => $project->uuid,- 'name' => $project->name,- 'environments' => $project->environments- ->map(fn ($environment) => [- 'uuid' => $environment->uuid,- 'name' => $environment->name,- ])- ->all(),])->all();}-- private function projectQuery(Team $currentTeam): Builder- {- return Project::query()- ->select(['id', 'uuid', 'name', 'team_id'])- ->where('team_id', $currentTeam->id)- ->with(['environments' => fn ($query) => $query- ->select(['id', 'uuid', 'name', 'project_id'])- ->orderByRaw("CASE WHEN LOWER(name) = 'production' THEN 0 ELSE 1 END")- ->orderByRaw('LOWER(name)')])- ->orderByRaw('LOWER(name)');- }}diff --git a/app/Http/Controllers/V5/ResourceConnectionController.php b/app/Http/Controllers/V5/ResourceConnectionController.phpnew file mode 100644index 0000000000..d901940d65--- /dev/null+++ b/app/Http/Controllers/V5/ResourceConnectionController.php@@ -0,0 +1,330 @@+<?php++namespace App\Http\Controllers\V5;++use App\Http\Controllers\Controller;+use App\Http\Controllers\V5\Concerns\ResolvesCurrentTeam;+use App\Http\Controllers\V5\Concerns\ResolvesProjectSelection;+use App\Models\Environment;+use App\Models\Project;+use App\Models\Team;+use App\Models\V5\Application as V5Application;+use App\Models\V5\ResourceConnection;+use App\Services\Flux\FluxClient;+use App\Support\V5\ConnectionFirewallSync;+use App\Support\V5\ResourceConnectionSerializer;+use Illuminate\Database\Eloquent\Model;+use Illuminate\Http\JsonResponse;+use Illuminate\Http\Request;+use Illuminate\Http\Response;+use Illuminate\Support\Collection;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Log;+use Illuminate\Validation\Rule;++class ResourceConnectionController extends Controller+{+ use ResolvesCurrentTeam;+ use ResolvesProjectSelection;++ public function __construct(+ private readonly ConnectionFirewallSync $firewallSync,+ private readonly ResourceConnectionSerializer $connectionSerializer,+ ) {}++ public function store(Request $request): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $projects = $this->projects($currentTeam);+ [$selectedProject, $selectedEnvironment] = $this->selectedProjectAndEnvironment($request, $projects);++ if ($selectedProject === null || $selectedEnvironment === null) {+ return response()->json([+ 'message' => 'Select a project and environment before connecting resources.',+ ], 422);+ }++ $project = $this->projectQuery($currentTeam)+ ->where('uuid', $selectedProject['uuid'])+ ->first();++ if (! $project instanceof Project) {+ abort(403);+ }++ $environment = $this->selectedEnvironment($project, $selectedEnvironment['uuid']);++ if (! $environment instanceof Environment) {+ abort(403);+ }++ $validated = $request->validate([+ 'resource_one' => ['required', 'array'],+ 'resource_one.type' => ['required', 'string', Rule::in(['application'])],+ 'resource_one.uuid' => ['required', 'string', 'max:255'],+ 'resource_two' => ['required', 'array'],+ 'resource_two.type' => ['required', 'string', Rule::in(['application'])],+ 'resource_two.uuid' => ['required', 'string', 'max:255'],+ ]);++ $resourceOne = $this->resolveConnectableResource($currentTeam, $project, $environment, $validated['resource_one']);+ $resourceTwo = $this->resolveConnectableResource($currentTeam, $project, $environment, $validated['resource_two']);++ if ($this->resourceIdentity($resourceOne) === $this->resourceIdentity($resourceTwo)) {+ return response()->json([+ 'message' => 'A resource cannot connect to itself.',+ ], 422);+ }++ $connection = ResourceConnection::query()->firstOrCreate(+ [+ 'team_id' => $currentTeam->id,+ 'resource_pair_key' => $this->resourcePairKey($resourceOne, $resourceTwo),+ ],+ [+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'resource_one_type' => $resourceOne->getMorphClass(),+ 'resource_one_id' => $resourceOne->getKey(),+ 'resource_two_type' => $resourceTwo->getMorphClass(),+ 'resource_two_id' => $resourceTwo->getKey(),+ 'created_by_user_id' => $request->user()->id,+ ],+ );++ return response()->json([+ 'connection' => $this->connectionSerializer->serialize($connection->load('rules')),+ ], $connection->wasRecentlyCreated ? 201 : 200);+ }++ /**+ * Update the connection's rules, then converge the node firewalls.+ *+ * Ordering & failure semantics:+ * 1. Snapshot the current DB rules and their firewall representation; abort+ * with 502 before mutating anything when the snapshot cannot be built.+ * 2. Commit the requested rules in a DB transaction — the DB always holds+ * the desired state.+ * 3. Converge the node firewalls through Flux. Nodes whose coold lacks the+ * firewall verbs (UnsupportedCooldVerb) are tolerated: the committed+ * rules are kept and the request succeeds.+ * 4. On a real Flux failure the previous rules are restored in a second DB+ * transaction, the node firewalls are rolled back to the restored rules+ * best-effort (warning-logged when that also fails — deterministic rule+ * ids keep a later re-sync idempotent), and the original error surfaces+ * to the caller as a 502 {message, detail} response.+ */+ public function update(Request $request, ResourceConnection $connection, FluxClient $fluxClient): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('update', [$connection, $currentTeam]);++ $validated = $request->validate([+ 'ports_by_direction' => ['present', 'array'],+ 'ports_by_direction.*' => ['array'],+ 'ports_by_direction.*.*' => ['integer', 'min:1', 'max:65535', 'distinct'],+ ]);++ $connection->load('rules');+ $oldRulePayloads = $connection->rules+ ->map(fn ($rule): array => [+ 'source_resource_type' => $rule->source_resource_type,+ 'source_resource_id' => $rule->source_resource_id,+ 'target_resource_type' => $rule->target_resource_type,+ 'target_resource_id' => $rule->target_resource_id,+ 'protocol' => $rule->protocol,+ 'port' => $rule->port,+ ])+ ->all();++ try {+ $oldFirewallRules = $this->firewallSync->rulesFor($connection);+ } catch (\RuntimeException $exception) {+ report($exception);+ Log::warning('V5 resource connection firewall snapshot failed', [+ 'connection_id' => $connection->id,+ 'message' => $exception->getMessage(),+ ]);++ return response()->json([+ 'message' => 'Could not sync firewall rules through Flux.',+ 'detail' => 'The connection was left unchanged. Check the server diagnostics and try again.',+ ], 502);+ }++ DB::transaction(function () use ($connection, $validated): void {+ $connection->rules()->delete();+ $resourcesByUuid = $this->connectionSerializer->applicationsByUuid($connection);++ foreach ($validated['ports_by_direction'] as $direction => $ports) {+ [$sourceResourceUuid, $targetResourceUuid] = array_pad(explode('->', (string) $direction, 2), 2, null);+ $sourceResource = is_string($sourceResourceUuid) ? $resourcesByUuid->get($sourceResourceUuid) : null;+ $targetResource = is_string($targetResourceUuid) ? $resourcesByUuid->get($targetResourceUuid) : null;++ if (! $sourceResource instanceof V5Application || ! $targetResource instanceof V5Application) {+ continue;+ }++ foreach (array_unique($ports) as $port) {+ $connection->rules()->create([+ 'source_resource_type' => $this->resourceTypeForConnectionUuid($connection, $sourceResource->uuid),+ 'source_resource_id' => $sourceResource->id,+ 'target_resource_type' => $this->resourceTypeForConnectionUuid($connection, $targetResource->uuid),+ 'target_resource_id' => $targetResource->id,+ 'protocol' => 'tcp',+ 'port' => (int) $port,+ ]);+ }+ }+ });++ $connection->refresh()->load('rules');++ $newFirewallRules = null;++ try {+ $newFirewallRules = $this->firewallSync->rulesFor($connection);+ $this->firewallSync->sync($fluxClient, $oldFirewallRules, $newFirewallRules);+ } catch (\RuntimeException $exception) {+ $this->restoreConnectionRules($connection, $oldRulePayloads);+ $this->rollBackFirewallRules($fluxClient, $connection, $newFirewallRules, $oldFirewallRules);+ report($exception);+ Log::warning('V5 resource connection firewall sync failed', [+ 'connection_id' => $connection->id,+ 'message' => $exception->getMessage(),+ ]);++ return response()->json([+ 'message' => 'Could not sync firewall rules through Flux.',+ 'detail' => 'The previous rules were restored. Check the server diagnostics and try again.',+ ], 502);+ }++ return response()->json([+ 'connection' => $this->connectionSerializer->serialize($connection),+ ]);+ }++ /**+ * Delete the connection using revoke-first ordering.+ *+ * The node firewall rules are revoked before any DB rows are removed. When+ * a revoke fails with a real error the delete is aborted with a 502+ * {message, detail} response so the DB never loses track of rules that may+ * still be open on a reachable node; UnsupportedCooldVerb and+ * already-missing rules are tolerated. When the firewall snapshot cannot+ * be built (an endpoint lost its server host id) the node cannot be+ * addressed at all, so the failure is reported and the delete proceeds.+ * Deterministic rule ids make a retried delete revoke the same node-side+ * rules idempotently.+ */+ public function destroy(Request $request, ResourceConnection $connection, FluxClient $fluxClient): Response|JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('delete', [$connection, $currentTeam]);++ try {+ $oldFirewallRules = $this->firewallSync->rulesFor($connection->load('rules'));+ } catch (\RuntimeException $exception) {+ report($exception);+ $oldFirewallRules = collect();+ }++ try {+ $this->firewallSync->sync($fluxClient, $oldFirewallRules, collect());+ } catch (\RuntimeException $exception) {+ report($exception);+ Log::warning('V5 resource connection firewall revoke failed', [+ 'connection_id' => $connection->id,+ 'message' => $exception->getMessage(),+ ]);++ return response()->json([+ 'message' => 'Could not sync firewall rules through Flux.',+ 'detail' => 'The connection was not deleted. Check the server diagnostics and try again.',+ ], 502);+ }++ $connection->delete();++ return response()->noContent();+ }++ /**+ * @param array{type: string, uuid: string} $resource+ */+ private function resolveConnectableResource(Team $team, Project $project, Environment $environment, array $resource): Model+ {+ return match ($resource['type']) {+ 'application' => V5Application::query()+ ->where('team_id', $team->id)+ ->where('project_id', $project->id)+ ->where('environment_id', $environment->id)+ ->where('uuid', $resource['uuid'])+ ->firstOrFail(),+ };+ }++ private function resourcePairKey(Model $resourceOne, Model $resourceTwo): string+ {+ return collect([+ $this->resourceIdentity($resourceOne),+ $this->resourceIdentity($resourceTwo),+ ])->sort()->implode('|');+ }++ private function resourceIdentity(Model $resource): string+ {+ return $resource->getMorphClass().':'.$resource->getKey();+ }++ private function resourceTypeForConnectionUuid(ResourceConnection $connection, string $resourceUuid): string+ {+ $resourcesByUuid = $this->connectionSerializer->applicationsByUuid($connection);+ $resource = $resourcesByUuid->get($resourceUuid);++ return $resource instanceof V5Application && (int) $connection->resource_one_id === $resource->id+ ? $connection->resource_one_type+ : $connection->resource_two_type;+ }++ /**+ * @param array<int, array<string, mixed>> $rulePayloads+ */+ private function restoreConnectionRules(ResourceConnection $connection, array $rulePayloads): void+ {+ DB::transaction(function () use ($connection, $rulePayloads): void {+ $connection->rules()->delete();++ foreach ($rulePayloads as $rulePayload) {+ $connection->rules()->create($rulePayload);+ }+ });+ }++ /**+ * Best-effort roll back of a partially converged node firewall to the+ * restored rules after a failed forward sync. Skipped when the forward+ * sync never started (the node was not touched). Failures are only logged+ * because the DB already holds the restored, authoritative rules and the+ * deterministic rule ids keep a later re-sync idempotent.+ *+ * @param Collection<int, array{id: string, hostId: string, rule: array{id: string, namespace: string, src: string, dst: string, proto: string, port: int}}>|null $attemptedFirewallRules+ * @param Collection<int, array{id: string, hostId: string, rule: array{id: string, namespace: string, src: string, dst: string, proto: string, port: int}}> $restoredFirewallRules+ */+ private function rollBackFirewallRules(FluxClient $fluxClient, ResourceConnection $connection, ?Collection $attemptedFirewallRules, Collection $restoredFirewallRules): void+ {+ if (! $attemptedFirewallRules instanceof Collection) {+ return;+ }++ try {+ $this->firewallSync->sync($fluxClient, $attemptedFirewallRules, $restoredFirewallRules);+ } catch (\RuntimeException $exception) {+ Log::warning('V5 resource connection firewall rollback failed; node firewall may diverge from the restored rules until the next sync', [+ 'connection_id' => $connection->id,+ 'message' => $exception->getMessage(),+ ]);+ }+ }+}diff --git a/app/Http/Controllers/V5/ServerController.php b/app/Http/Controllers/V5/ServerController.phpnew file mode 100644index 0000000000..6f92a844e1--- /dev/null+++ b/app/Http/Controllers/V5/ServerController.php@@ -0,0 +1,761 @@+<?php++namespace App\Http\Controllers\V5;++use App\Actions\V5\Proxy\StartCaddyIngress;+use App\Actions\V5\Proxy\StopCaddyIngress;+use App\Actions\V5\Server\RemoveBootstrapMarker;+use App\Enums\V5\ServerStatus;+use App\Events\V5ClusterUpdated;+use App\Http\Controllers\Controller;+use App\Http\Controllers\V5\Concerns\HandlesIngressSyncErrors;+use App\Http\Controllers\V5\Concerns\ResolvesCurrentTeam;+use App\Http\Controllers\V5\Concerns\ValidatesBuilderConfiguration;+use App\Jobs\V5BootstrapServerJob;+use App\Models\PrivateKey;+use App\Models\V5\Application as V5Application;+use App\Models\V5\Cluster as V5Cluster;+use App\Models\V5\Server as V5Server;+use App\Rules\ValidServerIp;+use App\Services\Flux\FluxClient;+use App\Support\V5\ClusterSerializer;+use Illuminate\Http\JsonResponse;+use Illuminate\Http\Request;+use Illuminate\Http\Response;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Facades\Process;+use Illuminate\Validation\Rule;++class ServerController extends Controller+{+ use HandlesIngressSyncErrors;+ use ResolvesCurrentTeam;+ use ValidatesBuilderConfiguration;++ public function store(Request $request, V5Cluster $cluster): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('create', [V5Server::class, $currentTeam, $cluster]);++ $validated = $request->validate([+ 'name' => ['required', 'string', 'max:255'],+ 'host' => [+ 'required',+ 'string',+ 'max:255',+ $this->noControlCharactersRule(),+ new ValidServerIp,+ Rule::unique('v5_servers', 'host')+ ->where('team_id', $currentTeam->id)+ ->where('ssh_port', (int) $request->input('ssh_port', 22)),+ ],+ 'ssh_user' => ['required', 'string', 'max:255', 'regex:/^[A-Za-z0-9._-]+$/', $this->noControlCharactersRule()],+ 'ssh_port' => ['required', 'integer', 'min:1', 'max:65535'],+ 'private_key_uuid' => [+ 'required',+ 'string',+ Rule::exists('private_keys', 'uuid')->where('team_id', $currentTeam->id),+ ],+ 'node_address' => [+ 'nullable',+ 'string',+ 'max:255',+ $this->noControlCharactersRule(),+ new ValidServerIp,+ Rule::unique('v5_servers', 'node_address')->where('team_id', $currentTeam->id),+ ],+ 'builder_enabled' => ['sometimes', 'boolean'],+ 'builder_capacity' => $this->builderCapacityRules(+ $this->requestedBuilderEnabled($request, $cluster->builder_enabled)+ ),+ 'builder_cpu_quota' => ['sometimes', 'string', 'max:32'],+ 'wireguard_listen_port_override' => ['nullable', 'integer', 'min:1', 'max:65535'],+ 'wireguard_endpoint_override' => [+ 'nullable',+ 'string',+ 'max:255',+ $this->noControlCharactersRule(),+ $this->hostPortRule(),+ Rule::unique('v5_servers', 'wireguard_endpoint_override')->where('cluster_id', $cluster->id),+ ],+ 'ingress_enabled' => ['sometimes', 'boolean'],+ 'ingress_type' => [+ Rule::requiredIf(fn () => $request->boolean('ingress_enabled')),+ 'nullable',+ 'string',+ Rule::in(['caddy']),+ ],+ ]);++ $capacity = $this->clusterServerCapacity($cluster);++ if ($capacity !== null && $cluster->servers()->count() >= $capacity) {+ return response()->json([+ 'message' => "This cluster's network pools are full ({$capacity} server(s) max). Grow the pools or remove a server first.",+ ], 422);+ }++ $builderEnabled = (bool) ($validated['builder_enabled'] ?? $cluster->builder_enabled);+ $ingressEnabled = (bool) ($validated['ingress_enabled'] ?? false);+ $ingressType = $ingressEnabled ? $validated['ingress_type'] : null;+ $builderCapacity = (int) ($validated['builder_capacity'] ?? $cluster->builder_capacity);+ $builderCpuQuota = $validated['builder_cpu_quota'] ?? $cluster->builder_cpu_quota;+ $devWireguardOverrides = $this->devLimaWireguardOverrides($validated['host'], (int) $validated['ssh_port']);+ $privateKey = PrivateKey::query()+ ->where('team_id', $currentTeam->id)+ ->where('uuid', $validated['private_key_uuid'])+ ->firstOrFail();++ V5Server::query()->create([+ 'team_id' => $currentTeam->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $request->user()->id,+ 'name' => $validated['name'],+ 'host' => $validated['host'],+ 'ssh_user' => $validated['ssh_user'],+ 'ssh_port' => $validated['ssh_port'],+ 'private_key_id' => $privateKey->id,+ 'status' => ServerStatus::Added->value,+ 'ingress_type' => $ingressType,+ 'is_ingress' => $ingressEnabled,+ 'builder_enabled' => $builderEnabled,+ 'builder_capacity' => $builderCapacity,+ 'builder_cpu_quota' => $builderCpuQuota,+ 'node_address' => $validated['node_address'] ?? $validated['host'],+ 'wireguard_listen_port_override' => $validated['wireguard_listen_port_override'] ?? $devWireguardOverrides['listen_port'],+ 'wireguard_endpoint_override' => $validated['wireguard_endpoint_override'] ?? $devWireguardOverrides['endpoint'],+ ]);++ return response()->json([+ 'cluster' => app(ClusterSerializer::class)->serializeFresh($cluster),+ ], 201);+ }++ public function update(Request $request, V5Cluster $cluster, V5Server $server): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('update', [$server, $currentTeam, $cluster]);++ $validated = $request->validate([+ 'builder_enabled' => ['required', 'boolean'],+ 'builder_capacity' => $this->builderCapacityRules(+ $request->boolean('builder_enabled'),+ required: true+ ),+ 'builder_cpu_quota' => ['required', 'string', 'max:32'],+ 'ingress_enabled' => ['sometimes', 'boolean'],+ 'ingress_type' => [+ Rule::requiredIf(fn () => $request->boolean('ingress_enabled')),+ 'nullable',+ 'string',+ Rule::in(['caddy']),+ ],+ ]);++ $wasIngress = $server->isIngress();+ $builderEnabled = (bool) $validated['builder_enabled'];+ $ingressEnabled = (bool) ($validated['ingress_enabled'] ?? $wasIngress);+ $ingressType = $ingressEnabled ? ($validated['ingress_type'] ?? $server->ingress_type ?? 'caddy') : null;+ $originalServerAttributes = $server->only([+ 'is_ingress',+ 'ingress_type',+ 'ingress_status',+ 'builder_enabled',+ 'builder_capacity',+ 'builder_cpu_quota',+ ]);++ // Stop the ingress before persisting the change: StopCaddyIngress needs+ // the server's current ingress state, and a failed stop must leave the+ // capability untouched.+ if ($wasIngress && ! $ingressEnabled && $server->status === ServerStatus::Installed->value) {+ try {+ StopCaddyIngress::run($server);+ } catch (\RuntimeException $exception) {+ return $this->ingressSyncErrorResponse($exception);+ }+ }++ $server->update([+ 'is_ingress' => $ingressEnabled,+ 'ingress_type' => $ingressType,+ 'builder_enabled' => $builderEnabled,+ 'builder_capacity' => (int) $validated['builder_capacity'],+ 'builder_cpu_quota' => $validated['builder_cpu_quota'],+ ]);++ $server->refresh();++ if (! $wasIngress && $ingressEnabled && $server->status === ServerStatus::Installed->value) {+ try {+ StartCaddyIngress::run($server);+ } catch (\RuntimeException $exception) {+ $server->update($originalServerAttributes);++ return $this->ingressSyncErrorResponse($exception);+ }+ }++ return response()->json([+ 'cluster' => app(ClusterSerializer::class)->serializeFresh($cluster),+ ]);+ }++ public function check(Request $request, V5Cluster $cluster, V5Server $server): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('check', [$server, $currentTeam, $cluster]);++ if (! $server->privateKey instanceof PrivateKey) {+ return response()->json([+ 'status' => 'failed',+ 'output' => 'No private key is attached to this server.',+ 'checkedAt' => now()->toJSON(),+ ]);+ }++ $keyDirectory = storage_path('app/ssh/keys');+ if (! is_dir($keyDirectory)) {+ mkdir($keyDirectory, 0700, true);+ }++ $keyLocation = tempnam($keyDirectory, 'v5_ssh_key_');+ if ($keyLocation === false) {+ return response()->json([+ 'status' => 'failed',+ 'output' => 'Could not create a temporary SSH key file.',+ 'checkedAt' => now()->toJSON(),+ ]);+ }++ file_put_contents($keyLocation, $server->privateKey->private_key);+ chmod($keyLocation, 0600);++ $target = "{$server->ssh_user}@{$server->host}";+ $command = [+ 'ssh',+ '-o',+ 'BatchMode=yes',+ '-o',+ 'LogLevel=ERROR',+ '-o',+ 'StrictHostKeyChecking=no',+ '-o',+ 'UserKnownHostsFile=/dev/null',+ '-o',+ 'ConnectTimeout=10',+ '-o',+ 'IdentitiesOnly=yes',+ '-i',+ $keyLocation,+ '-p',+ (string) $server->ssh_port,+ $target,+ "printf 'SSH connection OK\n'; hostname; uname -srm; command -v docker || true; command -v podman || true",+ ];++ try {+ $result = Process::timeout(15)->run($command);+ $output = trim($result->output()."\n".$result->errorOutput());+ $status = $result->successful() ? 'reachable' : 'failed';+ } catch (\Throwable $e) {+ $output = $e->getMessage();+ $status = 'failed';+ } finally {+ @unlink($keyLocation);+ }++ return response()->json([+ 'status' => $status,+ 'output' => str($output !== '' ? $output : 'No output returned.')->limit(10000)->toString(),+ 'checkedAt' => now()->toJSON(),+ ]);+ }++ public function cooldLogs(Request $request, V5Cluster $cluster, V5Server $server, FluxClient $fluxClient): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('viewDiagnostics', [$server, $currentTeam, $cluster]);++ $validated = $request->validate([+ 'tail' => ['sometimes', 'integer', 'min:1', 'max:1000'],+ ]);++ $hostId = $server->fluxHostId();++ if (! is_string($hostId) || $hostId === '') {+ return response()->json([+ 'message' => 'This server is missing its Flux host id.',+ ], 422);+ }++ try {+ $output = $fluxClient->cooldLogs($hostId, (int) ($validated['tail'] ?? 200));+ } catch (\Throwable $e) {+ Log::warning('V5 coold logs request failed', [+ 'server_id' => $server->id,+ 'message' => $e->getMessage(),+ ]);++ if ($server->privateKey instanceof PrivateKey) {+ try {+ return response()->json([+ 'output' => $this->cooldLogsOverSsh($server, (int) ($validated['tail'] ?? 200)),+ 'source' => 'ssh',+ 'fetchedAt' => now()->toJSON(),+ ]);+ } catch (\Throwable $sshException) {+ Log::warning('V5 coold logs SSH fallback failed', [+ 'server_id' => $server->id,+ 'message' => $sshException->getMessage(),+ ]);+ }+ }++ return response()->json([+ 'message' => 'Could not fetch coold logs through Flux. Check the Flux and coold status, then try again.',+ ], 502);+ }++ return response()->json([+ 'output' => $output,+ 'source' => 'flux',+ 'fetchedAt' => now()->toJSON(),+ ]);+ }++ private function cooldLogsOverSsh(V5Server $server, int $tail): string+ {+ return $this->runServerSshCommand(+ $server,+ 'sudo -n journalctl -u coold -n '.max(1, min($tail, 1000)).' --no-pager -q || journalctl -u coold -n '.max(1, min($tail, 1000)).' --no-pager -q',+ 'SSH coold log command failed.',+ );+ }++ private function runServerSshCommand(V5Server $server, string $remoteCommand, string $failureMessage): string+ {+ $keyDirectory = storage_path('app/ssh/keys');+ if (! is_dir($keyDirectory)) {+ mkdir($keyDirectory, 0700, true);+ }++ $keyLocation = tempnam($keyDirectory, 'v5_ssh_key_');+ if ($keyLocation === false) {+ throw new \RuntimeException('Could not create a temporary SSH key file.');+ }++ file_put_contents($keyLocation, $server->privateKey->private_key);+ chmod($keyLocation, 0600);++ try {+ $result = Process::timeout(15)->run([+ 'ssh',+ '-o',+ 'BatchMode=yes',+ '-o',+ 'LogLevel=ERROR',+ '-o',+ 'StrictHostKeyChecking=no',+ '-o',+ 'UserKnownHostsFile=/dev/null',+ '-o',+ 'ConnectTimeout=10',+ '-o',+ 'IdentitiesOnly=yes',+ '-i',+ $keyLocation,+ '-p',+ (string) $server->ssh_port,+ "{$server->ssh_user}@{$server->host}",+ $remoteCommand,+ ]);+ $output = trim($result->output()."\n".$result->errorOutput());++ if (! $result->successful()) {+ throw new \RuntimeException($output !== '' ? $output : $failureMessage);+ }++ return str($output)->limit(10000)->toString();+ } finally {+ @unlink($keyLocation);+ }+ }++ public function corrosionTables(Request $request, V5Cluster $cluster, V5Server $server, FluxClient $fluxClient): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('viewDiagnostics', [$server, $currentTeam, $cluster]);++ $validated = $request->validate([+ 'limit' => ['sometimes', 'integer', 'min:1', 'max:1000'],+ ]);++ $hostId = $server->fluxHostId();++ if (! is_string($hostId) || $hostId === '') {+ return response()->json([+ 'message' => 'This server is missing its Flux host id.',+ ], 422);+ }++ try {+ $output = $fluxClient->corrosionTables($hostId, (int) ($validated['limit'] ?? 200));+ } catch (\Throwable $e) {+ Log::warning('V5 corrosion tables request failed', [+ 'server_id' => $server->id,+ 'message' => $e->getMessage(),+ ]);++ if ($server->privateKey instanceof PrivateKey) {+ try {+ return response()->json([+ 'output' => $this->corrosionTablesOverSsh($server, $cluster, (int) ($validated['limit'] ?? 200)),+ 'source' => 'ssh',+ 'fetchedAt' => now()->toJSON(),+ ]);+ } catch (\Throwable $sshException) {+ Log::warning('V5 corrosion tables SSH fallback failed', [+ 'server_id' => $server->id,+ 'message' => $sshException->getMessage(),+ ]);+ }+ }++ return response()->json([+ 'message' => 'Could not fetch corrosion tables through Flux. Check the Flux and coold status, then try again.',+ ], 502);+ }++ return response()->json([+ 'output' => $output,+ 'source' => 'flux',+ 'fetchedAt' => now()->toJSON(),+ ]);+ }++ private function corrosionTablesOverSsh(V5Server $server, V5Cluster $cluster, int $limit): string+ {+ $limit = max(1, min($limit, 1000));+ $script = <<<'PYTHON'+python3 - <<'PY'+import json+import urllib.request++limit = __LIMIT__+url = "http://127.0.0.1:__PORT__/v1/queries"++def query(sql):+ request = urllib.request.Request(+ url,+ data=json.dumps([sql, []]).encode(),+ headers={"Content-Type": "application/json"},+ )+ with urllib.request.urlopen(request, timeout=10) as response:+ return json.loads(response.read().decode())++def quote_identifier(value):+ return '"' + value.replace('"', '""') + '"'++tables = []+for row in query("SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"):+ name = row[0] if row else None+ if not isinstance(name, str):+ continue++ identifier = quote_identifier(name)+ columns = [column[1] for column in query(f"PRAGMA table_info({identifier})") if len(column) > 1]+ rows = query(f"SELECT * FROM {identifier} LIMIT {limit}")+ tables.append({"name": name, "columns": columns, "rows": rows})++print(json.dumps({"limit": limit, "tables": tables}, separators=(",", ":")))+PY+PYTHON;++ return $this->runServerSshCommand($server, str_replace(+ ['__LIMIT__', '__PORT__'],+ [(string) $limit, (string) $cluster->corrosion_api_port],+ $script,+ ), 'SSH corrosion table command failed.');+ }++ public function firewallRules(Request $request, V5Cluster $cluster, V5Server $server, FluxClient $fluxClient): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('viewDiagnostics', [$server, $currentTeam, $cluster]);++ $validated = $request->validate([+ 'namespace' => ['sometimes', 'string', 'max:63'],+ ]);++ $hostId = $server->fluxHostId();++ if (! is_string($hostId) || $hostId === '') {+ return response()->json([+ 'message' => 'This server is missing its Flux host id.',+ ], 422);+ }++ try {+ $rules = $fluxClient->listFirewallRules($hostId, (string) ($validated['namespace'] ?? ''));+ } catch (\Throwable $e) {+ Log::warning('V5 firewall rules request failed', [+ 'server_id' => $server->id,+ 'message' => $e->getMessage(),+ ]);++ return response()->json([+ 'message' => 'Could not fetch firewall rules through Flux. Check the Flux and coold status, then try again.',+ ], 502);+ }++ return response()->json([+ 'rules' => $rules,+ 'source' => 'flux',+ 'fetchedAt' => now()->toJSON(),+ ]);+ }++ public function bootstrap(Request $request, V5Cluster $cluster, V5Server $server): JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('bootstrap', [$server, $currentTeam, $cluster]);++ // Fail fast: the bootstrap job hard-fails on Flux enrollment (after+ // the WireGuard mesh is already built) when no Flux URL is configured.+ if (trim((string) config('coold.flux_url', '')) === '') {+ return response()->json([+ 'message' => 'COOLIFY_COOLD_FLUX_URL is not configured, so bootstrapped servers cannot be enrolled into Flux. Set it and retry the bootstrap.',+ ], 422);+ }++ if ($server->last_bootstrapped_at !== null) {+ return response()->json([+ 'message' => 'This server is already bootstrapped.',+ ], 409);+ }++ $installedServers = $cluster->servers()+ ->with('privateKey')+ ->whereNotNull('last_bootstrapped_at')+ ->orderBy('name')+ ->get();+ $server->load('privateKey');+ $servers = $installedServers->toBase()+ ->push($server)+ ->unique('id')+ ->values();++ if ($servers->contains(fn (V5Server $server) => ! $server->privateKey instanceof PrivateKey)) {+ return response()->json([+ 'message' => 'The new server and every already-bootstrapped server in this cluster must have a private key before extending the cluster.',+ ], 422);+ }++ $claim = DB::transaction(function () use ($cluster, $server, $installedServers): array {+ $clusterServers = $cluster->servers()->lockForUpdate()->get();+ $activeServer = $clusterServers->first(fn (V5Server $candidate): bool => $this->hasActiveBootstrapClaim($candidate));++ if ($activeServer instanceof V5Server) {+ return ['claimed' => false, 'active_server_id' => $activeServer->id];+ }++ // Sweep provably dead claims (lost job or killed worker) so retries+ // are possible and the UI reflects reality.+ $clusterServers+ ->filter(fn (V5Server $candidate): bool => in_array($candidate->last_bootstrap_status, ['queued', 'running'], true))+ ->each(fn (V5Server $candidate) => $candidate->update([+ 'last_bootstrap_status' => 'failed',+ 'last_bootstrap_output' => 'The previous bootstrap attempt timed out or its worker died. Retry the bootstrap.',+ ]));++ $server->update([+ 'last_bootstrap_action' => $installedServers->isEmpty() ? 'bootstrap' : 'extend',+ 'last_bootstrap_status' => 'queued',+ 'last_bootstrap_output' => "Queued Coolify bootstrap for {$server->name}.",+ 'last_bootstrap_ran_at' => now(),+ ]);++ return ['claimed' => true, 'active_server_id' => null];+ });++ if (! $claim['claimed']) {+ return response()->json([+ 'cluster' => app(ClusterSerializer::class)->serializeFresh($cluster),+ 'message' => $claim['active_server_id'] === $server->id+ ? 'Bootstrap is already queued or running for this server.'+ : 'Another server bootstrap is already queued or running for this cluster.',+ ], 409);+ }++ V5ClusterUpdated::dispatch($currentTeam->id, $cluster->id);+ V5BootstrapServerJob::dispatch($cluster->id, $server->id);++ return response()->json([+ 'cluster' => app(ClusterSerializer::class)->serializeFresh($cluster),+ 'message' => 'Bootstrap queued.',+ ], 202);+ }++ public function destroy(Request $request, V5Cluster $cluster, V5Server $server): Response|JsonResponse+ {+ $currentTeam = $this->currentTeamOrFail($request);+ $this->authorize('delete', [$server, $currentTeam, $cluster]);++ if (V5Application::query()->where('server_id', $server->id)->exists()) {+ return response()->json([+ 'message' => 'Delete or move applications from this server before deleting it.',+ ], 422);+ }++ $warning = null;++ if ($server->last_bootstrapped_at !== null) {+ if ($server->isIngress() && $server->status === ServerStatus::Installed->value) {+ try {+ StopCaddyIngress::run($server);+ } catch (\Throwable $exception) {+ report($exception);+ $warning = 'Could not stop the Caddy ingress on the server before deleting it.';+ }+ }++ if (! RemoveBootstrapMarker::run($server)) {+ $warning = 'Could not clean up the server over SSH. Remove /etc/coolify/v5-node.json manually before re-adding this server.';+ }+ }++ $server->delete();++ return response()->json(array_filter([+ 'cluster' => app(ClusterSerializer::class)->serializeFresh($cluster),+ 'warning' => $warning,+ ]));+ }++ /**+ * A queued claim is active while the job could still pick it up; a running+ * claim is active until the job timeout (plus margin) has passed. Anything+ * older is provably dead because the job runs with $tries = 1.+ */+ private function hasActiveBootstrapClaim(V5Server $server): bool+ {+ $ranAt = $server->last_bootstrap_ran_at;++ return match ($server->last_bootstrap_status) {+ 'queued' => $ranAt !== null && $ranAt->gt(now()->subMinutes(15)),+ 'running' => $ranAt !== null && $ranAt->gt(now()->subSeconds(V5BootstrapServerJob::TIMEOUT_SECONDS + 300)),+ default => false,+ };+ }++ /**+ * @return array{listen_port: int|null, endpoint: string|null}+ */+ private function devLimaWireguardOverrides(string $host, int $sshPort): array+ {+ if (! app()->environment(['local', 'development', 'testing']) || $host !== 'host.docker.internal') {+ return ['listen_port' => null, 'endpoint' => null];+ }++ if ($sshPort < 60001 || $sshPort > 60009) {+ return ['listen_port' => null, 'endpoint' => null];+ }++ $wireguardPort = $sshPort - 8180;++ return [+ 'listen_port' => $wireguardPort,+ 'endpoint' => "host.lima.internal:{$wireguardPort}",+ ];+ }++ private function clusterServerCapacity(V5Cluster $cluster): ?int+ {+ $namespaceCount = max(1, count($cluster->namespaces ?? V5Cluster::DEFAULT_NAMESPACES));++ [, $poolPrefix] = array_pad(explode('/', (string) $cluster->container_network_pool, 2), 2, null);+ $containerPrefix = (int) $cluster->container_network_prefix;++ if (! is_string($poolPrefix) || ! ctype_digit($poolPrefix) || $containerPrefix < (int) $poolPrefix || $containerPrefix > 32) {+ return null;+ }++ $containerCapacity = intdiv(2 ** ($containerPrefix - (int) $poolPrefix), $namespaceCount);++ [, $managementPrefix] = array_pad(explode('/', (string) $cluster->wireguard_management_pool, 2), 2, null);+ $managementCapacity = is_string($managementPrefix) && ctype_digit($managementPrefix) && (int) $managementPrefix <= 30+ ? (2 ** (32 - (int) $managementPrefix)) - 2+ : null;++ return $managementCapacity === null ? $containerCapacity : min($containerCapacity, $managementCapacity);+ }++ private function noControlCharactersRule(): \Closure+ {+ return function (string $attribute, mixed $value, \Closure $fail): void {+ if (! is_string($value)) {+ return;+ }++ if (preg_match('/[\x00-\x1F\x7F]/', $value) === 1) {+ $fail('The :attribute contains invalid control characters.');+ }+ };+ }++ private function hostPortRule(): \Closure+ {+ return function (string $attribute, mixed $value, \Closure $fail): void {+ if ($value === null || $value === '') {+ return;+ }++ if (! is_string($value)) {+ $fail('The :attribute must be in host:port format.');++ return;+ }++ $value = trim($value);++ if (preg_match('/^\[(?<host>.+)]:(?<port>\d+)$/', $value, $matches) === 1) {+ $host = trim((string) $matches['host']);+ $port = trim((string) $matches['port']);+ } else {+ $separatorPosition = strrpos($value, ':');++ if ($separatorPosition === false) {+ $fail('The :attribute must be in host:port format.');++ return;+ }++ $host = trim(substr($value, 0, $separatorPosition));+ $port = trim(substr($value, $separatorPosition + 1));++ if (str_contains($host, ':')) {+ $fail('The :attribute must use [ipv6]:port format for IPv6 addresses.');++ return;+ }+ }++ if ($host === '' || $port === '' || ! ctype_digit($port) || (int) $port < 1 || (int) $port > 65535) {+ $fail('The :attribute must be in host:port format.');++ return;+ }++ $failed = false;+ (new ValidServerIp)->validate($attribute, $host, function () use (&$failed): void {+ $failed = true;+ });++ if ($failed) {+ $fail('The :attribute must be in host:port format.');+ }+ };+ }+}diff --git a/app/Http/Kernel.php b/app/Http/Kernel.phpindex c2b183cd4d..146a493ad4 100644--- a/app/Http/Kernel.php+++ b/app/Http/Kernel.php@@ -92,6 +92,7 @@ class Kernel extends HttpKernel'v5.authenticated' => ['auth','verified',+ 'throttle:v5',V5EnsureCurrentTeam::class,],diff --git a/app/Http/Middleware/V5/EnsureCurrentTeam.php b/app/Http/Middleware/V5/EnsureCurrentTeam.phpindex f8aa78f928..a8a05bf382 100644--- a/app/Http/Middleware/V5/EnsureCurrentTeam.php+++ b/app/Http/Middleware/V5/EnsureCurrentTeam.php@@ -25,7 +25,13 @@ class EnsureCurrentTeamabort(403, 'No team available for this user.');}- session(['currentTeam' => $currentTeam]);+ // The v4 UI stores a full Team model under the same session key and+ // reads arbitrary columns off it, so only rewrite the session when the+ // resolved team actually changed — and always store the full model.+ if (data_get(session('currentTeam'), 'id') !== $currentTeam->id) {+ session(['currentTeam' => $currentTeam]);+ }+$request->attributes->set('v5.currentTeam', $currentTeam);return $next($request);@@ -37,7 +43,6 @@ class EnsureCurrentTeamif ($sessionTeamId) {$sessionTeam = $user->teams()- ->select('teams.id', 'teams.name', 'teams.description', 'teams.personal_team')->whereKey($sessionTeamId)->first();@@ -47,7 +52,6 @@ class EnsureCurrentTeam}return $user->teams()- ->select('teams.id', 'teams.name', 'teams.description', 'teams.personal_team')->orderBy('teams.id')->first();}diff --git a/app/Jobs/V5BootstrapServerJob.php b/app/Jobs/V5BootstrapServerJob.phpindex d19ea4ccde..e8ed956742 100644--- a/app/Jobs/V5BootstrapServerJob.php+++ b/app/Jobs/V5BootstrapServerJob.php@@ -3,39 +3,47 @@namespace App\Jobs;use App\Actions\V5\Proxy\StartCaddyIngress;+use App\Enums\V5\ServerStatus;use App\Events\V5ClusterUpdated;use App\Models\PrivateKey;use App\Models\V5\Cluster as V5Cluster;use App\Models\V5\Server as V5Server;+use App\Services\Flux\AgentTokenIssuer;+use App\Services\Flux\FluxClient;use Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldBeEncrypted;+use Illuminate\Contracts\Queue\ShouldBeUnique;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;-use Illuminate\Queue\Middleware\WithoutOverlapping;use Illuminate\Queue\SerializesModels;use Illuminate\Support\Collection;use Illuminate\Support\Facades\Log;use Illuminate\Support\Facades\Process;-class V5BootstrapServerJob implements ShouldBeEncrypted, ShouldQueue+class V5BootstrapServerJob implements ShouldBeEncrypted, ShouldBeUnique, ShouldQueue{use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;private const BOOTSTRAP_MARKER_PATH = '/etc/coolify/v5-node.json';- public int $tries = 1;+ public const TIMEOUT_SECONDS = 7200;- public int $timeout = 7200;+ public int $tries = 1;- public function __construct(public int $clusterId, public int $serverId) {}+ public int $timeout = self::TIMEOUT_SECONDS;/**- * @return array<int, object>+ * Second idempotency layer on top of the controller's DB bootstrap claim,+ * aligned with its running-claim window (TIMEOUT_SECONDS plus margin).*/- public function middleware(): array+ public int $uniqueFor = self::TIMEOUT_SECONDS + 300;++ public function __construct(public int $clusterId, public int $serverId) {}++ public function uniqueId(): string{- return [(new WithoutOverlapping("v5-bootstrap-server-{$this->serverId}"))->expireAfter(7200)->dontRelease()];+ return (string) $this->serverId;}public function handle(): void@@ -58,18 +66,28 @@ class V5BootstrapServerJob implements ShouldBeEncrypted, ShouldQueue->unique('id')->values();+ $started = V5Server::query()+ ->whereKey($server->id)+ ->where('last_bootstrap_status', 'queued')+ ->update([+ 'last_bootstrap_action' => $action,+ 'last_bootstrap_status' => 'running',+ 'last_bootstrap_output' => "Starting Coolify CLI {$action} for {$server->name}...",+ 'last_bootstrap_ran_at' => now(),+ ]);++ if ($started === 0) {+ return;+ }++ $server->refresh();+if ($servers->contains(fn (V5Server $server) => ! $server->privateKey instanceof PrivateKey)) {$this->markFailed($server, $action, 'The new server and every already-bootstrapped server in this cluster must have a private key before extending the cluster.');return;}- $server->update([- 'last_bootstrap_action' => $action,- 'last_bootstrap_status' => 'running',- 'last_bootstrap_output' => "Starting Coolify CLI {$action} for {$server->name}...",- 'last_bootstrap_ran_at' => now(),- ]);$this->broadcastClusterUpdated($server);$keyDirectory = storage_path('app/ssh/keys');@@ -89,18 +107,23 @@ class V5BootstrapServerJob implements ShouldBeEncrypted, ShouldQueue$existingBootstrap = $this->detectExistingBootstrap($server, $sshConfigLocation);if (($existingBootstrap['cluster_id'] ?? null) !== null) {- if ((string) $existingBootstrap['cluster_id'] !== (string) $cluster->id) {+ $markerClusterUuid = $existingBootstrap['cluster_uuid'] ?? null;++ if (+ (string) $existingBootstrap['cluster_id'] !== (string) $cluster->id+ || (is_string($markerClusterUuid) && $markerClusterUuid !== $cluster->uuid)+ ) {$this->markFailed($server, $action, 'This server is already bootstrapped for another cluster. Reset the host bootstrap state before joining this cluster.');return;}- $this->adoptExistingBootstrap($server, $existingBootstrap);+ $this->adoptExistingBootstrap($cluster, $server, $existingBootstrap, $sshConfigLocation);return;}- $result = Process::timeout(300)+ $result = Process::timeout(7200)->run($this->bootstrapCommand($cluster, $servers, $server, $sshConfigLocation, $action));$output = trim($result->output()."\n".$result->errorOutput());$successful = $result->successful();@@ -117,22 +140,26 @@ class V5BootstrapServerJob implements ShouldBeEncrypted, ShouldQueuereturn;}- $capabilities = collect($server->capabilities ?? [])- ->push('coold')- ->when($server->isIngress(), fn ($capabilities) => $capabilities->push('ingress'))- ->unique()- ->values()- ->all();+ $this->persistBootstrapAssignments($cluster, $server, $result->output(), $sshConfigLocation);+ $server->refresh();++ // Resolve the coold version once so the on-host marker and the+ // database row always agree.+ $cooldVersion = $this->bootstrappedCooldVersion($cluster, $result->output());++ $this->writeBootstrapMarker($cluster, $server, $sshConfigLocation, $cooldVersion);++ $this->enrollCooldIntoFlux($server, $sshConfigLocation);+ $this->waitForFluxHostConnection($server);$server->update([- 'status' => 'installed',- 'capabilities' => $capabilities,+ 'status' => ServerStatus::Installed->value,+ 'has_coold' => true,+ 'coold_version' => $cooldVersion,'last_bootstrapped_at' => now(),]);$this->broadcastClusterUpdated($server);- $this->writeBootstrapMarker($cluster, $server, $sshConfigLocation);-if ($server->isIngress()) {StartCaddyIngress::run($server->fresh('privateKey'));}@@ -183,11 +210,13 @@ class V5BootstrapServerJob implements ShouldBeEncrypted, ShouldQueue'init',$action,'--format',- 'table',+ 'json','--nodes',$servers->map(fn (V5Server $server) => $this->bootstrapNode($server))->implode(','),'--ssh-config',$sshConfigLocation,+ '--ssh-user',+ $newServer->ssh_user,'--namespaces',implode(',', $cluster->namespaces ?? V5Cluster::DEFAULT_NAMESPACES),'--container-pool',@@ -308,14 +337,17 @@ class V5BootstrapServerJob implements ShouldBeEncrypted, ShouldQueue/*** @param array<string, mixed> $marker*/- private function adoptExistingBootstrap(V5Server $server, array $marker): void+ private function adoptExistingBootstrap(V5Cluster $cluster, V5Server $server, array $marker, string $sshConfigLocation): void{+ $bootstrapNode = $this->bootstrapNode($server);$serverUuid = is_string($marker['server_uuid'] ?? null) ? $marker['server_uuid'] : null;$updates = ['wireguard_management_ip' => is_string($marker['wireguard_management_ip'] ?? null) ? $marker['wireguard_management_ip'] : $server->wireguard_management_ip,'wireguard_public_key' => is_string($marker['wireguard_public_key'] ?? null) ? $marker['wireguard_public_key'] : $server->wireguard_public_key,+ 'coold_version' => is_string($marker['coold_version'] ?? null) && trim($marker['coold_version']) !== '' ? trim($marker['coold_version']) : $cluster->coold_version,'container_subnets' => is_array($marker['container_subnets'] ?? null) ? $marker['container_subnets'] : $server->container_subnets,- 'status' => 'installed',+ 'has_coold' => true,+ 'status' => ServerStatus::Installed->value,'last_bootstrap_status' => 'succeeded','last_bootstrap_output' => 'Adopted existing Coolify bootstrap state for this cluster.','last_bootstrap_ran_at' => now(),@@ -329,28 +361,399 @@ class V5BootstrapServerJob implements ShouldBeEncrypted, ShouldQueue$server->update($updates);$this->broadcastClusterUpdated($server);+ $this->enrollCooldIntoFlux($server->fresh(), $sshConfigLocation, $bootstrapNode);+ $this->waitForFluxHostConnection($server->fresh());+if ($server->isIngress()) {StartCaddyIngress::run($server->fresh('privateKey'));}}- private function writeBootstrapMarker(V5Cluster $cluster, V5Server $server, string $sshConfigLocation): void+ private function persistBootstrapAssignments(V5Cluster $cluster, V5Server $server, string $output, string $sshConfigLocation): void+ {+ $verifiedNode = $this->verifiedBootstrapNode($output, $server);+ $wireguardManagementIp = is_array($verifiedNode) && is_string($verifiedNode['wireguard_ip'] ?? null)+ ? $verifiedNode['wireguard_ip']+ : null;+ $warnings = [];++ if (! is_string($wireguardManagementIp) || $wireguardManagementIp === '') {+ $wireguardManagementIp = $this->readWireguardManagementIp($cluster, $server, $sshConfigLocation, $warnings);+ }++ $wireguardPublicKey = $this->readWireguardPublicKey($cluster, $server, $sshConfigLocation, $warnings);+ $containerSubnets = $this->readContainerSubnets($cluster, $server, $sshConfigLocation, $warnings);+ $updates = [];++ if ($wireguardManagementIp !== null && $wireguardManagementIp !== '') {+ $updates['wireguard_management_ip'] = $wireguardManagementIp;++ if (! is_string($server->node_address) || $server->node_address === '' || $server->node_address === $server->host) {+ $updates['node_address'] = $wireguardManagementIp;+ }+ } else {+ $warnings[] = 'Warning: could not determine the WireGuard management IP from the CLI output.';+ }++ if ($wireguardPublicKey !== null && $wireguardPublicKey !== '') {+ $updates['wireguard_public_key'] = $wireguardPublicKey;+ }++ if ($containerSubnets !== []) {+ $updates['container_subnets'] = $containerSubnets;+ }++ if ($warnings !== []) {+ $updates['last_bootstrap_output'] = str(trim($server->last_bootstrap_output."\n".implode("\n", $warnings)))+ ->limit(20000)+ ->toString();+ }++ if ($updates !== []) {+ $server->update($updates);+ }+ }++ /**+ * @param array<int, string> $warnings+ */+ private function readWireguardManagementIp(V5Cluster $cluster, V5Server $server, string $sshConfigLocation, array &$warnings): ?string+ {+ $interface = escapeshellarg($cluster->wireguard_interface);+ $script = implode("\n", [+ "SUDO=''",+ 'if [ "$(id -u)" != "0" ]; then SUDO=\'sudo\'; fi',+ "\$SUDO ip -4 -o addr show dev {$interface} | awk '{print \$4}' | cut -d/ -f1 | head -n1",+ ]);++ $result = Process::timeout(15)->run([+ 'ssh',+ '-F',+ $sshConfigLocation,+ $this->bootstrapNode($server),+ $script,+ ]);++ $ipAddress = trim($result->output());++ if (! $result->successful() || filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {+ $warnings[] = 'Warning: could not read the WireGuard management IP from the server.';++ return null;+ }++ return $ipAddress;+ }++ /**+ * @return array<string, mixed>|null+ */+ private function verifiedBootstrapNode(string $output, V5Server $server): ?array+ {+ $decoded = $this->decodedBootstrapOutput($output);++ if (! is_array($decoded)) {+ return null;+ }++ $verifiedNodes = data_get($decoded, 'verified');++ if (! is_array($verifiedNodes)) {+ return null;+ }++ $bootstrapNode = $this->bootstrapNode($server);++ foreach ($verifiedNodes as $verifiedNode) {+ if (! is_array($verifiedNode)) {+ continue;+ }++ $host = $verifiedNode['host'] ?? $verifiedNode['node'] ?? $verifiedNode['name'] ?? null;++ if ($host === $bootstrapNode || $host === $server->uuid || $host === $server->name || $host === $server->host) {+ return $verifiedNode;+ }+ }++ return null;+ }++ /**+ * @return array<string, mixed>|null+ */+ private function decodedBootstrapOutput(string $output): ?array+ {+ $output = trim($output);++ if ($output === '' || ! str_starts_with($output, '{')) {+ return null;+ }++ try {+ $decoded = json_decode($output, true, flags: JSON_THROW_ON_ERROR);+ } catch (\JsonException) {+ return null;+ }++ return is_array($decoded) ? $decoded : null;+ }++ /**+ * The CLI init JSON output does not currently report the installed coold+ * version, so fall back to the version the cluster asked the CLI to+ * install (`--coold-version`). If a future CLI adds a `coold_version` key+ * to its JSON output, prefer that.+ */+ private function bootstrappedCooldVersion(V5Cluster $cluster, string $output): ?string+ {+ $reported = data_get($this->decodedBootstrapOutput($output), 'coold_version');++ if (is_string($reported) && trim($reported) !== '') {+ return trim($reported);+ }++ return $cluster->coold_version;+ }++ /**+ * @param array<int, string> $warnings+ */+ private function readWireguardPublicKey(V5Cluster $cluster, V5Server $server, string $sshConfigLocation, array &$warnings): ?string+ {+ $interface = escapeshellarg($cluster->wireguard_interface);+ $script = implode("\n", [+ "SUDO=''",+ 'if [ "$(id -u)" != "0" ]; then SUDO=\'sudo\'; fi',+ "\$SUDO wg show {$interface} public-key",+ ]);++ $result = Process::timeout(15)->run([+ 'ssh',+ '-F',+ $sshConfigLocation,+ $this->bootstrapNode($server),+ $script,+ ]);++ $publicKey = trim($result->output());++ if (! $result->successful() || $publicKey === '') {+ $warnings[] = 'Warning: could not read the WireGuard public key from the server.';++ return null;+ }++ return $publicKey;+ }++ /**+ * The container subnets are allocated by the coolify CLI on the host; the podman+ * networks it creates are the source of truth, so read them back instead of+ * re-deriving the allocation locally.+ *+ * @param array<int, string> $warnings+ * @return array<string, string>+ */+ private function readContainerSubnets(V5Cluster $cluster, V5Server $server, string $sshConfigLocation, array &$warnings): array+ {+ $namespaces = $cluster->namespaces ?? V5Cluster::DEFAULT_NAMESPACES;++ if ($namespaces === []) {+ return [];+ }++ $namespaceArguments = collect($namespaces)+ ->map(fn (string $namespace): string => escapeshellarg($namespace))+ ->implode(' ');+ $script = implode("\n", [+ "SUDO=''",+ 'if [ "$(id -u)" != "0" ]; then SUDO=\'sudo\'; fi',+ "for ns in {$namespaceArguments}; do",+ ' printf \'%s=\' "$ns"',+ ' $SUDO podman network inspect "coolify-${ns}-mesh" --format \'{{range .Subnets}}{{.Subnet}}{{end}}\' 2>/dev/null || true',+ ' printf \'\n\'',+ 'done',+ ]);++ $result = Process::timeout(30)->run([+ 'ssh',+ '-F',+ $sshConfigLocation,+ $this->bootstrapNode($server),+ $script,+ ]);++ if (! $result->successful()) {+ $warnings[] = 'Warning: could not read the container subnets from the server.';++ return [];+ }++ $subnets = [];++ foreach (preg_split('/\r?\n/', trim($result->output())) ?: [] as $line) {+ [$namespace, $subnet] = array_pad(explode('=', trim($line), 2), 2, null);++ if (! is_string($namespace) || ! in_array($namespace, $namespaces, true) || ! $this->isIpv4Cidr($subnet)) {+ continue;+ }++ $subnets[$namespace] = $subnet;+ }++ if (count($subnets) !== count($namespaces)) {+ $warnings[] = 'Warning: could not read every container subnet from the server; the stored subnets may be incomplete.';+ }++ return $subnets;+ }++ private function isIpv4Cidr(?string $value): bool+ {+ if (! is_string($value) || ! str_contains($value, '/')) {+ return false;+ }++ [$ip, $prefix] = explode('/', $value, 2);++ return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false+ && ctype_digit($prefix)+ && (int) $prefix <= 32;+ }++ private function enrollCooldIntoFlux(V5Server $server, string $sshConfigLocation, ?string $bootstrapNode = null): void+ {+ $fluxUrl = trim((string) config('coold.flux_url', ''));++ if ($fluxUrl === '') {+ throw new \RuntimeException('COOLIFY_COOLD_FLUX_URL is not configured, so the server cannot be enrolled into Flux. Set it and retry the bootstrap.');+ }++ $jwtPath = trim((string) config('coold.flux_host_jwt_path', '/etc/coolify/host-jwt'));++ if ($jwtPath === '') {+ $jwtPath = '/etc/coolify/host-jwt';+ }++ $fluxUrl = str_replace(["\r", "\n"], '', $fluxUrl);+ $jwtPath = str_replace(["\r", "\n"], '', $jwtPath);+ $hostId = $server->fluxHostId();+ $token = app(AgentTokenIssuer::class)->issueForServer($server);+ $tokenArgument = $this->shellArg($token);+ $hostId = str_replace(["\r", "\n"], '', $hostId);+ $jwtPathArgument = $this->shellPathArg($jwtPath);+ $dropInDirectory = '/etc/systemd/system/coold.service.d';+ $dropInPath = "{$dropInDirectory}/10-flux.conf";+ $script = <<<SH+set -e+SUDO=''+if [ "\$(id -u)" != "0" ]; then SUDO='sudo'; fi+\$SUDO mkdir -p /etc/coolify {$dropInDirectory}+printf %s {$tokenArgument} | \$SUDO tee {$jwtPathArgument} >/dev/null+\$SUDO chmod 600 {$jwtPathArgument}+cat <<'COOLIFY_FLUX_ENV' | \$SUDO tee {$dropInPath} >/dev/null+[Service]+Environment=COOLIFY_COOLD_FLUX_URL={$fluxUrl}+Environment=COOLIFY_COOLD_HOST_ID={$hostId}+Environment=COOLIFY_COOLD_HOST_JWT_PATH={$jwtPath}+COOLIFY_FLUX_ENV+\$SUDO systemctl daemon-reload+\$SUDO systemctl restart coold.service+SH;++ $result = Process::timeout(60)->run([+ 'ssh',+ '-F',+ $sshConfigLocation,+ $bootstrapNode ?? $this->bootstrapNode($server),+ $script,+ ]);++ if (! $result->successful()) {+ $output = trim($result->output()."\n".$result->errorOutput());++ throw new \RuntimeException(+ ($output !== '' ? $output : 'Could not enroll coold into Flux.')+ ."\nThe WireGuard mesh was created successfully; retrying this bootstrap is safe and will resume from Flux enrollment."+ );+ }+ }++ private function waitForFluxHostConnection(V5Server $server): void+ {+ $timeoutSeconds = (int) config('flux.bootstrap_host_connection_timeout_seconds', 30);++ if ($timeoutSeconds <= 0) {+ return;+ }++ $hostId = $server->fluxHostId();++ if (! is_string($hostId) || $hostId === '') {+ throw new \RuntimeException('Server is missing its Flux host id after bootstrap.');+ }++ $deadline = time() + $timeoutSeconds;+ $lastError = null;++ do {+ try {+ app(FluxClient::class)->cooldLogs($hostId, 1);++ return;+ } catch (\Throwable $exception) {+ $lastError = $exception->getMessage();+ sleep(1);+ }+ } while (time() < $deadline);++ throw new \RuntimeException(+ 'The server was bootstrapped, but coold did not connect to Flux in time. '+ .'Wait a moment and retry the bootstrap before deploying applications.'+ .($lastError !== null ? " Last Flux error: {$lastError}" : '')+ );+ }++ private function shellArg(string $value): string+ {+ return escapeshellarg($value);+ }++ private function shellPathArg(string $value): string+ {+ if (preg_match('/^[A-Za-z0-9_\/:.,@%+=-]+$/', $value) === 1) {+ return $value;+ }++ return $this->shellArg($value);+ }++ private function writeBootstrapMarker(V5Cluster $cluster, V5Server $server, string $sshConfigLocation, ?string $cooldVersion = null): void{$payload = base64_encode(json_encode(['cluster_id' => $cluster->id,+ 'cluster_uuid' => $cluster->uuid,'server_uuid' => $server->uuid,'wireguard_management_ip' => $server->wireguard_management_ip,'wireguard_public_key' => $server->wireguard_public_key,+ 'coold_version' => $cooldVersion ?? $server->coold_version ?? $cluster->coold_version,'container_subnets' => $server->container_subnets ?? [],], JSON_THROW_ON_ERROR));- Process::timeout(15)->run([+ $result = Process::timeout(15)->run(['ssh','-F',$sshConfigLocation,$this->bootstrapNode($server),"payload='{$payload}'; if [ \"$(id -u)\" = \"0\" ]; then mkdir -p /etc/coolify && printf %s \"$payload\" | base64 -d > ".escapeshellarg(self::BOOTSTRAP_MARKER_PATH)."; else sudo mkdir -p /etc/coolify && printf %s \"$payload\" | base64 -d | sudo tee ".escapeshellarg(self::BOOTSTRAP_MARKER_PATH).' >/dev/null; fi',]);++ if (! $result->successful()) {+ $output = trim($result->output()."\n".$result->errorOutput());++ throw new \RuntimeException('Could not write the bootstrap marker to the server: '.($output !== '' ? $output : 'the SSH command failed.'));+ }}/**diff --git a/app/Jobs/V5DeployApplicationJob.php b/app/Jobs/V5DeployApplicationJob.phpnew file mode 100644index 0000000000..f81650ed61--- /dev/null+++ b/app/Jobs/V5DeployApplicationJob.php@@ -0,0 +1,53 @@+<?php++namespace App\Jobs;++use App\Actions\V5\Application\DeployNginxApplication;+use App\Models\V5\Application as V5Application;+use Illuminate\Bus\Queueable;+use Illuminate\Contracts\Queue\ShouldBeUnique;+use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Foundation\Bus\Dispatchable;+use Illuminate\Queue\InteractsWithQueue;+use Illuminate\Queue\SerializesModels;++class V5DeployApplicationJob implements ShouldBeUnique, ShouldQueue+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ public int $tries = 1;++ public int $timeout = 300;++ /**+ * Job timeout plus a safety margin so a lost lock can never block+ * redeploys of the same application forever.+ */+ public int $uniqueFor = 360;++ public function __construct(public int $applicationId) {}++ public function uniqueId(): string+ {+ return (string) $this->applicationId;+ }++ public function handle(): void+ {+ $application = V5Application::query()->find($this->applicationId);++ if (! $application instanceof V5Application) {+ return;+ }++ DeployNginxApplication::run($application);+ }++ public function failed(?\Throwable $exception): void+ {+ V5Application::query()->find($this->applicationId)?->update([+ 'status' => 'failed',+ 'status_message' => str($exception?->getMessage() ?? 'The deploy job failed.')->limit(10000)->toString(),+ ]);+ }+}diff --git a/app/Jobs/V5ReconcileServerStateJob.php b/app/Jobs/V5ReconcileServerStateJob.phpnew file mode 100644index 0000000000..3b5d072a4a--- /dev/null+++ b/app/Jobs/V5ReconcileServerStateJob.php@@ -0,0 +1,255 @@+<?php++namespace App\Jobs;++use App\Enums\V5\ApplicationStatus;+use App\Enums\V5\ContainerState;+use App\Enums\V5\ServerStatus;+use App\Models\V5\Application as V5Application;+use App\Models\V5\ContainerStatus;+use App\Models\V5\Server as V5Server;+use App\Services\Flux\FluxClient;+use App\Support\V5\StatusObservation;+use Carbon\CarbonImmutable;+use Carbon\CarbonInterface;+use Illuminate\Bus\Queueable;+use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Foundation\Bus\Dispatchable;+use Illuminate\Queue\InteractsWithQueue;+use Illuminate\Queue\SerializesModels;+use Illuminate\Support\Collection;+use Illuminate\Support\Facades\Log;++/**+ * Actively reconciles one v5 server against the containers coold actually+ * reports. V5 status is normally push-only (coold -> flux -> webhook), so a+ * dropped webhook leaves rows stale forever; this job is the pull-based+ * safety net scheduled via V5ReconcileServersJob.+ */+class V5ReconcileServerStateJob implements ShouldQueue+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ /**+ * Reconcile runs on its own queue so the 5-minute fleet fan-out (one+ * blocking flux call per server) can never starve user-triggered deploys+ * and bootstraps sharing the default queue. Set via onQueue() in the+ * constructor rather than a `$queue` property redeclaration, which the+ * Queueable trait already defines (redeclaring with a default is an+ * incompatible property composition and fatals on PHP 8.5).+ */+ public int $tries = 1;++ public int $timeout = 120;++ public function __construct(public int $serverId)+ {+ $this->onQueue('v5-reconcile');+ }++ public function handle(FluxClient $fluxClient): void+ {+ $server = V5Server::query()->find($this->serverId);++ if (! $server instanceof V5Server) {+ return;+ }++ $hostId = $server->fluxHostId();++ if ($hostId === '') {+ Log::warning('V5 reconcile skipped: server is missing a Flux host id.', ['server_id' => $server->id]);++ return;+ }++ // The moment we query coold is the observation time for every row this+ // pass writes; a webhook that lands with a newer observation while this+ // (possibly delayed) snapshot is processed must win the watermark.+ $observedAt = CarbonImmutable::now();++ try {+ $containers = collect($fluxClient->listContainers($hostId));+ } catch (\Throwable $exception) {+ $this->markServerUnreachable($server, $exception, $observedAt);++ return;+ }++ $this->markServerReachable($server, $containers->count(), $observedAt);+ $this->refreshContainerStatuses($server, $containers, $observedAt);+ $this->reconcileApplications($server, $containers, $observedAt);+ }++ private function markServerUnreachable(V5Server $server, \Throwable $exception, CarbonInterface $observedAt): void+ {+ Log::warning('V5 reconcile could not reach the server via flux.', [+ 'server_id' => $server->id,+ 'error' => $exception->getMessage(),+ ]);++ $attributes = [+ 'last_status_check' => 'reconcile',+ 'last_status_output' => str($exception->getMessage())->limit(1000)->toString(),+ 'last_status_checked_at' => now(),+ ];++ if (! StatusObservation::isStale($observedAt, $server->status_observed_at, 'server status', ['server_id' => $server->id])) {+ // Only an installed server can degrade to unreachable; added or+ // failed servers keep their bootstrap-driven status.+ $attributes['status'] = $server->status === ServerStatus::Installed->value+ ? ServerStatus::Unreachable->value+ : $server->status;+ $attributes['status_observed_at'] = $observedAt;+ }++ $server->update($attributes);+ }++ private function markServerReachable(V5Server $server, int $containerCount, CarbonInterface $observedAt): void+ {+ $attributes = [+ 'last_status_check' => 'reconcile',+ 'last_status_output' => "Reconciled {$containerCount} containers from coold.",+ 'last_status_checked_at' => now(),+ ];++ if (! StatusObservation::isStale($observedAt, $server->status_observed_at, 'server status', ['server_id' => $server->id])) {+ $attributes['status'] = $server->status === ServerStatus::Unreachable->value+ ? ServerStatus::Installed->value+ : $server->status;+ $attributes['status_observed_at'] = $observedAt;+ }++ $server->update($attributes);+ }++ /**+ * @param Collection<int, mixed> $containers+ */+ private function refreshContainerStatuses(V5Server $server, Collection $containers, CarbonInterface $observedAt): void+ {+ $containers->each(function (mixed $container) use ($server, $observedAt): void {+ if (! is_array($container) || ! is_string($container['id'] ?? null) || $container['id'] === '') {+ return;+ }++ $existing = ContainerStatus::query()+ ->where('server_id', $server->id)+ ->where('container_id', $container['id'])+ ->first();++ if (StatusObservation::isStale($observedAt, $existing?->status_observed_at, 'container status', [+ 'server_id' => $server->id,+ 'container_id' => $container['id'],+ ])) {+ return;+ }++ ContainerStatus::query()->updateOrCreate([+ 'server_id' => $server->id,+ 'container_id' => $container['id'],+ ], [+ 'team_id' => $server->team_id,+ 'container_name' => is_string($container['name'] ?? null) ? $container['name'] : null,+ 'image' => is_string($container['image'] ?? null) ? $container['image'] : null,+ 'status' => $this->containerState($container, ContainerState::class),+ 'status_message' => 'Container state reconciled from coold.',+ 'status_observed_at' => $observedAt,+ 'last_seen_at' => now(),+ ]);+ });+ }++ /**+ * @param Collection<int, mixed> $containers+ */+ private function reconcileApplications(V5Server $server, Collection $containers, CarbonInterface $observedAt): void+ {+ V5Application::query()+ ->where('server_id', $server->id)+ ->get()+ ->each(function (V5Application $application) use ($containers, $observedAt): void {+ try {+ $this->reconcileApplication($application, $containers, $observedAt);+ } catch (\Throwable $exception) {+ Log::warning('V5 reconcile failed for an application.', [+ 'application_id' => $application->id,+ 'error' => $exception->getMessage(),+ ]);+ }+ });+ }++ /**+ * @param Collection<int, mixed> $containers+ */+ private function reconcileApplication(V5Application $application, Collection $containers, CarbonInterface $observedAt): void+ {+ $container = $containers->first(function (mixed $container) use ($application): bool {+ return is_array($container)+ && (($application->runtime_container_id !== null && ($container['id'] ?? null) === $application->runtime_container_id)+ || ($container['name'] ?? null) === $application->container_name);+ });++ if (! is_array($container)) {+ // A creating application without a container id simply has not+ // materialized yet; the deploy job will settle it.+ if ($application->status === ApplicationStatus::Creating->value && $application->runtime_container_id === null) {+ return;+ }++ if (StatusObservation::isStale($observedAt, $application->status_observed_at, 'application status', ['application_id' => $application->id])) {+ return;+ }++ $attributes = [+ 'status' => ApplicationStatus::Exited->value,+ 'status_observed_at' => $observedAt,+ ];++ if ($application->status !== ApplicationStatus::Exited->value) {+ $attributes['status_message'] = 'Container not found on server during reconcile.';+ }++ $application->update($attributes);++ return;+ }++ if (StatusObservation::isStale($observedAt, $application->status_observed_at, 'application status', ['application_id' => $application->id])) {+ return;+ }++ $status = $this->containerState($container, ApplicationStatus::class);++ $attributes = [+ 'status' => $status,+ 'status_observed_at' => $observedAt,+ 'runtime_container_id' => is_string($container['id'] ?? null) && $container['id'] !== ''+ ? $container['id']+ : $application->runtime_container_id,+ ];++ // Only write status_message when the status actually changes: the+ // status column is what a viewer cares about, and a constant message+ // would otherwise fire a broadcast + full re-serialization every cycle.+ if ($status !== $application->status) {+ $attributes['status_message'] = 'Container state reconciled from coold.';+ }++ $application->update($attributes);+ }++ /**+ * @param array<string, mixed> $container+ * @param class-string<ApplicationStatus|ContainerState> $enumClass+ */+ private function containerState(array $container, string $enumClass): string+ {+ $state = $container['state'] ?? null;+ $raw = is_string($state) && $state !== '' ? $state : null;++ return StatusObservation::normalize($raw, $enumClass) ?? $enumClass::Unknown->value;+ }+}diff --git a/app/Jobs/V5ReconcileServersJob.php b/app/Jobs/V5ReconcileServersJob.phpnew file mode 100644index 0000000000..5deae2e57d--- /dev/null+++ b/app/Jobs/V5ReconcileServersJob.php@@ -0,0 +1,89 @@+<?php++namespace App\Jobs;++use App\Enums\V5\ServerStatus;+use App\Models\V5\Application as V5Application;+use App\Models\V5\ContainerStatus;+use App\Models\V5\Server as V5Server;+use Illuminate\Bus\Queueable;+use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Foundation\Bus\Dispatchable;+use Illuminate\Queue\InteractsWithQueue;+use Illuminate\Queue\SerializesModels;+use Illuminate\Support\Facades\Log;++/**+ * Scheduled fan-out for the v5 reconciliation loop: dispatches one+ * V5ReconcileServerStateJob per managed server and prunes container status+ * rows that no webhook has refreshed within the TTL.+ */+class V5ReconcileServersJob implements ShouldQueue+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ public const CONTAINER_STATUS_TTL_HOURS = 24;++ public int $tries = 1;++ public int $timeout = 60;++ /**+ * Reconcile runs on its own queue so the 5-minute fleet fan-out can never+ * starve user-triggered deploys and bootstraps sharing the default queue.+ * Set via onQueue() rather than a `$queue` property redeclaration, which+ * the Queueable trait already defines (redeclaring with a default is an+ * incompatible property composition and fatals on PHP 8.5).+ */+ public function __construct()+ {+ $this->onQueue('v5-reconcile');+ }++ public function handle(): void+ {+ $this->dispatchReconcileJobs();+ $this->pruneContainerStatuses();+ }++ private function dispatchReconcileJobs(): void+ {+ V5Server::query()+ // Unreachable servers stay in the loop so a recovered node is+ // restored to installed by its next successful reconcile.+ ->whereIn('status', [ServerStatus::Installed->value, ServerStatus::Unreachable->value])+ ->where('has_coold', true)+ ->get()+ ->each(function (V5Server $server): void {+ try {+ V5ReconcileServerStateJob::dispatch($server->id);+ } catch (\Throwable $exception) {+ Log::warning('V5 reconcile dispatch failed for a server.', [+ 'server_id' => $server->id,+ 'error' => $exception->getMessage(),+ ]);+ }+ });+ }++ private function pruneContainerStatuses(): void+ {+ $cutoff = now()->subHours(self::CONTAINER_STATUS_TTL_HOURS);+ $liveContainerIds = V5Application::query()+ ->whereNotNull('runtime_container_id')+ ->pluck('runtime_container_id')+ ->all();++ ContainerStatus::query()+ ->where(function ($query) use ($cutoff): void {+ $query+ ->where('last_seen_at', '<', $cutoff)+ ->orWhere(function ($query) use ($cutoff): void {+ $query->whereNull('last_seen_at')->where('created_at', '<', $cutoff);+ })+ ->orWhereNotIn('server_id', V5Server::query()->select('id'));+ })+ ->when($liveContainerIds !== [], fn ($query) => $query->whereNotIn('container_id', $liveContainerIds))+ ->delete();+ }+}diff --git a/app/Jobs/V5RotateAgentTokenJob.php b/app/Jobs/V5RotateAgentTokenJob.phpnew file mode 100644index 0000000000..c05f5be745--- /dev/null+++ b/app/Jobs/V5RotateAgentTokenJob.php@@ -0,0 +1,150 @@+<?php++namespace App\Jobs;++use App\Actions\V5\Server\PushHostAgentToken;+use App\Enums\V5\ServerStatus;+use App\Models\V5\Server as V5Server;+use App\Services\Flux\AgentTokenIssuer;+use App\Services\Flux\FluxClient;+use Illuminate\Bus\Queueable;+use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Foundation\Bus\Dispatchable;+use Illuminate\Queue\InteractsWithQueue;+use Illuminate\Queue\SerializesModels;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Str;++/**+ * Re-mints and delivers a fresh host JWT for one managed server before its+ * on-disk token expires.+ *+ * RPC-FIRST, SSH-FALLBACK: the new token is delivered over the live coold RPC+ * stream by default (Laravel -> flux UDS -> coold's `host.jwt.set` command),+ * because that reuses the already authenticated flux<->coold channel and works+ * while the CURRENT token is still valid — which is exactly when rotation runs+ * (at ~12h remaining, well before the 24h exp). Only if the RPC push fails (the+ * host's stream is down because its token already lapsed, flux rejects the verb,+ * a timeout, etc.) do we fall back to the SSH push, which recovers a node whose+ * token already expired and whose stream is therefore gone.+ *+ * PUSH-THEN-PERSIST: the new token is delivered to the host FIRST, and the+ * server's jti/expires_at are only advanced AFTER a successful delivery via+ * EITHER path. If both delivery paths fail the DB is left untouched, so the old+ * expires_at keeps the server inside the dispatcher's rotation window and the+ * next cycle simply retries — we never advance the watermark on a token the+ * host never received (which would strand the host on the expiring old token+ * until it fully lapsed).+ *+ * NO-REVOKE-ON-ROTATION: the previously issued jti is intentionally NOT revoked+ * here. The old token is still legitimately valid until its own exp and coold+ * may still be connected on it; revoking it would risk cutting the live stream.+ * Revocation belongs to teardown/re-home (RemoveBootstrapMarker), not routine+ * rotation — the old token simply ages out on its own exp.+ */+class V5RotateAgentTokenJob implements ShouldQueue+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ public int $tries = 3;++ public int $timeout = 60;++ /**+ * Rotation shares the reconcile queue so the hourly fleet fan-out can never+ * starve user-triggered deploys and bootstraps on the default queue. Set via+ * onQueue() rather than a `$queue` property redeclaration, which the+ * Queueable trait already defines (redeclaring with a default is an+ * incompatible property composition and fatals on PHP 8.5).+ */+ public function __construct(public int $serverId)+ {+ $this->onQueue('v5-reconcile');+ }++ public function handle(): void+ {+ $server = V5Server::query()->with('privateKey')->find($this->serverId);++ if (! $server instanceof V5Server) {+ return;+ }++ if (! $this->isEligible($server)) {+ return;+ }++ $hostId = $server->fluxHostId();++ if ($hostId === '') {+ Log::warning('V5 token rotation skipped: server is missing a Flux host id.', ['server_id' => $server->id]);++ return;+ }++ $ttl = (int) config('flux.host_token_ttl');+ $jti = (string) Str::uuid();++ $token = app(AgentTokenIssuer::class)->issue($hostId, null, $ttl, [+ 'jti' => $jti,+ 'team_id' => (string) $server->team_id,+ 'cluster_id' => (string) $server->cluster_id,+ 'server_id' => $hostId,+ 'wireguard_management_ip' => (string) $server->wireguard_management_ip,+ ]);++ $delivery = $this->deliverToken($server, $hostId, $token);++ if ($delivery === null) {+ Log::warning('V5 token rotation could not deliver the new host token; leaving the existing token in place.', [+ 'server_id' => $server->id,+ 'host' => $server->host,+ ]);++ return;+ }++ $server->update([+ 'agent_token_jti' => $jti,+ 'agent_token_expires_at' => now()->addSeconds($ttl),+ ]);++ Log::debug('V5 token rotation delivered a fresh host token.', [+ 'server_id' => $server->id,+ 'delivery' => $delivery,+ ]);+ }++ /**+ * Deliver the freshly minted token to the host, preferring the live coold+ * RPC stream and falling back to the SSH push on any RPC failure.+ *+ * @return 'rpc'|'ssh'|null The path that succeeded, or null if both failed.+ */+ private function deliverToken(V5Server $server, string $hostId, string $token): ?string+ {+ try {+ app(FluxClient::class)->pushHostToken($hostId, $token);++ return 'rpc';+ } catch (\Throwable $exception) {+ Log::info('V5 token rotation RPC push failed; falling back to SSH.', [+ 'server_id' => $server->id,+ 'error' => $exception->getMessage(),+ ]);+ }++ if (PushHostAgentToken::run($server, $token)) {+ return 'ssh';+ }++ return null;+ }++ private function isEligible(V5Server $server): bool+ {+ return $server->status === ServerStatus::Installed->value+ && (bool) $server->has_coold+ && $server->last_bootstrapped_at !== null;+ }+}diff --git a/app/Jobs/V5RotateAgentTokensJob.php b/app/Jobs/V5RotateAgentTokensJob.phpnew file mode 100644index 0000000000..537a6b474e--- /dev/null+++ b/app/Jobs/V5RotateAgentTokensJob.php@@ -0,0 +1,65 @@+<?php++namespace App\Jobs;++use App\Enums\V5\ServerStatus;+use App\Models\V5\Server as V5Server;+use Illuminate\Bus\Queueable;+use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Foundation\Bus\Dispatchable;+use Illuminate\Queue\InteractsWithQueue;+use Illuminate\Queue\SerializesModels;+use Illuminate\Support\Facades\Log;++/**+ * Scheduled fan-out for host JWT rotation: dispatches one V5RotateAgentTokenJob+ * per managed server whose on-disk token is missing or within the configured+ * refresh threshold of expiry, so a fresh token is always on disk before the+ * current one lapses.+ */+class V5RotateAgentTokensJob implements ShouldQueue+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ public int $tries = 1;++ public int $timeout = 60;++ /**+ * Rotation shares the reconcile queue so the hourly fleet fan-out can never+ * starve user-triggered deploys and bootstraps on the default queue. Set via+ * onQueue() rather than a `$queue` property redeclaration, which the+ * Queueable trait already defines (redeclaring with a default is an+ * incompatible property composition and fatals on PHP 8.5).+ */+ public function __construct()+ {+ $this->onQueue('v5-reconcile');+ }++ public function handle(): void+ {+ $threshold = now()->addSeconds((int) config('flux.host_token_refresh_threshold'));++ V5Server::query()+ ->where('status', ServerStatus::Installed->value)+ ->where('has_coold', true)+ ->whereNotNull('last_bootstrapped_at')+ ->where(function ($query) use ($threshold): void {+ $query+ ->whereNull('agent_token_expires_at')+ ->orWhere('agent_token_expires_at', '<', $threshold);+ })+ ->get()+ ->each(function (V5Server $server): void {+ try {+ V5RotateAgentTokenJob::dispatch($server->id);+ } catch (\Throwable $exception) {+ Log::warning('V5 token rotation dispatch failed for a server.', [+ 'server_id' => $server->id,+ 'error' => $exception->getMessage(),+ ]);+ }+ });+ }+}diff --git a/app/Jobs/V5TeardownTeamJob.php b/app/Jobs/V5TeardownTeamJob.phpnew file mode 100644index 0000000000..5f2a5eebd5--- /dev/null+++ b/app/Jobs/V5TeardownTeamJob.php@@ -0,0 +1,325 @@+<?php++namespace App\Jobs;++use App\Actions\V5\Application\DestroyNginxApplication;+use App\Actions\V5\Proxy\StopCaddyIngress;+use App\Actions\V5\Server\RemoveBootstrapMarker;+use App\Enums\V5\ServerStatus;+use App\Models\PrivateKey;+use App\Models\Team;+use App\Models\V5\Application as V5Application;+use App\Models\V5\Server as V5Server;+use App\Services\Flux\AgentTokenIssuer;+use Illuminate\Bus\Queueable;+use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Foundation\Bus\Dispatchable;+use Illuminate\Queue\InteractsWithQueue;+use Illuminate\Queue\SerializesModels;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Facades\Schema;++/**+ * Best-effort, on-host teardown for a team that is being deleted.+ *+ * Deleting a v4 Team DB-cascades every v5_servers / v5_applications /+ * v5_container_statuses / v5_resource_connections row (see the+ * cascadeOnDelete() foreign keys in the v5 migrations) WITHOUT running the+ * app-level teardown that the per-resource destroy flows use. That would leave+ * orphaned podman containers, a running Caddy ingress, the WireGuard mesh and+ * coold itself alive on every host with no DB record left to reach them.+ *+ * This job mirrors the ServerController::destroy / ApplicationController::destroy+ * teardown sequence for every v5 server owned by the team:+ * 1. remove each application's container (DestroyNginxApplication),+ * 2. stop the Caddy ingress on ingress servers (StopCaddyIngress),+ * 3. remove the on-host bootstrap identity — marker, host-jwt and Flux+ * drop-in (RemoveBootstrapMarker).+ *+ * Because the cascade deletes the servers, applications and private keys the+ * moment the team is gone, the payload is captured at dispatch time (from the+ * Team `deleting` hook, which fires BEFORE the rows vanish) as plain arrays,+ * including the SSH private-key material needed to reach each host. The job+ * rebuilds in-memory, non-persisted models from that payload so it can reuse+ * the exact same actions without touching the (now missing) DB rows.+ *+ * BEST-EFFORT / LIMITATIONS: teardown is best-effort. Each host and each action+ * is guarded so a single unreachable host can never abort teardown of the other+ * hosts, and the team deletion itself never fails because of teardown. The+ * payload is fully self-contained (host, SSH creds/private key, applications,+ * token jti + expiry), so a framework-level queue retry is safe — every step is+ * idempotent (podman rm -f / ingress stop / rm -f are all no-ops when the target+ * is already gone).+ *+ * RESIDUAL LIMITATION: a host that is unreachable at team-deletion time orphans+ * its containers, ingress and mesh PERMANENTLY — the DB rows the reconcilers key+ * off are gone, so there is no later reconciliation. The single operator-facing+ * signal is the `Log::error` emitted at the end of handle() listing the host+ * ids/hosts that could not be torn down; grep for "v5 team teardown incomplete"+ * to find them.+ */+class V5TeardownTeamJob implements ShouldQueue+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ /**+ * A small retry budget: the payload is self-contained and every teardown+ * step is idempotent, so retrying an unreachable host is safe. There is no+ * point retrying forever — the host may simply be gone.+ */+ public int $tries = 3;++ public int $timeout = 300;++ /**+ * @param array<int, array<string, mixed>> $servers Self-contained per-server teardown payload captured before the cascade.+ */+ public function __construct(+ public int $teamId,+ public array $servers,+ ) {}++ /**+ * Collect the team's v5 servers (with their applications and SSH key+ * material) into a self-contained payload and dispatch the teardown job.+ *+ * Must be called from the Team `deleting` hook, while the rows still exist.+ * Returns without dispatching when the team owns no v5 servers.+ */+ public static function dispatchForTeam(Team $team): void+ {+ // Guard against contexts where the v5 tables do not exist (e.g. v4-only+ // schemas) so team deletion is never broken by this teardown.+ if (! Schema::hasTable('v5_servers')) {+ return;+ }++ $servers = V5Server::query()+ ->where('team_id', $team->id)+ ->with('privateKey')+ ->get();++ if ($servers->isEmpty()) {+ return;+ }++ $applicationsByServer = V5Application::query()+ ->where('team_id', $team->id)+ ->whereNotNull('server_id')+ ->get()+ ->groupBy('server_id');++ $payload = $servers->map(function (V5Server $server) use ($applicationsByServer): array {+ return [+ 'id' => $server->id,+ 'uuid' => $server->uuid,+ 'name' => $server->name,+ 'host' => $server->host,+ 'ssh_user' => $server->ssh_user,+ 'ssh_port' => (int) $server->ssh_port,+ 'node_address' => $server->node_address,+ 'wireguard_management_ip' => $server->wireguard_management_ip,+ 'is_ingress' => (bool) $server->is_ingress,+ 'ingress_type' => $server->ingress_type,+ 'status' => $server->status,+ 'last_bootstrapped_at' => $server->last_bootstrapped_at?->toISOString(),+ // Captured before the cascade removes the row so the job can+ // revoke the host token after the DB rows are gone.+ 'agent_token_jti' => $server->agent_token_jti,+ 'agent_token_expires_at' => $server->agent_token_expires_at?->toISOString(),+ // Encrypted at rest on the model; needed to SSH into the host.+ 'private_key' => $server->privateKey instanceof PrivateKey ? $server->privateKey->private_key : null,+ 'applications' => ($applicationsByServer[$server->id] ?? collect())+ ->map(fn (V5Application $application): array => [+ 'id' => $application->id,+ 'container_name' => $application->container_name,+ 'runtime_container_id' => $application->runtime_container_id,+ ])+ ->values()+ ->all(),+ ];+ })->all();++ self::dispatch($team->id, $payload);+ }++ public function handle(): void+ {+ $incompleteHosts = [];++ foreach ($this->servers as $serverPayload) {+ if (! $this->teardownServer($serverPayload)) {+ $incompleteHosts[] = [+ 'server_id' => $serverPayload['id'] ?? null,+ 'host' => $serverPayload['host'] ?? null,+ ];+ }+ }++ // Teardown is best-effort and never fails the job (an unreachable host+ // must not abort the others), so this is the single operator-facing+ // signal that some hosts could not be reached and may now hold orphaned+ // containers/mesh with no DB row left to reconcile them.+ if ($incompleteHosts !== []) {+ Log::error('v5 team teardown incomplete — '.count($incompleteHosts).' host(s) may have orphaned containers/mesh', [+ 'team_id' => $this->teamId,+ 'hosts' => $incompleteHosts,+ ]);+ }+ }++ /**+ * Tear down a single host. Returns false when any on-host teardown step+ * (container removal, ingress stop, bootstrap-marker removal) failed, so the+ * caller can surface the host as potentially orphaned. Never throws: a+ * single unreachable host must not abort teardown of the other hosts.+ *+ * @param array<string, mixed> $serverPayload+ */+ private function teardownServer(array $serverPayload): bool+ {+ $server = $this->reconstructServer($serverPayload);+ $serverId = $serverPayload['id'] ?? null;+ $host = $serverPayload['host'] ?? null;+ $succeeded = true;++ foreach ($serverPayload['applications'] ?? [] as $applicationPayload) {+ try {+ $application = $this->reconstructApplication($applicationPayload, $server);+ DestroyNginxApplication::run($application);+ } catch (\Throwable $exception) {+ $succeeded = false;+ Log::warning('V5 team teardown: failed to remove application container', [+ 'team_id' => $this->teamId,+ 'server_id' => $serverId,+ 'host' => $host,+ 'container_name' => $applicationPayload['container_name'] ?? null,+ 'error' => $exception->getMessage(),+ ]);+ }+ }++ if ($server->isIngress() && $server->status === ServerStatus::Installed->value) {+ try {+ StopCaddyIngress::run($server);+ } catch (\Throwable $exception) {+ $succeeded = false;+ Log::warning('V5 team teardown: failed to stop Caddy ingress', [+ 'team_id' => $this->teamId,+ 'server_id' => $serverId,+ 'host' => $host,+ 'error' => $exception->getMessage(),+ ]);+ }+ }++ if (($serverPayload['last_bootstrapped_at'] ?? null) !== null) {+ try {+ if (! RemoveBootstrapMarker::run($server)) {+ $succeeded = false;+ Log::warning('V5 team teardown: could not remove on-host bootstrap identity over SSH', [+ 'team_id' => $this->teamId,+ 'server_id' => $serverId,+ 'host' => $host,+ ]);+ }+ } catch (\Throwable $exception) {+ $succeeded = false;+ Log::warning('V5 team teardown: bootstrap marker removal threw', [+ 'team_id' => $this->teamId,+ 'server_id' => $serverId,+ 'host' => $host,+ 'error' => $exception->getMessage(),+ ]);+ }+ }++ // Revocation is best-effort and independent of the on-host cleanup: a+ // failed flux push does not mean the host is orphaned, so it never flips+ // $succeeded (it is logged separately inside AgentTokenIssuer::revoke).+ $this->revokeAgentTokenIfSupported($server, $serverId, $host);++ return $succeeded;+ }++ /**+ * Reconstruct a non-persisted V5Server (with its private key relation+ * pre-set) so the teardown actions never hit the deleted DB rows.+ *+ * @param array<string, mixed> $serverPayload+ */+ private function reconstructServer(array $serverPayload): V5Server+ {+ $server = new V5Server;+ $server->forceFill([+ 'id' => $serverPayload['id'] ?? null,+ 'uuid' => $serverPayload['uuid'] ?? null,+ 'name' => $serverPayload['name'] ?? null,+ 'host' => $serverPayload['host'] ?? null,+ 'ssh_user' => $serverPayload['ssh_user'] ?? null,+ 'ssh_port' => $serverPayload['ssh_port'] ?? 22,+ 'node_address' => $serverPayload['node_address'] ?? null,+ 'wireguard_management_ip' => $serverPayload['wireguard_management_ip'] ?? null,+ 'is_ingress' => (bool) ($serverPayload['is_ingress'] ?? false),+ 'ingress_type' => $serverPayload['ingress_type'] ?? null,+ 'status' => $serverPayload['status'] ?? null,+ 'agent_token_jti' => $serverPayload['agent_token_jti'] ?? null,+ 'agent_token_expires_at' => $serverPayload['agent_token_expires_at'] ?? null,+ ]);+ // Non-persisted: StopCaddyIngress / the actions must not try to update a+ // row that the cascade already removed.+ $server->exists = false;++ $privateKeyMaterial = $serverPayload['private_key'] ?? null;+ if (is_string($privateKeyMaterial) && $privateKeyMaterial !== '') {+ $privateKey = new PrivateKey;+ $privateKey->forceFill(['private_key' => $privateKeyMaterial]);+ $server->setRelation('privateKey', $privateKey);+ } else {+ $server->setRelation('privateKey', null);+ }++ return $server;+ }++ /**+ * @param array<string, mixed> $applicationPayload+ */+ private function reconstructApplication(array $applicationPayload, V5Server $server): V5Application+ {+ $application = new V5Application;+ $application->forceFill([+ 'id' => $applicationPayload['id'] ?? null,+ 'container_name' => $applicationPayload['container_name'] ?? null,+ 'runtime_container_id' => $applicationPayload['runtime_container_id'] ?? null,+ 'server_id' => $server->id,+ ]);+ $application->exists = false;+ $application->setRelation('server', $server);++ return $application;+ }++ /**+ * If a coold-side agent-token revocation ever lands on AgentTokenIssuer,+ * call it best-effort. Guarded so this job never hard-depends on a method+ * that may not exist yet.+ */+ private function revokeAgentTokenIfSupported(V5Server $server, mixed $serverId, mixed $host): void+ {+ if (! method_exists(AgentTokenIssuer::class, 'revokeForServer')) {+ return;+ }++ try {+ app(AgentTokenIssuer::class)->revokeForServer($server);+ } catch (\Throwable $exception) {+ Log::warning('V5 team teardown: agent token revocation failed', [+ 'team_id' => $this->teamId,+ 'server_id' => $serverId,+ 'host' => $host,+ 'error' => $exception->getMessage(),+ ]);+ }+ }+}diff --git a/app/Models/Team.php b/app/Models/Team.phpindex a979b44fbd..d01bfc45c9 100644--- a/app/Models/Team.php+++ b/app/Models/Team.php@@ -4,6 +4,7 @@ namespace App\Models;use App\Actions\User\RevokeUserTeamTokens;use App\Events\ServerReachabilityChanged;+use App\Jobs\V5TeardownTeamJob;use App\Notifications\Channels\SendsDiscord;use App\Notifications\Channels\SendsEmail;use App\Notifications\Channels\SendsPushover;@@ -75,6 +76,17 @@ class Team extends Model implements SendsDiscord, SendsEmail, SendsPushover, Sen});static::deleting(function (Team $team) {+ // Best-effort on-host teardown of this team's v5 resources BEFORE the+ // DB cascade removes the servers/applications/private keys. Captured+ // synchronously into a queued job so an unreachable host cannot block+ // or fail the team deletion (see V5TeardownTeamJob). Guarded so a v5+ // teardown problem never breaks v4 team deletion.+ try {+ V5TeardownTeamJob::dispatchForTeam($team);+ } catch (\Throwable $exception) {+ report($exception);+ }+RevokeUserTeamTokens::forTeam($team->id);foreach ($team->privateKeys as $key) {diff --git a/app/Models/V5/Application.php b/app/Models/V5/Application.phpindex 9052ef11a9..9b673a97c8 100644--- a/app/Models/V5/Application.php+++ b/app/Models/V5/Application.php@@ -2,6 +2,7 @@namespace App\Models\V5;+use App\Enums\V5\ApplicationStatus;use App\Events\V5CanvasResourceUpdated;use App\Models\Environment;use App\Models\Project;@@ -9,6 +10,7 @@ use App\Models\Team;use App\Models\User;use Illuminate\Database\Eloquent\Relations\BelongsTo;use Illuminate\Database\Eloquent\Relations\HasMany;+use Illuminate\Support\Facades\DB;class Application extends V5Model{@@ -26,6 +28,7 @@ class Application extends V5Model'container_name','status','status_message',+ 'status_observed_at','runtime_container_id','mesh_namespace','ingress_enabled',@@ -35,7 +38,7 @@ class Application extends V5Model];protected $attributes = [- 'status' => 'creating',+ 'status' => ApplicationStatus::Creating->value,'mesh_namespace' => 'default','ingress_enabled' => false,'canvas_x' => 0,@@ -46,7 +49,7 @@ class Application extends V5Model{static::updated(function (self $application): void {if ($application->wasChanged(['status', 'status_message', 'runtime_container_id'])) {- V5CanvasResourceUpdated::dispatch($application->team_id, $application->id);+ DB::afterCommit(fn () => V5CanvasResourceUpdated::dispatch($application->team_id, $application->id));}});}@@ -54,6 +57,7 @@ class Application extends V5Modelprotected function casts(): array{return [+ 'status_observed_at' => 'datetime','ingress_enabled' => 'boolean','internal_port' => 'integer','canvas_x' => 'integer',diff --git a/app/Models/V5/ApplicationDomain.php b/app/Models/V5/ApplicationDomain.phpindex 5cabe62079..4a518dbfaa 100644--- a/app/Models/V5/ApplicationDomain.php+++ b/app/Models/V5/ApplicationDomain.php@@ -8,6 +8,8 @@ class ApplicationDomain extends V5Model{protected $table = 'v5_application_domains';+ protected bool $hasUuidColumn = false;+protected $fillable = ['application_id','domain',diff --git a/app/Models/V5/Cluster.php b/app/Models/V5/Cluster.phpindex d910ae6987..213b492eae 100644--- a/app/Models/V5/Cluster.php+++ b/app/Models/V5/Cluster.php@@ -11,6 +11,12 @@ class Cluster extends V5Model{protected $table = 'v5_clusters';+ /**+ * Single source of truth for cluster defaults: `$attributes` below is+ * built from these consts, and the column defaults in+ * 2026_06_16_130649_v5_create_clusters_table mirror them (kept there for+ * historical rows only — update both when changing a default).+ */public const DEFAULT_WIREGUARD_INTERFACE = 'wg0';public const DEFAULT_WIREGUARD_MANAGEMENT_POOL = '100.64.0.0/16';diff --git a/app/Models/V5/ContainerStatus.php b/app/Models/V5/ContainerStatus.phpindex 6985ccda86..ccea59618d 100644--- a/app/Models/V5/ContainerStatus.php+++ b/app/Models/V5/ContainerStatus.php@@ -9,6 +9,8 @@ class ContainerStatus extends V5Model{protected $table = 'v5_container_statuses';+ protected bool $hasUuidColumn = false;+protected $fillable = ['team_id','server_id',@@ -17,12 +19,14 @@ class ContainerStatus extends V5Model'image','status','status_message',+ 'status_observed_at','last_seen_at',];protected function casts(): array{return [+ 'status_observed_at' => 'datetime','last_seen_at' => 'datetime',];}diff --git a/app/Models/V5/ResourceConnectionRule.php b/app/Models/V5/ResourceConnectionRule.phpindex 10fe290ee1..8369c316de 100644--- a/app/Models/V5/ResourceConnectionRule.php+++ b/app/Models/V5/ResourceConnectionRule.php@@ -9,6 +9,8 @@ class ResourceConnectionRule extends V5Model{protected $table = 'v5_resource_connection_rules';+ protected bool $hasUuidColumn = false;+protected $fillable = ['connection_id','source_resource_type',diff --git a/app/Models/V5/RevokedAgentToken.php b/app/Models/V5/RevokedAgentToken.phpnew file mode 100644index 0000000000..c605238292--- /dev/null+++ b/app/Models/V5/RevokedAgentToken.php@@ -0,0 +1,45 @@+<?php++namespace App\Models\V5;++use Illuminate\Database\Eloquent\Relations\BelongsTo;++/**+ * A host-agent JWT that has been revoked (typically on server destroy/re-home).+ *+ * flux does not yet consult this list (see AgentTokenIssuer::revoke docblock);+ * it exists so the Laravel side owns the data and API needed for revocation the+ * moment flux gains a revocation check.+ */+class RevokedAgentToken extends V5Model+{+ protected bool $hasUuidColumn = false;++ protected $table = 'v5_revoked_agent_tokens';++ protected $fillable = [+ 'jti',+ 'server_id',+ 'revoked_at',+ 'expires_at',+ ];++ /**+ * @return array<string, string>+ */+ protected function casts(): array+ {+ return [+ 'revoked_at' => 'datetime',+ 'expires_at' => 'datetime',+ ];+ }++ /**+ * @return BelongsTo<Server, $this>+ */+ public function server(): BelongsTo+ {+ return $this->belongsTo(Server::class);+ }+}diff --git a/app/Models/V5/Server.php b/app/Models/V5/Server.phpindex 040618c5c3..9fc85bb74e 100644--- a/app/Models/V5/Server.php+++ b/app/Models/V5/Server.php@@ -2,12 +2,15 @@namespace App\Models\V5;+use App\Enums\V5\IngressStatus;use App\Events\V5CanvasResourceUpdated;use App\Events\V5ClusterUpdated;use App\Models\PrivateKey;use App\Models\Team;use App\Models\User;+use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Relations\BelongsTo;+use Illuminate\Support\Facades\DB;class Server extends V5Model{@@ -24,9 +27,12 @@ class Server extends V5Model'ssh_user','ssh_port','status',+ 'status_observed_at','ingress_type','ingress_status','capabilities',+ 'has_coold',+ 'is_ingress','builder_enabled','builder_capacity','builder_cpu_quota',@@ -35,6 +41,9 @@ class Server extends V5Model'wireguard_endpoint_override','wireguard_management_ip','wireguard_public_key',+ 'coold_version',+ 'agent_token_jti',+ 'agent_token_expires_at','container_subnets','canvas_x','canvas_y',@@ -60,22 +69,22 @@ class Server extends V5Model}if ($server->wasChanged('status') && $server->cluster_id !== null) {- V5ClusterUpdated::dispatch($server->team_id, $server->cluster_id);+ DB::afterCommit(fn () => V5ClusterUpdated::dispatch($server->team_id, $server->cluster_id));}if ($server->wasChanged('status')) {- V5CanvasResourceUpdated::dispatch(+ DB::afterCommit(fn () => V5CanvasResourceUpdated::dispatch($server->team_id,null,$server->isIngress() ? $server->id : null,$server->id,- );+ ));return;}if ($server->isIngress()) {- V5CanvasResourceUpdated::dispatch($server->team_id, null, $server->id);+ DB::afterCommit(fn () => V5CanvasResourceUpdated::dispatch($server->team_id, null, $server->id));}});}@@ -83,20 +92,56 @@ class Server extends V5Modelprotected function casts(): array{return [- 'capabilities' => 'array',+ 'has_coold' => 'boolean',+ 'is_ingress' => 'boolean','builder_enabled' => 'boolean','container_subnets' => 'array','canvas_x' => 'integer','canvas_y' => 'integer',+ 'status_observed_at' => 'datetime',+ 'agent_token_expires_at' => 'datetime','last_bootstrapped_at' => 'datetime','last_bootstrap_ran_at' => 'datetime','last_status_checked_at' => 'datetime',];}+ public function fluxHostId(): string+ {+ return (string) $this->uuid;+ }++ /**+ * Virtual attribute kept for wire-format compatibility: capabilities are+ * stored as the indexed has_coold / is_ingress booleans, but reads and+ * writes of `capabilities` keep working with the historical string array.+ * Unknown capability names are dropped on write.+ *+ * The dropped `capabilities` column intentionally stays in `$fillable`:+ * call sites still mass-assign it, and this mutator maps those writes+ * onto the boolean columns.+ */+ protected function capabilities(): Attribute+ {+ return Attribute::make(+ get: fn () => array_values(array_filter([+ $this->has_coold ? 'coold' : null,+ $this->is_ingress ? 'ingress' : null,+ ])),+ set: fn (?array $capabilities) => [+ 'has_coold' => in_array('coold', $capabilities ?? [], true),+ 'is_ingress' => in_array('ingress', $capabilities ?? [], true),+ ],+ );+ }+public function hasCapability(string $capability): bool{- return in_array($capability, $this->capabilities ?? [], true);+ return match ($capability) {+ 'coold' => (bool) $this->has_coold,+ 'ingress' => (bool) $this->is_ingress,+ default => false,+ };}/**@@ -104,7 +149,7 @@ class Server extends V5Model*/public function withCapability(string $capability): array{- return collect($this->capabilities ?? [])+ return collect($this->capabilities)->push($capability)->unique()->values()@@ -116,7 +161,7 @@ class Server extends V5Model*/public function withoutCapability(string $capability): array{- return collect($this->capabilities ?? [])+ return collect($this->capabilities)->reject(fn (string $existingCapability) => $existingCapability === $capability)->values()->all();@@ -124,16 +169,12 @@ class Server extends V5Modelpublic function isIngress(): bool{- return $this->hasCapability('ingress');+ return (bool) $this->is_ingress;}public function ingressStatus(): string{- if ($this->ingress_status !== null) {- return $this->ingress_status;- }-- return $this->status === 'installed' ? 'running' : 'unknown';+ return $this->ingress_status ?? IngressStatus::Unknown->value;}public function ingressType(): stringdiff --git a/app/Models/V5/V5Model.php b/app/Models/V5/V5Model.phpindex d1df6e12b5..935bd20acf 100644--- a/app/Models/V5/V5Model.php+++ b/app/Models/V5/V5Model.php@@ -3,26 +3,55 @@namespace App\Models\V5;use Illuminate\Database\Eloquent\Model;-use Illuminate\Support\Facades\Schema;abstract class V5Model extends Model{+ /**+ * Whether the model's table has a `uuid` column. Models without one (set+ * this to false there) skip public-id generation and route on the primary+ * key instead.+ */+ protected bool $hasUuidColumn = true;+public function getRouteKeyName(): string{- return 'uuid';+ return $this->hasUuidColumn ? 'uuid' : $this->getKeyName();}protected static function boot(): void{parent::boot();- static::creating(function (Model $model): void {- if (- Schema::hasColumn($model->getTable(), 'uuid')- && ! $model->getAttribute('uuid')- ) {- $model->setAttribute('uuid', new_public_id());+ static::creating(function (self $model): void {+ if ($model->hasUuidColumn && ! $model->getAttribute('uuid')) {+ $model->setAttribute('uuid', $model->newUniquePublicId());}});}++ /**+ * Generate a public id, regenerating (up to three candidates) when one is+ * already taken. A concurrent insert between this exists() check and our+ * own insert can still collide; the unique index then rejects the insert,+ * which is an acceptable residual race for these cheap, retryable writes.+ */+ protected function newUniquePublicId(): string+ {+ $attempts = 0;++ do {+ $candidate = $this->newPublicIdCandidate();+ $attempts++;+ } while (+ $attempts < 3+ && $this->newModelQuery()->where('uuid', $candidate)->exists()+ );++ return $candidate;+ }++ protected function newPublicIdCandidate(): string+ {+ return new_public_id();+ }}diff --git a/app/Policies/V5/ApplicationPolicy.php b/app/Policies/V5/ApplicationPolicy.phpnew file mode 100644index 0000000000..5b1877a002--- /dev/null+++ b/app/Policies/V5/ApplicationPolicy.php@@ -0,0 +1,74 @@+<?php++namespace App\Policies\V5;++use App\Models\Team;+use App\Models\User;+use App\Models\V5\Application;+use Illuminate\Auth\Access\Response;++class ApplicationPolicy+{+ /**+ * Determine whether the user can view the application within the current team.+ *+ * Read-only diagnostics (deploy status, container logs) are available to any+ * member of the owning team; apps from other teams stay hidden as a 404.+ */+ public function view(User $user, Application $application, Team $team): Response+ {+ return $this->belongsToTeam($application, $team);+ }++ /**+ * Determine whether the user can update the application within the current team.+ */+ public function update(User $user, Application $application, Team $team): Response+ {+ return $this->allowIfAdminAndScoped($user, $application, $team);+ }++ /**+ * Determine whether the user can update the application's ingress configuration.+ */+ public function updateIngress(User $user, Application $application, Team $team): Response+ {+ return $this->allowIfAdminAndScoped($user, $application, $team);+ }++ /**+ * Determine whether the user can delete the application within the current team.+ */+ public function delete(User $user, Application $application, Team $team): Response+ {+ return $this->allowIfAdminAndScoped($user, $application, $team);+ }++ /**+ * Run the team scoping check first (mismatch stays hidden as a 404) and+ * only then the role check (403 for members on their own team's app).+ */+ private function allowIfAdminAndScoped(User $user, Application $application, Team $team): Response+ {+ $scope = $this->belongsToTeam($application, $team);++ if ($scope->denied()) {+ return $scope;+ }++ return $user->isAdminOfTeam($team->id)+ ? Response::allow()+ : Response::deny('You do not have permission to manage applications in this team.');+ }++ /**+ * Applications outside the current team must stay invisible, so+ * mismatches deny as not found instead of forbidden.+ */+ private function belongsToTeam(Application $application, Team $team): Response+ {+ return $application->team_id === $team->id+ ? Response::allow()+ : Response::denyAsNotFound();+ }+}diff --git a/app/Policies/V5/ClusterPolicy.php b/app/Policies/V5/ClusterPolicy.phpnew file mode 100644index 0000000000..dec9e1c358--- /dev/null+++ b/app/Policies/V5/ClusterPolicy.php@@ -0,0 +1,64 @@+<?php++namespace App\Policies\V5;++use App\Models\Team;+use App\Models\User;+use App\Models\V5\Cluster;+use Illuminate\Auth\Access\Response;++class ClusterPolicy+{+ /**+ * Determine whether the user can view the cluster within the current team.+ * Read-only, so gated on team membership alone.+ */+ public function view(User $user, Cluster $cluster, Team $team): Response+ {+ return $this->belongsToTeam($cluster, $team);+ }++ /**+ * Determine whether the user can create a cluster in the current team.+ * There is no model to scope yet, so this is a pure role gate.+ */+ public function create(User $user, Team $team): Response+ {+ return $this->allowIfAdmin($user, $team);+ }++ /**+ * Determine whether the user can delete the cluster within the current team.+ */+ public function delete(User $user, Cluster $cluster, Team $team): Response+ {+ $scope = $this->belongsToTeam($cluster, $team);++ if ($scope->denied()) {+ return $scope;+ }++ return $this->allowIfAdmin($user, $team);+ }++ /**+ * Members may read but not mutate; only admins/owners of the team pass.+ */+ private function allowIfAdmin(User $user, Team $team): Response+ {+ return $user->isAdminOfTeam($team->id)+ ? Response::allow()+ : Response::deny('You do not have permission to manage clusters in this team.');+ }++ /**+ * Clusters outside the current team must stay invisible, so mismatches+ * deny as not found instead of forbidden.+ */+ private function belongsToTeam(Cluster $cluster, Team $team): Response+ {+ return $cluster->team_id === $team->id+ ? Response::allow()+ : Response::denyAsNotFound();+ }+}diff --git a/app/Policies/V5/ResourceConnectionPolicy.php b/app/Policies/V5/ResourceConnectionPolicy.phpnew file mode 100644index 0000000000..6b3dcde792--- /dev/null+++ b/app/Policies/V5/ResourceConnectionPolicy.php@@ -0,0 +1,55 @@+<?php++namespace App\Policies\V5;++use App\Models\Team;+use App\Models\User;+use App\Models\V5\ResourceConnection;+use Illuminate\Auth\Access\Response;++class ResourceConnectionPolicy+{+ /**+ * Determine whether the user can update the connection within the current team.+ */+ public function update(User $user, ResourceConnection $connection, Team $team): Response+ {+ return $this->allowIfAdminAndScoped($user, $connection, $team);+ }++ /**+ * Determine whether the user can delete the connection within the current team.+ */+ public function delete(User $user, ResourceConnection $connection, Team $team): Response+ {+ return $this->allowIfAdminAndScoped($user, $connection, $team);+ }++ /**+ * Run the team scoping check first (mismatch stays hidden as a 404) and+ * only then the role check (403 for members on their own team's connection).+ */+ private function allowIfAdminAndScoped(User $user, ResourceConnection $connection, Team $team): Response+ {+ $scope = $this->belongsToTeam($connection, $team);++ if ($scope->denied()) {+ return $scope;+ }++ return $user->isAdminOfTeam($team->id)+ ? Response::allow()+ : Response::deny('You do not have permission to manage resource connections in this team.');+ }++ /**+ * Connections outside the current team must stay invisible, so+ * mismatches deny as not found instead of forbidden.+ */+ private function belongsToTeam(ResourceConnection $connection, Team $team): Response+ {+ return $connection->team_id === $team->id+ ? Response::allow()+ : Response::denyAsNotFound();+ }+}diff --git a/app/Policies/V5/ServerPolicy.php b/app/Policies/V5/ServerPolicy.phpnew file mode 100644index 0000000000..af828b398d--- /dev/null+++ b/app/Policies/V5/ServerPolicy.php@@ -0,0 +1,121 @@+<?php++namespace App\Policies\V5;++use App\Models\Team;+use App\Models\User;+use App\Models\V5\Cluster;+use App\Models\V5\Server;+use Illuminate\Auth\Access\Response;++class ServerPolicy+{+ /**+ * Determine whether the user can add a server to the cluster within the+ * current team. Denies as forbidden (not "not found") to preserve the+ * historical 403 on cluster/team mismatch, and requires an admin/owner+ * role to mutate cluster infrastructure.+ */+ public function create(User $user, Team $team, Cluster $cluster): Response+ {+ if ($cluster->team_id !== $team->id) {+ return Response::deny();+ }++ return $this->allowIfAdmin($user, $team);+ }++ /**+ * Determine whether the user can update the server within the current team.+ */+ public function update(User $user, Server $server, Team $team, Cluster $cluster): Response+ {+ return $this->allowIfAdminAndScoped($user, $server, $team, $cluster);+ }++ /**+ * Determine whether the user can delete the server within the current team.+ */+ public function delete(User $user, Server $server, Team $team, Cluster $cluster): Response+ {+ return $this->allowIfAdminAndScoped($user, $server, $team, $cluster);+ }++ /**+ * Determine whether the user can run a connectivity check against the server.+ */+ public function check(User $user, Server $server, Team $team, Cluster $cluster): Response+ {+ return $this->allowIfAdminAndScoped($user, $server, $team, $cluster);+ }++ /**+ * Determine whether the user can bootstrap the server.+ */+ public function bootstrap(User $user, Server $server, Team $team, Cluster $cluster): Response+ {+ return $this->allowIfAdminAndScoped($user, $server, $team, $cluster);+ }++ /**+ * Determine whether the user can view server diagnostics (coold logs,+ * corrosion tables, firewall rules). Read-only, so gated on team+ * membership alone.+ */+ public function viewDiagnostics(User $user, Server $server, Team $team, Cluster $cluster): Response+ {+ return $this->belongsToClusterInTeam($server, $team, $cluster);+ }++ /**+ * Determine whether the user can move the server's Caddy ingress card on+ * the canvas. Non-ingress servers must stay invisible on the canvas, and+ * moving a card mutates persisted layout so it requires an admin/owner.+ */+ public function updateCanvasPosition(User $user, Server $server, Team $team): Response+ {+ if (! ($server->team_id === $team->id && $server->isIngress())) {+ return Response::denyAsNotFound();+ }++ return $this->allowIfAdmin($user, $team);+ }++ /**+ * Run the team/cluster scoping check first (mismatch stays hidden as a 404)+ * and only then the role check (403 for members on their own team's server).+ */+ private function allowIfAdminAndScoped(User $user, Server $server, Team $team, Cluster $cluster): Response+ {+ $scope = $this->belongsToClusterInTeam($server, $team, $cluster);++ if ($scope->denied()) {+ return $scope;+ }++ return $this->allowIfAdmin($user, $team);+ }++ /**+ * Members may read but not mutate; only admins/owners of the team pass.+ */+ private function allowIfAdmin(User $user, Team $team): Response+ {+ return $user->isAdminOfTeam($team->id)+ ? Response::allow()+ : Response::deny('You do not have permission to manage servers in this team.');+ }++ /**+ * Servers outside the current team (or outside the addressed cluster)+ * must stay invisible, so mismatches deny as not found.+ */+ private function belongsToClusterInTeam(Server $server, Team $team, Cluster $cluster): Response+ {+ return $cluster->team_id === $team->id+ && $server->team_id === $team->id+ && $server->cluster_id === $cluster->id+ ? Response::allow()+ : Response::denyAsNotFound();+ }+}diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.phpindex 2d0094f337..9e9bb1c6cb 100644--- a/app/Providers/AppServiceProvider.php+++ b/app/Providers/AppServiceProvider.php@@ -3,7 +3,9 @@namespace App\Providers;use App\Models\PersonalAccessToken;+use App\Models\V5\Application;use Illuminate\Database\Eloquent\Model;+use Illuminate\Database\Eloquent\Relations\Relation;use Illuminate\Support\Facades\App;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Http;@@ -27,6 +29,7 @@ class AppServiceProvider extends ServiceProviderpublic function boot(): void{$this->configureCommands();+ $this->configureMorphMap();$this->configureModels();$this->configurePasswords();$this->configureSanctumModel();@@ -41,6 +44,18 @@ class AppServiceProvider extends ServiceProvider}}+ /**+ * Map v5 models to stable morph aliases so polymorphic rows survive class+ * renames. Deliberately NOT enforced: v4 polymorphic relations store FQCNs+ * and must keep resolving them.+ */+ private function configureMorphMap(): void+ {+ Relation::morphMap([+ 'v5.application' => Application::class,+ ]);+ }+private function configureModels(): void{// Disabled because it's causing issues with the applicationdiff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.phpindex 5c1a79cf78..8903e750bf 100644--- a/app/Providers/AuthServiceProvider.php+++ b/app/Providers/AuthServiceProvider.php@@ -36,6 +36,10 @@ use App\Models\StandaloneRedis;use App\Models\SwarmDocker;use App\Models\Team;use App\Models\TelegramNotificationSettings;+use App\Models\V5\Application as V5Application;+use App\Models\V5\Cluster as V5Cluster;+use App\Models\V5\ResourceConnection as V5ResourceConnection;+use App\Models\V5\Server as V5Server;use App\Models\WebhookNotificationSettings;use App\Policies\ApiTokenPolicy;use App\Policies\ApplicationPolicy;@@ -61,6 +65,10 @@ use App\Policies\SharedEnvironmentVariablePolicy;use App\Policies\StandaloneDockerPolicy;use App\Policies\SwarmDockerPolicy;use App\Policies\TeamPolicy;+use App\Policies\V5\ApplicationPolicy as V5ApplicationPolicy;+use App\Policies\V5\ClusterPolicy as V5ClusterPolicy;+use App\Policies\V5\ResourceConnectionPolicy as V5ResourceConnectionPolicy;+use App\Policies\V5\ServerPolicy as V5ServerPolicy;use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;use Illuminate\Support\Facades\Gate;use Laravel\Sanctum\PersonalAccessToken;@@ -122,6 +130,12 @@ class AuthServiceProvider extends ServiceProviderCloudProviderToken::class => CloudProviderTokenPolicy::class,CloudInitScript::class => CloudInitScriptPolicy::class,+ // V5 policies - scoped to the current team resolved from the request+ V5Application::class => V5ApplicationPolicy::class,+ V5Cluster::class => V5ClusterPolicy::class,+ V5ResourceConnection::class => V5ResourceConnectionPolicy::class,+ V5Server::class => V5ServerPolicy::class,+];/**diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.phpindex 2bb5b40bdb..7c1969395c 100644--- a/app/Providers/RouteServiceProvider.php+++ b/app/Providers/RouteServiceProvider.php@@ -60,6 +60,14 @@ class RouteServiceProvider extends ServiceProviderreturn Limit::perMinute(5)->by($request->user()?->id ?: $request->ip());});+ // v5 authenticated web endpoints run synchronous SSH/Flux work per+ // request (connectivity checks, bootstrap, diagnostics). Throttle per+ // user so a single member cannot pin FPM workers by hammering them,+ // while leaving ample headroom for the canvas's 3s cluster polling.+ RateLimiter::for('v5', function (Request $request) {+ return Limit::perMinute(120)->by($request->user()?->id ?: $request->ip());+ });+RateLimiter::for('feedback', function (Request $request) {return Limit::perMinute(3)->by($request->user()?->id ?: $request->ip());});diff --git a/app/Rules/ValidHostname.php b/app/Rules/ValidHostname.phpindex 89b68663b1..c8e09d0436 100644--- a/app/Rules/ValidHostname.php+++ b/app/Rules/ValidHostname.php@@ -33,10 +33,19 @@ class ValidHostname implements ValidationRulereturn;}+ // Reject ASCII control characters (including embedded newlines, which+ // would otherwise slip through the trailing-newline-tolerant `$` anchor+ // in the per-label regex below).+ if (preg_match('/[\x00-\x1f\x7f]/', $hostname) === 1) {+ $fail('The :attribute contains invalid characters. Only letters (a-z, A-Z), numbers (0-9), hyphens (-), and dots (.) are allowed.');++ return;+ }+// Check for dangerous shell metacharacters$dangerousChars = [';', '|', '&', '$', '`', '(', ')', '{', '}',- '<', '>', '\n', '\r', '\0', '"', "'", '\\',+ '<', '>', "\n", "\r", "\0", '"', "'", '\\','!', '*', '?', '[', ']', '~', '^', ':', '#','@', '%', '=', '+', ',', ' ',];@@ -104,7 +113,7 @@ class ValidHostname implements ValidationRule}// Check if label contains only valid characters (letters, digits, hyphens)- if (! preg_match('/^[a-z0-9-]+$/', $label)) {+ if (! preg_match('/^[a-z0-9-]+$/D', $label)) {$fail('The :attribute contains invalid characters. Only letters (a-z, A-Z), numbers (0-9), hyphens (-), and dots (.) are allowed.');return;diff --git a/app/Rules/ValidServerIp.php b/app/Rules/ValidServerIp.phpindex 270ff1c348..bb642e18a8 100644--- a/app/Rules/ValidServerIp.php+++ b/app/Rules/ValidServerIp.php@@ -9,6 +9,12 @@ class ValidServerIp implements ValidationRule{/*** Accepts a valid IPv4 address, IPv6 address, or RFC 1123 hostname.+ *+ * IP literals in private/reserved ranges (loopback, link-local, RFC 1918,+ * etc.) are rejected by default to stop a member from pointing a server at+ * the Coolify host's internal network and abusing the synchronous SSH check+ * to probe it. Self-hosters on private LANs can allow them via+ * config('coold.allow_private_server_ips').*/public function validate(string $attribute, mixed $value, Closure $fail): void{@@ -19,10 +25,14 @@ class ValidServerIp implements ValidationRule$trimmed = trim($value);if (filter_var($trimmed, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {+ $this->failIfDisallowedRange($trimmed, $fail);+return;}if (filter_var($trimmed, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {+ $this->failIfDisallowedRange($trimmed, $fail);+return;}@@ -37,4 +47,25 @@ class ValidServerIp implements ValidationRule$fail('The :attribute must be a valid IPv4 address, IPv6 address, or hostname.');}}++ /**+ * Reject IPs in private/reserved ranges unless the operator has explicitly+ * opted in. The IP is already known to be a valid literal here.+ */+ private function failIfDisallowedRange(string $ip, Closure $fail): void+ {+ if (config('coold.allow_private_server_ips')) {+ return;+ }++ $isPublic = filter_var(+ $ip,+ FILTER_VALIDATE_IP,+ FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE+ );++ if ($isPublic === false) {+ $fail('The :attribute must not be a private or reserved IP address.');+ }+ }}diff --git a/app/Services/Flux/AgentTokenIssuer.php b/app/Services/Flux/AgentTokenIssuer.phpindex 4a06a6735c..51aa320a4d 100644--- a/app/Services/Flux/AgentTokenIssuer.php+++ b/app/Services/Flux/AgentTokenIssuer.php@@ -2,20 +2,41 @@namespace App\Services\Flux;+use App\Models\V5\RevokedAgentToken;use App\Models\V5\Server as V5Server;use Firebase\JWT\JWT;use Illuminate\Support\Facades\File;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Str;use RuntimeException;+/**+ * Mints the per-host ES256 JWT that authorizes a coold host agent against flux.+ *+ * Capability scoping: by default the token carries the EXPLICIT list of+ * primitive capability strings coold advertises (config('flux.host_capabilities'),+ * mirroring coold/coold/src/grpc/client.rs:204-231) rather than the+ * `host-agent:default` wildcard profile. flux intersects the jwt `caps` with+ * coold's advertised set (flux/src/main.rs:128-141), so the effective power is+ * unchanged, but the token no longer depends on flux's+ * `capability_profile_authorizes_all` wildcard bypass (main.rs:124-126).+ *+ * @see config/flux.php for the capability list, escape hatch, TTL and kid config.+ */class AgentTokenIssuer{public const DEFAULT_PROFILE = 'host-agent:default';+ private const TTL_FLOOR_SECONDS = 60;+/**- * @param array<int, string> $capabilities- * @param array<string, mixed> $extraClaims+ * Mint a host JWT.+ *+ * @param array<int, string>|null $capabilities Explicit caps; null resolves the configured default set (or escape-hatch profile).+ * @param int|null $ttl Lifetime in seconds; null resolves config('flux.host_token_ttl'). Clamped to a 60s floor.+ * @param array<string, mixed> $extraClaims Extra claims merged in (a `jti` here is honored, otherwise one is generated).*/- public function issue(string $hostId, array $capabilities = [self::DEFAULT_PROFILE], int $ttl = 86400, array $extraClaims = []): string+ public function issue(string $hostId, ?array $capabilities = null, ?int $ttl = null, array $extraClaims = []): string{if ($hostId === '') {throw new RuntimeException('Flux host id is required.');@@ -27,30 +48,186 @@ class AgentTokenIssuerthrow new RuntimeException("Flux JWT private key not found at {$privateKeyPath}.");}+ $this->assertPrivateKeyPermissions($privateKeyPath);++ $capabilities ??= $this->defaultCapabilities();+ $ttl ??= (int) config('flux.host_token_ttl', 3600);++ $jti = $extraClaims['jti'] ?? (string) Str::uuid();+ unset($extraClaims['jti']);+$now = time();+ $keyId = (string) config('flux.jwt_kid', 'flux-default');return JWT::encode(array_merge($extraClaims, ['sub' => $hostId,'aud' => 'coold','caps' => $this->normalizeCapabilities($capabilities),+ 'jti' => $jti,'iat' => $now,- 'exp' => $now + max(60, $ttl),- ]), File::get($privateKeyPath), 'ES256');+ 'exp' => $now + max(self::TTL_FLOOR_SECONDS, $ttl),+ ]), File::get($privateKeyPath), 'ES256', $keyId !== '' ? $keyId : null);}- public function issueForServer(V5Server $server, int $ttl = 86400): string+ public function issueForServer(V5Server $server, ?int $ttl = null): string{- $hostId = $server->wireguard_management_ip ?: $server->node_address;+ $hostId = $server->fluxHostId();- if (! is_string($hostId) || $hostId === '') {- throw new RuntimeException('Server is missing its Flux host id.');+ if ($hostId === '') {+ throw new RuntimeException('Server is missing a valid Flux host id.');}- return $this->issue($hostId, [self::DEFAULT_PROFILE], $ttl, [- 'team_id' => $server->team_id,- 'cluster_id' => $server->cluster_id,- 'server_id' => $server->id,+ $jti = (string) Str::uuid();+ $ttl ??= (int) config('flux.host_token_ttl', 3600);++ // team_id/cluster_id/server_id are minted as STRINGS: flux deserializes+ // the `team_id` claim as a string (coold/flux/src/auth.rs Claims), and+ // rejects the whole token with a JSON type error if it arrives as a JSON+ // integer. Keep the sibling ids string-typed for consistency.+ $token = $this->issue($hostId, $this->defaultCapabilities(), $ttl, [+ 'jti' => $jti,+ 'team_id' => (string) $server->team_id,+ 'cluster_id' => (string) $server->cluster_id,+ 'server_id' => $hostId,+ 'wireguard_management_ip' => (string) $server->wireguard_management_ip,]);++ // Persist the freshly issued jti (so a later destroy/re-home knows which+ // token to revoke) and its expiry (so the scheduled rotation loop knows+ // when to re-mint). Use a targeted update keyed by id so this neither+ // inserts an unsaved model nor flushes unrelated dirty attributes, and+ // does not depend on the Server model's $fillable.+ if ($server->exists) {+ $expiresAt = now()->addSeconds(max(self::TTL_FLOOR_SECONDS, $ttl));++ V5Server::query()->whereKey($server->getKey())->update([+ 'agent_token_jti' => $jti,+ 'agent_token_expires_at' => $expiresAt,+ ]);+ $server->setAttribute('agent_token_jti', $jti);+ $server->setAttribute('agent_token_expires_at', $expiresAt);+ $server->syncOriginalAttribute('agent_token_jti');+ $server->syncOriginalAttribute('agent_token_expires_at');+ }++ return $token;+ }++ /**+ * Record the server's currently-issued host token jti as revoked AND push+ * the revocation to flux so it rejects the jti at verify immediately.+ *+ * flux now consults a revocation denylist (flux/src/auth.rs `is_revoked`,+ * fed by `POST /v1/tokens/revoke` on the flux UDS), and Laravel pushes to it+ * here. The local `RevokedAgentToken` record remains the source of truth+ * Laravel owns; the flux push is best-effort — if flux is unreachable the+ * revocation is logged and the local record still stands, with the short TTL+ * and hourly rotation bounding the exposure until flux is reachable again.+ */+ public function revoke(V5Server $server): void+ {+ $jti = $server->agent_token_jti;++ if (! is_string($jti) || $jti === '') {+ return;+ }++ $expiresAt = $server->agent_token_expires_at;+ $expiresAtUnix = $expiresAt instanceof \DateTimeInterface ? $expiresAt->getTimestamp() : null;++ RevokedAgentToken::query()->updateOrCreate(+ ['jti' => $jti],+ [+ 'server_id' => $server->id,+ 'revoked_at' => now(),+ 'expires_at' => $expiresAt,+ ]+ );++ // Best-effort: a destroy/teardown must never fail because flux is down.+ try {+ app(FluxClient::class)->revokeToken($jti, $expiresAtUnix);+ } catch (\Throwable $exception) {+ Log::warning('Failed to push agent token revocation to Flux.', [+ 'server_id' => $server->id,+ 'jti' => $jti,+ 'error' => $exception->getMessage(),+ ]);+ }++ if ($server->exists) {+ V5Server::query()->whereKey($server->getKey())->update(['agent_token_jti' => null]);+ $server->setAttribute('agent_token_jti', null);+ $server->syncOriginalAttribute('agent_token_jti');+ }+ }++ /**+ * Revoke the server's currently-issued host token. Alias of {@see revoke()}+ * kept as the name the team-teardown job resolves via `method_exists`.+ */+ public function revokeForServer(V5Server $server): void+ {+ $this->revoke($server);+ }++ public function isRevoked(string $jti): bool+ {+ if ($jti === '') {+ return false;+ }++ return RevokedAgentToken::query()->where('jti', $jti)->exists();+ }++ /**+ * The default capability set for production host tokens: the explicit+ * advertised primitive list, unless the emergency escape hatch profile is+ * configured (then that single profile is minted instead).+ *+ * @return array<int, string>+ */+ private function defaultCapabilities(): array+ {+ $profile = config('flux.host_capability_profile');++ if (is_string($profile) && trim($profile) !== '') {+ return [trim($profile)];+ }++ $configured = config('flux.host_capabilities');++ if (is_array($configured) && $configured !== []) {+ return array_values($configured);+ }++ return [self::DEFAULT_PROFILE];+ }++ /**+ * Warn (but do not hard-fail — that could break existing installs) when the+ * private key file is readable by group/other or is not owner-readable. The+ * key should be generated 0600, e.g.:+ * openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 \+ * -out storage/app/flux/jwt.priv && chmod 600 storage/app/flux/jwt.priv+ */+ private function assertPrivateKeyPermissions(string $path): void+ {+ $perms = @fileperms($path);++ if ($perms === false) {+ return;+ }++ $mode = $perms & 0777;++ if (($mode & 0077) !== 0 || ($mode & 0400) === 0) {+ Log::warning('Flux JWT private key has insecure permissions.', [+ 'path' => $path,+ 'mode' => sprintf('%04o', $mode),+ 'expected' => '0600',+ ]);+ }}/**diff --git a/app/Services/Flux/FluxClient.php b/app/Services/Flux/FluxClient.phpindex fa5caacd5c..22f46db45b 100644--- a/app/Services/Flux/FluxClient.php+++ b/app/Services/Flux/FluxClient.php@@ -2,6 +2,7 @@namespace App\Services\Flux;+use App\Exceptions\V5\UnsupportedCooldVerb;use Illuminate\Support\Str;use RuntimeException;@@ -60,6 +61,28 @@ class FluxClientreturn $this->output($payload, 'Container started.');}+ public function stopContainer(string $hostId, string $id, int $timeoutSeconds = 10): string+ {+ $payload = $this->dispatch($hostId, [+ 'type' => 'containers.stop',+ 'id' => $id,+ 'timeout_seconds' => max(0, $timeoutSeconds),+ ]);++ return $this->output($payload, 'Container stopped.');+ }++ public function removeContainer(string $hostId, string $id, bool $force = false): string+ {+ $payload = $this->dispatch($hostId, [+ 'type' => 'containers.delete',+ 'id' => $id,+ 'force' => $force,+ ]);++ return $this->output($payload, 'Container removed.');+ }+/*** @return array<string, mixed>*/@@ -151,6 +174,19 @@ class FluxClientreturn $this->output($payload, 'No coold logs returned.');}+ public function containerLogs(string $hostId, string $containerId, int $tail = 200): string+ {+ $payload = $this->dispatch($hostId, [+ 'type' => 'containers.logs',+ 'id' => $containerId,+ 'tail' => max(1, min($tail, 1000)),+ 'stdout' => true,+ 'stderr' => true,+ ]);++ return $this->output($payload, 'No container logs returned.');+ }+public function corrosionTables(string $hostId, int $limit = 200): string{$payload = $this->dispatch($hostId, [@@ -161,11 +197,107 @@ class FluxClientreturn $this->output($payload, '{"limit":200,"tables":[]}');}+ /**+ * Deliver a freshly minted host JWT to the node over the live coold RPC+ * stream (flux gates the `host.jwt.set` capability; the token must carry+ * it). Preferred over the SSH push because it reuses the already+ * authenticated flux<->coold channel and works while the current token is+ * still valid — exactly the rotation window. Throws like the sibling+ * dispatch methods (host not connected / UnsupportedCooldVerb / generic+ * failure) so the caller can catch and fall back to SSH.+ */+ public function pushHostToken(string $hostId, string $token): void+ {+ $this->dispatch($hostId, [+ 'type' => 'host.jwt.set',+ 'jwt' => $token,+ ]);+ }++ /**+ * Revoke a host token by its `jti` on the flux revocation store so flux+ * rejects it at verify immediately, instead of waiting for the token's TTL+ * to lapse (flux/src/unix_bridge.rs `POST /v1/tokens/revoke`,+ * flux/src/auth.rs `is_revoked`). The optional `expiresAt` (the token `exp`,+ * unix seconds) lets flux prune the denylist entry once it can no longer+ * matter.+ *+ * Best-effort like the sibling dispatch methods: throws a RuntimeException on+ * connection failure / timeout / non-2xx so the caller can catch and treat+ * an unreachable flux as non-fatal (the local revocation record still+ * stands and the short TTL + rotation bound the exposure).+ */+ public function revokeToken(string $jti, ?int $expiresAt = null): void+ {+ if (trim($jti) === '') {+ return;+ }++ $requestBody = ['jti' => $jti];++ if ($expiresAt !== null) {+ $requestBody['expires_at'] = $expiresAt;+ }++ $body = json_encode($requestBody, JSON_THROW_ON_ERROR);+ $response = $this->sendOverSocket('/v1/tokens/revoke', $body);+ $statusCode = $this->statusCode($response);++ if ($statusCode < 200 || $statusCode >= 300) {+ $responseBody = $this->responseBody($response);+ $payload = $responseBody === '' ? null : json_decode($responseBody, true);++ throw new RuntimeException(+ $this->errorMessage($payload, $responseBody) ?? "Flux token revocation returned HTTP {$statusCode}."+ );+ }+ }+/*** @param array<string, mixed> $command* @return array<string, mixed>*/private function dispatch(string $hostId, array $command): array+ {+ $body = json_encode([+ 'host_id' => $hostId,+ 'request_id' => (string) Str::uuid(),+ 'command' => $command,+ ], JSON_THROW_ON_ERROR);++ $response = $this->sendOverSocket('/v1/coold/dispatch', $body);++ $statusCode = $this->statusCode($response);+ $responseBody = $this->responseBody($response);+ $payload = $responseBody === '' ? null : json_decode($responseBody, true);++ if ($statusCode < 200 || $statusCode >= 300) {+ throw $this->dispatchException(+ $command,+ $statusCode,+ $this->errorMessage($payload, $responseBody) ?? "Flux dispatch returned HTTP {$statusCode}."+ );+ }++ if (! is_array($payload)) {+ throw new RuntimeException('Flux dispatch returned an invalid response.');+ }++ if (($payload['status'] ?? null) === 'error') {+ $message = is_string($payload['message'] ?? null) ? $payload['message'] : 'Flux dispatch failed.';++ throw $this->dispatchException($command, $statusCode, $message);+ }++ return $payload;+ }++ /**+ * Send a single HTTP/1.1 request over the flux Unix-domain socket and return+ * the raw response. Shared by every flux verb (coold dispatch, host token+ * rotation, token revocation) — only the request path and JSON body differ.+ */+ private function sendOverSocket(string $path, string $body): string{$socketPath = config('flux.unix_socket_path');@@ -177,11 +309,6 @@ class FluxClientthrow new RuntimeException('Flux socket was not found.');}- $body = json_encode([- 'host_id' => $hostId,- 'request_id' => (string) Str::uuid(),- 'command' => $command,- ], JSON_THROW_ON_ERROR);$connectionTimeout = (float) config('flux.connection_timeout_seconds', 1.0);$dispatchTimeout = (float) config('flux.dispatch_timeout_seconds', 35.0);$stream = @stream_socket_client("unix://{$socketPath}", $errorCode, $errorMessage, $connectionTimeout);@@ -193,7 +320,7 @@ class FluxClientstream_set_timeout($stream, (int) ceil($dispatchTimeout));fwrite($stream, implode("\r\n", [- 'POST /v1/coold/dispatch HTTP/1.1',+ "POST {$path} HTTP/1.1",'Host: flux','Accept: application/json','Content-Type: application/json',@@ -206,25 +333,27 @@ class FluxClient$response = stream_get_contents($stream) ?: '';fclose($stream);- $statusCode = $this->statusCode($response);- $responseBody = $this->responseBody($response);- $payload = $responseBody === '' ? null : json_decode($responseBody, true);-- if ($statusCode < 200 || $statusCode >= 300) {- throw new RuntimeException($this->errorMessage($payload, $responseBody) ?? "Flux dispatch returned HTTP {$statusCode}.");- }-- if (! is_array($payload)) {- throw new RuntimeException('Flux dispatch returned an invalid response.');- }+ return $response;+ }- if (($payload['status'] ?? null) === 'error') {- $message = is_string($payload['message'] ?? null) ? $payload['message'] : 'Flux dispatch failed.';+ /**+ * Flux answers a verb the node's coold did not advertise with HTTP 501 and+ * the message "primitive <verb> is not supported by host" (coold repo:+ * flux/src/routing.rs:50-53, flux/src/unix_bridge.rs:227-245). Anything+ * else — including coold-side command failures relayed with their own+ * status code — is a generic dispatch failure.+ *+ * @param array<string, mixed> $command+ */+ private function dispatchException(array $command, int $statusCode, string $message): RuntimeException+ {+ $verb = is_string($command['type'] ?? null) ? $command['type'] : 'unknown';- throw new RuntimeException($message);+ if ($statusCode === 501 || preg_match('/primitive .+ is not supported by host/i', $message) === 1) {+ return new UnsupportedCooldVerb($verb, $message);}- return $payload;+ return new RuntimeException($message);}private function statusCode(string $response): intdiff --git a/app/Support/V5/CanvasResourceSerializer.php b/app/Support/V5/CanvasResourceSerializer.phpnew file mode 100644index 0000000000..3a2ec7b7d1--- /dev/null+++ b/app/Support/V5/CanvasResourceSerializer.php@@ -0,0 +1,87 @@+<?php++namespace App\Support\V5;++use App\Models\V5\Application as V5Application;+use App\Models\V5\Server as V5Server;++/**+ * Single source of truth for the canvas resource payloads served by the+ * dashboard Inertia props and broadcast by V5CanvasResourceUpdated — the two+ * must stay identical for websocket vs. initial-load parity.+ */+class CanvasResourceSerializer+{+ public const CARD_WIDTH = 320;++ public const CARD_HEIGHT = 144;++ public const CARD_GAP = 32;++ /**+ * @return array<string, mixed>+ */+ public function serializeApplication(V5Application $application): array+ {+ $application->loadMissing(['server', 'domains', 'project', 'environment']);+ $server = $application->server;+ $isServerReachable = ! $server instanceof V5Server || $this->isServerReachable($server);++ return [+ 'id' => $application->uuid,+ 'name' => $application->name,+ 'image' => $application->image,+ 'containerName' => $application->container_name,+ 'status' => $application->status,+ 'statusMessage' => $application->status_message,+ 'effectiveStatus' => $isServerReachable ? $application->status : 'unknown',+ 'effectiveStatusMessage' => $isServerReachable+ ? $application->status_message+ : $this->serverStatusMessage($server),+ 'runtimeContainerId' => $application->runtime_container_id,+ 'serverName' => $server?->name,+ 'serverStatus' => $server?->status,+ 'serverStatusMessage' => $server instanceof V5Server ? $this->serverStatusMessage($server) : null,+ 'isServerReachable' => $isServerReachable,+ 'serverIngressEnabled' => (bool) $server?->isIngress(),+ 'meshNamespace' => $application->mesh_namespace,+ 'ingressEnabled' => $application->ingress_enabled,+ 'internalPort' => $application->internal_port,+ 'domains' => $application->domains->pluck('domain')->values()->all(),+ 'meshFqdn' => $application->container_name.'.'.($application->mesh_namespace ?: 'default').'.coolify.internal',+ 'projectUuid' => $application->project?->uuid,+ 'environmentUuid' => $application->environment?->uuid,+ 'canvasX' => $application->canvas_x,+ 'canvasY' => $application->canvas_y,+ ];+ }++ /**+ * @return array<string, mixed>+ */+ public function serializeCaddyIngress(V5Server $server, int $index = 0): array+ {+ $isServerReachable = $this->isServerReachable($server);++ return [+ 'id' => $server->uuid,+ 'name' => $server->name,+ 'host' => $server->host,+ 'type' => $server->ingressType(),+ 'status' => $isServerReachable ? $server->ingressStatus() : 'unreachable',+ 'statusMessage' => $isServerReachable ? null : $this->serverStatusMessage($server),+ 'canvasX' => $server->canvas_x ?? -(self::CARD_WIDTH + self::CARD_GAP),+ 'canvasY' => $server->canvas_y ?? $index * (self::CARD_HEIGHT + self::CARD_GAP),+ ];+ }++ private function isServerReachable(V5Server $server): bool+ {+ return $server->status !== 'unreachable';+ }++ private function serverStatusMessage(?V5Server $server): ?string+ {+ return $server?->last_status_output ?: null;+ }+}diff --git a/app/Support/V5/ClusterSerializer.php b/app/Support/V5/ClusterSerializer.phpnew file mode 100644index 0000000000..4b94fd8ddb--- /dev/null+++ b/app/Support/V5/ClusterSerializer.php@@ -0,0 +1,90 @@+<?php++namespace App\Support\V5;++use App\Models\V5\Cluster as V5Cluster;+use App\Models\V5\Server as V5Server;++/**+ * Single source of truth for the cluster payload served by the Clusters+ * Inertia props and broadcast by V5ClusterUpdated — the two must stay+ * identical for websocket vs. initial-load parity.+ */+class ClusterSerializer+{+ /**+ * @return array<string, mixed>+ */+ public function serialize(V5Cluster $cluster): array+ {+ return [+ 'id' => $cluster->uuid,+ 'name' => $cluster->name,+ 'description' => $cluster->description,+ 'wireguardInterface' => $cluster->wireguard_interface,+ 'wireguardManagementPool' => $cluster->wireguard_management_pool,+ 'wireguardListenPort' => $cluster->wireguard_listen_port,+ 'containerNetworkPool' => $cluster->container_network_pool,+ 'containerNetworkPrefix' => $cluster->container_network_prefix,+ 'namespaces' => $cluster->namespaces ?? V5Cluster::DEFAULT_NAMESPACES,+ 'defaultDenyContainers' => $cluster->default_deny_containers,+ 'cooldVersion' => $cluster->coold_version,+ 'corrosionVersion' => $cluster->corrosion_version,+ 'corrosionGossipPort' => $cluster->corrosion_gossip_port,+ 'corrosionApiPort' => $cluster->corrosion_api_port,+ 'builderEnabled' => $cluster->builder_enabled,+ 'builderCapacity' => $cluster->builder_capacity,+ 'builderCpuQuota' => $cluster->builder_cpu_quota,+ 'builderMemoryMax' => $cluster->builder_memory_max,+ 'builderTimeoutSecs' => $cluster->builder_timeout_secs,+ 'lastCliAction' => $cluster->last_cli_action,+ 'lastCliStatus' => $cluster->last_cli_status,+ 'lastCliSummary' => $cluster->last_cli_summary,+ 'lastCliRanAt' => $cluster->last_cli_ran_at?->toJSON(),+ 'serversCount' => $cluster->servers_count ?? $cluster->servers->count(),+ 'servers' => $cluster->servers->map(fn (V5Server $server) => [+ 'id' => $server->uuid,+ 'name' => $server->name,+ 'host' => $server->host,+ 'status' => $server->status,+ 'capabilities' => $server->capabilities ?? [],+ 'builderEnabled' => $server->builder_enabled,+ 'builderCapacity' => $server->builder_capacity,+ 'builderCpuQuota' => $server->builder_cpu_quota,+ 'ingressEnabled' => $server->isIngress(),+ 'ingressType' => $server->ingress_type,+ 'uuid' => $server->uuid,+ 'nodeAddress' => $server->node_address,+ 'wireguardListenPortOverride' => $server->wireguard_listen_port_override,+ 'wireguardEndpointOverride' => $server->wireguard_endpoint_override,+ 'wireguardManagementIp' => $server->wireguard_management_ip,+ 'wireguardPublicKey' => $server->wireguard_public_key,+ 'containerSubnets' => $server->container_subnets ?? [],+ 'privateKeyName' => $server->privateKey?->name,+ 'lastBootstrappedAt' => $server->last_bootstrapped_at?->toJSON(),+ 'lastBootstrapAction' => $server->last_bootstrap_action,+ 'lastBootstrapStatus' => $server->last_bootstrap_status,+ 'lastBootstrapOutput' => $server->last_bootstrap_output,+ 'lastBootstrapRanAt' => $server->last_bootstrap_ran_at?->toJSON(),+ 'lastStatusOutput' => $server->last_status_output,+ 'lastStatusCheckedAt' => $server->last_status_checked_at?->toJSON(),+ ])->all(),+ ];+ }++ /**+ * Reload servers (with keys) and counts before serializing so the payload+ * always reflects the latest database state.+ *+ * @return array<string, mixed>+ */+ public function serializeFresh(V5Cluster $cluster): array+ {+ $cluster->load(['servers' => fn ($query) => $query+ ->with('privateKey')+ ->orderBy('name')]);+ $cluster->loadCount('servers');++ return $this->serialize($cluster);+ }+}diff --git a/app/Support/V5/ConnectionFirewallSync.php b/app/Support/V5/ConnectionFirewallSync.phpnew file mode 100644index 0000000000..04241db14b--- /dev/null+++ b/app/Support/V5/ConnectionFirewallSync.php@@ -0,0 +1,157 @@+<?php++namespace App\Support\V5;++use App\Exceptions\V5\UnsupportedCooldVerb;+use App\Models\V5\Application as V5Application;+use App\Models\V5\ResourceConnection;+use App\Models\V5\Server as V5Server;+use App\Services\Flux\FluxClient;+use Illuminate\Support\Collection;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Str;++/**+ * Single source of truth for deriving node firewall rules from a resource+ * connection's DB rules and converging them through Flux. Reusable from+ * controllers, jobs, and events alike; deterministic rule ids keep repeated+ * syncs and compensating rollbacks idempotent.+ */+class ConnectionFirewallSync+{+ /**+ * @return Collection<int, array{id: string, hostId: string, rule: array{id: string, namespace: string, src: string, dst: string, proto: string, port: int}}>+ */+ public function rulesFor(ResourceConnection $connection): Collection+ {+ $applicationIds = $connection->rules+ ->flatMap(fn ($rule) => [$rule->source_resource_id, $rule->target_resource_id])+ ->unique()+ ->values();++ $applications = V5Application::query()+ ->whereIn('id', $applicationIds)+ ->with('server')+ ->get()+ ->keyBy('id');++ return $connection->rules+ ->flatMap(function ($rule) use ($applications, $connection): Collection {+ $source = $applications->get($rule->source_resource_id);+ $target = $applications->get($rule->target_resource_id);++ if (! $source instanceof V5Application || ! $target instanceof V5Application) {+ return collect();+ }++ $missingHost = collect([$source, $target])+ ->first(function (V5Application $application): bool {+ $hostId = $application->server?->fluxHostId();++ return ! is_string($hostId) || $hostId === '';+ });++ if ($missingHost instanceof V5Application) {+ throw new \RuntimeException("Application {$missingHost->name} has no reachable server host id, so its firewall rules cannot be synced.");+ }++ $hostIds = collect([$source->server, $target->server])+ ->map(fn (V5Server $server) => $server->fluxHostId())+ ->unique()+ ->values();++ $firewallRule = [+ 'id' => $this->ruleId($connection, $rule),+ 'namespace' => $target->mesh_namespace ?: 'default',+ 'src' => $source->container_name,+ 'dst' => $target->container_name,+ 'proto' => $rule->protocol ?: 'tcp',+ 'port' => (int) $rule->port,+ ];++ return $hostIds->map(fn (string $hostId): array => [+ 'id' => $firewallRule['id'],+ 'hostId' => $hostId,+ 'rule' => $firewallRule,+ ]);+ })+ ->values();+ }++ /**+ * @param Collection<int, array{id: string, hostId: string, rule: array{id: string, namespace: string, src: string, dst: string, proto: string, port: int}}> $oldRules+ * @param Collection<int, array{id: string, hostId: string, rule: array{id: string, namespace: string, src: string, dst: string, proto: string, port: int}}> $newRules+ */+ public function sync(FluxClient $fluxClient, Collection $oldRules, Collection $newRules): void+ {+ $newRuleKeys = $newRules->map(fn (array $rule): string => $this->syncKey($rule))->all();+ $oldRuleKeys = $oldRules->map(fn (array $rule): string => $this->syncKey($rule))->all();++ $oldRules+ ->reject(fn (array $oldRule): bool => in_array($this->syncKey($oldRule), $newRuleKeys, true))+ ->each(fn (array $oldRule): ?string => $this->revokeRuleIfPresent($fluxClient, $oldRule['hostId'], $oldRule['id']));++ $newRules+ ->reject(fn (array $newRule): bool => in_array($this->syncKey($newRule), $oldRuleKeys, true))+ ->each(function (array $newRule) use ($fluxClient): void {+ try {+ $fluxClient->applyFirewallRule($newRule['hostId'], $newRule['rule']);+ } catch (UnsupportedCooldVerb $exception) {+ Log::warning('V5 resource connection firewall rule skipped: coold verb unsupported', [+ 'host_id' => $newRule['hostId'],+ 'rule_id' => $newRule['id'],+ 'verb' => $exception->verb,+ 'message' => $exception->getMessage(),+ ]);+ }+ });+ }++ public function revokeRuleIfPresent(FluxClient $fluxClient, string $hostId, string $ruleId): ?string+ {+ try {+ return $fluxClient->revokeFirewallRule($hostId, $ruleId);+ } catch (UnsupportedCooldVerb $exception) {+ Log::warning('V5 resource connection firewall revoke skipped: coold verb unsupported', [+ 'host_id' => $hostId,+ 'rule_id' => $ruleId,+ 'verb' => $exception->verb,+ 'message' => $exception->getMessage(),+ ]);++ return null;+ } catch (\RuntimeException $exception) {+ if (str_contains(Str::lower($exception->getMessage()), 'not found')) {+ return null;+ }++ throw $exception;+ }+ }++ /**+ * Deterministic node-side rule id derived only from the connection id and+ * the rule's stable attributes — never from the rule row's primary key —+ * so rewritten or restored DB rows resolve to the same firewall rule ids+ * and compensating re-syncs stay idempotent.+ */+ public function ruleId(ResourceConnection $connection, mixed $rule): string+ {+ return implode(':', [+ 'v5-resource-connection',+ $connection->id,+ $rule->source_resource_id,+ $rule->target_resource_id,+ $rule->protocol ?: 'tcp',+ (int) $rule->port,+ ]);+ }++ /**+ * @param array{id: string, hostId: string, rule: array{id: string, namespace: string, src: string, dst: string, proto: string, port: int}} $rule+ */+ private function syncKey(array $rule): string+ {+ return $rule['hostId'].'|'.$rule['id'];+ }+}diff --git a/app/Support/V5/ResourceConnectionSerializer.php b/app/Support/V5/ResourceConnectionSerializer.phpnew file mode 100644index 0000000000..db89a897b7--- /dev/null+++ b/app/Support/V5/ResourceConnectionSerializer.php@@ -0,0 +1,73 @@+<?php++namespace App\Support\V5;++use App\Models\V5\Application as V5Application;+use App\Models\V5\ResourceConnection;+use Illuminate\Support\Collection;++/**+ * Single source of truth for the resource connection payloads served by the+ * dashboard Inertia props and the connection endpoints — the wire format is+ * consumed by resources/js/v5/types.ts and must stay stable.+ */+class ResourceConnectionSerializer+{+ /**+ * @return array<string, mixed>+ */+ public function serialize(ResourceConnection $connection): array+ {+ $applications = $this->applicationsById($connection);+ $resourceOneUuid = $applications->get($connection->resource_one_id)?->uuid;+ $resourceTwoUuid = $applications->get($connection->resource_two_id)?->uuid;+ $applicationsById = $applications;++ return [+ 'id' => $connection->uuid,+ 'applicationIds' => array_values(array_filter([+ $resourceOneUuid,+ $resourceTwoUuid,+ ])),+ 'fromApplicationId' => $resourceOneUuid,+ 'toApplicationId' => $resourceTwoUuid,+ 'portsByDirection' => $connection->rules+ ->groupBy(function ($rule) use ($applicationsById): string {+ $sourceUuid = $applicationsById->get($rule->source_resource_id)?->uuid;+ $targetUuid = $applicationsById->get($rule->target_resource_id)?->uuid;++ return "{$sourceUuid}->{$targetUuid}";+ })+ ->filter(fn (Collection $rules, string $direction): bool => ! str_starts_with($direction, '->') && ! str_ends_with($direction, '->'))+ ->map(fn (Collection $rules) => $rules+ ->sortBy('port')+ ->pluck('port')+ ->map(fn ($port) => (string) $port)+ ->values()+ ->all())+ ->all(),+ ];+ }++ /**+ * @return Collection<string, V5Application>+ */+ public function applicationsByUuid(ResourceConnection $connection): Collection+ {+ return $this->applicationsById($connection)->keyBy('uuid');+ }++ /**+ * @return Collection<int, V5Application>+ */+ public function applicationsById(ResourceConnection $connection): Collection+ {+ return V5Application::query()+ ->whereIn('id', [+ (int) $connection->resource_one_id,+ (int) $connection->resource_two_id,+ ])+ ->get()+ ->keyBy('id');+ }+}diff --git a/app/Support/V5/StatusObservation.php b/app/Support/V5/StatusObservation.phpnew file mode 100644index 0000000000..877435ad1c--- /dev/null+++ b/app/Support/V5/StatusObservation.php@@ -0,0 +1,68 @@+<?php++namespace App\Support\V5;++use App\Enums\V5\ApplicationStatus;+use App\Enums\V5\ContainerState;+use App\Enums\V5\IngressStatus;+use App\Enums\V5\ServerStatus;+use Carbon\CarbonInterface;+use Illuminate\Support\Facades\Log;++/**+ * Shared status-observation watermarking and enum normalization used by every+ * v5 status write path (the flux webhook, the reconcile job, and the manual+ * refresh endpoint) so out-of-order updates are dropped and raw coold states+ * are normalized identically everywhere.+ */+class StatusObservation+{+ /**+ * A write whose observation timestamp is older than the one already+ * persisted is stale (delivered or computed out of order) and must not+ * clobber the newer state.+ *+ * @param array<string, mixed> $logContext+ */+ public static function isStale(?CarbonInterface $observedAt, ?CarbonInterface $currentObservedAt, string $context, array $logContext): bool+ {+ if ($observedAt === null || $currentObservedAt === null || ! $observedAt->lt($currentObservedAt)) {+ return false;+ }++ Log::debug("Dropping stale flux {$context} update.", [+ ...$logContext,+ 'observed_at' => $observedAt->toIso8601String(),+ 'current_status_observed_at' => $currentObservedAt->toIso8601String(),+ ]);++ return true;+ }++ /**+ * Map a raw status string onto the given status enum. Unknown values are+ * never written to the database: they fall back to the enum's Unknown case+ * and are logged. Returns null only when no raw value is supplied.+ *+ * @param class-string<ApplicationStatus|ContainerState|IngressStatus|ServerStatus> $enumClass+ */+ public static function normalize(?string $raw, string $enumClass): ?string+ {+ if ($raw === null || $raw === '') {+ return null;+ }++ $status = $enumClass::tryFrom(strtolower($raw));++ if ($status === null) {+ Log::warning('Received unknown flux resource status; falling back to unknown.', [+ 'raw_status' => $raw,+ 'status_enum' => $enumClass,+ ]);++ return $enumClass::Unknown->value;+ }++ return $status->value;+ }+}diff --git a/config/coold.php b/config/coold.phpindex 06b47083d6..cdd5b082ea 100644--- a/config/coold.php+++ b/config/coold.php@@ -5,4 +5,21 @@ return ['coold_version' => env('COOLIFY_COOLD_VERSION', 'nightly'),'corrosion_version' => env('COOLIFY_CORROSION_VERSION', 'v1.0.0'),'dev_ssh_user' => env('COOLIFY_CLI_SSH_USER', 'coolify'),+ 'flux_url' => env('COOLIFY_COOLD_FLUX_URL', env('COOLIFY_COOLD_VM_FLUX_URL')),+ 'flux_host_jwt_path' => env('COOLIFY_COOLD_HOST_JWT_PATH', '/etc/coolify/host-jwt'),++ /*+ * When false (the default), v5 server hosts/node addresses may not point at+ * private or reserved IP ranges (loopback, link-local, RFC 1918, CGNAT is+ * still allowed as it is the WireGuard mesh space). This blocks a team+ * member from adding a server that targets the Coolify host's internal+ * network and abusing the synchronous SSH connectivity check to probe it.+ *+ * Self-hosters running Coolify on a private LAN can opt back in by setting+ * COOLIFY_ALLOW_PRIVATE_SERVER_IPS=true.+ */+ 'allow_private_server_ips' => filter_var(+ env('COOLIFY_ALLOW_PRIVATE_SERVER_IPS', false),+ FILTER_VALIDATE_BOOLEAN+ ),];diff --git a/config/flux.php b/config/flux.phpindex 955559edde..adf011afe2 100644--- a/config/flux.php+++ b/config/flux.php@@ -7,5 +7,105 @@ return ['health_timeout_seconds' => (float) env('COOLIFY_FLUX_HEALTH_TIMEOUT_SECONDS', 1.0),'connection_timeout_seconds' => (float) env('COOLIFY_FLUX_CONNECTION_TIMEOUT_SECONDS', 1.0),'dispatch_timeout_seconds' => (float) env('COOLIFY_FLUX_DISPATCH_TIMEOUT_SECONDS', 35.0),+ 'bootstrap_host_connection_timeout_seconds' => (int) env('COOLIFY_FLUX_BOOTSTRAP_HOST_CONNECTION_TIMEOUT_SECONDS', 30),++ /*+ |--------------------------------------------------------------------------+ | Host agent (coold) token capabilities+ |--------------------------------------------------------------------------+ |+ | The EXACT set of primitive capability strings coold advertises to flux on+ | connect (coold/coold/src/grpc/client.rs, `primitive_capabilities`). Minting+ | these explicit strings — instead of the `host-agent:default` wildcard+ | profile — means the token no longer relies on flux's+ | `capability_profile_authorizes_all` bypass. flux INTERSECTS the jwt `caps`+ | with coold's advertised set, so as long as this list matches coold's+ | advertised primitives the host retains exactly the same effective power.+ |+ | SAFETY: keep this list byte-for-byte in sync with coold's+ | `primitive_capabilities()`. A string here that coold does not advertise is+ | silently dropped by flux's intersection; a verb coold needs that is missing+ | here means the host loses that ability.+ |+ | `host.jwt.set` authorizes RPC-delivered host-JWT rotation (the token can+ | authorize its own replacement over the live stream; Laravel is the root of+ | trust that holds the signing key).+ */+ 'host_capabilities' => [+ 'images.pull',+ 'images.list',+ 'images.delete',+ 'containers.create',+ 'containers.start',+ 'containers.stop',+ 'containers.restart',+ 'containers.delete',+ 'containers.inspect',+ 'containers.list',+ 'containers.logs',+ 'containers.exec',+ 'containers.healthcheck.run',+ 'ingress.apply',+ 'ingress.stop',+ 'firewall.allow',+ 'firewall.revoke',+ 'firewall.list',+ 'firewall.reconcile',+ 'coold.logs',+ 'corrosion.tables',+ 'host.jwt.set',+ ],++ /*+ | Emergency escape hatch: when set (e.g. to `host-agent:default`), minted+ | host tokens carry ONLY this single capability profile instead of the+ | explicit list above. This re-enables flux's wildcard bypass and is meant+ | purely for rollback without a code change if the explicit list ever drifts+ | from coold's advertised set and breaks the data plane. Leave NULL in+ | production so tokens are explicitly scoped.+ */+ 'host_capability_profile' => env('COOLIFY_FLUX_HOST_CAPABILITY_PROFILE'),++ /*+ | Host JWT lifetime and rotation.+ |+ | `host_token_ttl` is the token `exp` window (default 1h) — the maximum time+ | a leaked/undetected token stays valid if BOTH rotation and revocation fail.+ | Keep this at or below flux's `COOLIFY_FLUX_MAX_TOKEN_LIFETIME_SECS`+ | default (3600), otherwise flux rejects coold streams at connect.+ | `host_token_refresh_threshold` is the remaining-lifetime below which the+ | rotation job re-mints and re-delivers a fresh token (default 30m).+ | Keep the threshold below the TTL.+ */+ 'host_token_ttl' => (int) env('COOLIFY_FLUX_HOST_TOKEN_TTL', 3600),+ 'host_token_refresh_threshold' => (int) env('COOLIFY_FLUX_HOST_TOKEN_REFRESH_THRESHOLD', 1800),++ /*+ | JWT header `kid` minted into host tokens. flux selects the verification key+ | by this id (single default key today; a per-cluster keys directory can map+ | `kid = cluster-<id>` to `<kid>.pub` for per-tenant signing keys later).+ */+ 'jwt_kid' => env('COOLIFY_FLUX_JWT_KID', 'flux-default'),++ /*+ |--------------------------------------------------------------------------+ | Inbound flux -> Laravel API token(s)+ |--------------------------------------------------------------------------+ |+ | flux authenticates to Laravel's internal status-ingest endpoint with a+ | bearer token. `laravel_api_tokens` accepts SEVERAL tokens at once so an+ | operator can rotate with zero downtime:+ | 1. add the new token alongside the old:+ | COOLIFY_FLUX_LARAVEL_API_TOKENS=<old>,<new>+ | then `php artisan config:clear`+ | 2. cut every flux instance over to <new>+ | 3. drop <old> from the list and `config:clear` again+ | Generate tokens with `openssl rand -hex 32`. The single `laravel_api_token`+ | remains as a fallback so existing single-token installs keep working.+ */'laravel_api_token' => env('COOLIFY_FLUX_LARAVEL_API_TOKEN'),+ 'laravel_api_tokens' => array_values(array_filter(array_map(+ 'trim',+ explode(',', (string) env('COOLIFY_FLUX_LARAVEL_API_TOKENS', ''))+ ))),];diff --git a/config/horizon.php b/config/horizon.phpindex 0423f15494..71f9a45f86 100644--- a/config/horizon.php+++ b/config/horizon.php@@ -192,6 +192,24 @@ return ['sleep' => 3,'timeout' => env('HORIZON_TIMEOUT', 36000),],++ // Dedicated low-priority pool for the v5 reconcile + host-token rotation+ // jobs (queue `v5-reconcile`, set via onQueue()). Isolated from the+ // user-facing high/default deploy pool so a starved rotation cannot let+ // host tokens drift to expiry, and so the 5-minute fleet fan-out never+ // blocks deploys.+ 'v5reconcile' => [+ 'connection' => 'redis',+ 'balance' => env('HORIZON_V5_RECONCILE_BALANCE', 'false'),+ 'queue' => 'v5-reconcile',+ 'maxTime' => env('HORIZON_V5_RECONCILE_MAX_TIME', 0),+ 'maxJobs' => 200,+ 'memory' => 128,+ 'tries' => 1,+ 'nice' => 10,+ 'sleep' => 3,+ 'timeout' => env('HORIZON_V5_RECONCILE_TIMEOUT', 300),+ ],],'environments' => [@@ -203,7 +221,11 @@ return ['balanceMaxShift' => env('HORIZON_BALANCE_MAX_SHIFT', 1),'balanceCooldown' => env('HORIZON_BALANCE_COOLDOWN', 1),],-+ 'v5reconcile' => [+ 'autoScalingStrategy' => 'size',+ 'minProcesses' => env('HORIZON_V5_RECONCILE_MIN_PROCESSES', 1),+ 'maxProcesses' => env('HORIZON_V5_RECONCILE_MAX_PROCESSES', 2),+ ],],'local' => ['s6' => [@@ -213,6 +235,11 @@ return ['balanceMaxShift' => env('HORIZON_BALANCE_MAX_SHIFT', 1),'balanceCooldown' => env('HORIZON_BALANCE_COOLDOWN', 1),],+ 'v5reconcile' => [+ 'autoScalingStrategy' => 'size',+ 'minProcesses' => env('HORIZON_V5_RECONCILE_MIN_PROCESSES', 1),+ 'maxProcesses' => env('HORIZON_V5_RECONCILE_MAX_PROCESSES', 1),+ ],],],];diff --git a/database/migrations/2026_07_05_215736_v5_add_status_lookup_indexes.php b/database/migrations/2026_07_05_215736_v5_add_status_lookup_indexes.phpnew file mode 100644index 0000000000..09c8bd0936--- /dev/null+++ b/database/migrations/2026_07_05_215736_v5_add_status_lookup_indexes.php@@ -0,0 +1,48 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\Schema;++return new class extends Migration+{+ /**+ * Run the migrations.+ */+ public function up(): void+ {+ Schema::table('v5_servers', function (Blueprint $table) {+ $table->index('wireguard_management_ip');+ $table->index('node_address');+ $table->index('host');+ });++ Schema::table('v5_applications', function (Blueprint $table) {+ $table->index('runtime_container_id');+ });++ Schema::table('v5_container_statuses', function (Blueprint $table) {+ $table->index('last_seen_at');+ });+ }++ /**+ * Reverse the migrations.+ */+ public function down(): void+ {+ Schema::table('v5_servers', function (Blueprint $table) {+ $table->dropIndex(['wireguard_management_ip']);+ $table->dropIndex(['node_address']);+ $table->dropIndex(['host']);+ });++ Schema::table('v5_applications', function (Blueprint $table) {+ $table->dropIndex(['runtime_container_id']);+ });++ Schema::table('v5_container_statuses', function (Blueprint $table) {+ $table->dropIndex(['last_seen_at']);+ });+ }+};diff --git a/database/migrations/2026_07_05_215736_v5_make_servers_uuid_not_null.php b/database/migrations/2026_07_05_215736_v5_make_servers_uuid_not_null.phpnew file mode 100644index 0000000000..fcd8a7afe8--- /dev/null+++ b/database/migrations/2026_07_05_215736_v5_make_servers_uuid_not_null.php@@ -0,0 +1,39 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Schema;+use Illuminate\Support\Str;++return new class extends Migration+{+ /**+ * Run the migrations.+ */+ public function up(): void+ {+ DB::table('v5_servers')+ ->whereNull('uuid')+ ->pluck('id')+ ->each(function (int $id): void {+ DB::table('v5_servers')+ ->where('id', $id)+ ->update(['uuid' => Str::lower(Str::random(24))]);+ });++ Schema::table('v5_servers', function (Blueprint $table) {+ $table->string('uuid')->nullable(false)->change();+ });+ }++ /**+ * Reverse the migrations.+ */+ public function down(): void+ {+ Schema::table('v5_servers', function (Blueprint $table) {+ $table->string('uuid')->nullable()->change();+ });+ }+};diff --git a/database/migrations/2026_07_05_222616_v5_add_status_observed_at_columns.php b/database/migrations/2026_07_05_222616_v5_add_status_observed_at_columns.phpnew file mode 100644index 0000000000..2189edbb85--- /dev/null+++ b/database/migrations/2026_07_05_222616_v5_add_status_observed_at_columns.php@@ -0,0 +1,44 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\Schema;++return new class extends Migration+{+ /**+ * Run the migrations.+ */+ public function up(): void+ {+ Schema::table('v5_servers', function (Blueprint $table) {+ $table->timestamp('status_observed_at')->nullable()->after('status');+ });++ Schema::table('v5_applications', function (Blueprint $table) {+ $table->timestamp('status_observed_at')->nullable()->after('status_message');+ });++ Schema::table('v5_container_statuses', function (Blueprint $table) {+ $table->timestamp('status_observed_at')->nullable()->after('status_message');+ });+ }++ /**+ * Reverse the migrations.+ */+ public function down(): void+ {+ Schema::table('v5_servers', function (Blueprint $table) {+ $table->dropColumn('status_observed_at');+ });++ Schema::table('v5_applications', function (Blueprint $table) {+ $table->dropColumn('status_observed_at');+ });++ Schema::table('v5_container_statuses', function (Blueprint $table) {+ $table->dropColumn('status_observed_at');+ });+ }+};diff --git a/database/migrations/2026_07_05_222940_v5_add_coold_version_to_servers_table.php b/database/migrations/2026_07_05_222940_v5_add_coold_version_to_servers_table.phpnew file mode 100644index 0000000000..1d42ef4ab6--- /dev/null+++ b/database/migrations/2026_07_05_222940_v5_add_coold_version_to_servers_table.php@@ -0,0 +1,28 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\Schema;++return new class extends Migration+{+ /**+ * Run the migrations.+ */+ public function up(): void+ {+ Schema::table('v5_servers', function (Blueprint $table) {+ $table->string('coold_version')->nullable()->after('wireguard_public_key');+ });+ }++ /**+ * Reverse the migrations.+ */+ public function down(): void+ {+ Schema::table('v5_servers', function (Blueprint $table) {+ $table->dropColumn('coold_version');+ });+ }+};diff --git a/database/migrations/2026_07_06_090000_v5_convert_resource_connection_morphs_to_aliases.php b/database/migrations/2026_07_06_090000_v5_convert_resource_connection_morphs_to_aliases.phpnew file mode 100644index 0000000000..e81623fe15--- /dev/null+++ b/database/migrations/2026_07_06_090000_v5_convert_resource_connection_morphs_to_aliases.php@@ -0,0 +1,74 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Schema;++/**+ * Rewrites v5 polymorphic rows that stored the Application FQCN (written+ * before the 'v5.application' morph alias existed) so a future class rename+ * cannot orphan them. New rows pick up the alias via getMorphClass().+ */+return new class extends Migration+{+ private const FQCN = 'App\Models\V5\Application';++ private const ALIAS = 'v5.application';++ public function up(): void+ {+ $this->rewriteMorphTypes(self::FQCN, self::ALIAS);+ $this->rewritePairKeys(self::FQCN, self::ALIAS);+ }++ public function down(): void+ {+ $this->rewriteMorphTypes(self::ALIAS, self::FQCN);+ $this->rewritePairKeys(self::ALIAS, self::FQCN);+ }++ private function rewriteMorphTypes(string $from, string $to): void+ {+ if (Schema::hasTable('v5_resource_connections')) {+ foreach (['resource_one_type', 'resource_two_type'] as $column) {+ DB::table('v5_resource_connections')+ ->where($column, $from)+ ->update([$column => $to]);+ }+ }++ if (Schema::hasTable('v5_resource_connection_rules')) {+ foreach (['source_resource_type', 'target_resource_type'] as $column) {+ DB::table('v5_resource_connection_rules')+ ->where($column, $from)+ ->update([$column => $to]);+ }+ }+ }++ private function rewritePairKeys(string $from, string $to): void+ {+ if (! Schema::hasTable('v5_resource_connections')) {+ return;+ }++ // Backslash escaping in LIKE patterns differs between Postgres and+ // SQLite, so match the FQCN in PHP instead of in SQL.+ DB::table('v5_resource_connections')+ ->select(['id', 'resource_pair_key'])+ ->orderBy('id')+ ->chunkById(100, function ($connections) use ($from, $to): void {+ foreach ($connections as $connection) {+ if (! str_contains((string) $connection->resource_pair_key, $from)) {+ continue;+ }++ DB::table('v5_resource_connections')+ ->where('id', $connection->id)+ ->update([+ 'resource_pair_key' => str_replace($from, $to, $connection->resource_pair_key),+ ]);+ }+ });+ }+};diff --git a/database/migrations/2026_07_06_090100_v5_convert_server_capabilities_to_booleans.php b/database/migrations/2026_07_06_090100_v5_convert_server_capabilities_to_booleans.phpnew file mode 100644index 0000000000..80ab529f49--- /dev/null+++ b/database/migrations/2026_07_06_090100_v5_convert_server_capabilities_to_booleans.php@@ -0,0 +1,74 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Schema;++/**+ * Replaces the unindexable v5_servers.capabilities JSON array of magic strings+ * with indexed has_coold / is_ingress booleans. The Server model keeps+ * exposing a computed `capabilities` array so serialized payloads stay+ * identical.+ */+return new class extends Migration+{+ public function up(): void+ {+ Schema::table('v5_servers', function (Blueprint $table) {+ $table->boolean('has_coold')->default(false)->index();+ $table->boolean('is_ingress')->default(false)->index();+ });++ DB::table('v5_servers')+ ->select(['id', 'capabilities'])+ ->orderBy('id')+ ->chunkById(100, function ($servers): void {+ foreach ($servers as $server) {+ $capabilities = json_decode($server->capabilities ?? '[]', true);++ if (! is_array($capabilities) || $capabilities === []) {+ continue;+ }++ DB::table('v5_servers')->where('id', $server->id)->update([+ 'has_coold' => in_array('coold', $capabilities, true),+ 'is_ingress' => in_array('ingress', $capabilities, true),+ ]);+ }+ });++ Schema::table('v5_servers', function (Blueprint $table) {+ $table->dropColumn('capabilities');+ });+ }++ public function down(): void+ {+ Schema::table('v5_servers', function (Blueprint $table) {+ $table->json('capabilities')->nullable();+ });++ DB::table('v5_servers')+ ->select(['id', 'has_coold', 'is_ingress'])+ ->orderBy('id')+ ->chunkById(100, function ($servers): void {+ foreach ($servers as $server) {+ $capabilities = array_values(array_filter([+ $server->has_coold ? 'coold' : null,+ $server->is_ingress ? 'ingress' : null,+ ]));++ DB::table('v5_servers')->where('id', $server->id)->update([+ 'capabilities' => json_encode($capabilities),+ ]);+ }+ });++ Schema::table('v5_servers', function (Blueprint $table) {+ $table->dropIndex(['has_coold']);+ $table->dropIndex(['is_ingress']);+ $table->dropColumn(['has_coold', 'is_ingress']);+ });+ }+};diff --git a/database/migrations/2026_07_06_100000_v5_add_agent_token_jti_to_servers_table.php b/database/migrations/2026_07_06_100000_v5_add_agent_token_jti_to_servers_table.phpnew file mode 100644index 0000000000..edfaa4f965--- /dev/null+++ b/database/migrations/2026_07_06_100000_v5_add_agent_token_jti_to_servers_table.php@@ -0,0 +1,22 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\Schema;++return new class extends Migration+{+ public function up(): void+ {+ Schema::table('v5_servers', function (Blueprint $table) {+ $table->string('agent_token_jti')->nullable()->after('coold_version');+ });+ }++ public function down(): void+ {+ Schema::table('v5_servers', function (Blueprint $table) {+ $table->dropColumn('agent_token_jti');+ });+ }+};diff --git a/database/migrations/2026_07_06_100100_v5_create_revoked_agent_tokens_table.php b/database/migrations/2026_07_06_100100_v5_create_revoked_agent_tokens_table.phpnew file mode 100644index 0000000000..7136ee4ac3--- /dev/null+++ b/database/migrations/2026_07_06_100100_v5_create_revoked_agent_tokens_table.php@@ -0,0 +1,25 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\Schema;++return new class extends Migration+{+ public function up(): void+ {+ Schema::create('v5_revoked_agent_tokens', function (Blueprint $table) {+ $table->id();+ $table->string('jti')->unique();+ $table->foreignId('server_id')->nullable();+ $table->timestamp('revoked_at')->nullable();+ $table->timestamp('expires_at')->nullable()->index();+ $table->timestamps();+ });+ }++ public function down(): void+ {+ Schema::dropIfExists('v5_revoked_agent_tokens');+ }+};diff --git a/database/migrations/2026_07_06_110000_v5_add_agent_token_expires_at_to_servers_table.php b/database/migrations/2026_07_06_110000_v5_add_agent_token_expires_at_to_servers_table.phpnew file mode 100644index 0000000000..08cfe07fa7--- /dev/null+++ b/database/migrations/2026_07_06_110000_v5_add_agent_token_expires_at_to_servers_table.php@@ -0,0 +1,22 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\Schema;++return new class extends Migration+{+ public function up(): void+ {+ Schema::table('v5_servers', function (Blueprint $table) {+ $table->timestamp('agent_token_expires_at')->nullable()->after('agent_token_jti');+ });+ }++ public function down(): void+ {+ Schema::table('v5_servers', function (Blueprint $table) {+ $table->dropColumn('agent_token_expires_at');+ });+ }+};diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 555c8660c1..f4753465f0 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -22,6 +22,7 @@ services:COOLIFY_CONTAINER_ROLE: "${COOLIFY_CONTAINER_ROLE:-all}"COOLIFY_COOLD_VERSION: "${COOLIFY_COOLD_VERSION:-nightly}"COOLIFY_FLUX_VERSION: "${COOLIFY_FLUX_VERSION:-nightly}"+ COOLIFY_FLUX_REQUIRE_HOST_BINDING: "${COOLIFY_FLUX_REQUIRE_HOST_BINDING:-0}"COOLIFY_CLI_VERSION: "${COOLIFY_CLI_VERSION:-nightly}"COOLIFY_CLI_SSH_USER: "${COOLIFY_CLI_SSH_USER:-}"COOLIFY_CORROSION_VERSION: "${COOLIFY_CORROSION_VERSION:-v1.0.0}"diff --git a/docker/development/etc/s6-overlay/s6-rc.d/flux/run b/docker/development/etc/s6-overlay/s6-rc.d/flux/runindex 9d8598cf95..8760137508 100755--- a/docker/development/etc/s6-overlay/s6-rc.d/flux/run+++ b/docker/development/etc/s6-overlay/s6-rc.d/flux/run@@ -20,6 +20,7 @@ export COOLIFY_FLUX_UNIX_SOCKET_PATH="${COOLIFY_FLUX_UNIX_SOCKET_PATH:-/run/coolexport COOLIFY_FLUX_JWT_PRIVATE_KEY_PATH="${COOLIFY_FLUX_JWT_PRIVATE_KEY_PATH:-/var/www/html/storage/app/flux/jwt.priv}"export COOLIFY_FLUX_JWT_PUBLIC_KEY_PATH="${COOLIFY_FLUX_JWT_PUBLIC_KEY_PATH:-/var/www/html/storage/app/flux/jwt.pub}"export COOLIFY_FLUX_ALLOW_PUBLIC_BIND="${COOLIFY_FLUX_ALLOW_PUBLIC_BIND:-1}"+export COOLIFY_FLUX_REQUIRE_HOST_BINDING="${COOLIFY_FLUX_REQUIRE_HOST_BINDING:-0}"export COOLIFY_FLUX_LARAVEL_API_URL="${COOLIFY_FLUX_LARAVEL_API_URL:-http://127.0.0.1:8080}"if [ -z "${COOLIFY_FLUX_LARAVEL_API_TOKEN:-}" ] && [ -f .env ]; thenCOOLIFY_FLUX_LARAVEL_API_TOKEN="$(grep -E '^COOLIFY_FLUX_LARAVEL_API_TOKEN=' .env 2>/dev/null | tail -n1 | cut -d= -f2- | sed "s/^['\"]//; s/['\"]$//")"diff --git a/package-lock.json b/package-lock.jsonindex 3603826692..6a3fc221ab 100644--- a/package-lock.json+++ b/package-lock.json@@ -81,7 +81,6 @@"integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@babel/code-frame": "^7.29.7","@babel/generator": "^7.29.7",@@ -788,12 +787,36 @@"@noble/ciphers": "^1.0.0"}},+ "node_modules/@emnapi/core": {+ "version": "1.11.2",+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.2.tgz",+ "integrity": "sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA==",+ "license": "MIT",+ "optional": true,+ "peer": true,+ "dependencies": {+ "@emnapi/wasi-threads": "1.2.2",+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@emnapi/runtime": {+ "version": "1.11.2",+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.2.tgz",+ "integrity": "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==",+ "license": "MIT",+ "optional": true,+ "peer": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },"node_modules/@emnapi/wasi-threads": {"version": "1.2.2","resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz","integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==","license": "MIT","optional": true,+ "peer": true,"dependencies": {"tslib": "^2.4.0"}@@ -1017,7 +1040,6 @@"integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": "^14.21.3 || >=16"},@@ -1852,7 +1874,6 @@"integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==","devOptional": true,"license": "MIT",- "peer": true,"dependencies": {"csstype": "^3.2.2"}@@ -1908,8 +1929,7 @@"version": "5.5.0","resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-5.5.0.tgz","integrity": "sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==",- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/accepts": {"version": "2.0.0",@@ -2128,7 +2148,6 @@}],"license": "MIT",- "peer": true,"dependencies": {"baseline-browser-mapping": "^2.10.12","caniuse-lite": "^1.0.30001782",@@ -2949,7 +2968,6 @@"integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"accepts": "^2.0.0","body-parser": "^2.2.1",@@ -3399,7 +3417,6 @@"integrity": "sha512-2NFaIyNVgJmBs/ecmtGzlmluTFs5cHEWGTdu0t1HBwYzoGXOL5nUQBRMXsXWla5i4KkG//QMzVP88m1+I3fdAQ==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": ">=16.9.0"}@@ -5056,7 +5073,6 @@"resolved": "https://registry.npmjs.org/react/-/react-19.2.7.tgz","integrity": "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==","license": "MIT",- "peer": true,"engines": {"node": ">=0.10.0"}@@ -5066,7 +5082,6 @@"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.7.tgz","integrity": "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ==","license": "MIT",- "peer": true,"dependencies": {"scheduler": "^0.27.0"},@@ -5732,8 +5747,7 @@"version": "4.1.18","resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.18.tgz","integrity": "sha512-4+Z+0yiYyEtUVCScyfHCxOYP06L5Ne+JiHhY2IjR2KWMIWhJOYZKLSGZaP5HkZ8+bY0cxfzwDE5uOmzFXyIwxw==",- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/tapable": {"version": "2.3.0",@@ -5876,7 +5890,6 @@"integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==","dev": true,"license": "Apache-2.0",- "peer": true,"bin": {"tsc": "bin/tsc","tsserver": "bin/tsserver"@@ -5999,7 +6012,6 @@"resolved": "https://registry.npmjs.org/vite/-/vite-8.0.16.tgz","integrity": "sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==","license": "MIT",- "peer": true,"dependencies": {"lightningcss": "^1.32.0","picomatch": "^4.0.4",@@ -6451,7 +6463,6 @@"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==","dev": true,"license": "MIT",- "peer": true,"funding": {"url": "https://github.com/sponsors/colinhacks"}diff --git a/phpunit.xml b/phpunit.xmlindex 5d55acf750..a516aa4ace 100644--- a/phpunit.xml+++ b/phpunit.xml@@ -23,6 +23,9 @@<env name="SESSION_DRIVER" value="array" force="true"/><env name="TELESCOPE_ENABLED" value="false"/><env name="NIGHTWATCH_ENABLED" value="false"/>+ <!-- The v5 bootstrap endpoint refuses to queue without a Flux URL; tests+ that exercise the unconfigured path blank it via Config::set. -->+ <env name="COOLIFY_COOLD_FLUX_URL" value="http://flux.testing:6443" force="true"/></php><source><include>diff --git a/resources/js/v5/Pages/Clusters.tsx b/resources/js/v5/Pages/Clusters.tsxindex 5f87bd3077..7e59893368 100644--- a/resources/js/v5/Pages/Clusters.tsx+++ b/resources/js/v5/Pages/Clusters.tsx@@ -4,6 +4,7 @@ import { useEffect, useMemo, useState } from 'react';import type { FormEvent } from 'react';import { AppNavbar } from '@/components/app-navbar';+import { CanvasNotice } from '@/components/canvas/canvas-notice';import { Button } from '@/components/ui/button';import {DropdownMenu,@@ -25,8 +26,9 @@ import {DialogTitle,} from '@/components/ui/dialog';import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';-import { csrfToken } from '@/lib/csrf';+import { apiRequest } from '@/lib/api';import { usePendingIds } from '@/lib/use-pending-ids';+import { useTeamChannel } from '@/lib/use-team-channel';import type { V5Cluster, V5DashboardProps, V5Server } from '@/types';type ClusterFormErrors = {@@ -90,11 +92,13 @@ type DeleteServerResponse = {type CooldLogsResponse = {output: string;fetchedAt: string;+ source: 'flux' | 'ssh';};type CorrosionTablesResponse = {output: string;fetchedAt: string;+ source: 'flux' | 'ssh';};type FirewallRule = {@@ -127,16 +131,28 @@ type BootstrapServerResponse = {message?: string;};-type ServerSshCheck = {- status: string;- output: string;- checkedAt: string;+type ServerConnectionNotice = {+ message: string;+ description: string;+ variant: 'danger' | 'success';};type V5ClusterUpdatedEvent = {cluster: V5Cluster | null;};+type ParsedBootstrapLogSummary = {+ label: string;+ value: string;+ tone: 'success' | 'muted';+};++type ParsedBootstrapLogs = {+ summary: ParsedBootstrapLogSummary[];+ visibleOutput: string;+ rawOutput: string;+};+function formatCorrosionCell(value: unknown): string {if (value === null || value === undefined) {return 'null';@@ -163,6 +179,147 @@ function parseCorrosionTables(output: string): CorrosionTableDump | null {}}+function jsonValueToString(value: unknown): string {+ if (value === null || value === undefined || value === '') {+ return 'n/a';+ }++ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {+ return String(value);+ }++ return JSON.stringify(value);+}++function initialJsonEnd(output: string): number | null {+ const trimmedStart = output.search(/\S/);++ if (trimmedStart === -1 || output[trimmedStart] !== '{') {+ return null;+ }++ let depth = 0;+ let inString = false;+ let isEscaped = false;++ for (let index = trimmedStart; index < output.length; index += 1) {+ const character = output[index];++ if (isEscaped) {+ isEscaped = false;+ continue;+ }++ if (character === '\\') {+ isEscaped = inString;+ continue;+ }++ if (character === '"') {+ inString = !inString;+ continue;+ }++ if (inString) {+ continue;+ }++ if (character === '{') {+ depth += 1;+ }++ if (character === '}') {+ depth -= 1;+ }++ if (depth === 0) {+ return index + 1;+ }+ }++ return null;+}++function hideRawBootstrapPlan(output: string): string {+ const visibleLines: string[] = [];+ let isSkippingPlan = false;++ output.split('\n').forEach((line) => {+ if (line.trim() === 'Plan:') {+ isSkippingPlan = true;++ return;+ }++ if (isSkippingPlan) {+ const trimmedLine = line.trim();++ if (trimmedLine === '' || trimmedLine.startsWith('[') || line.startsWith(' ')) {+ return;+ }++ isSkippingPlan = false;+ }++ visibleLines.push(line);+ });++ return visibleLines.join('\n').trim();+}++function parseBootstrapOutput(output: string | null): ParsedBootstrapLogs {+ const rawOutput = output?.trim() || 'No install logs captured yet.';+ const jsonEnd = initialJsonEnd(rawOutput);++ if (jsonEnd === null) {+ return {+ summary: [],+ visibleOutput: rawOutput,+ rawOutput,+ };+ }++ try {+ const parsed = JSON.parse(rawOutput.slice(0, jsonEnd)) as {+ results?: Array<{+ action?: { action?: unknown; host?: unknown };+ status?: unknown;+ detail?: unknown;+ }>;+ verified?: Array<Record<string, unknown>>;+ };+ const summary = [+ ...(parsed.results ?? []).map((result) => ({+ label: jsonValueToString(result.action?.action ?? result.action?.host ?? 'Action'),+ value: `${jsonValueToString(result.status)}${result.detail ? ` · ${jsonValueToString(result.detail)}` : ''}`,+ tone: result.status === 'ok' ? ('success' as const) : ('muted' as const),+ })),+ ...(parsed.verified ?? []).map((node) => ({+ label: `Verified ${jsonValueToString(node.host)}`,+ value: [+ `status ${jsonValueToString(node.status)}`,+ `wg ${jsonValueToString(node.wireguard_ip)}`,+ `peers ${jsonValueToString(node.peer_count)}`,+ ].join(' · '),+ tone: node.status === 'ok' ? ('success' as const) : ('muted' as const),+ })),+ ];+ const remainingOutput = rawOutput.slice(jsonEnd).trim();++ return {+ summary,+ visibleOutput: hideRawBootstrapPlan(remainingOutput),+ rawOutput,+ };+ } catch {+ return {+ summary: [],+ visibleOutput: rawOutput,+ rawOutput,+ };+ }+}+function statusLabel(status: string): string {return status.split(/[-_\s]+/)@@ -187,24 +344,6 @@ function statusBadgeClass(status: string): string {return 'border-border bg-muted/40 text-muted-foreground';}-type EchoChannel = {- listen: (event: string, callback: (payload: unknown) => void) => EchoChannel;- subscribed?: (callback: () => void) => EchoChannel;- error?: (callback: (error: unknown) => void) => EchoChannel;-};--type EchoClient = {- private: (channel: string) => EchoChannel;- leave?: (channel: string) => void;- leaveChannel?: (channel: string) => void;-};--declare global {- interface Window {- Echo?: EchoClient;- }-}-const clusterDefaults = {wireguardInterface: 'wg0',wireguardManagementPool: '100.64.0.0/16',@@ -242,6 +381,18 @@ function formatDate(value: string | null): string {}).format(new Date(value));}+function diagnosticsSourceLabel(source: 'flux' | 'ssh' | null): string {+ if (source === 'ssh') {+ return 'SSH';+ }++ if (source === 'flux') {+ return 'Flux';+ }++ return 'Unknown';+}+export default function Clusters({flux,currentTeam = null,@@ -297,8 +448,9 @@ export default function Clusters({const [isServerSubmitting, setIsServerSubmitting] = useState(false);const [isServerUpdateSubmitting, setIsServerUpdateSubmitting] = useState(false);const checkingServers = usePendingIds<string>();- const [sshChecks, setSshChecks] = useState<Record<string, ServerSshCheck>>({});- const [visibleBootstrapLogs, setVisibleBootstrapLogs] = useState<Record<string, boolean>>({});+ const [serverConnectionNotice, setServerConnectionNotice] = useState<ServerConnectionNotice | null>(null);+ const [isBootstrapLogsDialogOpen, setIsBootstrapLogsDialogOpen] = useState(false);+ const [bootstrapLogsServerId, setBootstrapLogsServerId] = useState<string | null>(null);const bootstrappingServers = usePendingIds<string>();const [bootstrapServerError, setBootstrapServerError] = useState<string | null>(null);const deletingServers = usePendingIds<string>();@@ -314,12 +466,14 @@ export default function Clusters({const [cooldLogsServer, setCooldLogsServer] = useState<V5Server | null>(null);const [cooldLogsOutput, setCooldLogsOutput] = useState('');const [cooldLogsFetchedAt, setCooldLogsFetchedAt] = useState<string | null>(null);+ const [cooldLogsSource, setCooldLogsSource] = useState<'flux' | 'ssh' | null>(null);const [cooldLogsError, setCooldLogsError] = useState<string | null>(null);const [isLoadingCooldLogs, setIsLoadingCooldLogs] = useState(false);const [isCorrosionTablesDialogOpen, setIsCorrosionTablesDialogOpen] = useState(false);const [corrosionTablesServer, setCorrosionTablesServer] = useState<V5Server | null>(null);const [corrosionTablesOutput, setCorrosionTablesOutput] = useState('');const [corrosionTablesFetchedAt, setCorrosionTablesFetchedAt] = useState<string | null>(null);+ const [corrosionTablesSource, setCorrosionTablesSource] = useState<'flux' | 'ssh' | null>(null);const [corrosionTablesError, setCorrosionTablesError] = useState<string | null>(null);const [isLoadingCorrosionTables, setIsLoadingCorrosionTables] = useState(false);const [isFirewallRulesDialogOpen, setIsFirewallRulesDialogOpen] = useState(false);@@ -340,60 +494,23 @@ export default function Clusters({const initializedServers = selectedCluster?.servers.filter((server) => server.lastBootstrappedAt !== null) ?? [];const hasBootstrapInProgress =selectedCluster?.servers.some((server) => ['queued', 'running'].includes(server.lastBootstrapStatus ?? '')) ?? false;+ const bootstrapLogsServer = useMemo(+ () => clusterList.flatMap((cluster) => cluster.servers).find((server) => server.id === bootstrapLogsServerId) ?? null,+ [bootstrapLogsServerId, clusterList],+ );+ const parsedBootstrapLogs = parseBootstrapOutput(bootstrapLogsServer?.lastBootstrapOutput ?? null);- useEffect(() => {- if (!currentTeam) {+ useTeamChannel(currentTeam?.id ?? null, '.v5.cluster.updated', (payload) => {+ const event = payload as V5ClusterUpdatedEvent;++ if (!event.cluster) {return;}- let isCancelled = false;- let attempts = 0;- const channelName = `team.${currentTeam.id}`;-- const interval = window.setInterval(() => {- attempts += 1;-- if (!window.Echo) {- if (attempts === 1) {- console.debug('Waiting for window.Echo before subscribing to cluster updates');- }-- if (attempts >= 20) {- window.clearInterval(interval);- }-- return;- }-- window.clearInterval(interval);-- if (isCancelled) {- return;- }-- const channel = window.Echo.private(channelName);-- channel.subscribed?.(() => console.debug(`Subscribed to private-${channelName} for cluster updates`));- channel.error?.((error) => console.error(`Subscription error on private-${channelName}`, error));- channel.listen('.v5.cluster.updated', (payload) => {- const event = payload as V5ClusterUpdatedEvent;-- if (!event.cluster) {- return;- }-- setClusterList((currentClusters) =>- currentClusters.map((cluster) => (cluster.id === event.cluster?.id ? event.cluster : cluster)),- );- });- }, 500);-- return () => {- isCancelled = true;- window.clearInterval(interval);- window.Echo?.leave?.(channelName) ?? window.Echo?.leaveChannel?.(`private-${channelName}`);- };- }, [currentTeam]);+ setClusterList((currentClusters) =>+ currentClusters.map((cluster) => (cluster.id === event.cluster?.id ? event.cluster : cluster)),+ );+ });useEffect(() => {if (!selectedCluster || !hasBootstrapInProgress) {@@ -407,15 +524,9 @@ export default function Clusters({return;}- const response = await fetch(`/v5/clusters/${selectedCluster.id}`, {- method: 'GET',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- },- });+ const response = await apiRequest(`/v5/clusters/${selectedCluster.id}`, { method: 'GET' }).catch(() => null);- if (!response.ok || isCancelled) {+ if (!response?.ok || isCancelled) {return;}@@ -441,15 +552,9 @@ export default function Clusters({setIsSubmitting(true);setErrors({});- const response = await fetch('/v5/clusters', {+ const response = await apiRequest('/v5/clusters', {method: 'POST',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'Content-Type': 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },- body: JSON.stringify({+ body: {name,description: description.trim() === '' ? null : description,wireguard_interface: wireguardInterface,@@ -471,10 +576,10 @@ export default function Clusters({builder_cpu_quota: builderCpuQuota,builder_memory_max: builderMemoryMax,builder_timeout_secs: Number(builderTimeoutSecs),- }),- });+ },+ }).catch(() => null);- if (response.status === 422) {+ if (response?.status === 422) {const payload = (await response.json()) as {errors?: ClusterFormErrors;};@@ -484,7 +589,7 @@ export default function Clusters({return;}- if (!response.ok) {+ if (!response?.ok) {setErrors({name: ['Unable to create this cluster. Please try again.'],});@@ -517,15 +622,9 @@ export default function Clusters({setIsServerSubmitting(true);setServerErrors({});- const response = await fetch(`/v5/clusters/${selectedCluster.id}/servers`, {+ const response = await apiRequest(`/v5/clusters/${selectedCluster.id}/servers`, {method: 'POST',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'Content-Type': 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },- body: JSON.stringify({+ body: {name: serverName,host: serverHost,ssh_user: serverSshUser,@@ -540,10 +639,10 @@ export default function Clusters({wireguard_listen_port_override:wireguardListenPortOverride.trim() === '' ? null : Number(wireguardListenPortOverride),wireguard_endpoint_override: wireguardEndpointOverride.trim() === '' ? null : wireguardEndpointOverride,- }),- });+ },+ }).catch(() => null);- if (response.status === 422) {+ if (response?.status === 422) {const payload = (await response.json()) as {errors?: ServerFormErrors;};@@ -553,7 +652,7 @@ export default function Clusters({return;}- if (!response.ok) {+ if (!response?.ok) {setServerErrors({name: ['Unable to add this server. Please try again.'],});@@ -582,24 +681,18 @@ export default function Clusters({setIsServerUpdateSubmitting(true);setEditServerErrors({});- const response = await fetch(`/v5/clusters/${selectedCluster.id}/servers/${editingServer.id}`, {+ const response = await apiRequest(`/v5/clusters/${selectedCluster.id}/servers/${editingServer.id}`, {method: 'PATCH',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'Content-Type': 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },- body: JSON.stringify({+ body: {builder_enabled: editServerBuilderEnabled,ingress_enabled: editServerIngressEnabled,ingress_type: editServerIngressEnabled ? editServerIngressType : null,builder_capacity: Number(editServerBuilderCapacity),builder_cpu_quota: editServerBuilderCpuQuota,- }),- });+ },+ }).catch(() => null);- if (response.status === 422) {+ if (response?.status === 422) {const payload = (await response.json()) as {errors?: ServerFormErrors;};@@ -609,8 +702,8 @@ export default function Clusters({return;}- if (!response.ok) {- const payload = (await response.json().catch(() => null)) as { message?: string } | null;+ if (!response?.ok) {+ const payload = (await response?.json().catch(() => null)) as { message?: string } | null;setEditServerErrors({builder_capacity: [payload?.message ?? 'Unable to update this server. Please try again.'],@@ -637,24 +730,21 @@ export default function Clusters({checkingServers.start(server.id);- const response = await fetch(`/v5/clusters/${selectedCluster.id}/servers/${server.id}/check`, {+ const response = await apiRequest(`/v5/clusters/${selectedCluster.id}/servers/${server.id}/check`, {method: 'POST',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'Content-Type': 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },+ }).catch(() => null);+ const payload = (await response?.json().catch(() => null)) as (CheckServerResponse & { message?: string }) | null;++ setServerConnectionNotice({+ message: response?.ok+ ? `Connection check for ${server.name}: ${payload?.status ?? 'unknown'}`+ : `Connection check failed for ${server.name}`,+ description: response?.ok+ ? (payload?.output ?? 'No output returned.')+ : (payload?.message ?? 'Unable to check server connection.'),+ variant: response?.ok ? 'success' : 'danger',});- if (response.ok) {- const payload = (await response.json()) as CheckServerResponse;- setSshChecks((currentChecks) => ({- ...currentChecks,- [server.id]: payload,- }));- }-checkingServers.finish(server.id);}@@ -665,17 +755,12 @@ export default function Clusters({bootstrappingServers.start(server.id);setBootstrapServerError(null);+ openBootstrapLogs(server);- const response = await fetch(`/v5/clusters/${selectedCluster.id}/servers/${server.id}/bootstrap`, {+ const response = await apiRequest(`/v5/clusters/${selectedCluster.id}/servers/${server.id}/bootstrap`, {method: 'POST',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'Content-Type': 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },- });- const payload = (await response.json()) as BootstrapServerResponse;+ }).catch(() => null);+ const payload = ((await response?.json().catch(() => null)) ?? {}) as BootstrapServerResponse;if (payload.cluster) {setClusterList((currentClusters) =>@@ -683,13 +768,17 @@ export default function Clusters({);}- if (!response.ok) {+ if (!response?.ok) {setBootstrapServerError(payload.message ?? 'Unable to queue bootstrap for this server.');}bootstrappingServers.finish(server.id);}+ function openBootstrapLogs(server: V5Server): void {+ setBootstrapLogsServerId(server.id);+ setIsBootstrapLogsDialogOpen(true);+ }async function loadCooldLogs(server: V5Server): Promise<void> {if (!selectedCluster) {@@ -702,18 +791,15 @@ export default function Clusters({setCooldLogsError(null);setCooldLogsOutput('');setCooldLogsFetchedAt(null);+ setCooldLogsSource(null);- const response = await fetch(`/v5/clusters/${selectedCluster.id}/servers/${server.id}/coold-logs?tail=200`, {+ const response = await apiRequest(`/v5/clusters/${selectedCluster.id}/servers/${server.id}/coold-logs?tail=200`, {method: 'GET',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- },- });+ }).catch(() => null);- const payload = (await response.json().catch(() => null)) as CooldLogsResponse & { message?: string } | null;+ const payload = (await response?.json().catch(() => null)) as CooldLogsResponse & { message?: string } | null;- if (!response.ok) {+ if (!response?.ok) {setCooldLogsError(payload?.message ?? 'Unable to load coold logs.');setIsLoadingCooldLogs(false);@@ -722,6 +808,7 @@ export default function Clusters({setCooldLogsOutput(payload?.output ?? '');setCooldLogsFetchedAt(payload?.fetchedAt ?? null);+ setCooldLogsSource(payload?.source ?? null);setIsLoadingCooldLogs(false);}@@ -736,18 +823,15 @@ export default function Clusters({setCorrosionTablesError(null);setCorrosionTablesOutput('');setCorrosionTablesFetchedAt(null);+ setCorrosionTablesSource(null);- const response = await fetch(`/v5/clusters/${selectedCluster.id}/servers/${server.id}/corrosion-tables?limit=200`, {+ const response = await apiRequest(`/v5/clusters/${selectedCluster.id}/servers/${server.id}/corrosion-tables?limit=200`, {method: 'GET',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- },- });+ }).catch(() => null);- const payload = (await response.json().catch(() => null)) as CorrosionTablesResponse & { message?: string } | null;+ const payload = (await response?.json().catch(() => null)) as CorrosionTablesResponse & { message?: string } | null;- if (!response.ok) {+ if (!response?.ok) {setCorrosionTablesError(payload?.message ?? 'Unable to load Corrosion tables.');setIsLoadingCorrosionTables(false);@@ -756,6 +840,7 @@ export default function Clusters({setCorrosionTablesOutput(payload?.output ?? '');setCorrosionTablesFetchedAt(payload?.fetchedAt ?? null);+ setCorrosionTablesSource(payload?.source ?? null);setIsLoadingCorrosionTables(false);}@@ -772,17 +857,13 @@ export default function Clusters({setFirewallRules([]);setFirewallRulesFetchedAt(null);- const response = await fetch(`/v5/clusters/${selectedCluster.id}/servers/${server.id}/firewall-rules`, {+ const response = await apiRequest(`/v5/clusters/${selectedCluster.id}/servers/${server.id}/firewall-rules`, {method: 'GET',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- },- });+ }).catch(() => null);- const payload = (await response.json().catch(() => null)) as FirewallRulesResponse & { message?: string } | null;+ const payload = (await response?.json().catch(() => null)) as FirewallRulesResponse & { message?: string } | null;- if (!response.ok) {+ if (!response?.ok) {setFirewallRulesError(payload?.message ?? 'Unable to load firewall rules.');setIsLoadingFirewallRules(false);@@ -820,25 +901,32 @@ export default function Clusters({async function deleteServer(cluster: V5Cluster, server: V5Server): Promise<void> {deletingServers.start(server.id);+ setDeleteClusterError(null);- const response = await fetch(`/v5/clusters/${cluster.id}/servers/${server.id}`, {+ const response = await apiRequest(`/v5/clusters/${cluster.id}/servers/${server.id}`, {method: 'DELETE',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'Content-Type': 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },- });+ }).catch(() => null);- if (response.ok) {- const payload = (await response.json()) as DeleteServerResponse;+ if (!response?.ok) {+ const payload = (await response?.json().catch(() => null)) as { message?: string } | null;- setClusterList((currentClusters) =>- currentClusters.map((cluster) => (cluster.id === payload.cluster.id ? payload.cluster : cluster)),+ setDeleteClusterError(+ payload?.message ??+ (response?.status === 422+ ? 'Delete or move applications from this server before deleting it.'+ : 'Unable to delete this server. Please try again.'),);+ deletingServers.finish(server.id);++ return;}+ const payload = (await response.json()) as DeleteServerResponse;++ setClusterList((currentClusters) =>+ currentClusters.map((cluster) => (cluster.id === payload.cluster.id ? payload.cluster : cluster)),+ );+deletingServers.finish(server.id);setIsDeleteDialogOpen(false);setClusterPendingDelete(null);@@ -866,16 +954,11 @@ export default function Clusters({setIsDeletingCluster(true);setDeleteClusterError(null);- const response = await fetch(`/v5/clusters/${cluster.id}`, {+ const response = await apiRequest(`/v5/clusters/${cluster.id}`, {method: 'DELETE',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },- });+ }).catch(() => null);- if (response.status === 422) {+ if (response?.status === 422) {const payload = (await response.json()) as { message?: string };setDeleteClusterError(payload.message ?? 'Only empty clusters can be deleted.');setIsDeletingCluster(false);@@ -883,14 +966,14 @@ export default function Clusters({return;}- if (!response.ok) {+ if (!response?.ok) {setDeleteClusterError('Unable to delete this cluster. Please try again.');setIsDeletingCluster(false);return;}- const nextClusters = clusterList.filter((cluster) => cluster.id !== selectedCluster.id);+ const nextClusters = clusterList.filter((remainingCluster) => remainingCluster.id !== cluster.id);setClusterList(nextClusters);setSelectedClusterId(nextClusters[0]?.id ?? '');@@ -969,11 +1052,8 @@ export default function Clusters({const isBootstrappingServer = bootstrappingServers.has(server.id) || isBootstrapInProgress;const isDeletingServer = deletingServers.has(server.id);const isServerInitialized = server.lastBootstrappedAt !== null;- const latestSshCheck = sshChecks[server.id] ?? null;const hasBootstrapLogs = server.lastBootstrapOutput !== null && server.lastBootstrapOutput.trim() !== '';const canShowBootstrapLogs = hasBootstrapLogs || isBootstrapInProgress;- const isBootstrapLogVisible =- isBootstrapInProgress || (canShowBootstrapLogs && (visibleBootstrapLogs[server.id] ?? false));return (<article key={server.id} className="rounded-lg border border-border bg-background p-4">@@ -1035,20 +1115,8 @@ export default function Clusters({{isCheckingServer ? 'Checking...' : 'Check connection'}</DropdownMenuItem>{canShowBootstrapLogs ? (- <DropdownMenuItem- disabled={isBootstrapInProgress}- onClick={() =>- setVisibleBootstrapLogs((currentLogs) => ({- ...currentLogs,- [server.id]: !isBootstrapLogVisible,- }))- }- >- {isBootstrapInProgress- ? 'Install logs shown'- : isBootstrapLogVisible- ? 'Hide install logs'- : 'Show install logs'}+ <DropdownMenuItem onClick={() => openBootstrapLogs(server)}>+ View install logs</DropdownMenuItem>) : null}<DropdownMenuItem onClick={() => void loadCooldLogs(server)}>@@ -1113,37 +1181,6 @@ export default function Clusters({</dd></div></dl>-- {latestSshCheck ? (- <div className="mt-4 rounded-md border border-border bg-muted/30 p-3 text-xs">- <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between">- <span className="font-medium text-foreground">Latest SSH check: {latestSshCheck.status}</span>- <span className="text-muted-foreground">{formatDate(latestSshCheck.checkedAt)}</span>- </div>- <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap rounded bg-background p-2 text-muted-foreground">- {latestSshCheck.output}- </pre>- </div>- ) : null}-- {isBootstrapLogVisible ? (- <div className="mt-4 rounded-md border border-border bg-muted/30 p-3 text-xs">- <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between">- <span className="font-medium text-foreground">- Install logs- {server.lastBootstrapStatus ? `: ${server.lastBootstrapStatus}` : ''}- </span>- <span className="text-muted-foreground">{formatDate(server.lastBootstrapRanAt)}</span>- </div>- {server.lastBootstrapOutput ? (- <pre className="mt-2 max-h-48 overflow-auto whitespace-pre-wrap rounded bg-background p-2 text-muted-foreground">- {server.lastBootstrapOutput}- </pre>- ) : (- <p className="mt-2 text-muted-foreground">No install logs captured yet.</p>- )}- </div>- ) : null}</article>);}@@ -1161,6 +1198,15 @@ export default function Clusters({selectedEnvironmentUuid={selectedEnvironmentUuid}/>+ {serverConnectionNotice ? (+ <CanvasNotice+ message={serverConnectionNotice.message}+ description={serverConnectionNotice.description}+ variant={serverConnectionNotice.variant}+ onDismiss={() => setServerConnectionNotice(null)}+ />+ ) : null}+<main className="flex min-h-dvh overflow-visible px-4 pt-16 lg:h-full lg:min-h-0 lg:overflow-hidden lg:px-6"><section className="flex w-full flex-col gap-4 py-4 lg:min-h-0 lg:py-6"><div className="rounded-lg border border-border bg-card p-4">@@ -1487,6 +1533,7 @@ export default function Clusters({setIsDeleteDialogOpen(open);if (!open) {+ setDeleteClusterError(null);setClusterPendingDelete(null);setServerPendingDelete(null);}@@ -1501,6 +1548,14 @@ export default function Clusters({: `Delete cluster ${clusterPendingDelete?.name ?? ''}? This cannot be undone.`}</DialogDescription></DialogHeader>+ {deleteClusterError ? (+ <p+ role="alert"+ className="rounded-md border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive"+ >+ {deleteClusterError}+ </p>+ ) : null}<DialogFooter><Buttontype="button"@@ -2027,6 +2082,82 @@ export default function Clusters({</DialogContent></Dialog>+ <Dialog+ open={isBootstrapLogsDialogOpen}+ onOpenChange={(open) => {+ setIsBootstrapLogsDialogOpen(open);++ if (!open) {+ setBootstrapLogsServerId(null);+ }+ }}+ >+ <DialogContent className="max-w-6xl">+ <DialogHeader>+ <DialogTitle>Install logs</DialogTitle>+ <DialogDescription>+ Bootstrap output for {bootstrapLogsServer?.name ?? 'this server'}.+ </DialogDescription>+ </DialogHeader>++ <div className="mt-5 flex flex-col gap-3">+ <div className="flex flex-col gap-1 text-xs text-muted-foreground sm:flex-row sm:items-center sm:justify-between">+ <p>+ Status: {bootstrapLogsServer?.lastBootstrapStatus ?? 'unknown'}+ {['queued', 'running'].includes(bootstrapLogsServer?.lastBootstrapStatus ?? '')+ ? ' · Auto-refreshing while bootstrap runs'+ : ''}+ </p>+ <p>{formatDate(bootstrapLogsServer?.lastBootstrapRanAt ?? null)}</p>+ </div>++ {parsedBootstrapLogs.summary.length > 0 ? (+ <div className="rounded-lg border border-border bg-muted/20 p-4">+ <p className="mb-3 text-sm font-medium text-foreground">Action results</p>+ <div className="grid gap-2 sm:grid-cols-2">+ {parsedBootstrapLogs.summary.map((item, index) => (+ <div+ key={`${item.label}-${index}`}+ className="rounded-md border border-border bg-background p-3"+ >+ <div className="flex items-start justify-between gap-3">+ <p className="text-sm font-medium text-foreground">{item.label}</p>+ <span+ className={`rounded-full px-2 py-0.5 text-xs ${+ item.tone === 'success'+ ? 'bg-emerald-500/10 text-emerald-400'+ : 'bg-muted text-muted-foreground'+ }`}+ >+ {item.tone === 'success' ? 'OK' : 'Info'}+ </span>+ </div>+ <p className="mt-1 text-xs text-muted-foreground">{item.value}</p>+ </div>+ ))}+ </div>+ </div>+ ) : null}++ {parsedBootstrapLogs.visibleOutput ? (+ <pre className="max-h-[70dvh] max-w-full overflow-auto whitespace-pre-wrap rounded-lg border border-border bg-black p-4 font-mono text-xs leading-relaxed text-white">+ {parsedBootstrapLogs.visibleOutput}+ </pre>+ ) : null}++ {parsedBootstrapLogs.summary.length > 0 ? (+ <details className="rounded-lg border border-border bg-muted/20 p-4">+ <summary className="cursor-pointer text-sm font-medium text-foreground">+ Raw JSON output+ </summary>+ <pre className="mt-3 max-h-80 max-w-full overflow-auto whitespace-pre-wrap rounded-md bg-black p-3 font-mono text-xs leading-relaxed text-white">+ {parsedBootstrapLogs.rawOutput}+ </pre>+ </details>+ ) : null}+ </div>+ </DialogContent>+ </Dialog><Dialogopen={isCooldLogsDialogOpen}@@ -2037,6 +2168,7 @@ export default function Clusters({setCooldLogsServer(null);setCooldLogsOutput('');setCooldLogsFetchedAt(null);+ setCooldLogsSource(null);setCooldLogsError(null);}}}@@ -2051,9 +2183,16 @@ export default function Clusters({<div className="mt-5 flex flex-col gap-3"><div className="flex items-center justify-between gap-3">- <p className="text-xs text-muted-foreground">- {cooldLogsFetchedAt ? `Fetched ${formatDate(cooldLogsFetchedAt)}` : 'Last 200 lines'}- </p>+ <div className="flex flex-wrap items-center gap-2">+ <p className="text-xs text-muted-foreground">+ {cooldLogsFetchedAt ? `Fetched ${formatDate(cooldLogsFetchedAt)}` : 'Last 200 lines'}+ </p>+ {cooldLogsSource ? (+ <span className="rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs text-muted-foreground">+ Source: {diagnosticsSourceLabel(cooldLogsSource)}+ </span>+ ) : null}+ </div>{cooldLogsServer ? (<Buttontype="button"@@ -2089,6 +2228,7 @@ export default function Clusters({setCorrosionTablesServer(null);setCorrosionTablesOutput('');setCorrosionTablesFetchedAt(null);+ setCorrosionTablesSource(null);setCorrosionTablesError(null);}}}@@ -2103,11 +2243,18 @@ export default function Clusters({<div className="mt-5 flex flex-col gap-3"><div className="flex items-center justify-between gap-3">- <p className="text-xs text-muted-foreground">- {corrosionTablesFetchedAt- ? `Fetched ${formatDate(corrosionTablesFetchedAt)}`- : 'First 200 rows per table'}- </p>+ <div className="flex flex-wrap items-center gap-2">+ <p className="text-xs text-muted-foreground">+ {corrosionTablesFetchedAt+ ? `Fetched ${formatDate(corrosionTablesFetchedAt)}`+ : 'First 200 rows per table'}+ </p>+ {corrosionTablesSource ? (+ <span className="rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs text-muted-foreground">+ Source: {diagnosticsSourceLabel(corrosionTablesSource)}+ </span>+ ) : null}+ </div>{corrosionTablesServer ? (<Buttontype="button"diff --git a/resources/js/v5/Pages/Dashboard.tsx b/resources/js/v5/Pages/Dashboard.tsxindex 79fc4f6c80..3ee7522ede 100644--- a/resources/js/v5/Pages/Dashboard.tsx+++ b/resources/js/v5/Pages/Dashboard.tsx@@ -1,70 +1,51 @@import { Head } from '@inertiajs/react';-import { useEffect, useMemo, useRef, useState, type MouseEvent, type PointerEvent, type WheelEvent } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent, type PointerEvent } from 'react';import { AppNavbar } from '@/components/app-navbar';+import { ApplicationCard } from '@/components/canvas/application-card';+import { ApplicationInspectorSheet } from '@/components/canvas/application-inspector-sheet';+import { CaddyIngressCard } from '@/components/canvas/caddy-ingress-card';+import { CanvasNotice } from '@/components/canvas/canvas-notice';+import { CanvasToolbar } from '@/components/canvas/canvas-toolbar';+import { ConnectionLines } from '@/components/canvas/connection-lines';+import { ConnectionPortsEditor } from '@/components/canvas/connection-ports-editor';+import { IngressDialog } from '@/components/canvas/ingress-dialog';import { Button } from '@/components/ui/button';-import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';-import { Field, FieldLabel } from '@/components/ui/field';-import { Input } from '@/components/ui/input';-import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from '@/components/ui/sheet';-import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';-import { Textarea } from '@/components/ui/textarea';-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';-import { resolveCanvasNodeLayout, resolveCanvasNodePosition, type CanvasNodeBounds } from '@/lib/canvas-collision';-import { csrfToken } from '@/lib/csrf';-import { cn } from '@/lib/utils';-import type { V5Application, V5CaddyIngress, V5DashboardProps, V5ResourceConnection } from '@/types';--type Viewport = {- x: number;- y: number;- zoom: number;-};+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';+import { TooltipProvider } from '@/components/ui/tooltip';+import { canvasRequest } from '@/lib/canvas-api';+import {+ connectorPoint,+ resolveApplicationPosition,+ resolveIngressPosition,+ settleCanvasResources,+ type ConnectionEndpoint,+ type ConnectorSide,+ type DraftConnection,+} from '@/lib/canvas-geometry';+import { runOptimisticUpdate } from '@/lib/optimistic';+import { useApplicationIngress } from '@/lib/use-application-ingress';+import { useCanvasConnections } from '@/lib/use-canvas-connections';+import { useCanvasResourceMerge } from '@/lib/use-canvas-resource-merge';+import { useCanvasViewport, type Viewport } from '@/lib/use-canvas-viewport';+import { usePendingIds } from '@/lib/use-pending-ids';+import type { V5Application, V5CaddyIngress, V5DashboardProps } from '@/types';-type ConnectorSide = 'top' | 'right' | 'bottom' | 'left';+const DEFAULT_NGINX_IMAGE = 'docker.io/library/nginx:alpine';-type ConnectionEndpoint = {- applicationId: string;- side: ConnectorSide;+type CanvasPosition = {+ canvasX: number;+ canvasY: number;};-type V5CanvasResourceUpdatedEvent = {- application: V5Application | null;- applications?: V5Application[];- caddyIngress: V5CaddyIngress | null;+type DeleteApplicationResponse = {+ message?: string;+ can_delete_locally?: boolean;};-type IngressModalState = {+type PendingLocalDelete = {application: V5Application;- domains: string;- internalPort: string;- error: string | null;-};--type EchoChannel = {- listen: (event: string, callback: (payload: unknown) => void) => EchoChannel;- subscribed?: (callback: () => void) => EchoChannel;- error?: (callback: (error: unknown) => void) => EchoChannel;-};--type EchoClient = {- private: (channel: string) => EchoChannel;- leave?: (channel: string) => void;- leaveChannel?: (channel: string) => void;-};--declare global {- interface Window {- Echo?: EchoClient;- }-}--type CanvasConnection = V5ResourceConnection;--type DraftConnection = {- from: ConnectionEndpoint;- toX: number;- toY: number;+ message: string;};type PointerState =@@ -99,68 +80,6 @@ type PointerState =from: ConnectionEndpoint;};-const APPLICATION_CARD_WIDTH = 320;-const APPLICATION_CARD_HEIGHT = 160;-const CANVAS_CARD_GAP = 16;-const CONNECTOR_SIDES: ConnectorSide[] = ['top', 'right', 'bottom', 'left'];-const MIN_CANVAS_ZOOM = 0.5;-const MAX_CANVAS_ZOOM = 2;-const CANVAS_ZOOM_STEP = 0.1;-const PINCH_CANVAS_ZOOM_STEP = 0.03;-const DEFAULT_NGINX_IMAGE = 'docker.io/library/nginx:alpine';--function statusBadgeClass(status: string): string | false {- if (status === 'running') {- return 'bg-emerald-500/15 text-emerald-400';- }-- if (status === 'creating') {- return 'bg-warning/15 text-warning';- }-- if (status === 'unknown') {- return 'bg-muted text-muted-foreground';- }-- if (['failed', 'exited', 'unreachable'].includes(status)) {- return 'bg-destructive/15 text-destructive';- }-- return false;-}--async function persistApplicationPosition(application: V5Application): Promise<void> {- await fetch(`/v5/applications/${application.id}/position`, {- method: 'PATCH',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'Content-Type': 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },- body: JSON.stringify({- canvas_x: application.canvasX,- canvas_y: application.canvasY,- }),- });-}--async function persistCaddyIngressPosition(ingress: V5CaddyIngress): Promise<void> {- await fetch(`/v5/caddy-ingresses/${ingress.id}/position`, {- method: 'PATCH',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'Content-Type': 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },- body: JSON.stringify({- canvas_x: ingress.canvasX,- canvas_y: ingress.canvasY,- }),- });-}-export default function Dashboard({flux,currentTeam = null,@@ -174,26 +93,64 @@ export default function Dashboard({}: V5DashboardProps) {const [applications, setApplications] = useState<V5Application[]>(initialApplications);const [ingresses, setIngresses] = useState<V5CaddyIngress[]>(caddyIngresses);- const [connections, setConnections] = useState<CanvasConnection[]>(initialResourceConnections);- const [selectedConnectionId, setSelectedConnectionId] = useState<string | null>(null);const [selectedApplicationId, setSelectedApplicationId] = useState<string | null>(null);const [selectedInspectorApplicationId, setSelectedInspectorApplicationId] = useState<string | null>(null);- const [connectionPortInput, setConnectionPortInput] = useState<Record<string, string>>({});const [draftConnection, setDraftConnection] = useState<DraftConnection | null>(null);- const [viewport, setViewport] = useState<Viewport>({ x: 0, y: 0, zoom: 1 });const [pointerState, setPointerState] = useState<PointerState | null>(null);const [isCreating, setIsCreating] = useState(false);const [selectedNginxServerId, setSelectedNginxServerId] = useState<string>(nginxServers[0]?.id ?? '');const [nginxImage, setNginxImage] = useState<string>(DEFAULT_NGINX_IMAGE);const [isRefreshing, setIsRefreshing] = useState(false);const [notice, setNotice] = useState<string | null>(null);- const [ingressModal, setIngressModal] = useState<IngressModalState | null>(null);- const [isSavingIngress, setIsSavingIngress] = useState(false);- const [savingIngressApplicationId, setSavingIngressApplicationId] = useState<string | null>(null);- const [deletingApplicationIds, setDeletingApplicationIds] = useState<Set<string>>(() => new Set());- const canvasRef = useRef<HTMLDivElement | null>(null);- const hasCanvasNodes = applications.length > 0 || ingresses.length > 0;+ const [pendingLocalDelete, setPendingLocalDelete] = useState<PendingLocalDelete | null>(null);+ const deletingApplications = usePendingIds<string>();++ const applicationsRef = useRef(applications);++ applicationsRef.current = applications;++ /**+ * Cards that are mid-drag or whose position PATCH has not landed yet keep+ * their local canvasX/canvasY when a websocket merge arrives.+ */+ const locallyPositionedApplicationIdsRef = useRef<Set<string>>(new Set());+ const locallyPositionedIngressIdsRef = useRef<Set<string>>(new Set());++ const { canvasRef, viewport, setViewport, zoomCanvas, handleCanvasWheel, centerOnCanvasNodes, canvasPointFromPointer } =+ useCanvasViewport();+ const {+ connections,+ selectedConnectionId,+ setSelectedConnectionId,+ connectionPortInput,+ setConnectionPortDraft,+ resetConnections,+ connectionExists,+ persistNewConnection,+ deleteConnection,+ updateConnectionDirection,+ addConnectionPort,+ removeConnectionPort,+ removeConnectionsForApplication,+ } = useCanvasConnections(initialResourceConnections, setNotice);++ const applyApplicationUpdate = useCallback((application: V5Application): void => {+ setApplications((currentApplications) =>+ currentApplications.map((candidate) => (candidate.id === application.id ? application : candidate)),+ );+ }, []);++ const {+ ingressModal,+ closeIngressModal,+ setIngressModalDomains,+ setIngressModalInternalPort,+ submitApplicationIngress,+ toggleApplicationIngress,+ savingIngressApplications,+ } = useApplicationIngress({ notify: setNotice, onApplicationUpdated: applyApplicationUpdate });+ const hasCanvasNodes = applications.length > 0 || ingresses.length > 0;const statusCounts = useMemo(() => ({running: applications.filter((application) => application.effectiveStatus === 'running').length,@@ -206,746 +163,175 @@ export default function Dashboard({() => applications.find((application) => application.id === selectedInspectorApplicationId) ?? null,[applications, selectedInspectorApplicationId],);+ const selectedConnection = useMemo(+ () => connections.find((connection) => connection.id === selectedConnectionId) ?? null,+ [connections, selectedConnectionId],+ );useEffect(() => {const settledResources = settleCanvasResources(initialApplications, caddyIngresses);setApplications(settledResources.applications);setIngresses(settledResources.ingresses);- setConnections(initialResourceConnections);+ resetConnections(initialResourceConnections);setSelectedNginxServerId((currentServerId) => currentServerId || nginxServers[0]?.id || '');- setSelectedConnectionId(null);setSelectedApplicationId(null);setSelectedInspectorApplicationId(null);centerOnCanvasNodes(settledResources.applications, settledResources.ingresses);- }, [initialApplications, caddyIngresses, initialResourceConnections, selectedProjectUuid, selectedEnvironmentUuid]);-- useEffect(() => {- if (!currentTeam) {- return;- }-- let isCancelled = false;- let attempts = 0;- const channelName = `team.${currentTeam.id}`;-- const interval = window.setInterval(() => {- attempts += 1;-- if (!window.Echo) {- if (attempts === 1) {- console.debug('Waiting for window.Echo before subscribing to canvas updates');- }-- if (attempts >= 20) {- window.clearInterval(interval);- }-- return;- }-- window.clearInterval(interval);-- if (isCancelled) {- return;- }-- const channel = window.Echo.private(channelName);-- channel.subscribed?.(() => console.debug(`Subscribed to private-${channelName} for canvas updates`));- channel.error?.((error) => console.error(`Subscription error on private-${channelName}`, error));- channel.listen('.v5.canvas.resource.updated', (payload) => {- const event = payload as V5CanvasResourceUpdatedEvent;-- if (event.application) {- setApplications((currentApplications) =>- currentApplications.map((application) =>- application.id === event.application?.id ? event.application : application,- ),- );- }-- if (event.applications && event.applications.length > 0) {- setApplications((currentApplications) =>- currentApplications.map((application) => {- const updatedApplication = event.applications?.find((candidate) => candidate.id === application.id);-- return updatedApplication ?? application;- }),- );- }-- if (event.caddyIngress) {- setIngresses((currentIngresses) =>- currentIngresses.map((ingress) =>- ingress.id === event.caddyIngress?.id ? event.caddyIngress : ingress,- ),- );- }- });- }, 500);-- return () => {- isCancelled = true;- window.clearInterval(interval);- window.Echo?.leave?.(channelName) ?? window.Echo?.leaveChannel?.(`private-${channelName}`);- };- }, [currentTeam]);-- useEffect(() => {- function deleteSelectedConnection(event: KeyboardEvent): void {- const target = event.target as HTMLElement | null;-- if (target?.closest('input, textarea, [contenteditable="true"]')) {- return;- }-- if (!['Backspace', 'Delete'].includes(event.key) || !selectedConnectionId) {- return;- }-- deleteConnection(selectedConnectionId);- }-- window.addEventListener('keydown', deleteSelectedConnection);-- return () => window.removeEventListener('keydown', deleteSelectedConnection);- }, [selectedConnectionId]);-- function connectorPoint(endpoint: ConnectionEndpoint): { x: number; y: number } | null {- const application = applications.find((candidate) => candidate.id === endpoint.applicationId);-- if (!application) {- return null;- }-- switch (endpoint.side) {- case 'top':- return { x: application.canvasX + APPLICATION_CARD_WIDTH / 2, y: application.canvasY };- case 'right':- return { x: application.canvasX + APPLICATION_CARD_WIDTH, y: application.canvasY + APPLICATION_CARD_HEIGHT / 2 };- case 'bottom':- return { x: application.canvasX + APPLICATION_CARD_WIDTH / 2, y: application.canvasY + APPLICATION_CARD_HEIGHT };- case 'left':- return { x: application.canvasX, y: application.canvasY + APPLICATION_CARD_HEIGHT / 2 };- }- }-- function applicationConnectorPoints(applicationId: string): Array<{ side: ConnectorSide; x: number; y: number }> {- return CONNECTOR_SIDES.flatMap((side) => {- const point = connectorPoint({ applicationId, side });-- return point ? [{ side, ...point }] : [];- });- }-- function shortestConnectionPoints(connection: CanvasConnection): { from: { x: number; y: number }; to: { x: number; y: number } } | null {- const fromPoints = applicationConnectorPoints(connection.fromApplicationId);- const toPoints = applicationConnectorPoints(connection.toApplicationId);- let shortest: { from: { x: number; y: number }; to: { x: number; y: number }; distance: number } | null = null;-- for (const from of fromPoints) {- for (const to of toPoints) {- const distance = Math.hypot(from.x - to.x, from.y - to.y);-- if (!shortest || distance < shortest.distance) {- shortest = { from, to, distance };- }- }- }-- return shortest ? { from: shortest.from, to: shortest.to } : null;- }-- function connectionExists(fromApplicationId: string, toApplicationId: string): boolean {- return connections.some(- (connection) =>- (connection.fromApplicationId === fromApplicationId && connection.toApplicationId === toApplicationId) ||- (connection.fromApplicationId === toApplicationId && connection.toApplicationId === fromApplicationId),- );- }-- function applicationDirectionLabel(applicationId: string): string {- const application = applications.find((candidate) => candidate.id === applicationId);-- if (!application) {- return 'Unknown app';- }-- return `${application.name} (${application.id.slice(0, 8)})`;- }-- function connectionDirectionKey(fromApplicationId: string, toApplicationId: string): string {- return `${fromApplicationId}->${toApplicationId}`;- }-- function activeConnectionPorts(connection: CanvasConnection): string[] {- return connection.portsByDirection[connectionDirectionKey(connection.fromApplicationId, connection.toApplicationId)] ?? [];- }--function normalizeConnection(connection: V5ResourceConnection): CanvasConnection {- return {- ...connection,- applicationIds: [connection.applicationIds[0], connection.applicationIds[1]],- portsByDirection: connection.portsByDirection ?? {},- };- }-- function responseErrorMessage(payload: { message?: string; detail?: string }, fallback: string): string {- if (payload.message && payload.detail) {- return `${payload.message} ${payload.detail}`;- }-- return payload.message ?? fallback;- }-- async function persistNewConnection(fromApplicationId: string, toApplicationId: string): Promise<void> {- setNotice(null);--- try {- const response = await fetch('/v5/resource-connections', {- method: 'POST',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'Content-Type': 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },- body: JSON.stringify({- resource_one: { type: 'application', uuid: fromApplicationId },- resource_two: { type: 'application', uuid: toApplicationId },- }),- });- const payload = (await response.json()) as { connection?: V5ResourceConnection; message?: string; detail?: string };-- if (!response.ok || !payload.connection) {- setNotice(responseErrorMessage(payload, 'Could not save resource connection.'));-- return;- }-- const nextConnection = normalizeConnection(payload.connection);-- setConnections((currentConnections) => {- const withoutDuplicate = currentConnections.filter((connection) => connection.id !== nextConnection.id);-- return [...withoutDuplicate, nextConnection];- });- setSelectedConnectionId(nextConnection.id);- } catch (error) {- setNotice(error instanceof Error ? error.message : 'Could not save resource connection.');- }- }-- async function persistConnectionPorts(connection: CanvasConnection): Promise<void> {- const portsByDirection = Object.fromEntries(- Object.entries(connection.portsByDirection).map(([direction, ports]) => [- direction,- ports.map((port) => Number(port)).filter((port) => Number.isInteger(port)),- ]),- );--- try {- const response = await fetch(`/v5/resource-connections/${connection.id}`, {- method: 'PATCH',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'Content-Type': 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },- body: JSON.stringify({ ports_by_direction: portsByDirection }),- });- const payload = (await response.json()) as { connection?: V5ResourceConnection; message?: string; detail?: string };-- if (!response.ok || !payload.connection) {- setNotice(responseErrorMessage(payload, 'Could not save allowed ports.'));-- return;- }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [initialApplications, caddyIngresses, initialResourceConnections, nginxServers[0]?.id, selectedProjectUuid, selectedEnvironmentUuid]);++ useCanvasResourceMerge({+ teamId: currentTeam?.id ?? null,+ selectedProjectUuid,+ selectedEnvironmentUuid,+ setApplications,+ setIngresses,+ locallyPositionedApplicationIds: locallyPositionedApplicationIdsRef,+ locallyPositionedIngressIds: locallyPositionedIngressIdsRef,+ });- const nextConnection = normalizeConnection(payload.connection);- setConnections((currentConnections) =>- currentConnections.map((currentConnection) =>- currentConnection.id === nextConnection.id ? nextConnection : currentConnection,+ const persistApplicationPosition = useCallback(async (application: V5Application, previousPosition: CanvasPosition): Promise<void> => {+ await runOptimisticUpdate({+ rollback: () =>+ setApplications((currentApplications) =>+ currentApplications.map((candidate) => (candidate.id === application.id ? { ...candidate, ...previousPosition } : candidate)),),- );- } catch (error) {- setNotice(error instanceof Error ? error.message : 'Could not save allowed ports.');- }- }-- async function deletePersistedConnection(connectionId: string): Promise<void> {-- try {- const response = await fetch(`/v5/resource-connections/${connectionId}`, {- method: 'DELETE',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },- });-- if (!response.ok) {- setNotice('Could not delete resource connection.');- }- } catch (error) {- setNotice(error instanceof Error ? error.message : 'Could not delete resource connection.');- }- }-- function deleteConnection(connectionId: string): void {- setConnections((currentConnections) => currentConnections.filter((connection) => connection.id !== connectionId));- setSelectedConnectionId(null);- void deletePersistedConnection(connectionId);- }-- function updateConnectionDirection(connectionId: string, fromApplicationId: string, toApplicationId: string): void {- setConnections((currentConnections) =>- currentConnections.map((connection) =>- connection.id === connectionId- ? {- ...connection,- fromApplicationId,- toApplicationId,- }- : connection,- ),- );- }-- function addConnectionPort(connectionId: string): void {- const port = connectionPortInput[connectionId]?.trim();- const portNumber = Number(port);-- if (!port || !Number.isInteger(portNumber) || portNumber < 1 || portNumber > 65535) {- return;- }-- const connection = connections.find((candidate) => candidate.id === connectionId);-- if (!connection) {- return;- }-- const directionKey = connectionDirectionKey(connection.fromApplicationId, connection.toApplicationId);- const directionPorts = connection.portsByDirection[directionKey] ?? [];-- if (directionPorts.includes(port)) {- return;- }-- const updatedConnection = {- ...connection,- portsByDirection: {- ...connection.portsByDirection,- [directionKey]: [...directionPorts, port],- },- };-- setConnections((currentConnections) =>- currentConnections.map((currentConnection) =>- currentConnection.id === updatedConnection.id ? updatedConnection : currentConnection,- ),- );- void persistConnectionPorts(updatedConnection);- setConnectionPortInput((currentInputs) => ({ ...currentInputs, [connectionId]: '' }));- }-- function removeConnectionPort(connectionId: string, port: string): void {- const connection = connections.find((candidate) => candidate.id === connectionId);-- if (!connection) {- return;- }-- const directionKey = connectionDirectionKey(connection.fromApplicationId, connection.toApplicationId);- const updatedConnection = {- ...connection,- portsByDirection: {- ...connection.portsByDirection,- [directionKey]: activeConnectionPorts(connection).filter((allowedPort) => allowedPort !== port),- },- };-- setConnections((currentConnections) =>- currentConnections.map((currentConnection) =>- currentConnection.id === updatedConnection.id ? updatedConnection : currentConnection,- ),- );- void persistConnectionPorts(updatedConnection);- }-- function settleCanvasResources(- nextApplications: V5Application[],- nextIngresses: V5CaddyIngress[],- ): { applications: V5Application[]; ingresses: V5CaddyIngress[] } {- const settledNodes = resolveCanvasNodeLayout(- [- ...nextApplications.map((application) => ({- id: `application-${application.id}`,- x: application.canvasX,- y: application.canvasY,- width: APPLICATION_CARD_WIDTH,- height: APPLICATION_CARD_HEIGHT,- })),- ...nextIngresses.map((ingress) => ({- id: `ingress-${ingress.id}`,- x: ingress.canvasX,- y: ingress.canvasY,- width: APPLICATION_CARD_WIDTH,- height: APPLICATION_CARD_HEIGHT,- })),- ],- CANVAS_CARD_GAP,- );- const positionsById = new Map(settledNodes.map((node) => [node.id, node]));-- return {- applications: nextApplications.map((application) => {- const position = positionsById.get(`application-${application.id}`);-- return position ? { ...application, canvasX: position.x, canvasY: position.y } : application;- }),- ingresses: nextIngresses.map((ingress) => {- const position = positionsById.get(`ingress-${ingress.id}`);-- return position ? { ...ingress, canvasX: position.x, canvasY: position.y } : ingress;- }),- };- }-- function canvasCollisionNodes(): CanvasNodeBounds[] {- return [- ...applications.map((application) => ({- id: `application-${application.id}`,- x: application.canvasX,- y: application.canvasY,- width: APPLICATION_CARD_WIDTH,- height: APPLICATION_CARD_HEIGHT,- })),- ...ingresses.map((ingress) => ({- id: `ingress-${ingress.id}`,- x: ingress.canvasX,- y: ingress.canvasY,- width: APPLICATION_CARD_WIDTH,- height: APPLICATION_CARD_HEIGHT,- })),- ];- }-- function resolveApplicationPosition(application: V5Application): V5Application {- const position = resolveCanvasNodePosition(- {- id: `application-${application.id}`,- x: application.canvasX,- y: application.canvasY,- width: APPLICATION_CARD_WIDTH,- height: APPLICATION_CARD_HEIGHT,- },- canvasCollisionNodes(),- CANVAS_CARD_GAP,- );-- return { ...application, canvasX: position.x, canvasY: position.y };- }+ request: async () => {+ const response = await canvasRequest(`/v5/applications/${application.id}/position`, {+ method: 'PATCH',+ body: {+ canvas_x: application.canvasX,+ canvas_y: application.canvasY,+ },+ });- function resolveIngressPosition(ingress: V5CaddyIngress): V5CaddyIngress {- const position = resolveCanvasNodePosition(- {- id: `ingress-${ingress.id}`,- x: ingress.canvasX,- y: ingress.canvasY,- width: APPLICATION_CARD_WIDTH,- height: APPLICATION_CARD_HEIGHT,+ return response.ok ? { ok: true, payload: undefined } : { ok: false };},- canvasCollisionNodes(),- CANVAS_CARD_GAP,- );-- return { ...ingress, canvasX: position.x, canvasY: position.y };- }-- function canvasPointFromPointer(event: PointerEvent): { x: number; y: number } {- const rect = canvasRef.current?.getBoundingClientRect();-- if (!rect) {- return { x: 0, y: 0 };- }-- return {- x: (event.clientX - rect.left - viewport.x) / viewport.zoom,- y: (event.clientY - rect.top - viewport.y) / viewport.zoom,- };- }-- async function removeApplication(application: V5Application): Promise<void> {- setNotice(null);- setDeletingApplicationIds((currentIds) => new Set(currentIds).add(application.id));--- try {- const response = await fetch(`/v5/applications/${application.id}`, {- method: 'DELETE',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },- });-- if (!response.ok) {- setNotice('Could not delete application.');-- return;- }+ fallbackErrorMessage: 'Could not save the card position.',+ notify: setNotice,+ onSettled: () => locallyPositionedApplicationIdsRef.current.delete(application.id),+ });+ }, []);- setApplications((currentApplications) =>- currentApplications.filter((candidate) => candidate.id !== application.id),- );- setConnections((currentConnections) =>- currentConnections.filter(- (connection) =>- connection.fromApplicationId !== application.id && connection.toApplicationId !== application.id,+ const persistCaddyIngressPosition = useCallback(async (ingress: V5CaddyIngress, previousPosition: CanvasPosition): Promise<void> => {+ await runOptimisticUpdate({+ rollback: () =>+ setIngresses((currentIngresses) =>+ currentIngresses.map((candidate) => (candidate.id === ingress.id ? { ...candidate, ...previousPosition } : candidate)),),- );- } catch (error) {- setNotice(error instanceof Error ? error.message : 'Could not delete application.');- } finally {- setDeletingApplicationIds((currentIds) => {- const nextIds = new Set(currentIds);-- nextIds.delete(application.id);-- return nextIds;- });- }- }-- function openApplicationIngressModal(application: V5Application): void {- setNotice(null);-- if (!application.serverIngressEnabled) {- setNotice('Enable ingress on the server before enabling app ingress.');-- return;- }+ request: async () => {+ const response = await canvasRequest(`/v5/caddy-ingresses/${ingress.id}/position`, {+ method: 'PATCH',+ body: {+ canvas_x: ingress.canvasX,+ canvas_y: ingress.canvasY,+ },+ });- setIngressModal({- application,- domains: application.domains.join(', '),- internalPort: application.internalPort ? String(application.internalPort) : '',- error: null,+ return response.ok ? { ok: true, payload: undefined } : { ok: false };+ },+ fallbackErrorMessage: 'Could not save the card position.',+ notify: setNotice,+ onSettled: () => locallyPositionedIngressIdsRef.current.delete(ingress.id),});- }-- async function disableApplicationIngress(application: V5Application): Promise<void> {- await saveApplicationIngress(application, false, application.domains, application.internalPort);- }-- async function submitApplicationIngress(): Promise<void> {- if (!ingressModal) {- return;- }-- const domains = ingressModal.domains- .split(',')- .map((domain) => domain.trim().toLowerCase())- .filter(Boolean);- const internalPort = Number(ingressModal.internalPort);- const invalidDomain = domains.find((domain) => !isValidDomain(domain));-- if (domains.length === 0) {- setIngressModal({ ...ingressModal, error: 'Add at least one valid domain.' });+ }, []);- return;- }-- if (invalidDomain) {- setIngressModal({ ...ingressModal, error: `${invalidDomain} is not a valid domain.` });-- return;- }+ const removeApplication = useCallback(+ async (application: V5Application, deleteLocally = false): Promise<void> => {+ setNotice(null);+ deletingApplications.start(application.id);- if (!Number.isInteger(internalPort) || internalPort < 1 || internalPort > 65535) {- setIngressModal({ ...ingressModal, error: 'Choose a valid internal port between 1 and 65535.' });-- return;- }-- await saveApplicationIngress(ingressModal.application, true, [...new Set(domains)], internalPort);- }-- async function saveApplicationIngress(- application: V5Application,- enabled: boolean,- domains: string[],- internalPort: number | null,- ): Promise<void> {- setNotice(null);- setIsSavingIngress(true);- setSavingIngressApplicationId(application.id);-- try {- const response = await fetch(`/v5/applications/${application.id}/ingress`, {- method: 'PATCH',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'Content-Type': 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },- body: JSON.stringify({- ingress_enabled: enabled,- internal_port: internalPort,- domains,- }),- });+ try {+ const response = await canvasRequest(`/v5/applications/${application.id}`, {+ method: 'DELETE',+ body: deleteLocally ? { delete_locally: true } : undefined,+ });- if (!response.ok) {- const payload = (await response.json().catch(() => null)) as { message?: string } | null;- const message = payload?.message ?? 'Could not update application ingress.';+ if (!response.ok) {+ const payload = (await response.json().catch(() => ({}))) as DeleteApplicationResponse;+ const message = payload.message ?? 'Could not delete application.';- if (ingressModal) {- setIngressModal({ ...ingressModal, error: message });- } else {setNotice(message);- }- return;- }+ if (payload.can_delete_locally && !deleteLocally) {+ setPendingLocalDelete({ application, message });+ }- const payload = (await response.json()) as { application: V5Application };- setApplications((currentApplications) =>- currentApplications.map((candidate) =>- candidate.id === payload.application.id ? payload.application : candidate,- ),- );- setIngressModal(null);- } catch (error) {- const message = error instanceof Error ? error.message : 'Could not update application ingress.';+ return;+ }- if (ingressModal) {- setIngressModal({ ...ingressModal, error: message });- } else {- setNotice(message);+ setApplications((currentApplications) => currentApplications.filter((candidate) => candidate.id !== application.id));+ removeConnectionsForApplication(application.id);+ } catch (error) {+ setNotice(error instanceof Error ? error.message : 'Could not delete application.');+ } finally {+ deletingApplications.finish(application.id);}- } finally {- setIsSavingIngress(false);- setSavingIngressApplicationId(null);- }- }-- function isValidDomain(domain: string): boolean {- if (domain.length < 1 || domain.length > 253 || domain.startsWith('.') || domain.endsWith('.')) {- return false;- }-- return domain.split('.').every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label));- }-- function renderIngressButton(application: V5Application) {- const isDisabled = !application.ingressEnabled && !application.serverIngressEnabled;- const isApplicationIngressSaving = savingIngressApplicationId === application.id;- const button = (- <button- type="button"- onPointerDown={(event) => event.stopPropagation()}- disabled={isDisabled || isApplicationIngressSaving}- onClick={(event) => {- event.stopPropagation();- application.ingressEnabled- ? void disableApplicationIngress(application)- : openApplicationIngressModal(application);- }}- className="rounded-sm border border-border px-2 py-1 text-[0.625rem] font-semibold uppercase tracking-wide text-foreground transition hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50"- >- {isApplicationIngressSaving ? 'Saving...' : application.ingressEnabled ? 'Disable' : 'Enable'}- </button>- );-- if (!isDisabled) {- return button;- }+ },+ [deletingApplications.start, deletingApplications.finish, removeConnectionsForApplication],+ );- return (- <Tooltip>- <TooltipTrigger render={<span className="inline-flex" />}>{button}</TooltipTrigger>- <TooltipContent side="top">- <p>You need to enable ingress in server settings first.</p>- </TooltipContent>- </Tooltip>- );- }+ const deleteApplication = useCallback(+ (application: V5Application): void => {+ void removeApplication(application);+ },+ [removeApplication],+ );- async function addNginx(): Promise<void> {+ const addNginx = useCallback(async (): Promise<void> => {setIsCreating(true);setNotice(null);-try {- const response = await fetch('/v5/applications/nginx', {+ const response = await canvasRequest('/v5/applications/nginx', {method: 'POST',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'Content-Type': 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },- body: JSON.stringify({+ body: {server_uuid: selectedNginxServerId || null,image: nginxImage.trim() || DEFAULT_NGINX_IMAGE,- }),+ },});const payload = (await response.json()) as { application?: V5Application; message?: string };- if (payload.application) {- const settledResources = settleCanvasResources([...applications, payload.application], ingresses);- const settledApplication = settledResources.applications.find(- (application) => application.id === payload.application?.id,- );+ if (!response.ok || !payload.application) {+ setNotice(payload.message ?? 'Could not deploy nginx.');- setApplications(settledResources.applications);- setIngresses(settledResources.ingresses);- centerOnCanvasNodes(settledResources.applications, settledResources.ingresses);-- if (- settledApplication &&- (settledApplication.canvasX !== payload.application.canvasX ||- settledApplication.canvasY !== payload.application.canvasY)- ) {- void persistApplicationPosition(settledApplication);- }+ return;}- if (!response.ok) {- setNotice(payload.application?.statusMessage ?? payload.message ?? 'Could not deploy nginx.');+ const settledResources = settleCanvasResources([...applicationsRef.current, payload.application], ingresses);+ const settledApplication = settledResources.applications.find(+ (application) => application.id === payload.application?.id,+ );++ setApplications(settledResources.applications);+ setIngresses(settledResources.ingresses);+ centerOnCanvasNodes(settledResources.applications, settledResources.ingresses);++ if (+ settledApplication &&+ (settledApplication.canvasX !== payload.application.canvasX ||+ settledApplication.canvasY !== payload.application.canvasY)+ ) {+ locallyPositionedApplicationIdsRef.current.add(settledApplication.id);+ void persistApplicationPosition(settledApplication, {+ canvasX: payload.application.canvasX,+ canvasY: payload.application.canvasY,+ });}} catch (error) {setNotice(error instanceof Error ? error.message : 'Could not deploy nginx.');} finally {setIsCreating(false);}- }+ }, [selectedNginxServerId, nginxImage, ingresses, centerOnCanvasNodes, persistApplicationPosition]);- async function refreshApplications(): Promise<void> {+ const refreshApplications = useCallback(async (): Promise<void> => {setIsRefreshing(true);setNotice(null);-try {- const response = await fetch('/v5/applications/refresh', {- method: 'POST',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'Content-Type': 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },- });+ const response = await canvasRequest('/v5/applications/refresh', { method: 'POST' });const payload = (await response.json()) as {applications?: V5Application[];errors?: string[];@@ -969,80 +355,32 @@ function normalizeConnection(connection: V5ResourceConnection): CanvasConnection} finally {setIsRefreshing(false);}- }-- function centerOnCanvasNodes(- nextApplications = applications,- nextCaddyIngresses: V5CaddyIngress[] = ingresses,- ): void {- const canvas = canvasRef.current;- const nodes = [...nextApplications, ...nextCaddyIngresses];-- if (!canvas || nodes.length === 0) {- setViewport((currentViewport) => ({ x: 0, y: 0, zoom: currentViewport.zoom }));-- return;- }-- const bounds = nodes.reduce(- (currentBounds, node) => ({- minX: Math.min(currentBounds.minX, node.canvasX),- maxX: Math.max(currentBounds.maxX, node.canvasX),- minY: Math.min(currentBounds.minY, node.canvasY),- maxY: Math.max(currentBounds.maxY, node.canvasY),- }),- {- minX: nodes[0]?.canvasX ?? 0,- maxX: nodes[0]?.canvasX ?? 0,- minY: nodes[0]?.canvasY ?? 0,- maxY: nodes[0]?.canvasY ?? 0,- },- );- const centerX = (bounds.minX + bounds.maxX) / 2;- const centerY = (bounds.minY + bounds.maxY) / 2;- const rect = canvas.getBoundingClientRect();-- setViewport((currentViewport) => ({- x: rect.width / 2 - (centerX + APPLICATION_CARD_WIDTH / 2) * currentViewport.zoom,- y: rect.height / 2 - (centerY + APPLICATION_CARD_HEIGHT / 2) * currentViewport.zoom,- zoom: currentViewport.zoom,- }));- }-- function startPan(event: PointerEvent<HTMLDivElement>): void {- if (event.target !== event.currentTarget) {- return;- }-- event.currentTarget.setPointerCapture(event.pointerId);- setPointerState({- type: 'pan',- pointerId: event.pointerId,- startClientX: event.clientX,- startClientY: event.clientY,- startViewport: viewport,- });- }-- function startApplicationDrag(event: PointerEvent<HTMLDivElement>, application: V5Application): void {- event.stopPropagation();- event.currentTarget.setPointerCapture(event.pointerId);- setSelectedConnectionId(null);- setSelectedApplicationId(application.id);- setPointerState({- type: 'app',- pointerId: event.pointerId,- applicationId: application.id,- startClientX: event.clientX,- startClientY: event.clientY,- startX: application.canvasX,- startY: application.canvasY,- });- }+ }, [ingresses]);++ const startApplicationDrag = useCallback(+ (event: PointerEvent<HTMLDivElement>, application: V5Application): void => {+ event.stopPropagation();+ event.currentTarget.setPointerCapture(event.pointerId);+ setSelectedConnectionId(null);+ setSelectedApplicationId(application.id);+ locallyPositionedApplicationIdsRef.current.add(application.id);+ setPointerState({+ type: 'app',+ pointerId: event.pointerId,+ applicationId: application.id,+ startClientX: event.clientX,+ startClientY: event.clientY,+ startX: application.canvasX,+ startY: application.canvasY,+ });+ },+ [setSelectedConnectionId],+ );- function startIngressDrag(event: PointerEvent<HTMLDivElement>, ingress: V5CaddyIngress): void {+ const startIngressDrag = useCallback((event: PointerEvent<HTMLDivElement>, ingress: V5CaddyIngress): void => {event.stopPropagation();event.currentTarget.setPointerCapture(event.pointerId);+ locallyPositionedIngressIdsRef.current.add(ingress.id);setPointerState({type: 'ingress',pointerId: event.pointerId,@@ -1052,36 +390,60 @@ function normalizeConnection(connection: V5ResourceConnection): CanvasConnectionstartX: ingress.canvasX,startY: ingress.canvasY,});- }+ }, []);++ const startConnectionDrag = useCallback(+ (event: PointerEvent<HTMLButtonElement>, applicationId: string, side: ConnectorSide): void => {+ event.stopPropagation();++ const from = { applicationId, side };+ const fromApplication = applicationsRef.current.find((candidate) => candidate.id === applicationId);+ const startPoint = fromApplication ? connectorPoint(fromApplication, side) : canvasPointFromPointer(event);++ setDraftConnection({+ from,+ toX: startPoint.x,+ toY: startPoint.y,+ });+ setPointerState({+ type: 'connection',+ pointerId: event.pointerId,+ from,+ });+ },+ [canvasPointFromPointer],+ );++ const selectConnection = useCallback(+ (event: MouseEvent<SVGLineElement>, connectionId: string): void => {+ event.stopPropagation();+ setSelectedConnectionId(connectionId);+ setSelectedApplicationId(null);+ },+ [setSelectedConnectionId],+ );- function startConnectionDrag(- event: PointerEvent<HTMLButtonElement>,- applicationId: string,- side: ConnectorSide,- ): void {+ const openApplicationInspector = useCallback((event: MouseEvent<HTMLElement>, application: V5Application): void => {event.stopPropagation();+ setSelectedApplicationId(application.id);+ setSelectedInspectorApplicationId(application.id);+ }, []);- const from = { applicationId, side };- const startPoint = connectorPoint(from) ?? canvasPointFromPointer(event);+ function startPan(event: PointerEvent<HTMLDivElement>): void {+ if (event.target !== event.currentTarget) {+ return;+ }- setDraftConnection({- from,- toX: startPoint.x,- toY: startPoint.y,- });+ event.currentTarget.setPointerCapture(event.pointerId);setPointerState({- type: 'connection',+ type: 'pan',pointerId: event.pointerId,- from,+ startClientX: event.clientX,+ startClientY: event.clientY,+ startViewport: viewport,});}- function selectConnection(event: MouseEvent<SVGLineElement>, connectionId: string): void {- event.stopPropagation();- setSelectedConnectionId(connectionId);- setSelectedApplicationId(null);- }-function clearCanvasSelection(event: MouseEvent<HTMLDivElement>): void {if (event.target !== event.currentTarget) {return;@@ -1091,12 +453,6 @@ function normalizeConnection(connection: V5ResourceConnection): CanvasConnectionsetSelectedApplicationId(null);}- function openApplicationInspector(event: MouseEvent<HTMLElement>, application: V5Application): void {- event.stopPropagation();- setSelectedApplicationId(application.id);- setSelectedInspectorApplicationId(application.id);- }-function connectionTargetFromPointer(event: PointerEvent<HTMLDivElement>): HTMLElement | null {const pointerTarget = document.elementFromPoint(event.clientX, event.clientY) as HTMLElement | null;@@ -1163,47 +519,6 @@ function normalizeConnection(connection: V5ResourceConnection): CanvasConnection);}- function clampCanvasZoom(zoom: number): number {- return Math.min(MAX_CANVAS_ZOOM, Math.max(MIN_CANVAS_ZOOM, zoom));- }-- function zoomCanvas(direction: 1 | -1, step = CANVAS_ZOOM_STEP, origin?: { x: number; y: number }): void {- const rect = canvasRef.current?.getBoundingClientRect();-- setViewport((currentViewport) => {- const nextZoom = clampCanvasZoom(currentViewport.zoom + direction * step);-- if (!rect || nextZoom === currentViewport.zoom) {- return currentViewport;- }-- const originX = origin?.x ?? rect.width / 2;- const originY = origin?.y ?? rect.height / 2;- const canvasX = (originX - currentViewport.x) / currentViewport.zoom;- const canvasY = (originY - currentViewport.y) / currentViewport.zoom;-- return {- x: originX - canvasX * nextZoom,- y: originY - canvasY * nextZoom,- zoom: nextZoom,- };- });- }-- function handleCanvasWheel(event: WheelEvent<HTMLDivElement>): void {- if (!event.ctrlKey) {- return;- }-- const rect = event.currentTarget.getBoundingClientRect();-- event.preventDefault();- zoomCanvas(event.deltaY < 0 ? 1 : -1, PINCH_CANVAS_ZOOM_STEP, {- x: event.clientX - rect.left,- y: event.clientY - rect.top,- });- }-function stopPointer(event: PointerEvent<HTMLDivElement>): void {if (!pointerState || pointerState.pointerId !== event.pointerId) {return;@@ -1234,16 +549,23 @@ function normalizeConnection(connection: V5ResourceConnection): CanvasConnectionconst application = applications.find((candidate) => candidate.id === pointerState.applicationId);if (application) {- const updatedApplication = resolveApplicationPosition({- ...application,- canvasX: Math.round(pointerState.startX + deltaX / viewport.zoom),- canvasY: Math.round(pointerState.startY + deltaY / viewport.zoom),- });+ const updatedApplication = resolveApplicationPosition(+ {+ ...application,+ canvasX: Math.round(pointerState.startX + deltaX / viewport.zoom),+ canvasY: Math.round(pointerState.startY + deltaY / viewport.zoom),+ },+ applications,+ ingresses,+ );setApplications((currentApplications) =>currentApplications.map((candidate) => (candidate.id === updatedApplication.id ? updatedApplication : candidate)),);- void persistApplicationPosition(updatedApplication);+ void persistApplicationPosition(updatedApplication, {+ canvasX: pointerState.startX,+ canvasY: pointerState.startY,+ });}}@@ -1251,22 +573,46 @@ function normalizeConnection(connection: V5ResourceConnection): CanvasConnectionconst ingress = ingresses.find((candidate) => candidate.id === pointerState.ingressId);if (ingress) {- const updatedIngress = resolveIngressPosition({- ...ingress,- canvasX: Math.round(pointerState.startX + deltaX / viewport.zoom),- canvasY: Math.round(pointerState.startY + deltaY / viewport.zoom),- });+ const updatedIngress = resolveIngressPosition(+ {+ ...ingress,+ canvasX: Math.round(pointerState.startX + deltaX / viewport.zoom),+ canvasY: Math.round(pointerState.startY + deltaY / viewport.zoom),+ },+ applications,+ ingresses,+ );setIngresses((currentIngresses) =>currentIngresses.map((candidate) => (candidate.id === updatedIngress.id ? updatedIngress : candidate)),);- void persistCaddyIngressPosition(updatedIngress);+ void persistCaddyIngressPosition(updatedIngress, {+ canvasX: pointerState.startX,+ canvasY: pointerState.startY,+ });}}setPointerState(null);}+ const deployNginx = useCallback((): void => {+ void addNginx();+ }, [addNginx]);+ const refreshCanvas = useCallback((): void => {+ void refreshApplications();+ }, [refreshApplications]);+ const centerCanvas = useCallback((): void => {+ centerOnCanvasNodes(applications, ingresses);+ }, [applications, ingresses, centerOnCanvasNodes]);+ const zoomIn = useCallback((): void => zoomCanvas(1), [zoomCanvas]);+ const zoomOut = useCallback((): void => zoomCanvas(-1), [zoomCanvas]);+ const dismissNotice = useCallback((): void => setNotice(null), []);+ const closeInspector = useCallback((): void => setSelectedInspectorApplicationId(null), []);+ const submitIngress = useCallback((): void => {+ void submitApplicationIngress();+ }, [submitApplicationIngress]);+return (<TooltipProvider><Head title="Dashboard" />@@ -1280,111 +626,25 @@ function normalizeConnection(connection: V5ResourceConnection): CanvasConnection/><main className="relative h-full min-h-0 overflow-hidden pt-16">- <div className="absolute left-4 top-20 z-30 flex max-w-[calc(100%-2rem)] flex-wrap items-center gap-2 rounded-xl border border-border bg-background/95 p-2 shadow-lg backdrop-blur">- <select- aria-label="Select nginx server"- value={selectedNginxServerId}- onChange={(event) => setSelectedNginxServerId(event.target.value)}- disabled={isCreating || nginxServers.length === 0}- className="rounded-lg border border-border bg-background px-3 py-2 text-sm font-medium text-foreground transition disabled:cursor-not-allowed disabled:opacity-60"- >- {nginxServers.length === 0 ? (- <option value="">No servers available</option>- ) : (- nginxServers.map((server) => (- <option key={server.id} value={server.id}>- {server.name} ({server.host})- </option>- ))- )}- </select>- <input- type="text"- aria-label="Nginx image"- value={nginxImage}- onChange={(event) => setNginxImage(event.target.value)}- disabled={isCreating}- className="w-72 rounded-lg border border-border bg-background px-3 py-2 text-sm font-medium text-foreground transition disabled:cursor-not-allowed disabled:opacity-60"- />- <button- type="button"- onClick={() => void addNginx()}- disabled={isCreating || nginxServers.length === 0}- className="rounded-lg bg-warning px-3 py-2 text-sm font-semibold text-black transition hover:bg-warning/90 disabled:cursor-not-allowed disabled:opacity-60"- >- {isCreating ? 'Deploying…' : 'Deploy'}- </button>- <button- type="button"- onClick={() => centerOnCanvasNodes()}- className="rounded-lg border border-border px-3 py-2 text-sm font-medium text-foreground transition hover:bg-muted"- >- Center- </button>- <div className="flex items-center overflow-hidden rounded-lg border border-border">- <button- type="button"- aria-label="Zoom out"- onClick={() => zoomCanvas(-1)}- className="px-3 py-2 text-sm font-semibold text-foreground transition hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50"- disabled={viewport.zoom <= MIN_CANVAS_ZOOM}- >- −- </button>- <span className="min-w-14 border-x border-border px-2 py-2 text-center text-xs font-medium text-muted-foreground">- {Math.round(viewport.zoom * 100)}%- </span>- <button- type="button"- aria-label="Zoom in"- onClick={() => zoomCanvas(1)}- className="px-3 py-2 text-sm font-semibold text-foreground transition hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50"- disabled={viewport.zoom >= MAX_CANVAS_ZOOM}- >- +- </button>- </div>- <button- type="button"- onClick={() => void refreshApplications()}- disabled={isRefreshing}- className="rounded-lg border border-border px-3 py-2 text-sm font-medium text-foreground transition hover:bg-muted disabled:cursor-not-allowed disabled:opacity-60"- >- {isRefreshing ? 'Refreshing…' : 'Refresh state'}- </button>- <div className="hidden items-center gap-2 px-2 text-xs text-muted-foreground sm:flex">- <span>{applications.length} apps</span>- <span>•</span>- <span>{statusCounts.running} running</span>- {statusCounts.failed > 0 && (- <>- <span>•</span>- <span className="text-destructive">{statusCounts.failed} failed</span>- </>- )}- {statusCounts.unknown > 0 && (- <>- <span>•</span>- <span>{statusCounts.unknown} unknown</span>- </>- )}- </div>- </div>-- {notice && (- <div className="absolute right-4 top-20 z-30 flex max-w-sm items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive shadow-lg">- <span>{notice}</span>- <button- type="button"- aria-label="Dismiss notice"- onClick={() => setNotice(null)}- className="-m-1 rounded p-1 text-destructive/80 transition hover:bg-destructive/10 hover:text-destructive"- >- <span aria-hidden="true">×</span>- <span className="sr-only">Dismiss notice</span>- </button>- </div>- )}+ <CanvasToolbar+ nginxServers={nginxServers}+ selectedNginxServerId={selectedNginxServerId}+ onSelectNginxServer={setSelectedNginxServerId}+ nginxImage={nginxImage}+ onNginxImageChange={setNginxImage}+ isCreating={isCreating}+ onDeploy={deployNginx}+ onCenter={centerCanvas}+ zoom={viewport.zoom}+ onZoomIn={zoomIn}+ onZoomOut={zoomOut}+ isRefreshing={isRefreshing}+ onRefresh={refreshCanvas}+ applicationsCount={applications.length}+ statusCounts={statusCounts}+ />++ {notice && <CanvasNotice message={notice} onDismiss={dismissNotice} />}<divref={canvasRef}@@ -1413,596 +673,123 @@ function normalizeConnection(connection: V5ResourceConnection): CanvasConnection}}>{ingresses.map((ingress) => (- <div- key={`caddy-ingress-${ingress.id}`}- className="absolute w-80 select-none overflow-hidden rounded-xl border border-warning/40 bg-card p-4 shadow-xl transition-shadow hover:shadow-2xl"- style={{- transform: `translate3d(${ingress.canvasX}px, ${ingress.canvasY}px, 0)`,- }}- onPointerDown={(event) => startIngressDrag(event, ingress)}- >- <div className="flex items-start justify-between gap-3">- <div className="min-w-0">- <div className="truncate text-sm font-semibold text-foreground">Caddy ingress</div>- <div className="mt-1 truncate text-xs text-muted-foreground">{ingress.name}</div>- </div>- <span- className={cn(- 'shrink-0 rounded-full px-2 py-1 text-[0.625rem] font-semibold uppercase tracking-wide',- statusBadgeClass(ingress.status),- )}- title={ingress.statusMessage ?? undefined}- >- {ingress.status}- </span>- </div>-- <dl className="mt-4 grid gap-2 text-xs">- <div className="grid grid-cols-[auto_minmax(0,1fr)] gap-3">- <dt className="shrink-0 text-muted-foreground">Server</dt>- <dd className="truncate text-right font-medium text-foreground">{ingress.name}</dd>- </div>- <div className="grid grid-cols-[auto_minmax(0,1fr)] gap-3">- <dt className="shrink-0 text-muted-foreground">Host</dt>- <dd className="truncate text-right font-mono text-[0.6875rem] text-foreground">- {ingress.host}- </dd>- </div>- </dl>- </div>+ <CaddyIngressCard key={`caddy-ingress-${ingress.id}`} ingress={ingress} onDragStart={startIngressDrag} />))}- <svg className="pointer-events-none absolute inset-0 overflow-visible">- <defs>- <marker- id="dashboard-connection-arrow"- viewBox="0 0 10 10"- refX="9"- refY="5"- markerWidth="16"- markerHeight="16"- orient="auto"- markerUnits="userSpaceOnUse"- >- <path d="M 0 0 L 10 5 L 0 10 z" fill="var(--destructive)" />- </marker>- </defs>- {connections.map((connection) => {- const points = shortestConnectionPoints(connection);-- if (!points) {- return null;- }-- return (- <g key={connection.id}>- <line- x1={points.from.x}- y1={points.from.y}- x2={points.to.x}- y2={points.to.y}- aria-label="Select connection"- className="pointer-events-auto cursor-pointer"- stroke="transparent"- strokeWidth={12}- strokeLinecap="round"- onPointerDown={(event) => event.stopPropagation()}- onClick={(event) => selectConnection(event, connection.id)}- />- <line- x1={points.from.x}- y1={points.from.y}- x2={points.to.x}- y2={points.to.y}- className={cn(- 'pointer-events-none',- selectedConnectionId === connection.id ? 'stroke-destructive' : 'stroke-warning',- )}- strokeWidth={selectedConnectionId === connection.id ? 4 : 2}- strokeDasharray="6 6"- strokeLinecap="round"- markerEnd={selectedConnectionId === connection.id ? 'url(#dashboard-connection-arrow)' : undefined}- />- </g>- );- })}- {draftConnection &&- (() => {- const from = connectorPoint(draftConnection.from);-- if (!from) {- return null;- }-- return (- <line- x1={from.x}- y1={from.y}- x2={draftConnection.toX}- y2={draftConnection.toY}- className="stroke-warning/70"- strokeWidth={2}- strokeDasharray="6 6"- strokeLinecap="round"- />- );- })()}- </svg>-- {connections.map((connection) => {- if (connection.id !== selectedConnectionId) {- return null;- }-- const points = shortestConnectionPoints(connection);-- if (!points) {- return null;- }+ <ConnectionLines+ connections={connections}+ applications={applications}+ selectedConnectionId={selectedConnectionId}+ draftConnection={draftConnection}+ onSelectConnection={selectConnection}+ />++ {selectedConnection && (+ <ConnectionPortsEditor+ connection={selectedConnection}+ applications={applications}+ portInput={connectionPortInput[selectedConnection.id] ?? ''}+ onPortInputChange={setConnectionPortDraft}+ onUpdateDirection={updateConnectionDirection}+ onAddPort={addConnectionPort}+ onRemovePort={removeConnectionPort}+ onDelete={deleteConnection}+ />+ )}- const activePorts = activeConnectionPorts(connection);- const firstApplicationId = connection.applicationIds[0];- const secondApplicationId = connection.applicationIds[1];- const isForwardDirection =- connection.fromApplicationId === firstApplicationId &&- connection.toApplicationId === secondApplicationId;-- return (- <div- key={`connection-controls-${connection.id}`}- className="absolute z-20 flex w-72 -translate-x-1/2 -translate-y-1/2 flex-col gap-3 rounded-md border border-border bg-card p-3 shadow-lg"- style={{- left: (points.from.x + points.to.x) / 2,- top: (points.from.y + points.to.y) / 2,- }}- onPointerDown={(event) => event.stopPropagation()}- onClick={(event) => event.stopPropagation()}- >- <div className="space-y-2">- <div className="text-[0.625rem] font-semibold uppercase tracking-wide text-muted-foreground">- Firewall- </div>- <div className="grid gap-1">- <button- type="button"- onClick={() =>- updateConnectionDirection(- connection.id,- firstApplicationId,- secondApplicationId,- )- }- className={cn(- 'rounded-sm border px-2 py-1 text-left text-xs transition',- isForwardDirection- ? 'border-warning/40 bg-warning/10 text-foreground hover:bg-warning/20'- : 'border-border text-muted-foreground hover:bg-muted hover:text-foreground',- )}- >- {applicationDirectionLabel(firstApplicationId)} →{' '}- {applicationDirectionLabel(secondApplicationId)}- </button>- <button- type="button"- onClick={() =>- updateConnectionDirection(- connection.id,- secondApplicationId,- firstApplicationId,- )- }- className={cn(- 'rounded-sm border px-2 py-1 text-left text-xs transition',- !isForwardDirection- ? 'border-warning/40 bg-warning/10 text-foreground hover:bg-warning/20'- : 'border-border text-muted-foreground hover:bg-muted hover:text-foreground',- )}- >- {applicationDirectionLabel(secondApplicationId)} →{' '}- {applicationDirectionLabel(firstApplicationId)}- </button>- </div>- </div>-- <div className="space-y-2">- <div className="text-[0.625rem] font-semibold uppercase tracking-wide text-muted-foreground">- Allowed ports- </div>- <div className="flex flex-wrap gap-1">- {activePorts.length === 0 && (- <span className="text-xs text-muted-foreground">No ports yet.</span>- )}- {activePorts.map((port) => (- <button- key={port}- type="button"- onClick={() => removeConnectionPort(connection.id, port)}- className="rounded-full border border-border bg-muted px-2 py-1 text-[0.625rem] font-medium text-foreground transition hover:border-destructive/40 hover:text-destructive"- >- {port} ×- </button>- ))}- </div>- <div className="flex gap-1">- <input- type="number"- min={1}- max={65535}- placeholder="Port"- value={connectionPortInput[connection.id] ?? ''}- onChange={(event) =>- setConnectionPortInput((currentInputs) => ({- ...currentInputs,- [connection.id]: event.target.value,- }))- }- onKeyDown={(event) => {- if (event.key === 'Enter') {- addConnectionPort(connection.id);- }- }}- className="min-w-0 flex-1 rounded-sm border border-border bg-background px-2 py-1 text-xs text-foreground outline-none transition focus:border-warning"- />- <button- type="button"- onClick={() => addConnectionPort(connection.id)}- className="rounded-sm border border-border px-2 py-1 text-xs font-medium text-foreground transition hover:bg-muted"- >- Add- </button>- </div>- </div>-- <button- type="button"- aria-label="Delete connection"- onClick={() => deleteConnection(connection.id)}- className="rounded-sm border border-destructive/40 px-2 py-1 text-[0.625rem] font-semibold uppercase tracking-wide text-destructive transition hover:bg-destructive/10"- >- Delete- </button>- </div>- );- })}-- {applications.map((application) => {- const isDeletingApplication = deletingApplicationIds.has(application.id);-- return (- <div- key={application.id}- data-application-card="application-card"- data-application-id={application.id}- className="group/application absolute h-40 w-80 select-none overflow-visible rounded-xl border border-border bg-card p-4 shadow-xl transition-shadow hover:shadow-2xl"- style={{- transform: `translate3d(${application.canvasX}px, ${application.canvasY}px, 0)`,- }}- onPointerDown={(event) => startApplicationDrag(event, application)}- onDoubleClick={(event) => openApplicationInspector(event, application)}- >- {CONNECTOR_SIDES.map((side) => (- <button- key={side}- type="button"- aria-label={`${application.name} ${side} connector`}- data-application-connector="application-connector"- data-application-id={application.id}- data-connector-side={side}- onPointerDown={(event) => startConnectionDrag(event, application.id, side)}- className={cn(- 'application-connector group/connector absolute z-10 flex size-8 items-center justify-center rounded-full opacity-0 transition group-hover/application:opacity-100 md:size-3',- selectedApplicationId === application.id && 'opacity-100',- side === 'top' && 'left-1/2 top-0 -translate-x-1/2 -translate-y-1/2',- side === 'right' && 'right-0 top-1/2 -translate-y-1/2 translate-x-1/2',- side === 'bottom' && 'bottom-0 left-1/2 -translate-x-1/2 translate-y-1/2',- side === 'left' && 'left-0 top-1/2 -translate-x-1/2 -translate-y-1/2',- )}- >- <span className="size-3 rounded-full border-2 border-card bg-warning shadow ring-2 ring-background transition group-hover/connector:scale-125 group-hover/connector:bg-warning/90" />- </button>- ))}-- <div className="flex items-start justify-between gap-3">- <div className="min-w-0">- <div className="truncate text-sm font-semibold text-foreground">{application.name}</div>- <div className="mt-1 truncate text-xs text-muted-foreground">{application.image}</div>- </div>- <div className="flex shrink-0 items-center gap-2">- <span- className={cn(- 'rounded-full px-2 py-1 text-[0.625rem] font-semibold uppercase tracking-wide',- statusBadgeClass(application.effectiveStatus),- )}- title={application.effectiveStatusMessage ?? undefined}- >- {application.effectiveStatus}- </span>- <button- type="button"- onPointerDown={(event) => event.stopPropagation()}- onClick={(event) => openApplicationInspector(event, application)}- className="rounded-md border border-border px-2 py-1 text-[0.625rem] font-semibold uppercase tracking-wide text-foreground transition hover:bg-muted"- >- Configure- </button>- <button- type="button"- onPointerDown={(event) => event.stopPropagation()}- onClick={(event) => {- event.stopPropagation();- void removeApplication(application);- }}- disabled={isDeletingApplication}- className="rounded-md border border-destructive/40 px-2 py-1 text-[0.625rem] font-semibold uppercase tracking-wide text-destructive transition hover:bg-destructive/10 disabled:cursor-not-allowed disabled:opacity-60"- >- {isDeletingApplication ? 'Deleting…' : 'Delete'}- </button>- </div>- </div>-- <dl className="mt-4 grid gap-2 text-xs">- <div className="grid grid-cols-[auto_minmax(0,1fr)] gap-3">- <dt className="shrink-0 text-muted-foreground">Server</dt>- <dd className="truncate text-right font-medium text-foreground">- {application.serverName ?? 'Unknown'}- {!application.isServerReachable && (- <span className="ml-2 text-destructive">(unreachable)</span>- )}- </dd>- </div>- <div className="grid grid-cols-[auto_minmax(0,1fr)] gap-3">- <dt className="shrink-0 text-muted-foreground">Container</dt>- <dd className="truncate text-right font-mono text-[0.6875rem] text-foreground">- {application.containerName}- </dd>- </div>- <div className="grid grid-cols-[auto_minmax(0,1fr)] items-center gap-3">- <dt className="shrink-0 text-muted-foreground">Ingress</dt>- <dd className="flex items-center justify-end gap-2 text-right">- <span className="truncate text-muted-foreground">- {application.ingressEnabled- ? `${application.domains.length} domain${application.domains.length === 1 ? '' : 's'} → ${application.internalPort ?? 'no port'}`- : 'Private'}- </span>- {renderIngressButton(application)}- </dd>- </div>- </dl>- </div>- );- })}+ {applications.map((application) => (+ <ApplicationCard+ key={application.id}+ application={application}+ isSelected={selectedApplicationId === application.id}+ isDeleting={deletingApplications.pendingIds.has(application.id)}+ isIngressSaving={savingIngressApplications.pendingIds.has(application.id)}+ onDragStart={startApplicationDrag}+ onOpenInspector={openApplicationInspector}+ onDelete={deleteApplication}+ onToggleIngress={toggleApplicationIngress}+ onConnectorPointerDown={startConnectionDrag}+ />+ ))}</div></div></main></div>- <Sheet- open={selectedInspectorApplication !== null}- onOpenChange={(open) => {- if (!open) {- setSelectedInspectorApplicationId(null);- }- }}- >- <SheetContent side="right" className="w-full overflow-hidden bg-background sm:rounded-l-xl sm:border data-[side=right]:sm:!inset-y-4 data-[side=right]:sm:!h-auto data-[side=right]:sm:!w-[45vw] data-[side=right]:sm:!max-w-[45vw]" showCloseButton blurOverlay={false}>- {selectedInspectorApplication && (- <>- <SheetHeader className="p-6 pb-4">- <SheetTitle>App configuration</SheetTitle>- <SheetDescription>- Double-click an application card to open configuration. Review runtime, networking, and advanced settings for{' '}- {selectedInspectorApplication.name}.- </SheetDescription>- </SheetHeader>-- <div className="flex flex-1 flex-col gap-6 px-6 pb-6">- <Tabs defaultValue="overview" className="gap-4">- <TabsList className="w-full justify-start" variant="line">- <TabsTrigger value="overview">Overview</TabsTrigger>- <TabsTrigger value="networking">Networking</TabsTrigger>- <TabsTrigger value="advanced">Advanced</TabsTrigger>- </TabsList>-- <TabsContent value="overview" className="flex flex-col gap-4">- <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">- <Field>- <FieldLabel>Name</FieldLabel>- <Input value={selectedInspectorApplication.name} readOnly />- </Field>-- <Field>- <FieldLabel>Status</FieldLabel>- <Input value={selectedInspectorApplication.effectiveStatus} readOnly />- </Field>-- {selectedInspectorApplication.effectiveStatus !== selectedInspectorApplication.status && (- <Field>- <FieldLabel>Last known container status</FieldLabel>- <Input value={selectedInspectorApplication.status} readOnly />- </Field>- )}-- <Field>- <FieldLabel>Image</FieldLabel>- <Input value={selectedInspectorApplication.image} readOnly />- </Field>-- <Field>- <FieldLabel>Server</FieldLabel>- <Input- value={- selectedInspectorApplication.isServerReachable- ? (selectedInspectorApplication.serverName ?? 'Unknown')- : `${selectedInspectorApplication.serverName ?? 'Unknown'} (unreachable)`- }- readOnly- />- </Field>-- <Field>- <FieldLabel>Container</FieldLabel>- <Input value={selectedInspectorApplication.containerName} readOnly />- </Field>-- <Field>- <FieldLabel>Runtime container ID</FieldLabel>- <Input value={selectedInspectorApplication.runtimeContainerId ?? 'Not available'} readOnly />- </Field>- </div>-- <Field>- <FieldLabel>Status message</FieldLabel>- <Textarea- value={selectedInspectorApplication.effectiveStatusMessage ?? 'No status message yet.'}- readOnly- className="min-h-20"- />- </Field>- </TabsContent>-- <TabsContent value="networking" className="flex flex-col gap-4">- <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">- <Field>- <FieldLabel>Mesh namespace</FieldLabel>- <Input value={selectedInspectorApplication.meshNamespace} readOnly />- </Field>-- <Field>- <FieldLabel>Mesh FQDN</FieldLabel>- <Input value={selectedInspectorApplication.meshFqdn} readOnly />- </Field>-- <Field>- <FieldLabel>Internal port</FieldLabel>- <Input value={selectedInspectorApplication.internalPort?.toString() ?? 'Not configured'} readOnly />- </Field>-- <Field>- <FieldLabel>Public ingress</FieldLabel>- <Input value={selectedInspectorApplication.ingressEnabled ? 'Enabled' : 'Private'} readOnly />- </Field>- </div>-- <Field>- <FieldLabel>Domains</FieldLabel>- <Textarea- value={- selectedInspectorApplication.domains.length > 0- ? selectedInspectorApplication.domains.join('\n')- : 'No public domains configured.'- }- readOnly- />- </Field>-- <div className="flex flex-wrap items-center gap-2">- {renderIngressButton(selectedInspectorApplication)}- <span className="text-xs text-muted-foreground">- Use this action to publish or private-route the app through the server ingress.- </span>- </div>- </TabsContent>-- <TabsContent value="advanced" className="flex flex-col gap-4">- <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">- <Field>- <FieldLabel>Application ID</FieldLabel>- <Input value={selectedInspectorApplication.id} readOnly />- </Field>-- <Field>- <FieldLabel>Canvas position</FieldLabel>- <Input- value={`${selectedInspectorApplication.canvasX}, ${selectedInspectorApplication.canvasY}`}- readOnly- />- </Field>- </div>-- <Field>- <FieldLabel>Raw app config</FieldLabel>- <Textarea- value={JSON.stringify(selectedInspectorApplication, null, 2)}- readOnly- className="min-h-80 font-mono text-xs"- />- </Field>- </TabsContent>- </Tabs>- </div>- </>+ <ApplicationInspectorSheet+ application={selectedInspectorApplication}+ isIngressSaving={+ selectedInspectorApplication !== null && savingIngressApplications.pendingIds.has(selectedInspectorApplication.id)+ }+ onToggleIngress={toggleApplicationIngress}+ onClose={closeInspector}+ />++ <Dialog open={pendingLocalDelete !== null} onOpenChange={(open) => !open && setPendingLocalDelete(null)}>+ <DialogContent className="max-w-md" showCloseButton={false}>+ <DialogHeader>+ <DialogTitle>Delete from Coolify only?</DialogTitle>+ <DialogDescription>+ Coolify could not reach the server to clean up containers, volumes, networks, or ingress config.+ </DialogDescription>+ </DialogHeader>++ {pendingLocalDelete && (+ <div className="flex flex-col gap-3 text-sm text-muted-foreground">+ <p className="break-words rounded-md border border-border bg-muted/40 p-3 font-mono text-xs">+ {pendingLocalDelete.message}+ </p>+ <p>+ Deleting locally removes {pendingLocalDelete.application.name} from Coolify, but orphaned resources may remain on the unreachable server.+ </p>+ </div>)}- </SheetContent>- </Sheet>- {ingressModal && (- <Dialog- open- onOpenChange={(open) => {- if (!open && !isSavingIngress) {- setIngressModal(null);- }- }}- >- <DialogContent className="max-w-lg" showCloseButton>- <DialogHeader>- <DialogTitle>Enable app ingress</DialogTitle>- <DialogDescription>- Route public domains to {ingressModal.application.name} through the server ingress.- </DialogDescription>- </DialogHeader>-- <form- className="mt-6 flex flex-col gap-4"- onSubmit={(event) => {- event.preventDefault();- void submitApplicationIngress();+ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => setPendingLocalDelete(null)}>+ Cancel+ </Button>+ <Button+ type="button"+ variant="outline"+ onClick={() => {+ const application = pendingLocalDelete?.application;+ setPendingLocalDelete(null);++ if (application) {+ void removeApplication(application);+ }}}>- <Field>- <FieldLabel>Domains</FieldLabel>- <Input- type="text"- value={ingressModal.domains}- onChange={(event) =>- setIngressModal({ ...ingressModal, domains: event.target.value, error: null })- }- placeholder="example.com, www.example.com"- />- <span className="text-xs text-muted-foreground">- Use hostnames only, separated by commas. No scheme, path, wildcard, or port.- </span>- </Field>-- <Field>- <FieldLabel>Internal port</FieldLabel>- <Input- type="number"- min="1"- max="65535"- value={ingressModal.internalPort}- onChange={(event) =>- setIngressModal({ ...ingressModal, internalPort: event.target.value, error: null })- }- placeholder="3000"- />- </Field>+ Retry+ </Button>+ <Button+ type="button"+ variant="destructive"+ onClick={() => {+ const application = pendingLocalDelete?.application;+ setPendingLocalDelete(null);- {ingressModal.error && (- <div className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">- <p className="font-medium">Ingress update failed</p>- <p className="mt-1 text-destructive/90">{ingressModal.error}</p>- </div>- )}+ if (application) {+ void removeApplication(application, true);+ }+ }}+ >+ Delete from Coolify only+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>- <div className="flex justify-end">- <Button type="submit" variant="coolify" disabled={isSavingIngress}>- {isSavingIngress ? 'Saving...' : 'Enable ingress'}- </Button>- </div>- </form>- </DialogContent>- </Dialog>+ {ingressModal && (+ <IngressDialog+ modal={ingressModal}+ isSaving={savingIngressApplications.pendingIds.has(ingressModal.application.id)}+ onDomainsChange={setIngressModalDomains}+ onInternalPortChange={setIngressModalInternalPort}+ onSubmit={submitIngress}+ onClose={closeIngressModal}+ />)}</TooltipProvider>);diff --git a/resources/js/v5/Pages/RealtimeTest.tsx b/resources/js/v5/Pages/RealtimeTest.tsxindex f286fce41f..07af7d0bcd 100644--- a/resources/js/v5/Pages/RealtimeTest.tsx+++ b/resources/js/v5/Pages/RealtimeTest.tsx@@ -1,10 +1,11 @@import { Head } from '@inertiajs/react';-import { useEffect, useState } from 'react';+import { useCallback, useEffect, useState } from 'react';import { AppNavbar } from '@/components/app-navbar';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { csrfToken } from '@/lib/csrf';+import { useTeamChannel } from '@/lib/use-team-channel';import type { V5DashboardProps } from '@/types';type RealtimeTestProps = V5DashboardProps & {@@ -19,24 +20,6 @@ type RealtimeTestEvent = {sentAt: string;};-type EchoChannel = {- listen: (event: string, callback: (payload: unknown) => void) => EchoChannel;- subscribed?: (callback: () => void) => EchoChannel;- error?: (callback: (error: unknown) => void) => EchoChannel;-};--type EchoClient = {- private: (channel: string) => EchoChannel;- leave?: (channel: string) => void;- leaveChannel?: (channel: string) => void;-};--declare global {- interface Window {- Echo?: EchoClient;- }-}-function formatLogPayload(payload: unknown): string {if (typeof payload === 'string') {return payload;@@ -50,65 +33,30 @@ export default function RealtimeTest({ currentTeam, flux, projects = [], selecteconst [isBroadcasting, setIsBroadcasting] = useState(false);const [logs, setLogs] = useState<string[]>([]);- function addLog(label: string, payload?: unknown): void {+ const addLog = useCallback((label: string, payload?: unknown): void => {const timestamp = new Date().toLocaleTimeString();setLogs((currentLogs) => [`[${timestamp}] ${label}${payload === undefined ? '' : `\n${formatLogPayload(payload)}`}`,...currentLogs,]);- }+ }, []);useEffect(() => {if (!currentTeam) {addLog('No current team was provided to the page.');-- return;}+ }, [currentTeam, addLog]);- let isCancelled = false;- let attempts = 0;- const channelName = `team.${currentTeam.id}`;-- const interval = window.setInterval(() => {- attempts += 1;+ useTeamChannel(+ currentTeam?.id ?? null,+ '.v5.realtime.test',+ (payload) => {+ const event = payload as RealtimeTestEvent;- if (!window.Echo) {- if (attempts === 1) {- addLog('Waiting for window.Echo...');- }-- if (attempts >= 20) {- window.clearInterval(interval);- addLog('window.Echo was not available after 10 seconds.');- }-- return;- }-- window.clearInterval(interval);-- if (isCancelled) {- return;- }-- addLog(`Subscribing to private-${channelName}`);- const channel = window.Echo.private(channelName);-- channel.subscribed?.(() => addLog(`Subscribed to private-${channelName}`));- channel.error?.((error: unknown) => addLog(`Subscription error on private-${channelName}`, error));- channel.listen('.v5.realtime.test', (payload) => {- const event = payload as RealtimeTestEvent;-- addLog('Received .v5.realtime.test', event);- });- }, 500);-- return () => {- isCancelled = true;- window.clearInterval(interval);- window.Echo?.leave?.(channelName) ?? window.Echo?.leaveChannel?.(`private-${channelName}`);- };- }, [currentTeam]);+ addLog('Received .v5.realtime.test', event);+ },+ { onDebug: addLog, onError: addLog },+ );async function broadcastTestEvent(): Promise<void> {setIsBroadcasting(true);diff --git a/resources/js/v5/components/app-navbar.tsx b/resources/js/v5/components/app-navbar.tsxindex a853f5d676..b429ad6c14 100644--- a/resources/js/v5/components/app-navbar.tsx+++ b/resources/js/v5/components/app-navbar.tsx@@ -7,25 +7,44 @@ import { csrfToken } from '@/lib/csrf';import { cn } from '@/lib/utils';import type { SelectItemOption, V5DashboardProps, V5Project } from '@/types';-async function persistSelection(projectUuid: string, environmentUuid: string): Promise<void> {- await fetch('/v5/selection', {- method: 'POST',- credentials: 'same-origin',- headers: {- Accept: 'application/json',- 'Content-Type': 'application/json',- 'X-CSRF-TOKEN': csrfToken(),- },- body: JSON.stringify({- project_uuid: projectUuid,- environment_uuid: environmentUuid,- }),- });+async function persistSelection(projectUuid: string, environmentUuid: string): Promise<boolean> {+ try {+ const response = await fetch('/v5/selection', {+ method: 'POST',+ credentials: 'same-origin',+ headers: {+ Accept: 'application/json',+ 'Content-Type': 'application/json',+ 'X-CSRF-TOKEN': csrfToken(),+ },+ body: JSON.stringify({+ project_uuid: projectUuid,+ environment_uuid: environmentUuid,+ }),+ });++ if (!response.ok) {+ console.error(`Could not persist the project/environment selection (HTTP ${response.status}).`);+ }++ return response.ok;+ } catch (error) {+ console.error('Could not persist the project/environment selection.', error);++ return false;+ }}function refreshCurrentPageSelection(): void {router.reload({- only: ['applications', 'selectedProjectUuid', 'selectedEnvironmentUuid'],+ only: [+ 'applications',+ 'caddyIngresses',+ 'resourceConnections',+ 'nginxServers',+ 'selectedProjectUuid',+ 'selectedEnvironmentUuid',+ ],});}@@ -65,10 +84,21 @@ export function AppNavbar({const nextProject = projects.find((project) => project.uuid === nextProjectUuid);const nextEnvironmentUuid = nextProject?.environments?.[0]?.uuid ?? '';+ const previousProjectUuid = projectUuid;+ const previousEnvironmentUuid = environmentUuid;setProjectUuid(nextProjectUuid);setEnvironmentUuid(nextEnvironmentUuid);- void persistSelection(nextProjectUuid, nextEnvironmentUuid).then(refreshCurrentPageSelection);+ void persistSelection(nextProjectUuid, nextEnvironmentUuid).then((persisted) => {+ if (persisted) {+ refreshCurrentPageSelection();++ return;+ }++ setProjectUuid(previousProjectUuid);+ setEnvironmentUuid(previousEnvironmentUuid);+ });}function selectEnvironment(nextEnvironmentUuid: string | null): void {@@ -76,8 +106,18 @@ export function AppNavbar({return;}+ const previousEnvironmentUuid = environmentUuid;+setEnvironmentUuid(nextEnvironmentUuid);- void persistSelection(projectUuid, nextEnvironmentUuid).then(refreshCurrentPageSelection);+ void persistSelection(projectUuid, nextEnvironmentUuid).then((persisted) => {+ if (persisted) {+ refreshCurrentPageSelection();++ return;+ }++ setEnvironmentUuid(previousEnvironmentUuid);+ });}const projectItems: SelectItemOption[] = projects.map((project) => ({diff --git a/resources/js/v5/components/canvas/application-card.tsx b/resources/js/v5/components/canvas/application-card.tsxnew file mode 100644index 0000000000..210a739743--- /dev/null+++ b/resources/js/v5/components/canvas/application-card.tsx@@ -0,0 +1,129 @@+import { memo, type MouseEvent, type PointerEvent } from 'react';++import { ApplicationIngressButton } from '@/components/canvas/application-ingress-button';+import { statusBadgeClass } from '@/components/canvas/status-badge';+import { CONNECTOR_SIDES, type ConnectorSide } from '@/lib/canvas-geometry';+import { cn } from '@/lib/utils';+import type { V5Application } from '@/types';++type ApplicationCardProps = {+ application: V5Application;+ isSelected: boolean;+ isDeleting: boolean;+ isIngressSaving: boolean;+ onDragStart: (event: PointerEvent<HTMLDivElement>, application: V5Application) => void;+ onOpenInspector: (event: MouseEvent<HTMLElement>, application: V5Application) => void;+ onDelete: (application: V5Application) => void;+ onToggleIngress: (application: V5Application) => void;+ onConnectorPointerDown: (event: PointerEvent<HTMLButtonElement>, applicationId: string, side: ConnectorSide) => void;+};++export const ApplicationCard = memo(function ApplicationCard({+ application,+ isSelected,+ isDeleting,+ isIngressSaving,+ onDragStart,+ onOpenInspector,+ onDelete,+ onToggleIngress,+ onConnectorPointerDown,+}: ApplicationCardProps) {+ return (+ <div+ data-application-card="application-card"+ data-application-id={application.id}+ className="group/application absolute h-40 w-80 select-none overflow-visible rounded-xl border border-border bg-card p-4 shadow-xl transition-shadow hover:shadow-2xl"+ style={{+ transform: `translate3d(${application.canvasX}px, ${application.canvasY}px, 0)`,+ }}+ onPointerDown={(event) => onDragStart(event, application)}+ onDoubleClick={(event) => onOpenInspector(event, application)}+ >+ {CONNECTOR_SIDES.map((side) => (+ <button+ key={side}+ type="button"+ aria-label={`${application.name} ${side} connector`}+ data-application-connector="application-connector"+ data-application-id={application.id}+ data-connector-side={side}+ onPointerDown={(event) => onConnectorPointerDown(event, application.id, side)}+ className={cn(+ 'application-connector group/connector absolute z-10 flex size-8 items-center justify-center rounded-full opacity-0 transition group-hover/application:opacity-100 md:size-3',+ isSelected && 'opacity-100',+ side === 'top' && 'left-1/2 top-0 -translate-x-1/2 -translate-y-1/2',+ side === 'right' && 'right-0 top-1/2 -translate-y-1/2 translate-x-1/2',+ side === 'bottom' && 'bottom-0 left-1/2 -translate-x-1/2 translate-y-1/2',+ side === 'left' && 'left-0 top-1/2 -translate-x-1/2 -translate-y-1/2',+ )}+ >+ <span className="size-3 rounded-full border-2 border-card bg-warning shadow ring-2 ring-background transition group-hover/connector:scale-125 group-hover/connector:bg-warning/90" />+ </button>+ ))}++ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="truncate text-sm font-semibold text-foreground">{application.name}</div>+ <div className="mt-1 truncate text-xs text-muted-foreground">{application.image}</div>+ </div>+ <div className="flex shrink-0 items-center gap-2">+ <span+ className={cn(+ 'rounded-full px-2 py-1 text-[0.625rem] font-semibold uppercase tracking-wide',+ statusBadgeClass(application.effectiveStatus),+ )}+ title={application.effectiveStatusMessage ?? undefined}+ >+ {application.effectiveStatus}+ </span>+ <button+ type="button"+ onPointerDown={(event) => event.stopPropagation()}+ onClick={(event) => onOpenInspector(event, application)}+ className="rounded-md border border-border px-2 py-1 text-[0.625rem] font-semibold uppercase tracking-wide text-foreground transition hover:bg-muted"+ >+ Configure+ </button>+ <button+ type="button"+ onPointerDown={(event) => event.stopPropagation()}+ onClick={(event) => {+ event.stopPropagation();+ onDelete(application);+ }}+ disabled={isDeleting}+ className="rounded-md border border-destructive/40 px-2 py-1 text-[0.625rem] font-semibold uppercase tracking-wide text-destructive transition hover:bg-destructive/10 disabled:cursor-not-allowed disabled:opacity-60"+ >+ {isDeleting ? 'Deleting…' : 'Delete'}+ </button>+ </div>+ </div>++ <dl className="mt-4 grid gap-2 text-xs">+ <div className="grid grid-cols-[auto_minmax(0,1fr)] gap-3">+ <dt className="shrink-0 text-muted-foreground">Server</dt>+ <dd className="truncate text-right font-medium text-foreground">+ {application.serverName ?? 'Unknown'}+ {!application.isServerReachable && <span className="ml-2 text-destructive">(unreachable)</span>}+ </dd>+ </div>+ <div className="grid grid-cols-[auto_minmax(0,1fr)] gap-3">+ <dt className="shrink-0 text-muted-foreground">Container</dt>+ <dd className="truncate text-right font-mono text-[0.6875rem] text-foreground">{application.containerName}</dd>+ </div>+ <div className="grid grid-cols-[auto_minmax(0,1fr)] items-center gap-3">+ <dt className="shrink-0 text-muted-foreground">Ingress</dt>+ <dd className="flex items-center justify-end gap-2 text-right">+ <span className="truncate text-muted-foreground">+ {application.ingressEnabled+ ? `${application.domains.length} domain${application.domains.length === 1 ? '' : 's'} → ${application.internalPort ?? 'no port'}`+ : 'Private'}+ </span>+ <ApplicationIngressButton application={application} isSaving={isIngressSaving} onToggle={onToggleIngress} />+ </dd>+ </div>+ </dl>+ </div>+ );+});diff --git a/resources/js/v5/components/canvas/application-ingress-button.tsx b/resources/js/v5/components/canvas/application-ingress-button.tsxnew file mode 100644index 0000000000..536668dced--- /dev/null+++ b/resources/js/v5/components/canvas/application-ingress-button.tsx@@ -0,0 +1,39 @@+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';+import type { V5Application } from '@/types';++type ApplicationIngressButtonProps = {+ application: V5Application;+ isSaving: boolean;+ onToggle: (application: V5Application) => void;+};++export function ApplicationIngressButton({ application, isSaving, onToggle }: ApplicationIngressButtonProps) {+ const isDisabled = !application.ingressEnabled && !application.serverIngressEnabled;+ const button = (+ <button+ type="button"+ onPointerDown={(event) => event.stopPropagation()}+ disabled={isDisabled || isSaving}+ onClick={(event) => {+ event.stopPropagation();+ onToggle(application);+ }}+ className="rounded-sm border border-border px-2 py-1 text-[0.625rem] font-semibold uppercase tracking-wide text-foreground transition hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50"+ >+ {isSaving ? 'Saving...' : application.ingressEnabled ? 'Disable' : 'Enable'}+ </button>+ );++ if (!isDisabled) {+ return button;+ }++ return (+ <Tooltip>+ <TooltipTrigger render={<span className="inline-flex" />}>{button}</TooltipTrigger>+ <TooltipContent side="top">+ <p>You need to enable ingress in server settings first.</p>+ </TooltipContent>+ </Tooltip>+ );+}diff --git a/resources/js/v5/components/canvas/application-inspector-sheet.tsx b/resources/js/v5/components/canvas/application-inspector-sheet.tsxnew file mode 100644index 0000000000..90ed8758b6--- /dev/null+++ b/resources/js/v5/components/canvas/application-inspector-sheet.tsx@@ -0,0 +1,276 @@+import { ApplicationIngressButton } from '@/components/canvas/application-ingress-button';+import { Button } from '@/components/ui/button';+import { Field, FieldLabel } from '@/components/ui/field';+import { Input } from '@/components/ui/input';+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from '@/components/ui/sheet';+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';+import { Textarea } from '@/components/ui/textarea';+import { apiRequest } from '@/lib/api';+import type { V5Application } from '@/types';+import { useCallback, useEffect, useState } from 'react';++type ApplicationInspectorSheetProps = {+ application: V5Application | null;+ isIngressSaving: boolean;+ onToggleIngress: (application: V5Application) => void;+ onClose: () => void;+};++type ApplicationLogsResponse = {+ status: string;+ statusMessage: string | null;+ containerId: string | null;+ logs: string | null;+ logsError: string | null;+};++function ApplicationLogsTab({ application }: { application: V5Application }) {+ const [isLoading, setIsLoading] = useState(false);+ const [logs, setLogs] = useState<string | null>(null);+ const [logsError, setLogsError] = useState<string | null>(null);+ const [hasLoaded, setHasLoaded] = useState(false);++ const fetchLogs = useCallback(async () => {+ setIsLoading(true);+ setLogsError(null);++ try {+ const response = await apiRequest(`/v5/applications/${application.id}/logs`, { method: 'GET' });++ if (!response.ok) {+ throw new Error(`Request failed with status ${response.status}`);+ }++ const data = (await response.json()) as ApplicationLogsResponse;+ setLogs(data.logs);+ setLogsError(data.logsError);+ } catch {+ setLogs(null);+ setLogsError('Could not reach the server to fetch container logs. Try again.');+ } finally {+ setIsLoading(false);+ setHasLoaded(true);+ }+ }, [application.id]);++ // Lazily fetch when the Logs tab first mounts for this app, and reset/refetch+ // whenever a different application is inspected.+ useEffect(() => {+ setLogs(null);+ setLogsError(null);+ setHasLoaded(false);+ void fetchLogs();+ }, [fetchLogs]);++ const statusMessage = application.effectiveStatusMessage ?? application.statusMessage;++ return (+ <div className="flex flex-col gap-4">+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">+ <Field>+ <FieldLabel>Deploy status</FieldLabel>+ <Input value={application.effectiveStatus} readOnly />+ </Field>++ <Field>+ <FieldLabel>Container</FieldLabel>+ <Input value={application.runtimeContainerId ?? 'Not created yet'} readOnly />+ </Field>+ </div>++ <Field>+ <FieldLabel>Status message</FieldLabel>+ <Textarea value={statusMessage ?? 'No status message yet.'} readOnly className="min-h-16" />+ </Field>++ <Field>+ <div className="flex items-center justify-between">+ <FieldLabel>Container logs</FieldLabel>+ <Button variant="outline" size="sm" onClick={() => void fetchLogs()} disabled={isLoading}>+ {isLoading ? 'Refreshing…' : 'Refresh'}+ </Button>+ </div>+ <Textarea+ value={+ isLoading && !hasLoaded+ ? 'Loading container logs…'+ : logsError+ ? logsError+ : logs+ ? logs+ : hasLoaded+ ? 'No container logs yet — the container has not been created. See the status message above for the deploy result.'+ : ''+ }+ readOnly+ className="min-h-80 font-mono text-xs"+ />+ </Field>+ </div>+ );+}++export function ApplicationInspectorSheet({ application, isIngressSaving, onToggleIngress, onClose }: ApplicationInspectorSheetProps) {+ return (+ <Sheet+ open={application !== null}+ onOpenChange={(open) => {+ if (!open) {+ onClose();+ }+ }}+ >+ <SheetContent side="right" className="w-full overflow-hidden bg-background sm:rounded-l-xl sm:border data-[side=right]:sm:!inset-y-4 data-[side=right]:sm:!h-auto data-[side=right]:sm:!w-[45vw] data-[side=right]:sm:!max-w-[45vw]" showCloseButton blurOverlay={false}>+ {application && (+ <>+ <SheetHeader className="p-6 pb-4">+ <SheetTitle>App configuration</SheetTitle>+ <SheetDescription>+ Double-click an application card to open configuration. Review runtime, networking, and advanced settings for{' '}+ {application.name}.+ </SheetDescription>+ </SheetHeader>++ <div className="flex flex-1 flex-col gap-6 px-6 pb-6">+ <Tabs defaultValue="overview" className="gap-4">+ <TabsList className="w-full justify-start" variant="line">+ <TabsTrigger value="overview">Overview</TabsTrigger>+ <TabsTrigger value="networking">Networking</TabsTrigger>+ <TabsTrigger value="logs">Logs</TabsTrigger>+ <TabsTrigger value="advanced">Advanced</TabsTrigger>+ </TabsList>++ <TabsContent value="overview" className="flex flex-col gap-4">+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">+ <Field>+ <FieldLabel>Name</FieldLabel>+ <Input value={application.name} readOnly />+ </Field>++ <Field>+ <FieldLabel>Status</FieldLabel>+ <Input value={application.effectiveStatus} readOnly />+ </Field>++ {application.effectiveStatus !== application.status && (+ <Field>+ <FieldLabel>Last known container status</FieldLabel>+ <Input value={application.status} readOnly />+ </Field>+ )}++ <Field>+ <FieldLabel>Image</FieldLabel>+ <Input value={application.image} readOnly />+ </Field>++ <Field>+ <FieldLabel>Server</FieldLabel>+ <Input+ value={+ application.isServerReachable+ ? (application.serverName ?? 'Unknown')+ : `${application.serverName ?? 'Unknown'} (unreachable)`+ }+ readOnly+ />+ </Field>++ <Field>+ <FieldLabel>Container</FieldLabel>+ <Input value={application.containerName} readOnly />+ </Field>++ <Field>+ <FieldLabel>Runtime container ID</FieldLabel>+ <Input value={application.runtimeContainerId ?? 'Not available'} readOnly />+ </Field>+ </div>++ <Field>+ <FieldLabel>Status message</FieldLabel>+ <Textarea+ value={application.effectiveStatusMessage ?? 'No status message yet.'}+ readOnly+ className="min-h-20"+ />+ </Field>+ </TabsContent>++ <TabsContent value="networking" className="flex flex-col gap-4">+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">+ <Field>+ <FieldLabel>Mesh namespace</FieldLabel>+ <Input value={application.meshNamespace} readOnly />+ </Field>++ <Field>+ <FieldLabel>Mesh FQDN</FieldLabel>+ <Input value={application.meshFqdn} readOnly />+ </Field>++ <Field>+ <FieldLabel>Internal port</FieldLabel>+ <Input value={application.internalPort?.toString() ?? 'Not configured'} readOnly />+ </Field>++ <Field>+ <FieldLabel>Public ingress</FieldLabel>+ <Input value={application.ingressEnabled ? 'Enabled' : 'Private'} readOnly />+ </Field>+ </div>++ <Field>+ <FieldLabel>Domains</FieldLabel>+ <Textarea+ value={+ application.domains.length > 0+ ? application.domains.join('\n')+ : 'No public domains configured.'+ }+ readOnly+ />+ </Field>++ <div className="flex flex-wrap items-center gap-2">+ <ApplicationIngressButton application={application} isSaving={isIngressSaving} onToggle={onToggleIngress} />+ <span className="text-xs text-muted-foreground">+ Use this action to publish or private-route the app through the server ingress.+ </span>+ </div>+ </TabsContent>++ <TabsContent value="logs">+ <ApplicationLogsTab key={application.id} application={application} />+ </TabsContent>++ <TabsContent value="advanced" className="flex flex-col gap-4">+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">+ <Field>+ <FieldLabel>Application ID</FieldLabel>+ <Input value={application.id} readOnly />+ </Field>++ <Field>+ <FieldLabel>Canvas position</FieldLabel>+ <Input value={`${application.canvasX}, ${application.canvasY}`} readOnly />+ </Field>+ </div>++ <Field>+ <FieldLabel>Raw app config</FieldLabel>+ <Textarea+ value={JSON.stringify(application, null, 2)}+ readOnly+ className="min-h-80 font-mono text-xs"+ />+ </Field>+ </TabsContent>+ </Tabs>+ </div>+ </>+ )}+ </SheetContent>+ </Sheet>+ );+}diff --git a/resources/js/v5/components/canvas/caddy-ingress-card.tsx b/resources/js/v5/components/canvas/caddy-ingress-card.tsxnew file mode 100644index 0000000000..7088e3716d--- /dev/null+++ b/resources/js/v5/components/canvas/caddy-ingress-card.tsx@@ -0,0 +1,49 @@+import { memo, type PointerEvent } from 'react';++import { statusBadgeClass } from '@/components/canvas/status-badge';+import { cn } from '@/lib/utils';+import type { V5CaddyIngress } from '@/types';++type CaddyIngressCardProps = {+ ingress: V5CaddyIngress;+ onDragStart: (event: PointerEvent<HTMLDivElement>, ingress: V5CaddyIngress) => void;+};++export const CaddyIngressCard = memo(function CaddyIngressCard({ ingress, onDragStart }: CaddyIngressCardProps) {+ return (+ <div+ className="absolute w-80 select-none overflow-hidden rounded-xl border border-warning/40 bg-card p-4 shadow-xl transition-shadow hover:shadow-2xl"+ style={{+ transform: `translate3d(${ingress.canvasX}px, ${ingress.canvasY}px, 0)`,+ }}+ onPointerDown={(event) => onDragStart(event, ingress)}+ >+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="truncate text-sm font-semibold text-foreground">Caddy ingress</div>+ <div className="mt-1 truncate text-xs text-muted-foreground">{ingress.name}</div>+ </div>+ <span+ className={cn(+ 'shrink-0 rounded-full px-2 py-1 text-[0.625rem] font-semibold uppercase tracking-wide',+ statusBadgeClass(ingress.status),+ )}+ title={ingress.statusMessage ?? undefined}+ >+ {ingress.status}+ </span>+ </div>++ <dl className="mt-4 grid gap-2 text-xs">+ <div className="grid grid-cols-[auto_minmax(0,1fr)] gap-3">+ <dt className="shrink-0 text-muted-foreground">Server</dt>+ <dd className="truncate text-right font-medium text-foreground">{ingress.name}</dd>+ </div>+ <div className="grid grid-cols-[auto_minmax(0,1fr)] gap-3">+ <dt className="shrink-0 text-muted-foreground">Host</dt>+ <dd className="truncate text-right font-mono text-[0.6875rem] text-foreground">{ingress.host}</dd>+ </div>+ </dl>+ </div>+ );+});diff --git a/resources/js/v5/components/canvas/canvas-notice.tsx b/resources/js/v5/components/canvas/canvas-notice.tsxnew file mode 100644index 0000000000..ad49364f6e--- /dev/null+++ b/resources/js/v5/components/canvas/canvas-notice.tsx@@ -0,0 +1,38 @@+type CanvasNoticeProps = {+ message: string;+ description?: string;+ onDismiss: () => void;+ variant?: 'danger' | 'success' | 'info';+};++const noticeClasses = {+ danger: 'border-destructive/40 text-destructive',+ success: 'border-emerald-500/40 text-emerald-400',+ info: 'border-blue-500/40 text-blue-400',+};++export function CanvasNotice({ message, description, onDismiss, variant = 'danger' }: CanvasNoticeProps) {+ return (+ <div+ className={`fixed right-4 top-20 z-50 flex max-w-sm items-start gap-3 rounded-lg border bg-card p-3 text-sm shadow-lg ${noticeClasses[variant]}`}+ >+ <div className="min-w-0">+ <p className="font-medium">{message}</p>+ {description ? (+ <p className="mt-1 max-h-32 overflow-auto whitespace-pre-wrap break-words text-xs text-muted-foreground">+ {description}+ </p>+ ) : null}+ </div>+ <button+ type="button"+ aria-label="Dismiss notice"+ onClick={onDismiss}+ className="-m-1 rounded p-1 opacity-80 transition hover:bg-background/20 hover:opacity-100"+ >+ <span aria-hidden="true">×</span>+ <span className="sr-only">Dismiss notice</span>+ </button>+ </div>+ );+}diff --git a/resources/js/v5/components/canvas/canvas-toolbar.tsx b/resources/js/v5/components/canvas/canvas-toolbar.tsxnew file mode 100644index 0000000000..1ddbe3e7c5--- /dev/null+++ b/resources/js/v5/components/canvas/canvas-toolbar.tsx@@ -0,0 +1,139 @@+import { memo } from 'react';++import { MAX_CANVAS_ZOOM, MIN_CANVAS_ZOOM } from '@/lib/use-canvas-viewport';+import type { V5NginxServer } from '@/types';++export type CanvasStatusCounts = {+ running: number;+ failed: number;+ unknown: number;+};++type CanvasToolbarProps = {+ nginxServers: V5NginxServer[];+ selectedNginxServerId: string;+ onSelectNginxServer: (serverId: string) => void;+ nginxImage: string;+ onNginxImageChange: (image: string) => void;+ isCreating: boolean;+ onDeploy: () => void;+ onCenter: () => void;+ zoom: number;+ onZoomIn: () => void;+ onZoomOut: () => void;+ isRefreshing: boolean;+ onRefresh: () => void;+ applicationsCount: number;+ statusCounts: CanvasStatusCounts;+};++export const CanvasToolbar = memo(function CanvasToolbar({+ nginxServers,+ selectedNginxServerId,+ onSelectNginxServer,+ nginxImage,+ onNginxImageChange,+ isCreating,+ onDeploy,+ onCenter,+ zoom,+ onZoomIn,+ onZoomOut,+ isRefreshing,+ onRefresh,+ applicationsCount,+ statusCounts,+}: CanvasToolbarProps) {+ return (+ <div className="absolute left-4 top-20 z-30 flex max-w-[calc(100%-2rem)] flex-wrap items-center gap-2 rounded-xl border border-border bg-background/95 p-2 shadow-lg backdrop-blur">+ <select+ aria-label="Select nginx server"+ value={selectedNginxServerId}+ onChange={(event) => onSelectNginxServer(event.target.value)}+ disabled={isCreating || nginxServers.length === 0}+ className="rounded-lg border border-border bg-background px-3 py-2 text-sm font-medium text-foreground transition disabled:cursor-not-allowed disabled:opacity-60"+ >+ {nginxServers.length === 0 ? (+ <option value="">No servers available</option>+ ) : (+ nginxServers.map((server) => (+ <option key={server.id} value={server.id}>+ {server.name} ({server.host})+ </option>+ ))+ )}+ </select>+ <input+ type="text"+ aria-label="Nginx image"+ value={nginxImage}+ onChange={(event) => onNginxImageChange(event.target.value)}+ disabled={isCreating}+ className="w-72 rounded-lg border border-border bg-background px-3 py-2 text-sm font-medium text-foreground transition disabled:cursor-not-allowed disabled:opacity-60"+ />+ <button+ type="button"+ onClick={onDeploy}+ disabled={isCreating || nginxServers.length === 0}+ className="rounded-lg bg-warning px-3 py-2 text-sm font-semibold text-black transition hover:bg-warning/90 disabled:cursor-not-allowed disabled:opacity-60"+ >+ {isCreating ? 'Deploying…' : 'Deploy'}+ </button>+ <button+ type="button"+ onClick={onCenter}+ className="rounded-lg border border-border px-3 py-2 text-sm font-medium text-foreground transition hover:bg-muted"+ >+ Center+ </button>+ <div className="flex items-center overflow-hidden rounded-lg border border-border">+ <button+ type="button"+ aria-label="Zoom out"+ onClick={onZoomOut}+ className="px-3 py-2 text-sm font-semibold text-foreground transition hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50"+ disabled={zoom <= MIN_CANVAS_ZOOM}+ >+ −+ </button>+ <span className="min-w-14 border-x border-border px-2 py-2 text-center text-xs font-medium text-muted-foreground">+ {Math.round(zoom * 100)}%+ </span>+ <button+ type="button"+ aria-label="Zoom in"+ onClick={onZoomIn}+ className="px-3 py-2 text-sm font-semibold text-foreground transition hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50"+ disabled={zoom >= MAX_CANVAS_ZOOM}+ >+ ++ </button>+ </div>+ <button+ type="button"+ onClick={onRefresh}+ disabled={isRefreshing}+ className="rounded-lg border border-border px-3 py-2 text-sm font-medium text-foreground transition hover:bg-muted disabled:cursor-not-allowed disabled:opacity-60"+ >+ {isRefreshing ? 'Refreshing…' : 'Refresh state'}+ </button>+ <div className="hidden items-center gap-2 px-2 text-xs text-muted-foreground sm:flex">+ <span>{applicationsCount} apps</span>+ <span>•</span>+ <span>{statusCounts.running} running</span>+ {statusCounts.failed > 0 && (+ <>+ <span>•</span>+ <span className="text-destructive">{statusCounts.failed} failed</span>+ </>+ )}+ {statusCounts.unknown > 0 && (+ <>+ <span>•</span>+ <span>{statusCounts.unknown} unknown</span>+ </>+ )}+ </div>+ </div>+ );+});diff --git a/resources/js/v5/components/canvas/connection-lines.tsx b/resources/js/v5/components/canvas/connection-lines.tsxnew file mode 100644index 0000000000..fc7e2bdbda--- /dev/null+++ b/resources/js/v5/components/canvas/connection-lines.tsx@@ -0,0 +1,111 @@+import { memo, useMemo, type MouseEvent } from 'react';++import { connectorPoint, shortestConnectionPoints, type DraftConnection } from '@/lib/canvas-geometry';+import { cn } from '@/lib/utils';+import type { CanvasConnection } from '@/lib/use-canvas-connections';+import type { V5Application } from '@/types';++type ConnectionLineProps = {+ connection: CanvasConnection;+ fromApplication: V5Application;+ toApplication: V5Application;+ isSelected: boolean;+ onSelect: (event: MouseEvent<SVGLineElement>, connectionId: string) => void;+};++const ConnectionLine = memo(function ConnectionLine({ connection, fromApplication, toApplication, isSelected, onSelect }: ConnectionLineProps) {+ const points = useMemo(() => shortestConnectionPoints(fromApplication, toApplication), [fromApplication, toApplication]);++ return (+ <g>+ <line+ x1={points.from.x}+ y1={points.from.y}+ x2={points.to.x}+ y2={points.to.y}+ aria-label="Select connection"+ className="pointer-events-auto cursor-pointer"+ stroke="transparent"+ strokeWidth={12}+ strokeLinecap="round"+ onPointerDown={(event) => event.stopPropagation()}+ onClick={(event) => onSelect(event, connection.id)}+ />+ <line+ x1={points.from.x}+ y1={points.from.y}+ x2={points.to.x}+ y2={points.to.y}+ className={cn('pointer-events-none', isSelected ? 'stroke-destructive' : 'stroke-warning')}+ strokeWidth={isSelected ? 4 : 2}+ strokeDasharray="6 6"+ strokeLinecap="round"+ markerEnd={isSelected ? 'url(#dashboard-connection-arrow)' : undefined}+ />+ </g>+ );+});++type ConnectionLinesProps = {+ connections: CanvasConnection[];+ applications: V5Application[];+ selectedConnectionId: string | null;+ draftConnection: DraftConnection | null;+ onSelectConnection: (event: MouseEvent<SVGLineElement>, connectionId: string) => void;+};++export function ConnectionLines({ connections, applications, selectedConnectionId, draftConnection, onSelectConnection }: ConnectionLinesProps) {+ const applicationsById = useMemo(() => new Map(applications.map((application) => [application.id, application])), [applications]);+ const draftFromApplication = draftConnection ? applicationsById.get(draftConnection.from.applicationId) : undefined;+ const draftFrom = draftConnection && draftFromApplication ? connectorPoint(draftFromApplication, draftConnection.from.side) : null;++ return (+ <svg className="pointer-events-none absolute inset-0 overflow-visible">+ <defs>+ <marker+ id="dashboard-connection-arrow"+ viewBox="0 0 10 10"+ refX="9"+ refY="5"+ markerWidth="16"+ markerHeight="16"+ orient="auto"+ markerUnits="userSpaceOnUse"+ >+ <path d="M 0 0 L 10 5 L 0 10 z" fill="var(--destructive)" />+ </marker>+ </defs>+ {connections.map((connection) => {+ const fromApplication = applicationsById.get(connection.fromApplicationId);+ const toApplication = applicationsById.get(connection.toApplicationId);++ if (!fromApplication || !toApplication) {+ return null;+ }++ return (+ <ConnectionLine+ key={connection.id}+ connection={connection}+ fromApplication={fromApplication}+ toApplication={toApplication}+ isSelected={selectedConnectionId === connection.id}+ onSelect={onSelectConnection}+ />+ );+ })}+ {draftConnection && draftFrom && (+ <line+ x1={draftFrom.x}+ y1={draftFrom.y}+ x2={draftConnection.toX}+ y2={draftConnection.toY}+ className="stroke-warning/70"+ strokeWidth={2}+ strokeDasharray="6 6"+ strokeLinecap="round"+ />+ )}+ </svg>+ );+}diff --git a/resources/js/v5/components/canvas/connection-ports-editor.tsx b/resources/js/v5/components/canvas/connection-ports-editor.tsxnew file mode 100644index 0000000000..f44f00cf0b--- /dev/null+++ b/resources/js/v5/components/canvas/connection-ports-editor.tsx@@ -0,0 +1,146 @@+import { useMemo } from 'react';++import { shortestConnectionPoints } from '@/lib/canvas-geometry';+import { activeConnectionPorts, type CanvasConnection } from '@/lib/use-canvas-connections';+import { cn } from '@/lib/utils';+import type { V5Application } from '@/types';++type ConnectionPortsEditorProps = {+ connection: CanvasConnection;+ applications: V5Application[];+ portInput: string;+ onPortInputChange: (connectionId: string, value: string) => void;+ onUpdateDirection: (connectionId: string, fromApplicationId: string, toApplicationId: string) => void;+ onAddPort: (connectionId: string) => void;+ onRemovePort: (connectionId: string, port: string) => void;+ onDelete: (connectionId: string) => void;+};++export function ConnectionPortsEditor({+ connection,+ applications,+ portInput,+ onPortInputChange,+ onUpdateDirection,+ onAddPort,+ onRemovePort,+ onDelete,+}: ConnectionPortsEditorProps) {+ const fromApplication = applications.find((candidate) => candidate.id === connection.fromApplicationId);+ const toApplication = applications.find((candidate) => candidate.id === connection.toApplicationId);+ const points = useMemo(+ () => (fromApplication && toApplication ? shortestConnectionPoints(fromApplication, toApplication) : null),+ [fromApplication, toApplication],+ );++ if (!points) {+ return null;+ }++ function applicationDirectionLabel(applicationId: string): string {+ const application = applications.find((candidate) => candidate.id === applicationId);++ if (!application) {+ return 'Unknown app';+ }++ return `${application.name} (${application.id.slice(0, 8)})`;+ }++ const activePorts = activeConnectionPorts(connection);+ const firstApplicationId = connection.applicationIds[0];+ const secondApplicationId = connection.applicationIds[1];+ const isForwardDirection =+ connection.fromApplicationId === firstApplicationId && connection.toApplicationId === secondApplicationId;++ return (+ <div+ className="absolute z-20 flex w-72 -translate-x-1/2 -translate-y-1/2 flex-col gap-3 rounded-md border border-border bg-card p-3 shadow-lg"+ style={{+ left: (points.from.x + points.to.x) / 2,+ top: (points.from.y + points.to.y) / 2,+ }}+ onPointerDown={(event) => event.stopPropagation()}+ onClick={(event) => event.stopPropagation()}+ >+ <div className="space-y-2">+ <div className="text-[0.625rem] font-semibold uppercase tracking-wide text-muted-foreground">Firewall</div>+ <div className="grid gap-1">+ <button+ type="button"+ onClick={() => onUpdateDirection(connection.id, firstApplicationId, secondApplicationId)}+ className={cn(+ 'rounded-sm border px-2 py-1 text-left text-xs transition',+ isForwardDirection+ ? 'border-warning/40 bg-warning/10 text-foreground hover:bg-warning/20'+ : 'border-border text-muted-foreground hover:bg-muted hover:text-foreground',+ )}+ >+ {applicationDirectionLabel(firstApplicationId)} → {applicationDirectionLabel(secondApplicationId)}+ </button>+ <button+ type="button"+ onClick={() => onUpdateDirection(connection.id, secondApplicationId, firstApplicationId)}+ className={cn(+ 'rounded-sm border px-2 py-1 text-left text-xs transition',+ !isForwardDirection+ ? 'border-warning/40 bg-warning/10 text-foreground hover:bg-warning/20'+ : 'border-border text-muted-foreground hover:bg-muted hover:text-foreground',+ )}+ >+ {applicationDirectionLabel(secondApplicationId)} → {applicationDirectionLabel(firstApplicationId)}+ </button>+ </div>+ </div>++ <div className="space-y-2">+ <div className="text-[0.625rem] font-semibold uppercase tracking-wide text-muted-foreground">Allowed ports</div>+ <div className="flex flex-wrap gap-1">+ {activePorts.length === 0 && <span className="text-xs text-muted-foreground">No ports yet.</span>}+ {activePorts.map((port) => (+ <button+ key={port}+ type="button"+ onClick={() => onRemovePort(connection.id, port)}+ className="rounded-full border border-border bg-muted px-2 py-1 text-[0.625rem] font-medium text-foreground transition hover:border-destructive/40 hover:text-destructive"+ >+ {port} ×+ </button>+ ))}+ </div>+ <div className="flex gap-1">+ <input+ type="number"+ min={1}+ max={65535}+ placeholder="Port"+ value={portInput}+ onChange={(event) => onPortInputChange(connection.id, event.target.value)}+ onKeyDown={(event) => {+ if (event.key === 'Enter') {+ onAddPort(connection.id);+ }+ }}+ className="min-w-0 flex-1 rounded-sm border border-border bg-background px-2 py-1 text-xs text-foreground outline-none transition focus:border-warning"+ />+ <button+ type="button"+ onClick={() => onAddPort(connection.id)}+ className="rounded-sm border border-border px-2 py-1 text-xs font-medium text-foreground transition hover:bg-muted"+ >+ Add+ </button>+ </div>+ </div>++ <button+ type="button"+ aria-label="Delete connection"+ onClick={() => onDelete(connection.id)}+ className="rounded-sm border border-destructive/40 px-2 py-1 text-[0.625rem] font-semibold uppercase tracking-wide text-destructive transition hover:bg-destructive/10"+ >+ Delete+ </button>+ </div>+ );+}diff --git a/resources/js/v5/components/canvas/ingress-dialog.tsx b/resources/js/v5/components/canvas/ingress-dialog.tsxnew file mode 100644index 0000000000..d59618f2f3--- /dev/null+++ b/resources/js/v5/components/canvas/ingress-dialog.tsx@@ -0,0 +1,82 @@+import { Button } from '@/components/ui/button';+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';+import { Field, FieldLabel } from '@/components/ui/field';+import { Input } from '@/components/ui/input';+import type { IngressModalState } from '@/lib/use-application-ingress';++type IngressDialogProps = {+ modal: IngressModalState;+ isSaving: boolean;+ onDomainsChange: (domains: string) => void;+ onInternalPortChange: (internalPort: string) => void;+ onSubmit: () => void;+ onClose: () => void;+};++export function IngressDialog({ modal, isSaving, onDomainsChange, onInternalPortChange, onSubmit, onClose }: IngressDialogProps) {+ return (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open && !isSaving) {+ onClose();+ }+ }}+ >+ <DialogContent className="max-w-lg" showCloseButton>+ <DialogHeader>+ <DialogTitle>Enable app ingress</DialogTitle>+ <DialogDescription>+ Route public domains to {modal.application.name} through the server ingress.+ </DialogDescription>+ </DialogHeader>++ <form+ className="mt-6 flex flex-col gap-4"+ onSubmit={(event) => {+ event.preventDefault();+ onSubmit();+ }}+ >+ <Field>+ <FieldLabel>Domains</FieldLabel>+ <Input+ type="text"+ value={modal.domains}+ onChange={(event) => onDomainsChange(event.target.value)}+ placeholder="example.com, www.example.com"+ />+ <span className="text-xs text-muted-foreground">+ Use hostnames only, separated by commas. No scheme, path, wildcard, or port.+ </span>+ </Field>++ <Field>+ <FieldLabel>Internal port</FieldLabel>+ <Input+ type="number"+ min="1"+ max="65535"+ value={modal.internalPort}+ onChange={(event) => onInternalPortChange(event.target.value)}+ placeholder="3000"+ />+ </Field>++ {modal.error && (+ <div className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">+ <p className="font-medium">Ingress update failed</p>+ <p className="mt-1 text-destructive/90">{modal.error}</p>+ </div>+ )}++ <div className="flex justify-end">+ <Button type="submit" variant="coolify" disabled={isSaving}>+ {isSaving ? 'Saving...' : 'Enable ingress'}+ </Button>+ </div>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/resources/js/v5/components/canvas/status-badge.ts b/resources/js/v5/components/canvas/status-badge.tsnew file mode 100644index 0000000000..2dfd3d4691--- /dev/null+++ b/resources/js/v5/components/canvas/status-badge.ts@@ -0,0 +1,19 @@+export function statusBadgeClass(status: string): string {+ if (status === 'running') {+ return 'bg-emerald-500/15 text-emerald-400';+ }++ if (['creating', 'starting'].includes(status)) {+ return 'bg-warning/15 text-warning';+ }++ if (status === 'unknown') {+ return 'bg-muted text-muted-foreground';+ }++ if (['failed', 'exited', 'unreachable'].includes(status)) {+ return 'bg-destructive/15 text-destructive';+ }++ return 'bg-muted text-muted-foreground';+}diff --git a/resources/js/v5/lib/api.ts b/resources/js/v5/lib/api.tsnew file mode 100644index 0000000000..6a6197af29--- /dev/null+++ b/resources/js/v5/lib/api.ts@@ -0,0 +1,7 @@+/**+ * General-purpose JSON request helper for v5 pages: same-origin credentials,+ * CSRF header, and a 30 second timeout on every request. The implementation+ * currently lives in canvas-api.ts; import from this module in non-canvas+ * code so the canvas-specific name can be retired later.+ */+export { canvasRequest as apiRequest } from '@/lib/canvas-api';diff --git a/resources/js/v5/lib/canvas-api.ts b/resources/js/v5/lib/canvas-api.tsnew file mode 100644index 0000000000..de2a5d0a03--- /dev/null+++ b/resources/js/v5/lib/canvas-api.ts@@ -0,0 +1,24 @@+import { csrfToken } from '@/lib/csrf';++type CanvasRequestOptions = {+ method: 'GET' | 'POST' | 'PATCH' | 'DELETE';+ body?: unknown;+};++/**+ * Shared JSON fetch for the canvas endpoints: same-origin credentials,+ * CSRF header, and a 30 second timeout on every request.+ */+export function canvasRequest(url: string, { method, body }: CanvasRequestOptions): Promise<Response> {+ return fetch(url, {+ method,+ credentials: 'same-origin',+ headers: {+ Accept: 'application/json',+ ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),+ 'X-CSRF-TOKEN': csrfToken(),+ },+ body: body !== undefined ? JSON.stringify(body) : undefined,+ signal: AbortSignal.timeout(30_000),+ });+}diff --git a/resources/js/v5/lib/canvas-geometry.ts b/resources/js/v5/lib/canvas-geometry.tsnew file mode 100644index 0000000000..30edfbb136--- /dev/null+++ b/resources/js/v5/lib/canvas-geometry.ts@@ -0,0 +1,132 @@+import { resolveCanvasNodeLayout, resolveCanvasNodePosition, type CanvasNodeBounds } from '@/lib/canvas-collision';+import type { V5Application, V5CaddyIngress } from '@/types';++export const APPLICATION_CARD_WIDTH = 320;+export const APPLICATION_CARD_HEIGHT = 160;+export const CANVAS_CARD_GAP = 16;++export type ConnectorSide = 'top' | 'right' | 'bottom' | 'left';++export const CONNECTOR_SIDES: ConnectorSide[] = ['top', 'right', 'bottom', 'left'];++export type CanvasPoint = {+ x: number;+ y: number;+};++export type CanvasCardNode = {+ canvasX: number;+ canvasY: number;+};++export type ConnectionEndpoint = {+ applicationId: string;+ side: ConnectorSide;+};++export type DraftConnection = {+ from: ConnectionEndpoint;+ toX: number;+ toY: number;+};++export function connectorPoint(node: CanvasCardNode, side: ConnectorSide): CanvasPoint {+ switch (side) {+ case 'top':+ return { x: node.canvasX + APPLICATION_CARD_WIDTH / 2, y: node.canvasY };+ case 'right':+ return { x: node.canvasX + APPLICATION_CARD_WIDTH, y: node.canvasY + APPLICATION_CARD_HEIGHT / 2 };+ case 'bottom':+ return { x: node.canvasX + APPLICATION_CARD_WIDTH / 2, y: node.canvasY + APPLICATION_CARD_HEIGHT };+ case 'left':+ return { x: node.canvasX, y: node.canvasY + APPLICATION_CARD_HEIGHT / 2 };+ }+}++export function shortestConnectionPoints(fromNode: CanvasCardNode, toNode: CanvasCardNode): { from: CanvasPoint; to: CanvasPoint } {+ let shortest = {+ from: connectorPoint(fromNode, 'top'),+ to: connectorPoint(toNode, 'top'),+ distance: Number.POSITIVE_INFINITY,+ };++ for (const fromSide of CONNECTOR_SIDES) {+ const from = connectorPoint(fromNode, fromSide);++ for (const toSide of CONNECTOR_SIDES) {+ const to = connectorPoint(toNode, toSide);+ const distance = Math.hypot(from.x - to.x, from.y - to.y);++ if (distance < shortest.distance) {+ shortest = { from, to, distance };+ }+ }+ }++ return { from: shortest.from, to: shortest.to };+}++function applicationBounds(application: V5Application): CanvasNodeBounds {+ return {+ id: `application-${application.id}`,+ x: application.canvasX,+ y: application.canvasY,+ width: APPLICATION_CARD_WIDTH,+ height: APPLICATION_CARD_HEIGHT,+ };+}++function ingressBounds(ingress: V5CaddyIngress): CanvasNodeBounds {+ return {+ id: `ingress-${ingress.id}`,+ x: ingress.canvasX,+ y: ingress.canvasY,+ width: APPLICATION_CARD_WIDTH,+ height: APPLICATION_CARD_HEIGHT,+ };+}++export function canvasCollisionNodes(applications: V5Application[], ingresses: V5CaddyIngress[]): CanvasNodeBounds[] {+ return [...applications.map(applicationBounds), ...ingresses.map(ingressBounds)];+}++export function settleCanvasResources(+ nextApplications: V5Application[],+ nextIngresses: V5CaddyIngress[],+): { applications: V5Application[]; ingresses: V5CaddyIngress[] } {+ const settledNodes = resolveCanvasNodeLayout(canvasCollisionNodes(nextApplications, nextIngresses), CANVAS_CARD_GAP);+ const positionsById = new Map(settledNodes.map((node) => [node.id, node]));++ return {+ applications: nextApplications.map((application) => {+ const position = positionsById.get(`application-${application.id}`);++ return position ? { ...application, canvasX: position.x, canvasY: position.y } : application;+ }),+ ingresses: nextIngresses.map((ingress) => {+ const position = positionsById.get(`ingress-${ingress.id}`);++ return position ? { ...ingress, canvasX: position.x, canvasY: position.y } : ingress;+ }),+ };+}++export function resolveApplicationPosition(+ application: V5Application,+ applications: V5Application[],+ ingresses: V5CaddyIngress[],+): V5Application {+ const position = resolveCanvasNodePosition(applicationBounds(application), canvasCollisionNodes(applications, ingresses), CANVAS_CARD_GAP);++ return { ...application, canvasX: position.x, canvasY: position.y };+}++export function resolveIngressPosition(+ ingress: V5CaddyIngress,+ applications: V5Application[],+ ingresses: V5CaddyIngress[],+): V5CaddyIngress {+ const position = resolveCanvasNodePosition(ingressBounds(ingress), canvasCollisionNodes(applications, ingresses), CANVAS_CARD_GAP);++ return { ...ingress, canvasX: position.x, canvasY: position.y };+}diff --git a/resources/js/v5/lib/optimistic.ts b/resources/js/v5/lib/optimistic.tsnew file mode 100644index 0000000000..7d2eb2afca--- /dev/null+++ b/resources/js/v5/lib/optimistic.ts@@ -0,0 +1,57 @@+export type OptimisticRequestResult<TPayload> =+ | { ok: true; payload: TPayload }+ | { ok: false; errorMessage?: string };++export type OptimisticUpdateOptions<TPayload> = {+ /** Apply the optimistic state change before the request is sent. */+ apply?: () => void;+ /** Restore the previous state after a failed request. */+ rollback?: () => void;+ /** Perform the persistence request; return ok=false (or throw) on failure. */+ request: () => Promise<OptimisticRequestResult<TPayload>>;+ /** Notice used when the failure carries no specific error message. */+ fallbackErrorMessage: string;+ notify: (message: string | null) => void;+ /** Reconcile local state with the server payload after success. */+ onSuccess?: (payload: TPayload) => void;+ /** Runs after success or failure, e.g. to clear pending markers. */+ onSettled?: () => void;+};++/**+ * Unified optimistic-update flow: apply the local change, persist it, and on+ * any failure roll the local state back and surface a notice.+ */+export async function runOptimisticUpdate<TPayload = void>({+ apply,+ rollback,+ request,+ fallbackErrorMessage,+ notify,+ onSuccess,+ onSettled,+}: OptimisticUpdateOptions<TPayload>): Promise<boolean> {+ apply?.();++ try {+ const result = await request();++ if (!result.ok) {+ rollback?.();+ notify(result.errorMessage ?? fallbackErrorMessage);++ return false;+ }++ onSuccess?.(result.payload);++ return true;+ } catch (error) {+ rollback?.();+ notify(error instanceof Error ? error.message : fallbackErrorMessage);++ return false;+ } finally {+ onSettled?.();+ }+}diff --git a/resources/js/v5/lib/use-application-ingress.ts b/resources/js/v5/lib/use-application-ingress.tsnew file mode 100644index 0000000000..10db9ac359--- /dev/null+++ b/resources/js/v5/lib/use-application-ingress.ts@@ -0,0 +1,169 @@+import { useCallback, useRef, useState } from 'react';++import { canvasRequest } from '@/lib/canvas-api';+import { usePendingIds } from '@/lib/use-pending-ids';+import type { CanvasNotify } from '@/lib/use-canvas-connections';+import type { V5Application } from '@/types';++export type IngressModalState = {+ application: V5Application;+ domains: string;+ internalPort: string;+ error: string | null;+};++export function isValidDomain(domain: string): boolean {+ if (domain.length < 1 || domain.length > 253 || domain.startsWith('.') || domain.endsWith('.')) {+ return false;+ }++ return domain.split('.').every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label));+}++/**+ * Owns the application ingress modal and the enable/disable persistence flow,+ * tracking per-application saving state through usePendingIds.+ */+export function useApplicationIngress(options: {+ notify: CanvasNotify;+ onApplicationUpdated: (application: V5Application) => void;+}) {+ const { notify, onApplicationUpdated } = options;+ const [ingressModal, setIngressModal] = useState<IngressModalState | null>(null);+ const savingIngressApplications = usePendingIds<string>();+ const ingressModalRef = useRef<IngressModalState | null>(null);++ ingressModalRef.current = ingressModal;++ const saveApplicationIngress = useCallback(+ async (application: V5Application, enabled: boolean, domains: string[], internalPort: number | null): Promise<void> => {+ notify(null);+ savingIngressApplications.start(application.id);++ const reportError = (message: string): void => {+ if (ingressModalRef.current) {+ setIngressModal((currentModal) => (currentModal ? { ...currentModal, error: message } : currentModal));+ } else {+ notify(message);+ }+ };++ try {+ const response = await canvasRequest(`/v5/applications/${application.id}/ingress`, {+ method: 'PATCH',+ body: {+ ingress_enabled: enabled,+ internal_port: internalPort,+ domains,+ },+ });++ if (!response.ok) {+ const payload = (await response.json().catch(() => null)) as { message?: string } | null;++ reportError(payload?.message ?? 'Could not update application ingress.');++ return;+ }++ const payload = (await response.json()) as { application: V5Application };++ onApplicationUpdated(payload.application);+ setIngressModal(null);+ } catch (error) {+ reportError(error instanceof Error ? error.message : 'Could not update application ingress.');+ } finally {+ savingIngressApplications.finish(application.id);+ }+ },+ [notify, onApplicationUpdated, savingIngressApplications.start, savingIngressApplications.finish],+ );++ const openApplicationIngressModal = useCallback(+ (application: V5Application): void => {+ notify(null);++ if (!application.serverIngressEnabled) {+ notify('Enable ingress on the server before enabling app ingress.');++ return;+ }++ setIngressModal({+ application,+ domains: application.domains.join(', '),+ internalPort: application.internalPort ? String(application.internalPort) : '',+ error: null,+ });+ },+ [notify],+ );++ const toggleApplicationIngress = useCallback(+ (application: V5Application): void => {+ if (application.ingressEnabled) {+ void saveApplicationIngress(application, false, application.domains, application.internalPort);+ } else {+ openApplicationIngressModal(application);+ }+ },+ [saveApplicationIngress, openApplicationIngressModal],+ );++ const submitApplicationIngress = useCallback(async (): Promise<void> => {+ const currentModal = ingressModalRef.current;++ if (!currentModal) {+ return;+ }++ const domains = currentModal.domains+ .split(',')+ .map((domain) => domain.trim().toLowerCase())+ .filter(Boolean);+ const internalPort = Number(currentModal.internalPort);+ const invalidDomain = domains.find((domain) => !isValidDomain(domain));++ if (domains.length === 0) {+ setIngressModal({ ...currentModal, error: 'Add at least one valid domain.' });++ return;+ }++ if (invalidDomain) {+ setIngressModal({ ...currentModal, error: `${invalidDomain} is not a valid domain.` });++ return;+ }++ if (!Number.isInteger(internalPort) || internalPort < 1 || internalPort > 65535) {+ setIngressModal({ ...currentModal, error: 'Choose a valid internal port between 1 and 65535.' });++ return;+ }++ await saveApplicationIngress(currentModal.application, true, [...new Set(domains)], internalPort);+ }, [saveApplicationIngress]);++ const closeIngressModal = useCallback((): void => {+ setIngressModal(null);+ }, []);++ const setIngressModalDomains = useCallback((domains: string): void => {+ setIngressModal((currentModal) => (currentModal ? { ...currentModal, domains, error: null } : currentModal));+ }, []);++ const setIngressModalInternalPort = useCallback((internalPort: string): void => {+ setIngressModal((currentModal) => (currentModal ? { ...currentModal, internalPort, error: null } : currentModal));+ }, []);++ return {+ ingressModal,+ closeIngressModal,+ setIngressModalDomains,+ setIngressModalInternalPort,+ submitApplicationIngress,+ toggleApplicationIngress,+ savingIngressApplications,+ };+}diff --git a/resources/js/v5/lib/use-canvas-channel.ts b/resources/js/v5/lib/use-canvas-channel.tsnew file mode 100644index 0000000000..0864f20acc--- /dev/null+++ b/resources/js/v5/lib/use-canvas-channel.ts@@ -0,0 +1,19 @@+import { useTeamChannel } from '@/lib/use-team-channel';+import type { V5Application, V5CaddyIngress } from '@/types';++export type V5CanvasResourceUpdatedEvent = {+ application: V5Application | null;+ applications?: V5Application[];+ caddyIngress: V5CaddyIngress | null;+};++/**+ * Subscribes the canvas to the private team channel and forwards+ * `.v5.canvas.resource.updated` payloads to the latest onEvent callback+ * without resubscribing when the callback identity changes.+ */+export function useCanvasResourceChannel(teamId: number | null, onEvent: (event: V5CanvasResourceUpdatedEvent) => void): void {+ useTeamChannel(teamId, '.v5.canvas.resource.updated', (payload) => {+ onEvent(payload as V5CanvasResourceUpdatedEvent);+ });+}diff --git a/resources/js/v5/lib/use-canvas-connections.ts b/resources/js/v5/lib/use-canvas-connections.tsnew file mode 100644index 0000000000..9b06b6c114--- /dev/null+++ b/resources/js/v5/lib/use-canvas-connections.ts@@ -0,0 +1,314 @@+import { useCallback, useEffect, useRef, useState } from 'react';++import { canvasRequest } from '@/lib/canvas-api';+import { runOptimisticUpdate, type OptimisticRequestResult } from '@/lib/optimistic';+import type { V5ResourceConnection } from '@/types';++export type CanvasConnection = V5ResourceConnection;++export type CanvasNotify = (message: string | null) => void;++export function connectionDirectionKey(fromApplicationId: string, toApplicationId: string): string {+ return `${fromApplicationId}->${toApplicationId}`;+}++export function activeConnectionPorts(connection: CanvasConnection): string[] {+ return connection.portsByDirection[connectionDirectionKey(connection.fromApplicationId, connection.toApplicationId)] ?? [];+}++export function pruneConnectionPortsByDirection(+ connection: CanvasConnection,+ fromApplicationId = connection.fromApplicationId,+ toApplicationId = connection.toApplicationId,+): Record<string, string[]> {+ const directionKey = connectionDirectionKey(fromApplicationId, toApplicationId);++ return {+ [directionKey]: connection.portsByDirection[directionKey] ?? [],+ };+}++function normalizeConnection(connection: V5ResourceConnection): CanvasConnection {+ return {+ ...connection,+ applicationIds: [...connection.applicationIds],+ portsByDirection: connection.portsByDirection ?? {},+ };+}++function responseErrorMessage(payload: { message?: string; detail?: string }, fallback: string): string {+ if (payload.message && payload.detail) {+ return `${payload.message} ${payload.detail}`;+ }++ return payload.message ?? fallback;+}++async function parseConnectionResponse(response: Response, fallback: string): Promise<OptimisticRequestResult<CanvasConnection>> {+ const payload = (await response.json()) as { connection?: V5ResourceConnection; message?: string; detail?: string };++ if (!response.ok || !payload.connection) {+ return { ok: false, errorMessage: responseErrorMessage(payload, fallback) };+ }++ return { ok: true, payload: normalizeConnection(payload.connection) };+}++/**+ * Owns the canvas resource connections: selection, per-direction allowed+ * ports, and the optimistic persistence flows for creating, updating, and+ * deleting connections.+ */+export function useCanvasConnections(initialConnections: V5ResourceConnection[], notify: CanvasNotify) {+ const [connections, setConnections] = useState<CanvasConnection[]>(initialConnections);+ const [selectedConnectionId, setSelectedConnectionId] = useState<string | null>(null);+ const [connectionPortInput, setConnectionPortInput] = useState<Record<string, string>>({});+ const connectionsRef = useRef(connections);++ connectionsRef.current = connections;++ const resetConnections = useCallback((nextConnections: V5ResourceConnection[]): void => {+ setConnections(nextConnections);+ setSelectedConnectionId(null);+ setConnectionPortInput({});+ }, []);++ const connectionExists = useCallback(+ (fromApplicationId: string, toApplicationId: string): boolean =>+ connectionsRef.current.some(+ (connection) =>+ (connection.fromApplicationId === fromApplicationId && connection.toApplicationId === toApplicationId) ||+ (connection.fromApplicationId === toApplicationId && connection.toApplicationId === fromApplicationId),+ ),+ [],+ );++ const replaceConnection = useCallback((nextConnection: CanvasConnection): void => {+ setConnections((currentConnections) =>+ currentConnections.map((currentConnection) =>+ currentConnection.id === nextConnection.id ? nextConnection : currentConnection,+ ),+ );+ }, []);++ const persistNewConnection = useCallback(+ async (fromApplicationId: string, toApplicationId: string): Promise<void> => {+ notify(null);++ await runOptimisticUpdate<CanvasConnection>({+ request: async () => {+ const response = await canvasRequest('/v5/resource-connections', {+ method: 'POST',+ body: {+ resource_one: { type: 'application', uuid: fromApplicationId },+ resource_two: { type: 'application', uuid: toApplicationId },+ },+ });++ return parseConnectionResponse(response, 'Could not save resource connection.');+ },+ fallbackErrorMessage: 'Could not save resource connection.',+ notify,+ onSuccess: (nextConnection) => {+ setConnections((currentConnections) => {+ const withoutDuplicate = currentConnections.filter((connection) => connection.id !== nextConnection.id);++ return [...withoutDuplicate, nextConnection];+ });+ setSelectedConnectionId(nextConnection.id);+ },+ });+ },+ [notify],+ );++ const persistConnectionPorts = useCallback(+ async (updatedConnection: CanvasConnection, previousConnection: CanvasConnection): Promise<void> => {+ const portsByDirection = Object.fromEntries(+ Object.entries(pruneConnectionPortsByDirection(updatedConnection)).map(([direction, ports]) => [+ direction,+ ports.map((port) => Number(port)).filter((port) => Number.isInteger(port)),+ ]),+ );++ await runOptimisticUpdate<CanvasConnection>({+ apply: () => replaceConnection(updatedConnection),+ rollback: () => replaceConnection(previousConnection),+ request: async () => {+ const response = await canvasRequest(`/v5/resource-connections/${updatedConnection.id}`, {+ method: 'PATCH',+ body: { ports_by_direction: portsByDirection },+ });++ return parseConnectionResponse(response, 'Could not save allowed ports.');+ },+ fallbackErrorMessage: 'Could not save allowed ports.',+ notify,+ onSuccess: replaceConnection,+ });+ },+ [notify, replaceConnection],+ );++ const deleteConnection = useCallback(+ (connectionId: string): void => {+ const connectionIndex = connectionsRef.current.findIndex((candidate) => candidate.id === connectionId);+ const connection = connectionsRef.current[connectionIndex];++ if (!connection) {+ return;+ }++ setSelectedConnectionId(null);+ void runOptimisticUpdate({+ apply: () => setConnections((currentConnections) => currentConnections.filter((candidate) => candidate.id !== connectionId)),+ rollback: () =>+ setConnections((currentConnections) => {+ if (currentConnections.some((candidate) => candidate.id === connectionId)) {+ return currentConnections;+ }++ const restoredConnections = [...currentConnections];++ restoredConnections.splice(Math.min(connectionIndex, restoredConnections.length), 0, connection);++ return restoredConnections;+ }),+ request: async () => {+ const response = await canvasRequest(`/v5/resource-connections/${connectionId}`, { method: 'DELETE' });++ return response.ok ? { ok: true, payload: undefined } : { ok: false };+ },+ fallbackErrorMessage: 'Could not delete resource connection.',+ notify,+ });+ },+ [notify],+ );++ const updateConnectionDirection = useCallback(+ (connectionId: string, fromApplicationId: string, toApplicationId: string): void => {+ const connection = connectionsRef.current.find((candidate) => candidate.id === connectionId);++ if (!connection) {+ return;+ }++ const updatedConnection = {+ ...connection,+ fromApplicationId,+ toApplicationId,+ portsByDirection: pruneConnectionPortsByDirection(connection, fromApplicationId, toApplicationId),+ };++ void persistConnectionPorts(updatedConnection, connection);+ },+ [persistConnectionPorts],+ );++ const setConnectionPortDraft = useCallback((connectionId: string, value: string): void => {+ setConnectionPortInput((currentInputs) => ({ ...currentInputs, [connectionId]: value }));+ }, []);++ const addConnectionPort = useCallback(+ (connectionId: string): void => {+ const port = connectionPortInput[connectionId]?.trim();+ const portNumber = Number(port);++ if (!port || !Number.isInteger(portNumber) || portNumber < 1 || portNumber > 65535) {+ return;+ }++ const connection = connectionsRef.current.find((candidate) => candidate.id === connectionId);++ if (!connection) {+ return;+ }++ const directionKey = connectionDirectionKey(connection.fromApplicationId, connection.toApplicationId);+ const directionPorts = connection.portsByDirection[directionKey] ?? [];++ if (directionPorts.includes(port)) {+ return;+ }++ const updatedConnection = {+ ...connection,+ portsByDirection: {+ ...connection.portsByDirection,+ [directionKey]: [...directionPorts, port],+ },+ };++ void persistConnectionPorts(updatedConnection, connection);+ setConnectionPortInput((currentInputs) => ({ ...currentInputs, [connectionId]: '' }));+ },+ [connectionPortInput, persistConnectionPorts],+ );++ const removeConnectionPort = useCallback(+ (connectionId: string, port: string): void => {+ const connection = connectionsRef.current.find((candidate) => candidate.id === connectionId);++ if (!connection) {+ return;+ }++ const directionKey = connectionDirectionKey(connection.fromApplicationId, connection.toApplicationId);+ const updatedConnection = {+ ...connection,+ portsByDirection: {+ ...connection.portsByDirection,+ [directionKey]: activeConnectionPorts(connection).filter((allowedPort) => allowedPort !== port),+ },+ };++ void persistConnectionPorts(updatedConnection, connection);+ },+ [persistConnectionPorts],+ );++ const removeConnectionsForApplication = useCallback((applicationId: string): void => {+ setConnections((currentConnections) =>+ currentConnections.filter(+ (connection) => connection.fromApplicationId !== applicationId && connection.toApplicationId !== applicationId,+ ),+ );+ }, []);++ useEffect(() => {+ function deleteSelectedConnection(event: KeyboardEvent): void {+ const target = event.target as HTMLElement | null;++ if (target?.closest('input, textarea, [contenteditable="true"]')) {+ return;+ }++ if (!['Backspace', 'Delete'].includes(event.key) || !selectedConnectionId) {+ return;+ }++ deleteConnection(selectedConnectionId);+ }++ window.addEventListener('keydown', deleteSelectedConnection);++ return () => window.removeEventListener('keydown', deleteSelectedConnection);+ }, [selectedConnectionId, deleteConnection]);++ return {+ connections,+ selectedConnectionId,+ setSelectedConnectionId,+ connectionPortInput,+ setConnectionPortDraft,+ resetConnections,+ connectionExists,+ persistNewConnection,+ deleteConnection,+ updateConnectionDirection,+ addConnectionPort,+ removeConnectionPort,+ removeConnectionsForApplication,+ };+}diff --git a/resources/js/v5/lib/use-canvas-resource-merge.ts b/resources/js/v5/lib/use-canvas-resource-merge.tsnew file mode 100644index 0000000000..4ac4945067--- /dev/null+++ b/resources/js/v5/lib/use-canvas-resource-merge.ts@@ -0,0 +1,98 @@+import { useCallback, type Dispatch, type RefObject, type SetStateAction } from 'react';++import { useCanvasResourceChannel, type V5CanvasResourceUpdatedEvent } from '@/lib/use-canvas-channel';+import type { V5Application, V5CaddyIngress } from '@/types';++type UseCanvasResourceMergeOptions = {+ teamId: number | null;+ selectedProjectUuid: string | null;+ selectedEnvironmentUuid: string | null;+ setApplications: Dispatch<SetStateAction<V5Application[]>>;+ setIngresses: Dispatch<SetStateAction<V5CaddyIngress[]>>;+ /** Cards mid-drag or with an unsaved position keep their local canvasX/canvasY. */+ locallyPositionedApplicationIds: RefObject<Set<string>>;+ locallyPositionedIngressIds: RefObject<Set<string>>;+};++/**+ * Merges `.v5.canvas.resource.updated` broadcasts into the canvas state.+ *+ * The team channel broadcasts every canvas resource of the team, so incoming+ * applications are only appended when they belong to the selected+ * project+environment; existing entries are updated in place regardless.+ */+export function useCanvasResourceMerge({+ teamId,+ selectedProjectUuid,+ selectedEnvironmentUuid,+ setApplications,+ setIngresses,+ locallyPositionedApplicationIds,+ locallyPositionedIngressIds,+}: UseCanvasResourceMergeOptions): void {+ const belongsToCurrentCanvas = useCallback(+ (application: V5Application): boolean =>+ selectedProjectUuid !== null &&+ selectedEnvironmentUuid !== null &&+ application.projectUuid === selectedProjectUuid &&+ application.environmentUuid === selectedEnvironmentUuid,+ [selectedProjectUuid, selectedEnvironmentUuid],+ );++ const mergeIncomingApplications = useCallback(+ (incomingApplications: V5Application[]): void => {+ setApplications((currentApplications) => {+ const updatedApplications = currentApplications.map((application) => {+ const incoming = incomingApplications.find((candidate) => candidate.id === application.id);++ if (!incoming) {+ return application;+ }++ return locallyPositionedApplicationIds.current.has(incoming.id)+ ? { ...incoming, canvasX: application.canvasX, canvasY: application.canvasY }+ : incoming;+ });+ const appendedApplications = incomingApplications.filter(+ (candidate) =>+ !currentApplications.some((application) => application.id === candidate.id) &&+ belongsToCurrentCanvas(candidate),+ );++ return [...updatedApplications, ...appendedApplications];+ });+ },+ [belongsToCurrentCanvas, setApplications, locallyPositionedApplicationIds],+ );++ const handleCanvasResourceEvent = useCallback(+ (event: V5CanvasResourceUpdatedEvent): void => {+ if (event.application) {+ mergeIncomingApplications([event.application]);+ }++ if (event.applications && event.applications.length > 0) {+ mergeIncomingApplications(event.applications);+ }++ const incomingIngress = event.caddyIngress;++ if (incomingIngress) {+ setIngresses((currentIngresses) =>+ currentIngresses.map((ingress) => {+ if (ingress.id !== incomingIngress.id) {+ return ingress;+ }++ return locallyPositionedIngressIds.current.has(incomingIngress.id)+ ? { ...incomingIngress, canvasX: ingress.canvasX, canvasY: ingress.canvasY }+ : incomingIngress;+ }),+ );+ }+ },+ [mergeIncomingApplications, setIngresses, locallyPositionedIngressIds],+ );++ useCanvasResourceChannel(teamId, handleCanvasResourceEvent);+}diff --git a/resources/js/v5/lib/use-canvas-viewport.ts b/resources/js/v5/lib/use-canvas-viewport.tsnew file mode 100644index 0000000000..060a1547ca--- /dev/null+++ b/resources/js/v5/lib/use-canvas-viewport.ts@@ -0,0 +1,125 @@+import { useCallback, useRef, useState, type PointerEvent, type WheelEvent } from 'react';++import { APPLICATION_CARD_HEIGHT, APPLICATION_CARD_WIDTH, type CanvasCardNode } from '@/lib/canvas-geometry';++export type Viewport = {+ x: number;+ y: number;+ zoom: number;+};++export const MIN_CANVAS_ZOOM = 0.5;+export const MAX_CANVAS_ZOOM = 2;+export const CANVAS_ZOOM_STEP = 0.1;+export const PINCH_CANVAS_ZOOM_STEP = 0.03;++function clampCanvasZoom(zoom: number): number {+ return Math.min(MAX_CANVAS_ZOOM, Math.max(MIN_CANVAS_ZOOM, zoom));+}++export function useCanvasViewport() {+ const canvasRef = useRef<HTMLDivElement | null>(null);+ const [viewport, setViewport] = useState<Viewport>({ x: 0, y: 0, zoom: 1 });+ const viewportRef = useRef(viewport);++ viewportRef.current = viewport;++ const zoomCanvas = useCallback((direction: 1 | -1, step = CANVAS_ZOOM_STEP, origin?: { x: number; y: number }): void => {+ const rect = canvasRef.current?.getBoundingClientRect();++ setViewport((currentViewport) => {+ const nextZoom = clampCanvasZoom(currentViewport.zoom + direction * step);++ if (!rect || nextZoom === currentViewport.zoom) {+ return currentViewport;+ }++ const originX = origin?.x ?? rect.width / 2;+ const originY = origin?.y ?? rect.height / 2;+ const canvasX = (originX - currentViewport.x) / currentViewport.zoom;+ const canvasY = (originY - currentViewport.y) / currentViewport.zoom;++ return {+ x: originX - canvasX * nextZoom,+ y: originY - canvasY * nextZoom,+ zoom: nextZoom,+ };+ });+ }, []);++ const handleCanvasWheel = useCallback(+ (event: WheelEvent<HTMLDivElement>): void => {+ if (!event.ctrlKey) {+ return;+ }++ const rect = event.currentTarget.getBoundingClientRect();++ event.preventDefault();+ zoomCanvas(event.deltaY < 0 ? 1 : -1, PINCH_CANVAS_ZOOM_STEP, {+ x: event.clientX - rect.left,+ y: event.clientY - rect.top,+ });+ },+ [zoomCanvas],+ );++ const centerOnCanvasNodes = useCallback((applications: CanvasCardNode[], ingresses: CanvasCardNode[]): void => {+ const canvas = canvasRef.current;+ const nodes = [...applications, ...ingresses];++ if (!canvas || nodes.length === 0) {+ setViewport((currentViewport) => ({ x: 0, y: 0, zoom: currentViewport.zoom }));++ return;+ }++ const bounds = nodes.reduce(+ (currentBounds, node) => ({+ minX: Math.min(currentBounds.minX, node.canvasX),+ maxX: Math.max(currentBounds.maxX, node.canvasX),+ minY: Math.min(currentBounds.minY, node.canvasY),+ maxY: Math.max(currentBounds.maxY, node.canvasY),+ }),+ {+ minX: nodes[0]?.canvasX ?? 0,+ maxX: nodes[0]?.canvasX ?? 0,+ minY: nodes[0]?.canvasY ?? 0,+ maxY: nodes[0]?.canvasY ?? 0,+ },+ );+ const centerX = (bounds.minX + bounds.maxX) / 2;+ const centerY = (bounds.minY + bounds.maxY) / 2;+ const rect = canvas.getBoundingClientRect();++ setViewport((currentViewport) => ({+ x: rect.width / 2 - (centerX + APPLICATION_CARD_WIDTH / 2) * currentViewport.zoom,+ y: rect.height / 2 - (centerY + APPLICATION_CARD_HEIGHT / 2) * currentViewport.zoom,+ zoom: currentViewport.zoom,+ }));+ }, []);++ const canvasPointFromPointer = useCallback((event: PointerEvent): { x: number; y: number } => {+ const rect = canvasRef.current?.getBoundingClientRect();+ const currentViewport = viewportRef.current;++ if (!rect) {+ return { x: 0, y: 0 };+ }++ return {+ x: (event.clientX - rect.left - currentViewport.x) / currentViewport.zoom,+ y: (event.clientY - rect.top - currentViewport.y) / currentViewport.zoom,+ };+ }, []);++ return {+ canvasRef,+ viewport,+ setViewport,+ zoomCanvas,+ handleCanvasWheel,+ centerOnCanvasNodes,+ canvasPointFromPointer,+ };+}diff --git a/resources/js/v5/lib/use-team-channel.ts b/resources/js/v5/lib/use-team-channel.tsnew file mode 100644index 0000000000..5f9fd3d1c0--- /dev/null+++ b/resources/js/v5/lib/use-team-channel.ts@@ -0,0 +1,116 @@+import { useEffect, useRef } from 'react';++type EchoChannel = {+ listen: (event: string, callback: (payload: unknown) => void) => EchoChannel;+ subscribed?: (callback: () => void) => EchoChannel;+ error?: (callback: (error: unknown) => void) => EchoChannel;+};++type EchoClient = {+ private: (channel: string) => EchoChannel;+ leave?: (channel: string) => void;+ leaveChannel?: (channel: string) => void;+};++declare global {+ interface Window {+ Echo?: EchoClient;+ }+}++export type TeamChannelLogger = (message: string, payload?: unknown) => void;++export type UseTeamChannelOptions = {+ /** Receives subscription lifecycle messages; defaults to console.debug. */+ onDebug?: TeamChannelLogger;+ /** Receives subscription failures; defaults to console.error. */+ onError?: TeamChannelLogger;+};++/**+ * Subscribes to the private `team.{teamId}` channel and forwards `eventName`+ * payloads to the latest onEvent callback without resubscribing when the+ * callback identity changes. Polls for window.Echo (500ms, up to 20 attempts)+ * because the Echo script can finish loading after React mounts.+ */+export function useTeamChannel(+ teamId: number | null,+ eventName: string,+ onEvent: (payload: unknown) => void,+ options: UseTeamChannelOptions = {},+): void {+ const onEventRef = useRef(onEvent);+ const onDebugRef = useRef(options.onDebug);+ const onErrorRef = useRef(options.onError);++ onEventRef.current = onEvent;+ onDebugRef.current = options.onDebug;+ onErrorRef.current = options.onError;++ useEffect(() => {+ if (teamId === null) {+ return;+ }++ const debug: TeamChannelLogger = (message, payload) => {+ if (onDebugRef.current) {+ onDebugRef.current(message, payload);++ return;+ }++ console.debug(message);+ };+ const fail: TeamChannelLogger = (message, payload) => {+ if (onErrorRef.current) {+ onErrorRef.current(message, payload);++ return;+ }++ console.error(message, payload);+ };++ let isCancelled = false;+ let attempts = 0;+ const channelName = `team.${teamId}`;++ const interval = window.setInterval(() => {+ attempts += 1;++ if (!window.Echo) {+ if (attempts === 1) {+ debug(`Waiting for window.Echo before subscribing to ${eventName} updates`);+ }++ if (attempts >= 20) {+ window.clearInterval(interval);+ fail('window.Echo was not available after 10 seconds.');+ }++ return;+ }++ window.clearInterval(interval);++ if (isCancelled) {+ return;+ }++ debug(`Subscribing to private-${channelName} for ${eventName} updates`);+ const channel = window.Echo.private(channelName);++ channel.subscribed?.(() => debug(`Subscribed to private-${channelName} for ${eventName} updates`));+ channel.error?.((error) => fail(`Subscription error on private-${channelName}`, error));+ channel.listen(eventName, (payload) => {+ onEventRef.current(payload);+ });+ }, 500);++ return () => {+ isCancelled = true;+ window.clearInterval(interval);+ window.Echo?.leave?.(channelName) ?? window.Echo?.leaveChannel?.(`private-${channelName}`);+ };+ }, [teamId, eventName]);+}diff --git a/resources/js/v5/types.ts b/resources/js/v5/types.tsindex 26a115d314..24f48894b6 100644--- a/resources/js/v5/types.ts+++ b/resources/js/v5/types.ts@@ -9,7 +9,6 @@ export type V5Server = {id: string;name: string;host: string;- type: string;status: string;capabilities: string[];builderEnabled: boolean;@@ -23,7 +22,8 @@ export type V5Server = {wireguardEndpointOverride: string | null;wireguardManagementIp: string | null;wireguardPublicKey: string | null;- containerSubnets: Record<string, string> | string[];+ /** Namespace → subnet map; serialized as an empty JSON array when no subnets are recorded. */+ containerSubnets: Record<string, string> | [];privateKeyName: string | null;lastBootstrappedAt: string | null;lastBootstrapAction: string | null;@@ -105,6 +105,8 @@ export type V5Application = {internalPort: number | null;domains: string[];meshFqdn: string;+ projectUuid: string | null;+ environmentUuid: string | null;canvasX: number;canvasY: number;};@@ -113,6 +115,7 @@ export type V5CaddyIngress = {id: string;name: string;host: string;+ type: string;status: string;statusMessage: string | null;canvasX: number;@@ -122,7 +125,7 @@ export type V5CaddyIngress = {export type V5ResourceConnection = {id: string;- applicationIds: [string, string];+ applicationIds: string[];fromApplicationId: string;toApplicationId: string;portsByDirection: Record<string, string[]>;diff --git a/resources/views/v5/app.blade.php b/resources/views/v5/app.blade.phpindex 18dd296423..7a4afe13f8 100644--- a/resources/views/v5/app.blade.php+++ b/resources/views/v5/app.blade.php@@ -27,7 +27,7 @@forceTLS: false,encrypted: true,enableStats: false,- enableLogging: true,+ enableLogging: @json(app()->environment('local')),enabledTransports: ['ws', 'wss'],disabledTransports: ['sockjs', 'xhr_streaming', 'xhr_polling'],});diff --git a/routes/v5.php b/routes/v5.phpindex 1e4ffa7f2a..acec7a869d 100644--- a/routes/v5.php+++ b/routes/v5.php@@ -1,6 +1,10 @@<?php+use App\Http\Controllers\V5\ApplicationController;+use App\Http\Controllers\V5\ClusterController;use App\Http\Controllers\V5\DashboardController;+use App\Http\Controllers\V5\ResourceConnectionController;+use App\Http\Controllers\V5\ServerController;use Illuminate\Support\Facades\Route;Route::middleware('v5.authenticated')->group(function () {@@ -8,25 +12,26 @@ Route::middleware('v5.authenticated')->group(function () {Route::get('/realtime-test', [DashboardController::class, 'realtimeTest'])->name('realtime-test');Route::post('/realtime-test', [DashboardController::class, 'broadcastRealtimeTest'])->name('realtime-test.broadcast');Route::post('/selection', [DashboardController::class, 'updateSelection'])->name('selection.update');- Route::post('/applications/nginx', [DashboardController::class, 'storeNginxApplication'])->name('applications.nginx');- Route::post('/applications/refresh', [DashboardController::class, 'refreshApplications'])->name('applications.refresh');- Route::delete('/applications/{application}', [DashboardController::class, 'destroyApplication'])->name('applications.destroy');- Route::patch('/applications/{application}/position', [DashboardController::class, 'updateApplicationPosition'])->name('applications.position');- Route::patch('/applications/{application}/ingress', [DashboardController::class, 'updateApplicationIngress'])->name('applications.ingress');- Route::patch('/caddy-ingresses/{server}/position', [DashboardController::class, 'updateCaddyIngressPosition'])->name('caddy-ingresses.position');- Route::post('/resource-connections', [DashboardController::class, 'storeResourceConnection'])->name('resource-connections.store');- Route::patch('/resource-connections/{connection}', [DashboardController::class, 'updateResourceConnection'])->name('resource-connections.update');- Route::delete('/resource-connections/{connection}', [DashboardController::class, 'destroyResourceConnection'])->name('resource-connections.destroy');- Route::get('/clusters', [DashboardController::class, 'clustersIndex'])->name('clusters.index');- Route::get('/clusters/{cluster}', [DashboardController::class, 'showCluster'])->name('clusters.show');- Route::post('/clusters', [DashboardController::class, 'storeCluster'])->name('clusters.store');- Route::delete('/clusters/{cluster}', [DashboardController::class, 'destroyCluster'])->name('clusters.destroy');- Route::post('/clusters/{cluster}/servers', [DashboardController::class, 'storeServer'])->name('clusters.servers.store');- Route::patch('/clusters/{cluster}/servers/{server}', [DashboardController::class, 'updateServer'])->name('clusters.servers.update');- Route::post('/clusters/{cluster}/servers/{server}/check', [DashboardController::class, 'checkServer'])->name('clusters.servers.check');- Route::get('/clusters/{cluster}/servers/{server}/coold-logs', [DashboardController::class, 'serverCooldLogs'])->name('clusters.servers.coold-logs');- Route::get('/clusters/{cluster}/servers/{server}/corrosion-tables', [DashboardController::class, 'serverCorrosionTables'])->name('clusters.servers.corrosion-tables');- Route::get('/clusters/{cluster}/servers/{server}/firewall-rules', [DashboardController::class, 'serverFirewallRules'])->name('clusters.servers.firewall-rules');- Route::post('/clusters/{cluster}/servers/{server}/bootstrap', [DashboardController::class, 'bootstrapServer'])->name('clusters.servers.bootstrap');- Route::delete('/clusters/{cluster}/servers/{server}', [DashboardController::class, 'destroyServer'])->name('clusters.servers.destroy');+ Route::post('/applications/nginx', [ApplicationController::class, 'store'])->name('applications.nginx');+ Route::post('/applications/refresh', [ApplicationController::class, 'refresh'])->name('applications.refresh');+ Route::delete('/applications/{application}', [ApplicationController::class, 'destroy'])->name('applications.destroy');+ Route::patch('/applications/{application}/position', [ApplicationController::class, 'updatePosition'])->name('applications.position');+ Route::patch('/applications/{application}/ingress', [ApplicationController::class, 'updateIngress'])->name('applications.ingress');+ Route::get('/applications/{application}/logs', [ApplicationController::class, 'logs'])->name('applications.logs');+ Route::patch('/caddy-ingresses/{server}/position', [ApplicationController::class, 'updateCaddyIngressPosition'])->name('caddy-ingresses.position');+ Route::post('/resource-connections', [ResourceConnectionController::class, 'store'])->name('resource-connections.store');+ Route::patch('/resource-connections/{connection}', [ResourceConnectionController::class, 'update'])->name('resource-connections.update');+ Route::delete('/resource-connections/{connection}', [ResourceConnectionController::class, 'destroy'])->name('resource-connections.destroy');+ Route::get('/clusters', [ClusterController::class, 'index'])->name('clusters.index');+ Route::get('/clusters/{cluster}', [ClusterController::class, 'show'])->name('clusters.show');+ Route::post('/clusters', [ClusterController::class, 'store'])->name('clusters.store');+ Route::delete('/clusters/{cluster}', [ClusterController::class, 'destroy'])->name('clusters.destroy');+ Route::post('/clusters/{cluster}/servers', [ServerController::class, 'store'])->name('clusters.servers.store');+ Route::patch('/clusters/{cluster}/servers/{server}', [ServerController::class, 'update'])->name('clusters.servers.update');+ Route::post('/clusters/{cluster}/servers/{server}/check', [ServerController::class, 'check'])->name('clusters.servers.check');+ Route::get('/clusters/{cluster}/servers/{server}/coold-logs', [ServerController::class, 'cooldLogs'])->name('clusters.servers.coold-logs');+ Route::get('/clusters/{cluster}/servers/{server}/corrosion-tables', [ServerController::class, 'corrosionTables'])->name('clusters.servers.corrosion-tables');+ Route::get('/clusters/{cluster}/servers/{server}/firewall-rules', [ServerController::class, 'firewallRules'])->name('clusters.servers.firewall-rules');+ Route::post('/clusters/{cluster}/servers/{server}/bootstrap', [ServerController::class, 'bootstrap'])->name('clusters.servers.bootstrap');+ Route::delete('/clusters/{cluster}/servers/{server}', [ServerController::class, 'destroy'])->name('clusters.servers.destroy');});diff --git a/tests/Feature/DevEnvironmentExampleTest.php b/tests/Feature/DevEnvironmentExampleTest.phpindex fb2ef713d6..fb7d6cae7e 100644--- a/tests/Feature/DevEnvironmentExampleTest.php+++ b/tests/Feature/DevEnvironmentExampleTest.php@@ -35,6 +35,14 @@ it('runs the v5 dev Lima seeder with the normal development database seeder', fu->and($developmentSeederBlock)->toContain('V5DevLimaSeeder::class');});+it('disables Flux host binding by default in the Docker development environment', function () {+ $compose = file_get_contents(base_path('docker-compose.dev.yml'));+ $runScript = file_get_contents(base_path('docker/development/etc/s6-overlay/s6-rc.d/flux/run'));++ expect($compose)->toContain('COOLIFY_FLUX_REQUIRE_HOST_BINDING: "${COOLIFY_FLUX_REQUIRE_HOST_BINDING:-0}"')+ ->and($runScript)->toContain('COOLIFY_FLUX_REQUIRE_HOST_BINDING="${COOLIFY_FLUX_REQUIRE_HOST_BINDING:-0}"');+});+it('cache busts mutable nightly coold assets with resolved checksums', function () {$compose = file_get_contents(base_path('docker-compose.dev.yml'));$dockerfile = file_get_contents(base_path('docker/development/Dockerfile'));diff --git a/tests/Feature/FluxDevCommandTest.php b/tests/Feature/FluxDevCommandTest.phpindex 6abe5a12c0..431da4309a 100644--- a/tests/Feature/FluxDevCommandTest.php+++ b/tests/Feature/FluxDevCommandTest.php@@ -17,7 +17,8 @@ it('issues production host tokens with the default capability profile', functionexpect($claims->sub)->toBe('100.64.0.10')->and($claims->aud)->toBe('coold')- ->and($claims->caps)->toBe(['host-agent:default'])+ ->and((array) $claims->caps)->toBe(config('flux.host_capabilities'))+ ->and((array) $claims->caps)->not->toContain('host-agent:default')->and($claims->exp)->toBeGreaterThan(time());});@@ -28,6 +29,7 @@ it('issues production server tokens with server identity claims', function () {$server = new V5Server;$server->forceFill([+ 'uuid' => 'server_prod_123','id' => 123,'team_id' => 7,'cluster_id' => 'cluster-456',@@ -38,11 +40,12 @@ it('issues production server tokens with server identity claims', function () {$token = app(AgentTokenIssuer::class)->issueForServer($server);$claims = JWT::decode($token, new Key(file_get_contents($publicKeyPath), 'ES256'));- expect($claims->sub)->toBe('100.64.0.10')- ->and($claims->caps)->toBe(['host-agent:default'])- ->and($claims->team_id)->toBe(7)+ expect($claims->sub)->toBe('server_prod_123')+ ->and((array) $claims->caps)->toBe(config('flux.host_capabilities'))+ ->and($claims->team_id)->toBe('7')->and($claims->cluster_id)->toBe('cluster-456')- ->and($claims->server_id)->toBe(123);+ ->and($claims->server_id)->toBe('server_prod_123')+ ->and($claims->wireguard_management_ip)->toBe('100.64.0.10');});it('mints a host jwt signed by the configured flux private key', function () {diff --git a/tests/Feature/V5/AgentTokenRevocationTest.php b/tests/Feature/V5/AgentTokenRevocationTest.phpnew file mode 100644index 0000000000..9d1ba3f58e--- /dev/null+++ b/tests/Feature/V5/AgentTokenRevocationTest.php@@ -0,0 +1,167 @@+<?php++use App\Actions\V5\Server\RemoveBootstrapMarker;+use App\Models\V5\RevokedAgentToken;+use App\Models\V5\Server as V5Server;+use App\Services\Flux\AgentTokenIssuer;+use App\Services\Flux\FluxClient;+use Firebase\JWT\JWT;+use Firebase\JWT\Key;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Schema;+use Tests\Support\V5TestSchema;++/**+ * @return array{0: string, 1: string}+ */+function createRevocationJwtKeypair(): array+{+ $directory = storage_path('framework/testing/revocation-keys-'.bin2hex(random_bytes(4)));+ mkdir($directory, 0777, true);++ $privateKeyPath = $directory.'/jwt.priv';+ $publicKeyPath = $directory.'/jwt.pub';++ exec('openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out '.escapeshellarg($privateKeyPath), $out, $code);+ expect($code)->toBe(0);+ chmod($privateKeyPath, 0600);++ exec('openssl pkey -in '.escapeshellarg($privateKeyPath).' -pubout -out '.escapeshellarg($publicKeyPath), $out, $code);+ expect($code)->toBe(0);++ return [$privateKeyPath, $publicKeyPath];+}++function createRevocationServer(): V5Server+{+ return V5Server::query()->create([+ 'team_id' => 1,+ 'created_by_user_id' => 1,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'wireguard_management_ip' => '100.64.0.5',+ ]);+}++beforeEach(function () {+ Config::set('broadcasting.default', 'log');+ Config::set('cache.default', 'array');++ Schema::dropIfExists('v5_revoked_agent_tokens');+ Schema::dropIfExists('v5_servers');+ V5TestSchema::createServersTable();+ V5TestSchema::createRevokedAgentTokensTable();++ [$this->privateKeyPath, $this->publicKeyPath] = createRevocationJwtKeypair();+ Config::set('flux.jwt_private_key_path', $this->privateKeyPath);+});++afterEach(function () {+ Schema::dropIfExists('v5_revoked_agent_tokens');+ Schema::dropIfExists('v5_servers');+});++it('persists the issued jti on the server and reports it as not revoked', function () {+ $server = createRevocationServer();++ $token = app(AgentTokenIssuer::class)->issueForServer($server);+ $claims = JWT::decode($token, new Key(file_get_contents($this->publicKeyPath), 'ES256'));++ expect($server->fresh()->agent_token_jti)->toBe($claims->jti)+ ->and(app(AgentTokenIssuer::class)->isRevoked($claims->jti))->toBeFalse();+});++it('revokes the currently-issued token and clears the server jti', function () {+ $issuer = app(AgentTokenIssuer::class);+ $server = createRevocationServer();++ $token = $issuer->issueForServer($server);+ $jti = JWT::decode($token, new Key(file_get_contents($this->publicKeyPath), 'ES256'))->jti;++ $issuer->revoke($server->fresh());++ expect($issuer->isRevoked($jti))->toBeTrue()+ ->and(RevokedAgentToken::query()->where('jti', $jti)->where('server_id', $server->id)->exists())->toBeTrue()+ ->and($server->fresh()->agent_token_jti)->toBeNull();+});++it('is idempotent when revoking a server with no issued token', function () {+ $server = createRevocationServer();++ app(AgentTokenIssuer::class)->revoke($server);++ expect(RevokedAgentToken::query()->count())->toBe(0);+});++it('pushes the revocation to flux with the jti and expires_at', function () {+ $issuer = app(AgentTokenIssuer::class);+ $server = createRevocationServer();++ $token = $issuer->issueForServer($server);+ $server = $server->fresh();+ $jti = JWT::decode($token, new Key(file_get_contents($this->publicKeyPath), 'ES256'))->jti;+ $expiresAtUnix = $server->agent_token_expires_at->getTimestamp();++ $flux = Mockery::mock(FluxClient::class);+ $flux->shouldReceive('revokeToken')->once()->with($jti, $expiresAtUnix);+ app()->instance(FluxClient::class, $flux);++ $issuer->revoke($server);++ expect($issuer->isRevoked($jti))->toBeTrue()+ ->and(RevokedAgentToken::query()->where('jti', $jti)->exists())->toBeTrue();+});++it('does not throw and keeps the local revocation record when the flux push fails', function () {+ $issuer = app(AgentTokenIssuer::class);+ $server = createRevocationServer();++ $token = $issuer->issueForServer($server);+ $jti = JWT::decode($token, new Key(file_get_contents($this->publicKeyPath), 'ES256'))->jti;++ $flux = Mockery::mock(FluxClient::class);+ $flux->shouldReceive('revokeToken')->once()->andThrow(new RuntimeException('flux socket unreachable'));+ app()->instance(FluxClient::class, $flux);++ // Flux is down: revoke must not throw, and the local record still stands.+ $issuer->revoke($server->fresh());++ expect($issuer->isRevoked($jti))->toBeTrue()+ ->and(RevokedAgentToken::query()->where('jti', $jti)->exists())->toBeTrue()+ ->and($server->fresh()->agent_token_jti)->toBeNull();+});++it('revokeForServer revokes the token and pushes to flux like revoke', function () {+ $issuer = app(AgentTokenIssuer::class);+ $server = createRevocationServer();++ $token = $issuer->issueForServer($server);+ $jti = JWT::decode($token, new Key(file_get_contents($this->publicKeyPath), 'ES256'))->jti;++ $flux = Mockery::mock(FluxClient::class);+ $flux->shouldReceive('revokeToken')->once()->with($jti, Mockery::type('int'));+ app()->instance(FluxClient::class, $flux);++ $issuer->revokeForServer($server->fresh());++ expect($issuer->isRevoked($jti))->toBeTrue()+ ->and($server->fresh()->agent_token_jti)->toBeNull();+});++it('revokes the host token when the bootstrap marker is removed', function () {+ $issuer = app(AgentTokenIssuer::class);+ $server = createRevocationServer();++ $token = $issuer->issueForServer($server);+ $jti = JWT::decode($token, new Key(file_get_contents($this->publicKeyPath), 'ES256'))->jti;++ // The server has no private key, so the SSH cleanup returns false, but the+ // revocation (a pure DB write) still runs first.+ $result = RemoveBootstrapMarker::run($server->fresh());++ expect($result)->toBeFalse()+ ->and($issuer->isRevoked($jti))->toBeTrue();+});diff --git a/tests/Feature/V5/AgentTokenRotationTest.php b/tests/Feature/V5/AgentTokenRotationTest.phpnew file mode 100644index 0000000000..e3c0b8c5bb--- /dev/null+++ b/tests/Feature/V5/AgentTokenRotationTest.php@@ -0,0 +1,366 @@+<?php++use App\Jobs\V5RotateAgentTokenJob;+use App\Jobs\V5RotateAgentTokensJob;+use App\Models\V5\Server as V5Server;+use App\Services\Flux\AgentTokenIssuer;+use App\Services\Flux\FluxClient;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Facades\Process;+use Illuminate\Support\Facades\Queue;++/**+ * @return array{0: string, 1: string}+ */+function createRotationJwtKeypair(): array+{+ $directory = storage_path('framework/testing/rotation-keys-'.bin2hex(random_bytes(4)));+ mkdir($directory, 0777, true);++ $privateKeyPath = $directory.'/jwt.priv';+ $publicKeyPath = $directory.'/jwt.pub';++ exec('openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out '.escapeshellarg($privateKeyPath), $out, $code);+ expect($code)->toBe(0);+ chmod($privateKeyPath, 0600);++ exec('openssl pkey -in '.escapeshellarg($privateKeyPath).' -pubout -out '.escapeshellarg($publicKeyPath), $out, $code);+ expect($code)->toBe(0);++ return [$privateKeyPath, $publicKeyPath];+}++beforeEach(function () {+ resetV5DashboardTestState();+ createSharedUserAndTeamTables();++ [$this->user, $this->team] = createV5UserWithTeam();++ [$this->privateKeyPath, $this->publicKeyPath] = createRotationJwtKeypair();+ Config::set('flux.jwt_private_key_path', $this->privateKeyPath);+});++/**+ * @param array<string, mixed> $attributes+ */+function createRotationServer(array $attributes = []): V5Server+{+ static $counter = 0;+ $counter++;++ return V5Server::query()->create([+ 'team_id' => test()->team->id,+ 'created_by_user_id' => test()->user->id,+ 'name' => 'edge-'.$counter,+ 'host' => '203.0.113.'.$counter,+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['coold'],+ 'wireguard_management_ip' => '100.64.0.'.$counter,+ 'last_bootstrapped_at' => now(),+ ...$attributes,+ ]);+}++it('issueForServer persists agent_token_expires_at approximately now plus the ttl', function () {+ Config::set('flux.host_token_ttl', 3600);++ $server = createRotationServer();++ app(AgentTokenIssuer::class)->issueForServer($server);++ $server->refresh();++ expect($server->agent_token_jti)->toBeString()->not->toBe('')+ ->and($server->agent_token_expires_at)->not->toBeNull()+ ->and($server->agent_token_expires_at->timestamp)+ ->toBeGreaterThanOrEqual(now()->addSeconds(3600)->subSeconds(30)->timestamp)+ ->toBeLessThanOrEqual(now()->addSeconds(3600)->addSeconds(30)->timestamp);+});++it('dispatches rotation only for eligible servers whose token is missing or near expiry', function () {+ Config::set('flux.host_token_refresh_threshold', 43200);+ Queue::fake();++ $neverIssued = createRotationServer(['agent_token_expires_at' => null]);+ $expiringSoon = createRotationServer(['agent_token_expires_at' => now()->addHours(6)]);+ $stillFresh = createRotationServer(['agent_token_expires_at' => now()->addHours(20)]);+ $notInstalled = createRotationServer(['status' => 'added', 'agent_token_expires_at' => null]);+ $withoutCoold = createRotationServer(['capabilities' => [], 'agent_token_expires_at' => null]);+ $notBootstrapped = createRotationServer(['last_bootstrapped_at' => null, 'agent_token_expires_at' => null]);++ (new V5RotateAgentTokensJob)->handle();++ Queue::assertPushed(V5RotateAgentTokenJob::class, 2);+ Queue::assertPushed(V5RotateAgentTokenJob::class, fn (V5RotateAgentTokenJob $job) => $job->serverId === $neverIssued->id);+ Queue::assertPushed(V5RotateAgentTokenJob::class, fn (V5RotateAgentTokenJob $job) => $job->serverId === $expiringSoon->id);+ Queue::assertNotPushed(V5RotateAgentTokenJob::class, fn (V5RotateAgentTokenJob $job) => $job->serverId === $stillFresh->id);+ Queue::assertNotPushed(V5RotateAgentTokenJob::class, fn (V5RotateAgentTokenJob $job) => $job->serverId === $notInstalled->id);+ Queue::assertNotPushed(V5RotateAgentTokenJob::class, fn (V5RotateAgentTokenJob $job) => $job->serverId === $withoutCoold->id);+ Queue::assertNotPushed(V5RotateAgentTokenJob::class, fn (V5RotateAgentTokenJob $job) => $job->serverId === $notBootstrapped->id);+});++it('delivers the fresh token over RPC and never touches SSH on RPC success', function () {+ Config::set('flux.host_token_ttl', 86400);+ Process::fake();+ Log::spy();++ $server = createRotationServer([+ 'agent_token_jti' => 'old-jti',+ 'agent_token_expires_at' => now()->addHour(),+ ]);+ $privateKey = createV5PrivateKey($server->team, 'Rotation Key');+ $server->update(['private_key_id' => $privateKey->id]);++ $flux = Mockery::mock(FluxClient::class);+ $flux->shouldReceive('pushHostToken')+ ->once()+ ->with($server->fluxHostId(), Mockery::type('string'));+ app()->instance(FluxClient::class, $flux);++ (new V5RotateAgentTokenJob($server->id))->handle();++ $server->refresh();++ expect($server->agent_token_jti)->not->toBe('old-jti')->toBeString()->not->toBe('')+ ->and($server->agent_token_expires_at->timestamp)+ ->toBeGreaterThan(now()->addHours(20)->timestamp);++ Process::assertNothingRan();+ Log::shouldHaveReceived('debug')->withArgs(+ fn (string $message, array $context = []) => ($context['delivery'] ?? null) === 'rpc'+ );+});++it('falls back to the SSH push when RPC delivery fails and advances jti on SSH success', function () {+ Config::set('flux.host_token_ttl', 86400);+ Process::fake(['*' => Process::result(output: '')]);+ Log::spy();++ $server = createRotationServer([+ 'agent_token_jti' => 'old-jti',+ 'agent_token_expires_at' => now()->addHour(),+ ]);+ $privateKey = createV5PrivateKey($server->team, 'Rotation Key');+ $server->update(['private_key_id' => $privateKey->id]);++ $flux = Mockery::mock(FluxClient::class);+ $flux->shouldReceive('pushHostToken')+ ->once()+ ->andThrow(new RuntimeException('host is not connected'));+ app()->instance(FluxClient::class, $flux);++ (new V5RotateAgentTokenJob($server->id))->handle();++ $server->refresh();++ expect($server->agent_token_jti)->not->toBe('old-jti')->toBeString()->not->toBe('')+ ->and($server->agent_token_expires_at->timestamp)+ ->toBeGreaterThan(now()->addHours(20)->timestamp);++ Process::assertRan(function ($process): bool {+ $command = $process->command;++ if (! is_array($command) || ($command[0] ?? null) !== 'ssh') {+ return false;+ }++ $script = end($command);++ return str_contains($script, '/etc/coolify/host-jwt')+ && str_contains($script, 'chmod 600 /etc/coolify/host-jwt')+ && str_contains($script, 'tee /etc/coolify/host-jwt');+ });+ Log::shouldHaveReceived('debug')->withArgs(+ fn (string $message, array $context = []) => ($context['delivery'] ?? null) === 'ssh'+ );+});++it('leaves jti and expires_at unchanged when both RPC and SSH delivery fail', function () {+ Config::set('flux.host_token_ttl', 86400);+ Process::fake(['*' => Process::result(errorOutput: 'connection refused', exitCode: 255)]);++ $expiresAt = now()->addHour();+ $server = createRotationServer([+ 'agent_token_jti' => 'old-jti',+ 'agent_token_expires_at' => $expiresAt,+ ]);+ $privateKey = createV5PrivateKey($server->team, 'Rotation Key');+ $server->update(['private_key_id' => $privateKey->id]);++ $flux = Mockery::mock(FluxClient::class);+ $flux->shouldReceive('pushHostToken')+ ->once()+ ->andThrow(new RuntimeException('host is not connected'));+ app()->instance(FluxClient::class, $flux);++ (new V5RotateAgentTokenJob($server->id))->handle();++ $server->refresh();++ expect($server->agent_token_jti)->toBe('old-jti')+ ->and($server->agent_token_expires_at->timestamp)->toBe($expiresAt->timestamp);+});++it('pushHostToken dispatches the host.jwt.set command with the jwt for the target host', function () {+ if (! function_exists('pcntl_fork')) {+ $this->markTestSkipped('pcntl is required to fake a Flux Unix socket.');+ }++ $responseBody = json_encode([+ 'request_id' => 'test-request',+ 'status' => 'ok',+ 'data' => [],+ ], JSON_THROW_ON_ERROR);++ $captured = withCapturingFluxSocket(+ "HTTP/1.1 200 OK\r\n".+ "Content-Type: application/json\r\n".+ 'Content-Length: '.strlen($responseBody)."\r\n".+ "\r\n".+ $responseBody,+ function (): void {+ (new FluxClient)->pushHostToken('100.64.0.42', 'the-new-host-jwt');+ }+ );++ $position = strpos($captured, "\r\n\r\n");+ $requestBody = $position === false ? '' : substr($captured, $position + 4);+ $decoded = json_decode($requestBody, true);++ expect($decoded)->toBeArray()+ ->and($decoded['host_id'])->toBe('100.64.0.42')+ ->and($decoded['command'])->toBe(['type' => 'host.jwt.set', 'jwt' => 'the-new-host-jwt']);+});++it('revokeToken posts the jti and expires_at to the flux revocation endpoint', function () {+ if (! function_exists('pcntl_fork')) {+ $this->markTestSkipped('pcntl is required to fake a Flux Unix socket.');+ }++ $responseBody = json_encode(['revoked' => 'the-jti'], JSON_THROW_ON_ERROR);++ $captured = withCapturingFluxSocket(+ "HTTP/1.1 200 OK\r\n".+ "Content-Type: application/json\r\n".+ 'Content-Length: '.strlen($responseBody)."\r\n".+ "\r\n".+ $responseBody,+ function (): void {+ (new FluxClient)->revokeToken('the-jti', 1893456000);+ }+ );++ $requestLine = strtok($captured, "\r\n");+ $position = strpos($captured, "\r\n\r\n");+ $requestBody = $position === false ? '' : substr($captured, $position + 4);+ $decoded = json_decode($requestBody, true);++ expect($requestLine)->toBe('POST /v1/tokens/revoke HTTP/1.1')+ ->and($decoded)->toBe(['jti' => 'the-jti', 'expires_at' => 1893456000]);+});++it('revokeToken omits expires_at from the body when it is null', function () {+ if (! function_exists('pcntl_fork')) {+ $this->markTestSkipped('pcntl is required to fake a Flux Unix socket.');+ }++ $responseBody = json_encode(['revoked' => 'the-jti'], JSON_THROW_ON_ERROR);++ $captured = withCapturingFluxSocket(+ "HTTP/1.1 200 OK\r\n".+ "Content-Type: application/json\r\n".+ 'Content-Length: '.strlen($responseBody)."\r\n".+ "\r\n".+ $responseBody,+ function (): void {+ (new FluxClient)->revokeToken('the-jti');+ }+ );++ $position = strpos($captured, "\r\n\r\n");+ $requestBody = $position === false ? '' : substr($captured, $position + 4);++ expect(json_decode($requestBody, true))->toBe(['jti' => 'the-jti']);+});++it('runs the rotation jobs on the dedicated v5-reconcile queue', function () {+ expect((new V5RotateAgentTokensJob)->queue)->toBe('v5-reconcile')+ ->and((new V5RotateAgentTokenJob(1))->queue)->toBe('v5-reconcile');+});++/**+ * Runs $callback against a fake Flux Unix socket that records the full HTTP+ * request (headers + body) it receives, then returns the captured raw request+ * so the wire command can be asserted.+ */+function withCapturingFluxSocket(string $response, Closure $callback): string+{+ $directory = storage_path('framework/testing');++ if (! is_dir($directory)) {+ mkdir($directory, 0777, true);+ }++ $socketPath = $directory.'/flux-'.bin2hex(random_bytes(8)).'.sock';+ $capturePath = $directory.'/flux-capture-'.bin2hex(random_bytes(8)).'.txt';+ $socketServer = stream_socket_server("unix://{$socketPath}", $errorCode, $errorMessage);++ expect($socketServer)->not->toBeFalse("Could not create fake Flux socket: {$errorMessage} ({$errorCode})");++ $pid = pcntl_fork();++ if ($pid === 0) {+ $connection = stream_socket_accept($socketServer, 5);++ if ($connection !== false) {+ $request = '';++ while (! str_contains($request, "\r\n\r\n") && ! feof($connection)) {+ $request .= fread($connection, 8192);+ }++ if (preg_match('/Content-Length:\s*(\d+)/i', $request, $matches) === 1) {+ $headerEnd = strpos($request, "\r\n\r\n") + 4;+ $needed = (int) $matches[1];++ while (strlen($request) - $headerEnd < $needed && ! feof($connection)) {+ $chunk = fread($connection, 8192);++ if ($chunk === '' || $chunk === false) {+ break;+ }++ $request .= $chunk;+ }+ }++ file_put_contents($capturePath, $request);+ fwrite($connection, $response);+ fclose($connection);+ }++ fclose($socketServer);+ exit(0);+ }++ fclose($socketServer);+ Config::set('flux.unix_socket_path', $socketPath);+ Config::set('flux.connection_timeout_seconds', 1.0);+ Config::set('flux.dispatch_timeout_seconds', 1.0);++ try {+ $callback();+ } finally {+ pcntl_waitpid($pid, $status);+ }++ $captured = is_file($capturePath) ? (string) file_get_contents($capturePath) : '';++ @unlink($socketPath);+ @unlink($capturePath);++ return $captured;+}diff --git a/tests/Feature/V5/ApplicationControllerTest.php b/tests/Feature/V5/ApplicationControllerTest.phpnew file mode 100644index 0000000000..7f763afdf1--- /dev/null+++ b/tests/Feature/V5/ApplicationControllerTest.php@@ -0,0 +1,1771 @@+<?php++use App\Events\V5CanvasResourceUpdated;+use App\Exceptions\V5\UnsupportedCooldVerb;+use App\Jobs\V5DeployApplicationJob;+use App\Models\V5\Application as V5Application;+use App\Models\V5\ApplicationDomain as V5ApplicationDomain;+use App\Models\V5\Cluster;+use App\Models\V5\ResourceConnection;+use App\Models\V5\Server as V5Server;+use App\Services\Flux\FluxClient;+use Illuminate\Support\Facades\Event;+use Illuminate\Support\Facades\Process;+use Illuminate\Support\Facades\Queue;+use Mockery\MockInterface;++beforeEach(function () {+ resetV5DashboardTestState();+});++it('uses v5 resource uuids at http boundaries while keeping database ids internal', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');+ $server = V5Server::query()->create([+ 'uuid' => 'server-public-uuid',+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '200%',+ 'wireguard_management_ip' => '100.64.0.10',+ 'last_bootstrapped_at' => now(),+ ]);+ $application = V5Application::query()->create([+ 'uuid' => 'application-public-uuid',+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-test',+ 'status' => 'running',+ 'mesh_namespace' => 'default',+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/applications/{$application->uuid}/position", [+ 'canvas_x' => 123,+ 'canvas_y' => 456,+ ])+ ->assertSuccessful()+ ->assertJsonPath('application.id', $application->uuid);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/applications/{$application->id}/position", [+ 'canvas_x' => 789,+ 'canvas_y' => 999,+ ])+ ->assertNotFound();++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('pullImage')->once()->andReturn('Image pulled.');+ $fluxClient->shouldReceive('createContainer')->once()->andReturn('container-id');+ $fluxClient->shouldReceive('startContainer')->once()->andReturn('Container started.');+ $fluxClient->shouldReceive('inspectContainer')->once()->andReturn(['State' => ['Running' => true]]);+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ ])+ ->postJson('/v5/applications/nginx', [+ 'server_uuid' => $server->uuid,+ 'image' => 'docker.io/library/nginx:alpine',+ ])+ ->assertSuccessful()+ ->assertJsonPath('application.id', fn (string $id): bool => $id !== (string) V5Application::query()->latest('id')->value('id'));+});++it('generates http-only caddy routes for application ingress', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['ingress'],+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '200%',+ 'wireguard_management_ip' => '100.64.0.10',+ 'last_bootstrapped_at' => now(),+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-test',+ 'status' => 'running',+ 'mesh_namespace' => 'default',+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient+ ->shouldReceive('applyIngress')+ ->once()+ ->with(+ Mockery::type('string'),+ 'caddy',+ Mockery::on(fn (string $caddyfile): bool => str_contains($caddyfile, 'import apps/*.caddy')),+ Mockery::on(fn (array $apps): bool => count($apps) === 1+ && str_contains($apps[0]['config'], 'http://app.example.com {')+ && ! str_contains($apps[0]['config'], 'https://')+ && str_contains($apps[0]['config'], 'reverse_proxy coolify-v5-nginx-test.default.coolify.internal:3000'))+ )+ ->andReturn('Caddy ingress applied.');+ expectCaddyIngressFirewallRule($fluxClient);+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/applications/{$application->uuid}/ingress", [+ 'ingress_enabled' => true,+ 'internal_port' => 3000,+ 'domains' => ['app.example.com'],+ ])+ ->assertSuccessful();+});++it('rejects malformed ingress domains before they reach the caddy configuration', function (string $domain) {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['ingress'],+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '200%',+ 'wireguard_management_ip' => '100.64.0.10',+ 'last_bootstrapped_at' => now(),+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-test',+ 'status' => 'running',+ 'mesh_namespace' => 'default',+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldNotReceive('applyIngress');+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/applications/{$application->uuid}/ingress", [+ 'ingress_enabled' => true,+ 'internal_port' => 3000,+ 'domains' => [$domain],+ ])+ ->assertStatus(422)+ ->assertJsonValidationErrors('domains.0');++ expect($application->refresh()->ingress_enabled)->toBeFalse()+ ->and($application->domains()->count())->toBe(0);+})->with([+ 'caddy block injection' => "evil.com {\n} http://x",+ 'embedded newline' => "evil\n.com",+ 'braces' => 'evil.com{}',+ 'whitespace' => 'evil.com respond',+ 'too long' => str_repeat('a', 254),+]);++it('creates an nginx v5 application on the first installed team server', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'last_bootstrapped_at' => now(),+ ]);++ fakeSuccessfulNginxFluxDeployment();++ $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ ])+ ->postJson('/v5/applications/nginx')+ ->assertAccepted()+ ->assertJsonPath('application.name', 'nginx-test')+ ->assertJsonPath('application.image', 'docker.io/library/nginx:alpine')+ ->assertJsonPath('application.status', 'creating')+ ->assertJsonPath('application.serverName', 'edge-01')+ ->assertJsonPath('application.meshNamespace', 'default')+ ->assertJsonPath('application.canvasX', 0)+ ->assertJsonPath('application.canvasY', 0);++ expect(V5Application::query()+ ->where('team_id', $team->id)+ ->where('project_id', $project->id)+ ->where('environment_id', $environment->id)+ ->where('name', 'nginx-test')+ ->where('status', 'running')+ ->where('runtime_container_id', 'nginx-container-id')+ ->exists())->toBeTrue();+});++it('creates an nginx v5 application with a custom image', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'private_key_uuid' => $privateKey->uuid,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'last_bootstrapped_at' => now(),+ ]);++ fakeSuccessfulNginxFluxDeployment(image: 'docker.io/library/httpd:alpine');++ $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ ])+ ->postJson('/v5/applications/nginx', [+ 'image' => 'docker.io/library/httpd:alpine',+ ])+ ->assertAccepted()+ ->assertJsonPath('application.image', 'docker.io/library/httpd:alpine');++ expect(V5Application::query()+ ->where('image', 'docker.io/library/httpd:alpine')+ ->where('runtime_container_id', 'nginx-container-id')+ ->exists())->toBeTrue();+});++it('creates an nginx v5 application on the selected team server', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'last_bootstrapped_at' => now(),+ ]);+ $selectedServer = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'edge-02',+ 'host' => '203.0.113.11',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'last_bootstrapped_at' => now(),+ ]);++ fakeSuccessfulNginxFluxDeployment();++ $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ ])+ ->postJson('/v5/applications/nginx', [+ 'server_uuid' => $selectedServer->uuid,+ ])+ ->assertAccepted()+ ->assertJsonPath('application.serverName', 'edge-02');++ expect(V5Application::query()+ ->where('server_id', $selectedServer->id)+ ->where('runtime_container_id', 'nginx-container-id')+ ->exists())->toBeTrue();+});++it('places a new nginx v5 application next to existing canvas nodes', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'last_bootstrapped_at' => now(),+ ]);++ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-existing',+ 'status' => 'running',+ 'status_message' => 'Running.',+ 'mesh_namespace' => 'default',+ 'canvas_x' => 0,+ 'canvas_y' => 0,+ ]);++ fakeSuccessfulNginxFluxDeployment();++ $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ ])+ ->postJson('/v5/applications/nginx')+ ->assertAccepted()+ ->assertJsonPath('application.canvasX', 352)+ ->assertJsonPath('application.canvasY', 0);+});++it('marks an nginx v5 application failed when the launch command fails', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'private_key_uuid' => $privateKey->uuid,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'last_bootstrapped_at' => now(),+ ]);++ $this->mock(FluxClient::class, function (MockInterface $mock): void {+ $mock->shouldReceive('pullImage')->once()->andThrow(new RuntimeException('podman failed'));+ });++ $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ ])+ ->postJson('/v5/applications/nginx')+ ->assertAccepted()+ ->assertJsonPath('application.status', 'creating');++ expect(V5Application::query()+ ->where('status', 'failed')+ ->where('status_message', 'podman failed')+ ->exists())->toBeTrue();+});++it('queues the nginx deploy instead of running it in the http request', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'last_bootstrapped_at' => now(),+ ]);++ Queue::fake();++ $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ ])+ ->postJson('/v5/applications/nginx')+ ->assertAccepted()+ ->assertJsonPath('application.status', 'creating');++ Queue::assertPushed(V5DeployApplicationJob::class);+});++it('refuses to deploy nginx to a server that is not bootstrapped', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'capabilities' => [],+ ]);++ $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ ])+ ->postJson('/v5/applications/nginx', [+ 'server_uuid' => $server->uuid,+ ])+ ->assertUnprocessable()+ ->assertJsonPath('message', 'Bootstrap server edge-01 before deploying to it.');++ expect(V5Application::query()->count())->toBe(0);+});++it('does not create an nginx v5 application on another teams selected server', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$otherUser, $otherTeam] = createV5UserWithTeam('[email protected]');+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $privateKey = createV5PrivateKey($otherTeam, 'Other SSH Key');+ $otherServer = V5Server::query()->create([+ 'team_id' => $otherTeam->id,+ 'created_by_user_id' => $otherUser->id,+ 'private_key_uuid' => $privateKey->uuid,+ 'name' => 'other-edge-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'last_bootstrapped_at' => now(),+ ]);++ $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ ])+ ->postJson('/v5/applications/nginx', [+ 'server_id' => $otherServer->id,+ ])+ ->assertUnprocessable()+ ->assertJsonPath('message', 'Add a v5 server before deploying nginx.');++ expect(V5Application::query()->count())->toBe(0);+});++it('does not create an nginx v5 application without a team server', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');++ $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ ])+ ->postJson('/v5/applications/nginx')+ ->assertUnprocessable()+ ->assertJsonPath('message', 'Add a v5 server before deploying nginx.');++ expect(V5Application::query()->count())->toBe(0);+});++it('deletes a v5 application for the current team', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->deleteJson("/v5/applications/{$application->uuid}")+ ->assertNoContent();++ expect(V5Application::query()->whereKey($application->id)->exists())->toBeFalse();+});++it('stops and deletes the nginx container before deleting a v5 application', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ 'runtime_container_id' => 'nginx-container-id',+ ]);++ Process::fake([+ '*' => Process::result(),+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->deleteJson("/v5/applications/{$application->uuid}")+ ->assertNoContent();++ Process::assertRan(function ($process): bool {+ $command = is_array($process->command) ? implode(' ', $process->command) : $process->command;++ return is_string($command)+ && str_contains($command, '203.0.113.10')+ && str_contains($command, 'podman rm -f')+ && str_contains($command, 'coolify-v5-nginx-1');+ });+ expect(V5Application::query()->whereKey($application->id)->exists())->toBeFalse();+});++it('cleans v5 application ingress routes and firewall connections before deleting an application', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['ingress'],+ 'wireguard_management_ip' => '100.64.0.10',+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'api',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-api',+ 'status' => 'running',+ 'mesh_namespace' => 'default',+ 'ingress_enabled' => true,+ 'internal_port' => 8080,+ ]);+ V5ApplicationDomain::query()->create([+ 'application_id' => $application->id,+ 'domain' => 'api.example.com',+ ]);+ $target = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'postgres',+ 'image' => 'docker.io/library/postgres:16',+ 'container_name' => 'coolify-v5-postgres',+ 'status' => 'running',+ 'mesh_namespace' => 'default',+ ]);+ $connection = ResourceConnection::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'resource_one_type' => $application->getMorphClass(),+ 'resource_one_id' => $application->id,+ 'resource_two_type' => $target->getMorphClass(),+ 'resource_two_id' => $target->id,+ 'resource_pair_key' => "application:{$application->id}|application:{$target->id}",+ 'created_by_user_id' => $user->id,+ ]);+ $connection->rules()->create([+ 'source_resource_type' => $application->getMorphClass(),+ 'source_resource_id' => $application->id,+ 'target_resource_type' => $target->getMorphClass(),+ 'target_resource_id' => $target->id,+ 'protocol' => 'tcp',+ 'port' => 5432,+ ]);++ $firewallRuleId = "v5-resource-connection:{$connection->id}:{$application->id}:{$target->id}:tcp:5432";+ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient+ ->shouldReceive('revokeFirewallRule')+ ->once()+ ->with(Mockery::type('string'), $firewallRuleId)+ ->andReturn('Firewall rule removed.');+ $fluxClient+ ->shouldReceive('applyIngress')+ ->once()+ ->with(+ Mockery::type('string'),+ 'caddy',+ Mockery::on(fn (string $caddyfile): bool => str_contains($caddyfile, 'import apps/*.caddy')),+ Mockery::on(fn (array $apps): bool => $apps === [])+ )+ ->andReturn('Caddy ingress applied.');+ expectCaddyIngressFirewallRule($fluxClient);+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->deleteJson("/v5/applications/{$application->uuid}")+ ->assertNoContent();++ expect(V5Application::query()->whereKey($application->id)->exists())->toBeFalse()+ ->and(ResourceConnection::query()->whereKey($connection->id)->exists())->toBeFalse();+});++it('deletes a v5 application locally when remote cleanup is explicitly skipped', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'edge-01',+ 'host' => 'coold-dev-2.local',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'unknown',+ 'runtime_container_id' => 'nginx-container-id',+ ]);++ Process::fake([+ '*' => Process::result(errorOutput: 'ssh: Could not resolve hostname coold-dev-2.local: Try again', exitCode: 255),+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->deleteJson("/v5/applications/{$application->uuid}", ['delete_locally' => true])+ ->assertNoContent();++ Process::assertNothingRan();++ expect(V5Application::query()->whereKey($application->id)->exists())->toBeFalse();+});++it('restores v5 application ingress and firewall rules when application runtime deletion fails', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['ingress'],+ 'wireguard_management_ip' => '100.64.0.10',+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'api',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-api',+ 'status' => 'running',+ 'mesh_namespace' => 'default',+ 'ingress_enabled' => true,+ 'internal_port' => 8080,+ ]);+ V5ApplicationDomain::query()->create([+ 'application_id' => $application->id,+ 'domain' => 'api.example.com',+ ]);+ $target = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'postgres',+ 'image' => 'docker.io/library/postgres:16',+ 'container_name' => 'coolify-v5-postgres',+ 'status' => 'running',+ 'mesh_namespace' => 'default',+ ]);+ $connection = ResourceConnection::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'resource_one_type' => $application->getMorphClass(),+ 'resource_one_id' => $application->id,+ 'resource_two_type' => $target->getMorphClass(),+ 'resource_two_id' => $target->id,+ 'resource_pair_key' => "application:{$application->id}|application:{$target->id}",+ 'created_by_user_id' => $user->id,+ ]);+ $connection->rules()->create([+ 'source_resource_type' => $application->getMorphClass(),+ 'source_resource_id' => $application->id,+ 'target_resource_type' => $target->getMorphClass(),+ 'target_resource_id' => $target->id,+ 'protocol' => 'tcp',+ 'port' => 5432,+ ]);++ $firewallRuleId = "v5-resource-connection:{$connection->id}:{$application->id}:{$target->id}:tcp:5432";+ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient+ ->shouldReceive('revokeFirewallRule')+ ->once()+ ->with(Mockery::type('string'), $firewallRuleId)+ ->andReturn('Firewall rule removed.');+ $fluxClient+ ->shouldReceive('applyIngress')+ ->twice()+ ->with(+ Mockery::type('string'),+ 'caddy',+ Mockery::type('string'),+ Mockery::on(fn (array $apps): bool => $apps === [] || collect($apps)->contains(fn (array $app): bool => $app['name'] === "app_{$application->id}"))+ )+ ->andReturn('Caddy ingress applied.');+ $fluxClient+ ->shouldReceive('applyFirewallRule')+ ->twice()+ ->with(Mockery::type('string'), Mockery::on(fn (array $rule): bool => $rule['id'] === 'v5-caddy-ingress:80'))+ ->andReturn('Caddy firewall rule applied.');+ $fluxClient+ ->shouldReceive('applyFirewallRule')+ ->once()+ ->with(Mockery::type('string'), Mockery::on(fn (array $rule): bool => $rule['id'] === $firewallRuleId && $rule['port'] === 5432))+ ->andReturn('Firewall rule restored.');+ app()->instance(FluxClient::class, $fluxClient);+ Process::fake([+ '*' => Process::result(errorOutput: "ssh failed\n", exitCode: 1),+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->deleteJson("/v5/applications/{$application->uuid}")+ ->assertUnprocessable()+ ->assertJsonPath('message', 'ssh failed')+ ->assertJsonPath('can_delete_locally', true);++ $application->refresh();++ expect(V5Application::query()->whereKey($application->id)->exists())->toBeTrue()+ ->and($application->ingress_enabled)->toBeTrue()+ ->and($application->internal_port)->toBe(8080)+ ->and($application->domains()->pluck('domain')->all())->toBe(['api.example.com'])+ ->and($connection->rules()->count())->toBe(1);+});++it('does not delete another teams v5 application', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$otherUser, $otherTeam] = createV5UserWithTeam();+ [$otherProject, $otherEnvironment] = createV5ProjectWithEnvironment($otherTeam, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $otherTeam->id,+ 'created_by_user_id' => $otherUser->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $otherTeam->id,+ 'project_id' => $otherProject->id,+ 'environment_id' => $otherEnvironment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $otherUser->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->deleteJson("/v5/applications/{$application->uuid}")+ ->assertNotFound();++ expect(V5Application::query()->whereKey($application->id)->exists())->toBeTrue();+});++it('updates v5 application canvas position for the current team', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ 'canvas_x' => 0,+ 'canvas_y' => 0,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/applications/{$application->uuid}/position", [+ 'canvas_x' => 320,+ 'canvas_y' => -160,+ ])+ ->assertSuccessful()+ ->assertJsonPath('application.canvasX', 320)+ ->assertJsonPath('application.canvasY', -160);++ expect($application->refresh()->canvas_x)->toBe(320)+ ->and($application->canvas_y)->toBe(-160);+});++it('refreshes v5 application state from flux container inventory', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.5',+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ 'status_message' => 'Container started.',+ 'runtime_container_id' => 'nginx-container-id',+ 'canvas_x' => 0,+ 'canvas_y' => 0,+ ]);++ $this->mock(FluxClient::class, function (MockInterface $mock): void {+ $mock->shouldReceive('listContainers')+ ->once()+ ->with(Mockery::type('string'))+ ->andReturn([+ [+ 'id' => 'nginx-container-id',+ 'name' => 'coolify-v5-nginx-1',+ 'image' => 'docker.io/library/nginx:alpine',+ 'state' => 'exited',+ 'networks' => ['coolify-default-mesh'],+ ],+ ]);+ });++ $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ ])+ ->postJson('/v5/applications/refresh')+ ->assertSuccessful()+ ->assertJsonPath('applications.0.id', $application->uuid)+ ->assertJsonPath('applications.0.status', 'exited')+ ->assertJsonPath('applications.0.statusMessage', 'Container state refreshed from coold.');++ expect($application->refresh()->status)->toBe('exited')+ ->and($application->status_message)->toBe('Container state refreshed from coold.');+});++it('refreshes v5 caddy ingress state from flux container inventory', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-ingress-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'ingress_status' => 'running',+ 'capabilities' => ['ingress'],+ 'wireguard_management_ip' => '100.64.0.6',+ ]);++ Event::fake([V5CanvasResourceUpdated::class]);++ $this->mock(FluxClient::class, function (MockInterface $mock): void {+ $mock->shouldReceive('listContainers')+ ->once()+ ->with(Mockery::type('string'))+ ->andReturn([+ [+ 'id' => 'caddy-container-id',+ 'name' => 'coolify-v5-caddy',+ 'image' => 'docker.io/library/caddy:2-alpine',+ 'state' => 'exited',+ ],+ ]);+ });++ $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ ])+ ->postJson('/v5/applications/refresh')+ ->assertSuccessful()+ ->assertJsonPath('caddyIngresses.0.id', $server->uuid)+ ->assertJsonPath('caddyIngresses.0.type', 'caddy')+ ->assertJsonPath('caddyIngresses.0.status', 'exited');++ expect($server->refresh()->status)->toBe('installed')+ ->and($server->ingress_type)->toBe('caddy')+ ->and($server->ingress_status)->toBe('exited')+ ->and($server->last_status_check)->toBe('flux')+ ->and($server->last_status_output)->toBe('Caddy ingress state refreshed from coold.');++ Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id+ && $event->caddyIngressServerId === $server->id);+});++it('rejects application ingress when server ingress is disabled', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'app-01',+ 'host' => '203.0.113.21',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '200%',+ 'wireguard_management_ip' => '100.64.0.11',+ 'last_bootstrapped_at' => now(),+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'private-app',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-private-app',+ 'status' => 'running',+ 'mesh_namespace' => 'default',+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldNotReceive('applyIngress');+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/applications/{$application->uuid}/ingress", [+ 'ingress_enabled' => true,+ 'internal_port' => 3000,+ 'domains' => ['app.example.com'],+ ])+ ->assertUnprocessable()+ ->assertJsonPath('message', 'Enable ingress on the server before enabling app ingress.');++ expect($application->refresh()->ingress_enabled)->toBeFalse()+ ->and($application->domains()->count())->toBe(0);+});++it('enables application ingress without publishing domains by default', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['ingress'],+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '200%',+ 'wireguard_management_ip' => '100.64.0.10',+ 'last_bootstrapped_at' => now(),+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-test',+ 'status' => 'running',+ 'mesh_namespace' => 'default',+ ]);+ V5ApplicationDomain::query()->create([+ 'application_id' => $application->id,+ 'domain' => 'kept.example.com',+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient+ ->shouldReceive('applyIngress')+ ->once()+ ->with(+ Mockery::type('string'),+ 'caddy',+ Mockery::on(fn (string $caddyfile): bool => str_contains($caddyfile, 'import apps/*.caddy')),+ []+ )+ ->andReturn('Caddy ingress applied.');+ expectCaddyIngressFirewallRule($fluxClient);+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/applications/{$application->uuid}/ingress", [+ 'ingress_enabled' => false,+ 'internal_port' => 8080,+ ])+ ->assertSuccessful()+ ->assertJsonPath('application.ingressEnabled', false)+ ->assertJsonPath('application.internalPort', 8080)+ ->assertJsonPath('application.domains.0', 'kept.example.com');++ expect($application->refresh()->ingress_enabled)->toBeFalse();+});++it('validates application ingress domains', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['ingress'],+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '200%',+ 'wireguard_management_ip' => '100.64.0.10',+ 'last_bootstrapped_at' => now(),+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-test',+ 'status' => 'running',+ 'mesh_namespace' => 'default',+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldNotReceive('applyIngress');+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/applications/{$application->uuid}/ingress", [+ 'ingress_enabled' => true,+ 'internal_port' => 3000,+ 'domains' => ['https://bad.example.com'],+ ])+ ->assertUnprocessable()+ ->assertInvalid(['domains.0']);++ expect($application->refresh()->ingress_enabled)->toBeFalse();+});++it('enables application ingress with explicit domains and port', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['ingress'],+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '200%',+ 'wireguard_management_ip' => '100.64.0.10',+ 'last_bootstrapped_at' => now(),+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-test',+ 'status' => 'running',+ 'mesh_namespace' => 'default',+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient+ ->shouldReceive('applyIngress')+ ->once()+ ->with(+ Mockery::type('string'),+ 'caddy',+ Mockery::on(fn (string $caddyfile): bool => str_contains($caddyfile, 'import apps/*.caddy')),+ Mockery::on(fn (array $apps): bool => count($apps) === 1+ && str_contains($apps[0]['config'], 'http://app.example.com {')+ && str_contains($apps[0]['config'], 'reverse_proxy coolify-v5-nginx-test.default.coolify.internal:3000'))+ )+ ->andReturn('Caddy ingress applied.');+ expectCaddyIngressFirewallRule($fluxClient);+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/applications/{$application->uuid}/ingress", [+ 'ingress_enabled' => true,+ 'internal_port' => 3000,+ 'domains' => ['app.example.com'],+ ])+ ->assertSuccessful()+ ->assertJsonPath('application.ingressEnabled', true)+ ->assertJsonPath('application.internalPort', 3000)+ ->assertJsonPath('application.domains.0', 'app.example.com');++ expect($application->refresh()->ingress_enabled)->toBeTrue()+ ->and($application->internal_port)->toBe(3000)+ ->and($application->domains()->pluck('domain')->all())->toBe(['app.example.com']);+});++it('returns flux error details when application ingress sync fails', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['ingress'],+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '200%',+ 'wireguard_management_ip' => '100.64.0.10',+ 'last_bootstrapped_at' => now(),+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-test',+ 'status' => 'running',+ 'mesh_namespace' => 'default',+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient+ ->shouldReceive('applyIngress')+ ->once()+ ->andThrow(new RuntimeException('start Caddy ingress: podman exited with status 125'));+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/applications/{$application->uuid}/ingress", [+ 'ingress_enabled' => true,+ 'internal_port' => 3000,+ 'domains' => ['app.example.com'],+ ])+ ->assertStatus(502)+ ->assertJsonPath('message', 'Could not start Caddy ingress on the server. Check that Podman is running and port 80 is available.')+ ->assertJsonPath('detail', 'start Caddy ingress: podman exited with status 125');++ expect($application->refresh()->ingress_enabled)->toBeFalse()+ ->and($application->internal_port)->toBeNull()+ ->and($application->domains()->count())->toBe(0);+});++it('rejects a domain already claimed by another application on the same ingress server', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'capabilities' => ['ingress'],+ 'ingress_type' => 'caddy',+ ]);+ $otherServer = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-02',+ 'host' => '203.0.113.11',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'capabilities' => ['ingress'],+ 'ingress_type' => 'caddy',+ ]);+ $owner = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'owner-app',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-owner',+ 'status' => 'running',+ 'ingress_enabled' => true,+ 'internal_port' => 8080,+ ]);+ V5ApplicationDomain::query()->create([+ 'application_id' => $owner->id,+ 'domain' => 'app.example.com',+ ]);+ $sameServerApp = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'challenger-app',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-challenger',+ 'status' => 'running',+ ]);+ $otherServerApp = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $otherServer->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'elsewhere-app',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-elsewhere',+ 'status' => 'running',+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])+ ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')+ ->patchJson("/v5/applications/{$sameServerApp->uuid}/ingress", [+ 'ingress_enabled' => true,+ 'internal_port' => 8081,+ 'domains' => ['App.Example.Com'],+ ])+ ->assertUnprocessable()+ ->assertJsonPath('message', 'The domain app.example.com is already used by application "owner-app" on this server.');++ expect($sameServerApp->refresh()->ingress_enabled)->toBeFalse();++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])+ ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')+ ->patchJson("/v5/applications/{$otherServerApp->uuid}/ingress", [+ 'ingress_enabled' => true,+ 'internal_port' => 8081,+ 'domains' => ['app.example.com'],+ ])+ ->assertSuccessful();++ expect($otherServerApp->refresh()->ingress_enabled)->toBeTrue();+});++it('does not mark creating v5 applications as exited during a refresh', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.10',+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'creating',+ 'status_message' => 'Starting nginx container.',+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('listContainers')->andReturn([]);+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ '_token' => 'test-csrf-token',+ ])+ ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')+ ->postJson('/v5/applications/refresh')+ ->assertSuccessful();++ expect($application->refresh()->status)->toBe('creating');+});++it('returns deploy status without logs for a failed v5 application that has no container', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.10',+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'failed',+ 'status_message' => 'host not connected',+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldNotReceive('containerLogs');+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->getJson("/v5/applications/{$application->uuid}/logs")+ ->assertSuccessful()+ ->assertJson([+ 'status' => 'failed',+ 'statusMessage' => 'host not connected',+ 'containerId' => null,+ 'logs' => null,+ 'logsError' => null,+ ]);+});++it('returns container logs for a v5 application through flux', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.10',+ 'node_address' => '203.0.113.10',+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ 'status_message' => 'Container running.',+ 'runtime_container_id' => 'container-abc',+ ]);++ $this->mock(FluxClient::class, function (MockInterface $mock): void {+ $mock->shouldReceive('containerLogs')+ ->once()+ ->with(Mockery::type('string'), 'container-abc')+ ->andReturn("nginx started\nlistening on :80");+ });++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->getJson("/v5/applications/{$application->uuid}/logs")+ ->assertSuccessful()+ ->assertJson([+ 'status' => 'running',+ 'containerId' => 'container-abc',+ 'logs' => "nginx started\nlistening on :80",+ 'logsError' => null,+ ]);+});++it('reports a friendly error when the node coold does not support container logs', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.10',+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ 'status_message' => 'Container running.',+ 'runtime_container_id' => 'container-abc',+ ]);++ $this->mock(FluxClient::class, function (MockInterface $mock): void {+ $mock->shouldReceive('containerLogs')+ ->once()+ ->andThrow(new UnsupportedCooldVerb('containers.logs', 'primitive containers.logs is not supported by host'));+ });++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->getJson("/v5/applications/{$application->uuid}/logs")+ ->assertSuccessful()+ ->assertJson([+ 'logs' => null,+ 'logsError' => "This node's coold does not support container logs.",+ ]);+});++it('hides another team v5 application logs as a not found', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$otherUser, $otherTeam] = createV5UserWithTeam('[email protected]');+ [$project, $environment] = createV5ProjectWithEnvironment($otherTeam, 'Other Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $otherTeam->id,+ 'created_by_user_id' => $otherUser->id,+ 'name' => 'edge-99',+ 'host' => '203.0.113.99',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.99',+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $otherTeam->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $otherUser->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-9',+ 'status' => 'running',+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->getJson("/v5/applications/{$application->uuid}/logs")+ ->assertNotFound();+});diff --git a/tests/Feature/V5/BootstrapPreflightTest.php b/tests/Feature/V5/BootstrapPreflightTest.phpnew file mode 100644index 0000000000..7745bb0610--- /dev/null+++ b/tests/Feature/V5/BootstrapPreflightTest.php@@ -0,0 +1,251 @@+<?php++use App\Events\V5CanvasResourceUpdated;+use App\Events\V5ClusterUpdated;+use App\Jobs\V5BootstrapServerJob;+use App\Models\PrivateKey;+use App\Models\Team;+use App\Models\User;+use App\Models\V5\Cluster;+use App\Models\V5\Server as V5Server;+use App\Services\Flux\AgentTokenIssuer;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Event;+use Illuminate\Support\Facades\Process;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Facades\Schema;+use Tests\Support\V5TestSchema;++beforeEach(function () {+ Config::set('broadcasting.default', 'log');+ Config::set('cache.default', 'array');++ Schema::dropIfExists('v5_servers');+ Schema::dropIfExists('v5_clusters');+ Schema::dropIfExists('private_keys');+ Schema::dropIfExists('team_user');+ Schema::dropIfExists('teams');+ Schema::dropIfExists('users');+});++function createBootstrapPreflightTables(): void+{+ Schema::create('users', function ($table) {+ $table->id();+ $table->string('name')->default('Anonymous');+ $table->string('email');+ $table->timestamp('email_verified_at')->nullable();+ $table->string('password')->nullable();+ $table->rememberToken();+ $table->timestamps();+ });++ Schema::create('teams', function ($table) {+ $table->id();+ $table->string('name');+ $table->string('description')->nullable();+ $table->boolean('personal_team')->default(false);+ $table->boolean('show_boarding')->default(false);+ $table->timestamps();+ });++ Schema::create('team_user', function ($table) {+ $table->id();+ $table->foreignId('team_id');+ $table->foreignId('user_id');+ $table->string('role')->default('member');+ $table->timestamps();++ $table->unique(['team_id', 'user_id']);+ });++ Schema::create('private_keys', function ($table) {+ $table->id();+ $table->string('uuid')->unique();+ $table->string('name');+ $table->string('description')->nullable();+ $table->longText('private_key');+ $table->string('fingerprint')->nullable();+ $table->boolean('is_git_related')->default(false);+ $table->foreignId('team_id');+ $table->timestamps();+ });++ V5TestSchema::createClustersTable();+ V5TestSchema::createServersTable();+}++/**+ * @return array{0: User, 1: Team}+ */+function createBootstrapPreflightUserWithTeam(): array+{+ $user = User::withoutEvents(fn () => User::query()->create([+ 'name' => 'Margaret Hamilton',+ 'email' => '[email protected]',+ 'email_verified_at' => now(),+ 'password' => 'password',+ ]));+ $team = Team::withoutEvents(fn () => Team::query()->create([+ 'name' => 'V5 Tooling Team',+ 'description' => null,+ 'personal_team' => false,+ 'show_boarding' => false,+ ]));+ $user->teams()->attach($team, ['role' => 'owner']);++ return [$user, $team];+}++function createBootstrapPreflightPrivateKey(Team $team): PrivateKey+{+ return PrivateKey::withoutEvents(fn () => PrivateKey::query()->forceCreate([+ 'uuid' => 'preflight-key-uuid',+ 'name' => 'Preflight SSH Key',+ 'description' => null,+ 'private_key' => "-----BEGIN OPENSSH PRIVATE KEY-----\ntest-key\n-----END OPENSSH PRIVATE KEY-----\n",+ 'fingerprint' => 'preflight-key',+ 'is_git_related' => false,+ 'team_id' => $team->id,+ ]));+}++/**+ * @return array{0: User, 1: Team, 2: Cluster, 3: V5Server}+ */+function createBootstrapPreflightClusterWithServer(array $clusterAttributes = [], array $serverAttributes = []): array+{+ [$user, $team] = createBootstrapPreflightUserWithTeam();+ $privateKey = createBootstrapPreflightPrivateKey($team);+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ...$clusterAttributes,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ ...$serverAttributes,+ ]);++ return [$user, $team, $cluster, $server];+}++it('rejects bootstrap when flux url is not configured', function () {+ createBootstrapPreflightTables();+ Config::set('coold.flux_url', '');++ [$user, $team, $cluster, $server] = createBootstrapPreflightClusterWithServer();++ Queue::fake();++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/bootstrap")+ ->assertUnprocessable()+ ->assertJsonPath('message', 'COOLIFY_COOLD_FLUX_URL is not configured, so bootstrapped servers cannot be enrolled into Flux. Set it and retry the bootstrap.');++ Queue::assertNothingPushed();++ // The claim must not have been written either.+ expect($server->refresh()->last_bootstrap_status)->toBeNull();+});++it('queues the bootstrap when the flux url is configured', function () {+ createBootstrapPreflightTables();+ Config::set('coold.flux_url', 'http://coolify.example.com:6443');++ [$user, $team, $cluster, $server] = createBootstrapPreflightClusterWithServer();++ Queue::fake();++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/bootstrap")+ ->assertAccepted()+ ->assertJsonPath('message', 'Bootstrap queued.');++ Queue::assertPushed(V5BootstrapServerJob::class);+});++it('writes the marker with the same coold version that is persisted on the server row', function () {+ createBootstrapPreflightTables();+ Config::set('coold.coolify_cli_bin', '/tmp/coolify');+ Config::set('coold.flux_url', 'http://coolify.example.com:6443');++ [, , $cluster, $server] = createBootstrapPreflightClusterWithServer([+ 'namespaces' => ['default'],+ 'coold_version' => 'v0.9.9',+ ], [+ 'last_bootstrap_status' => 'queued',+ 'last_bootstrap_ran_at' => now(),+ ]);++ $issuer = Mockery::mock(AgentTokenIssuer::class);+ $issuer->shouldReceive('issueForServer')->andReturn('signed-host-jwt');+ app()->instance(AgentTokenIssuer::class, $issuer);++ // The CLI reports a newer coold version than the cluster asked for; the+ // marker and the database row must both use the reported version.+ Process::fake([+ '*' => Process::sequence()+ ->push(Process::result(output: ''))+ ->push(Process::result(output: json_encode([+ 'results' => [],+ 'coold_version' => 'v1.2.3',+ 'verified' => [[+ 'host' => "v5-server-{$server->uuid}",+ 'wireguard_ip' => '100.64.0.1',+ 'peer_count' => 0,+ 'status' => 'ok',+ ]],+ ], JSON_THROW_ON_ERROR)."\n"))+ ->push(Process::result(output: "public-key\n"))+ ->push(Process::result(output: "default=10.210.0.0/24\n"))+ ->push(Process::result(output: "marker written\n"))+ ->push(Process::result(output: "coold restarted\n")),+ ]);++ Event::fake([V5ClusterUpdated::class, V5CanvasResourceUpdated::class]);++ (new V5BootstrapServerJob($cluster->id, $server->id))->handle();++ $server->refresh();++ expect($server->last_bootstrap_status)->toBe('succeeded')+ ->and($server->status)->toBe('installed')+ ->and($server->coold_version)->toBe('v1.2.3');++ $markerPayload = null;++ Process::assertRan(function ($process) use (&$markerPayload): bool {+ $command = implode(' ', array_map(fn ($part) => is_string($part) ? $part : json_encode($part), $process->command));++ if (! str_contains($command, 'v5-node.json') || ! str_contains($command, 'base64 -d')) {+ return false;+ }++ if (preg_match("/payload='([^']+)'/", $command, $matches) === 1) {+ $markerPayload = json_decode(base64_decode($matches[1], true), true);+ }++ return true;+ });++ expect($markerPayload)->toBeArray()+ ->and($markerPayload['coold_version'])->toBe('v1.2.3')+ ->and($markerPayload['coold_version'])->toBe($server->coold_version)+ ->and($markerPayload['server_uuid'])->toBe($server->uuid)+ ->and($markerPayload['wireguard_management_ip'])->toBe('100.64.0.1');+});diff --git a/tests/Feature/V5/BroadcastChannelAuthTest.php b/tests/Feature/V5/BroadcastChannelAuthTest.phpnew file mode 100644index 0000000000..a384d71608--- /dev/null+++ b/tests/Feature/V5/BroadcastChannelAuthTest.php@@ -0,0 +1,71 @@+<?php++use App\Models\Team;+use App\Models\User;+use Illuminate\Support\Facades\Config;++beforeEach(function () {+ resetV5DashboardTestState();+ createSharedUserAndTeamTables();++ Config::set('broadcasting.default', 'pusher');+ Config::set('broadcasting.connections.pusher.key', 'test-key');+ Config::set('broadcasting.connections.pusher.secret', 'test-secret');+ Config::set('broadcasting.connections.pusher.app_id', 'test-app-id');+ Config::set('broadcasting.connections.pusher.options', [+ 'host' => '127.0.0.1',+ 'port' => 6001,+ 'scheme' => 'http',+ 'useTLS' => false,+ ]);+});++it('authorizes team members on their private team channel', function () {+ [$user, $team] = createV5UserWithTeam();++ $this+ ->actingAs($user)+ ->postJson('/broadcasting/auth', [+ 'channel_name' => "private-team.{$team->id}",+ 'socket_id' => '1234.5678',+ ])+ ->assertSuccessful()+ ->assertJsonStructure(['auth']);+});++it('rejects users outside the team on the private team channel', function () {+ [, $team] = createV5UserWithTeam();++ $outsider = User::withoutEvents(fn () => User::query()->create([+ 'name' => 'Outsider',+ 'email' => '[email protected]',+ 'email_verified_at' => now(),+ 'password' => 'password',+ ]));+ $otherTeam = Team::withoutEvents(fn () => Team::query()->create([+ 'name' => 'Another Team',+ 'description' => null,+ 'personal_team' => false,+ 'show_boarding' => false,+ ]));+ $outsider->teams()->attach($otherTeam, ['role' => 'owner']);++ $this+ ->actingAs($outsider)+ ->postJson('/broadcasting/auth', [+ 'channel_name' => "private-team.{$team->id}",+ 'socket_id' => '1234.5678',+ ])+ ->assertForbidden();+});++it('rejects guests on the private team channel', function () {+ [, $team] = createV5UserWithTeam();++ $this+ ->postJson('/broadcasting/auth', [+ 'channel_name' => "private-team.{$team->id}",+ 'socket_id' => '1234.5678',+ ])+ ->assertForbidden();+});diff --git a/tests/Feature/V5/ClusterControllerTest.php b/tests/Feature/V5/ClusterControllerTest.phpnew file mode 100644index 0000000000..394c8b9af1--- /dev/null+++ b/tests/Feature/V5/ClusterControllerTest.php@@ -0,0 +1,417 @@+<?php++use App\Models\Team;+use App\Models\User;+use App\Models\V5\Cluster;+use App\Models\V5\Server as V5Server;++beforeEach(function () {+ resetV5DashboardTestState();+});++it('returns fresh v5 cluster bootstrap state for realtime fallback refreshes', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'last_bootstrap_action' => 'bootstrap',+ 'last_bootstrap_status' => 'running',+ 'last_bootstrap_output' => 'Starting Coolify CLI bootstrap for prod-01...',+ 'last_bootstrap_ran_at' => now(),+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->getJson("/v5/clusters/{$cluster->uuid}")+ ->assertSuccessful()+ ->assertJsonPath('cluster.id', $cluster->uuid)+ ->assertJsonPath('cluster.servers.0.id', $server->uuid)+ ->assertJsonPath('cluster.servers.0.lastBootstrapStatus', 'running')+ ->assertJsonPath('cluster.servers.0.lastBootstrapOutput', 'Starting Coolify CLI bootstrap for prod-01...');+});++it('shows v5 clusters with their servers on the cluster page', function () {+ $this->withoutVite();+ fakeFluxHealth();+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Lima Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Development-Lima',+ 'description' => 'Local Lima development cluster managed by scripts/dev.sh.',+ ]);+ V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'coold-dev',+ 'host' => 'lima-coold-dev',+ 'ssh_user' => 'developer',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['builder'],+ 'builder_enabled' => true,+ 'builder_capacity' => 2,+ 'last_bootstrapped_at' => now(),+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->get('/v5/clusters')+ ->assertSuccessful()+ ->assertSee('Clusters', false)+ ->assertSee('"clusters":[', false)+ ->assertSee('"privateKeys":[', false)+ ->assertSee('"name":"Lima Key"', false)+ ->assertSee('"name":"Development-Lima"', false)+ ->assertSee('"serversCount":1', false)+ ->assertSee('"name":"coold-dev"', false)+ ->assertSee('"host":"lima-coold-dev"', false)+ ->assertDontSee('"sshUser"', false)+ ->assertDontSee('"sshPort"', false)+ ->assertSee('"builderEnabled":true', false)+ ->assertSee('"builderCapacity":2', false)+ ->assertSee('"wireguardInterface":"wg0"', false)+ ->assertSee('"wireguardManagementPool":"100.64.0.0\\/16"', false)+ ->assertSee('"containerNetworkPool":"10.210.0.0\\/16"', false)+ ->assertSee('"namespaces":["default"]', false)+ ->assertSee('"defaultDenyContainers":true', false)+ ->assertSee('"cooldVersion":"nightly"', false)+ ->assertSee('"corrosionVersion":"v1.0.0"', false)+ ->assertSee('"builderCpuQuota":"200%"', false)+ ->assertSee('"builderMemoryMax":"2G"', false)+ ->assertSee('"builderTimeoutSecs":1800', false)+ ->assertSee('"lastCliStatus":null', false)+ ->assertSee('"privateKeyName":"Lima Key"', false)+ ->assertSee('"nodeAddress":null', false)+ ->assertSee('"wireguardManagementIp":null', false)+ ->assertSee('"containerSubnets":[]', false)+ ->assertSee('"lastBootstrappedAt":"', false);+});++it('creates a v5 cluster for the current team', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson('/v5/clusters', [+ 'name' => 'Production Mesh',+ 'description' => 'Primary production cluster.',+ ])+ ->assertCreated()+ ->assertJsonPath('cluster.name', 'Production Mesh')+ ->assertJsonPath('cluster.description', 'Primary production cluster.')+ ->assertJsonPath('cluster.wireguardInterface', 'wg0')+ ->assertJsonPath('cluster.wireguardManagementPool', '100.64.0.0/16')+ ->assertJsonPath('cluster.wireguardListenPort', 51820)+ ->assertJsonPath('cluster.containerNetworkPool', '10.210.0.0/16')+ ->assertJsonPath('cluster.containerNetworkPrefix', 24)+ ->assertJsonPath('cluster.namespaces', ['default'])+ ->assertJsonPath('cluster.defaultDenyContainers', true)+ ->assertJsonPath('cluster.cooldVersion', 'nightly')+ ->assertJsonPath('cluster.corrosionVersion', 'v1.0.0')+ ->assertJsonPath('cluster.corrosionGossipPort', 8787)+ ->assertJsonPath('cluster.corrosionApiPort', 8080)+ ->assertJsonPath('cluster.builderEnabled', true)+ ->assertJsonPath('cluster.builderCapacity', 2)+ ->assertJsonPath('cluster.builderCpuQuota', '200%')+ ->assertJsonPath('cluster.builderMemoryMax', '2G')+ ->assertJsonPath('cluster.builderTimeoutSecs', 1800)+ ->assertJsonPath('cluster.lastCliAction', null)+ ->assertJsonPath('cluster.lastCliStatus', null)+ ->assertJsonPath('cluster.lastCliSummary', null)+ ->assertJsonPath('cluster.lastCliRanAt', null)+ ->assertJsonPath('cluster.serversCount', 0)+ ->assertJsonPath('cluster.servers', []);++ expect(Cluster::query()+ ->where('team_id', $team->id)+ ->where('created_by_user_id', $user->id)+ ->where('name', 'Production Mesh')+ ->where('description', 'Primary production cluster.')+ ->where('wireguard_interface', 'wg0')+ ->where('wireguard_management_pool', '100.64.0.0/16')+ ->where('container_network_pool', '10.210.0.0/16')+ ->exists())->toBeTrue();+});++it('creates a v5 cluster with advanced cli configuration', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson('/v5/clusters', [+ 'name' => 'Custom Mesh',+ 'description' => null,+ 'wireguard_interface' => 'wg-prod',+ 'wireguard_management_pool' => '100.65.0.0/16',+ 'wireguard_listen_port' => 51830,+ 'container_network_pool' => '10.211.0.0/16',+ 'container_network_prefix' => 25,+ 'namespaces' => ['default', 'preview'],+ 'default_deny_containers' => false,+ 'coold_version' => 'v0.2.0',+ 'corrosion_version' => 'v1.1.0',+ 'corrosion_gossip_port' => 8788,+ 'corrosion_api_port' => 8081,+ 'builder_enabled' => true,+ 'builder_capacity' => 4,+ 'builder_cpu_quota' => '400%',+ 'builder_memory_max' => '4G',+ 'builder_timeout_secs' => 2400,+ ])+ ->assertCreated()+ ->assertJsonPath('cluster.wireguardInterface', 'wg-prod')+ ->assertJsonPath('cluster.wireguardManagementPool', '100.65.0.0/16')+ ->assertJsonPath('cluster.wireguardListenPort', 51830)+ ->assertJsonPath('cluster.containerNetworkPool', '10.211.0.0/16')+ ->assertJsonPath('cluster.containerNetworkPrefix', 25)+ ->assertJsonPath('cluster.namespaces', ['default', 'preview'])+ ->assertJsonPath('cluster.defaultDenyContainers', false)+ ->assertJsonPath('cluster.cooldVersion', 'v0.2.0')+ ->assertJsonPath('cluster.corrosionVersion', 'v1.1.0')+ ->assertJsonPath('cluster.builderCapacity', 4)+ ->assertJsonPath('cluster.builderCpuQuota', '400%')+ ->assertJsonPath('cluster.builderMemoryMax', '4G')+ ->assertJsonPath('cluster.builderTimeoutSecs', 2400);+});++it('validates advanced v5 cluster cli configuration', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson('/v5/clusters', [+ 'name' => 'Broken Mesh',+ 'wireguard_management_pool' => 'not-a-cidr',+ 'container_network_pool' => '10.211.0.0',+ 'wireguard_listen_port' => 70000,+ 'namespaces' => ['Default'],+ ])+ ->assertUnprocessable()+ ->assertJsonValidationErrors([+ 'wireguard_management_pool',+ 'container_network_pool',+ 'wireguard_listen_port',+ 'namespaces.0',+ ]);+});++it('requires positive v5 cluster builder capacity when builders are enabled', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson('/v5/clusters', [+ 'name' => 'Zero Builder Mesh',+ 'builder_enabled' => true,+ 'builder_capacity' => 0,+ ])+ ->assertUnprocessable()+ ->assertJsonValidationErrors(['builder_capacity']);+});++it('validates v5 cluster creation input', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson('/v5/clusters', [+ 'name' => '',+ 'description' => str_repeat('a', 1001),+ ])+ ->assertUnprocessable()+ ->assertJsonValidationErrors(['name', 'description']);+});++it('rejects duplicate v5 cluster names in the same team', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson('/v5/clusters', [+ 'name' => 'Production Mesh',+ 'description' => null,+ ])+ ->assertUnprocessable()+ ->assertJsonValidationErrors(['name']);+});++it('deletes an empty v5 cluster in the current team', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Empty Mesh',+ 'description' => null,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->deleteJson('/v5/clusters/'.$cluster->uuid)+ ->assertNoContent();++ expect(Cluster::query()->whereKey($cluster->id)->exists())->toBeFalse();+});++it('does not delete a v5 cluster that has servers', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Lima Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Development-Lima',+ 'description' => null,+ ]);+ V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'coold-dev',+ 'host' => 'lima-coold-dev',+ 'ssh_user' => 'developer',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['builder'],+ 'builder_enabled' => true,+ 'builder_capacity' => 2,+ 'last_bootstrapped_at' => now(),+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->deleteJson('/v5/clusters/'.$cluster->uuid)+ ->assertUnprocessable()+ ->assertJsonPath('message', 'Only empty clusters can be deleted.');++ expect(Cluster::query()->whereKey($cluster->id)->exists())->toBeTrue();+});++it('does not delete a v5 cluster outside the current team', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $otherTeam = Team::withoutEvents(fn () => Team::query()->create([+ 'name' => 'Other V5 Team',+ 'description' => null,+ 'personal_team' => false,+ 'show_boarding' => false,+ ]));+ $otherUser = User::withoutEvents(fn () => User::query()->create([+ 'name' => 'Other User',+ 'email' => '[email protected]',+ 'email_verified_at' => now(),+ 'password' => 'password',+ ]));+ $cluster = Cluster::query()->create([+ 'team_id' => $otherTeam->id,+ 'created_by_user_id' => $otherUser->id,+ 'name' => 'Other Mesh',+ 'description' => null,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->deleteJson('/v5/clusters/'.$cluster->uuid)+ ->assertNotFound();++ expect(Cluster::query()->whereKey($cluster->id)->exists())->toBeTrue();+});++it('allows the same v5 cluster name in another team without leaking it', function () {+ $this->withoutVite();+ fakeFluxHealth();+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $otherTeam = Team::withoutEvents(fn () => Team::query()->create([+ 'name' => 'Other V5 Team',+ 'description' => null,+ 'personal_team' => false,+ 'show_boarding' => false,+ ]));+ $otherUser = User::withoutEvents(fn () => User::query()->create([+ 'name' => 'Other User',+ 'email' => '[email protected]',+ 'email_verified_at' => now(),+ 'password' => 'password',+ ]));+ Cluster::query()->create([+ 'team_id' => $otherTeam->id,+ 'created_by_user_id' => $otherUser->id,+ 'name' => 'Production Mesh',+ 'description' => 'Other team cluster.',+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson('/v5/clusters', [+ 'name' => 'Production Mesh',+ 'description' => 'Current team cluster.',+ ])+ ->assertCreated()+ ->assertJsonPath('cluster.description', 'Current team cluster.');++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->get('/v5/clusters')+ ->assertSuccessful()+ ->assertSee('Current team cluster.')+ ->assertDontSee('Other team cluster.');+});diff --git a/tests/Feature/V5/DashboardControllerTest.php b/tests/Feature/V5/DashboardControllerTest.phpnew file mode 100644index 0000000000..2569d6405f--- /dev/null+++ b/tests/Feature/V5/DashboardControllerTest.php@@ -0,0 +1,483 @@+<?php++use App\Events\V5RealtimeTestEvent;+use App\Models\Team;+use App\Models\User;+use App\Models\V5\Application as V5Application;+use App\Models\V5\Server as V5Server;+use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;+use Illuminate\Support\Facades\Event;++beforeEach(function () {+ resetV5DashboardTestState();+});++it('serves the v5 inertia shell', function () {+ app()->detectEnvironment(fn () => 'local');++ $this->withoutVite();+ $this->withoutExceptionHandling();+ fakeFluxHealth();+ createSharedUserAndTeamTables();++ $user = User::withoutEvents(fn () => User::query()->create([+ 'name' => 'Ada Lovelace',+ 'email' => '[email protected]',+ 'email_verified_at' => now(),+ 'password' => 'password',+ ]));+ $team = Team::withoutEvents(fn () => Team::query()->create([+ 'name' => 'V5 Shared Team',+ 'description' => 'Shared team details',+ 'personal_team' => true,+ 'show_boarding' => false,+ ]));+ $user->teams()->attach($team, ['role' => 'owner']);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->get('/v5')+ ->assertSuccessful()+ ->assertSee('<html lang="en" class="dark">', false)+ ->assertSee('coolify-logo-dev-transparent.png', false)+ ->assertDontSee('coolify-logo.svg', false)+ ->assertSee('js/echo.js', false)+ ->assertSee('js/pusher.js', false)+ ->assertSee('window.Echo', false)+ ->assertSee('v5-app', false)+ ->assertSee('Dashboard', false)+ ->assertDontSee('Home', false)+ ->assertDontSee('v5-ready', false)+ ->assertDontSee('This page is served from Laravel through Inertia and React')+ ->assertDontSee('Bootstrap server')+ ->assertDontSee('privateKeys', false)+ ->assertSee('Running')+ ->assertSee('Flux is running.')+ ->assertDontSee('"clusters":', false)+ ->assertDontSee('cooldServers', false)+ ->assertDontSee('coold-dev')+ ->assertDontSee('Create cluster')+ ->assertDontSee('Cluster details')+ ->assertDontSee('100.64.0.1')+ ->assertDontSee('Current team')+ ->assertDontSee('Your teams')+ ->assertSee('currentTeam', false)+ ->assertSee('"currentTeam":{"id":'.$team->id, false)+ ->assertDontSee('teams', false)+ ->assertDontSee('V5 Shared Team')+ ->assertDontSee('Shared team details');+});++it('serves v5 dashboard applications as canvas nodes', function () {+ app()->detectEnvironment(fn () => 'local');++ $this->withoutVite();+ fakeFluxHealth();+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ [$otherProject, $otherEnvironment] = createV5ProjectWithEnvironment($team, 'Staging Project', 'Staging');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ ]);++ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ 'status_message' => 'Container started.',+ 'runtime_container_id' => 'abc123',+ 'mesh_namespace' => 'default',+ 'canvas_x' => 120,+ 'canvas_y' => -80,+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $otherProject->id,+ 'environment_id' => $otherEnvironment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'other-nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-other',+ 'status' => 'running',+ ]);++ $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ ])+ ->get('/v5')+ ->assertSuccessful()+ ->assertSee('"applications":[', false)+ ->assertSee('"name":"nginx-test"', false)+ ->assertSee('"serverName":"edge-01"', false)+ ->assertSee('"meshNamespace":"default"', false)+ ->assertSee('"meshFqdn":"coolify-v5-nginx-1.default.coolify.internal"', false)+ ->assertSee('"canvasX":120', false)+ ->assertSee('"canvasY":-80', false)+ ->assertDontSee('other-nginx-test', false);+});++it('marks v5 application status as unknown when its server is unreachable', function () {+ app()->detectEnvironment(fn () => 'local');++ $this->withoutVite();+ fakeFluxHealth();+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'unreachable',+ 'last_status_output' => 'coold heartbeat timed out.',+ 'capabilities' => [],+ ]);++ V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ 'status_message' => 'Container started.',+ ]);++ $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ ])+ ->get('/v5')+ ->assertSuccessful()+ ->assertSee('"status":"running"', false)+ ->assertSee('"effectiveStatus":"unknown"', false)+ ->assertSee('"effectiveStatusMessage":"coold heartbeat timed out."', false)+ ->assertSee('"serverStatus":"unreachable"', false)+ ->assertSee('"isServerReachable":false', false);+});++it('shows v5 caddy ingress as unreachable when its server is unreachable', function () {+ app()->detectEnvironment(fn () => 'local');++ $this->withoutVite();+ fakeFluxHealth();+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-ingress-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'unreachable',+ 'ingress_status' => 'running',+ 'last_status_output' => 'coold heartbeat timed out.',+ 'capabilities' => ['ingress'],+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->get('/v5')+ ->assertSuccessful()+ ->assertSee('"caddyIngresses":[', false)+ ->assertSee('"status":"unreachable"', false)+ ->assertSee('"statusMessage":"coold heartbeat timed out."', false);+});++it('serves enabled v5 caddy ingress servers as canvas nodes', function () {+ app()->detectEnvironment(fn () => 'local');++ $this->withoutVite();+ fakeFluxHealth();+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ createV5ProjectWithEnvironment($team, 'Production Project', 'Production');++ V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-ingress-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'ingress_status' => 'running',+ 'capabilities' => ['ingress'],+ 'canvas_x' => -160,+ 'canvas_y' => 240,+ ]);+ V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-ingress-02',+ 'host' => '203.0.113.22',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'ingress_status' => 'exited',+ 'capabilities' => ['ingress'],+ ]);+ V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-worker-01',+ 'host' => '203.0.113.21',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->get('/v5')+ ->assertSuccessful()+ ->assertSee('"caddyIngresses":[', false)+ ->assertSee('"name":"edge-ingress-01"', false)+ ->assertSee('"host":"203.0.113.20"', false)+ ->assertSee('"type":"caddy"', false)+ ->assertSee('"status":"running"', false)+ ->assertSee('"name":"edge-ingress-02"', false)+ ->assertSee('"status":"exited"', false)+ ->assertSee('"canvasX":-160', false)+ ->assertSee('"canvasY":240', false);+});++it('broadcasts manual v5 realtime test events immediately', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();++ Event::fake([V5RealtimeTestEvent::class]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson('/v5/realtime-test', [+ 'message' => 'hello socket',+ ])+ ->assertAccepted()+ ->assertJsonPath('message', 'Realtime test event broadcasted.');++ Event::assertDispatched(V5RealtimeTestEvent::class, fn (V5RealtimeTestEvent $event): bool => $event->teamId === $team->id+ && $event->message === 'hello socket'+ && $event->broadcastAs() === 'v5.realtime.test'+ && $event instanceof ShouldBroadcastNow);+});++it('serves the production v5 favicon outside local environments', function () {+ app()->detectEnvironment(fn () => 'production');++ $this->withoutVite();+ fakeFluxHealth();+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->get('/v5')+ ->assertSuccessful()+ ->assertSee('coolify-logo.svg', false)+ ->assertDontSee('coolify-logo-dev-transparent.png', false);+});++it('shares existing projects and environments with the v5 dashboard page', function () {+ $this->withoutVite();+ fakeFluxHealth();+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'gravy-truck', 'production');+ createV5ProjectWithEnvironment($team, 'rocket-bike', 'staging');+ $otherTeam = Team::withoutEvents(fn () => Team::query()->create([+ 'name' => 'Other V5 Team',+ 'description' => null,+ 'personal_team' => false,+ 'show_boarding' => false,+ ]));+ [$otherProject, $otherEnvironment] = createV5ProjectWithEnvironment($otherTeam, 'secret-saucer', 'private');++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->get('/v5')+ ->assertSuccessful()+ ->assertSee('"projects":[', false)+ ->assertSee('"name":"gravy-truck"', false)+ ->assertSee('"uuid":"'.$project->uuid.'"', false)+ ->assertSee('"environments":[', false)+ ->assertSee('"name":"production"', false)+ ->assertSee('"uuid":"'.$environment->uuid.'"', false)+ ->assertSee('"selectedProjectUuid":"'.$project->uuid.'"', false)+ ->assertSee('"selectedEnvironmentUuid":"'.$environment->uuid.'"', false)+ ->assertDontSee('"id":"'.$project->id.'","uuid":"'.$project->uuid.'"', false)+ ->assertDontSee('"id":"'.$environment->id.'","uuid":"'.$environment->uuid.'"', false)+ ->assertDontSee($otherProject->name)+ ->assertDontSee($otherProject->uuid)+ ->assertDontSee($otherEnvironment->name)+ ->assertDontSee($otherEnvironment->uuid);+});++it('persists the selected v5 project and environment in the session', function () {+ $this->withoutVite();+ fakeFluxHealth();+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ createV5ProjectWithEnvironment($team, 'alpha-project', 'production');+ [$selectedProject, $selectedEnvironment] = createV5ProjectWithEnvironment($team, 'zebra-project', 'staging');++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson('/v5/selection', [+ 'project_uuid' => $selectedProject->uuid,+ 'environment_uuid' => $selectedEnvironment->uuid,+ ])+ ->assertNoContent()+ ->assertSessionHas('v5.selectedProjectUuid', $selectedProject->uuid)+ ->assertSessionHas('v5.selectedEnvironmentUuid', $selectedEnvironment->uuid);++ $this+ ->actingAs($user)+ ->get('/v5')+ ->assertSuccessful()+ ->assertSee('"selectedProjectUuid":"'.$selectedProject->uuid.'"', false)+ ->assertSee('"selectedEnvironmentUuid":"'.$selectedEnvironment->uuid.'"', false);+});++it('rejects persisted v5 selections outside the current team', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $otherTeam = Team::withoutEvents(fn () => Team::query()->create([+ 'name' => 'Other V5 Team',+ 'description' => null,+ 'personal_team' => false,+ 'show_boarding' => false,+ ]));+ [$otherProject, $otherEnvironment] = createV5ProjectWithEnvironment($otherTeam, 'secret-saucer', 'private');++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson('/v5/selection', [+ 'project_uuid' => $otherProject->uuid,+ 'environment_uuid' => $otherEnvironment->uuid,+ ])+ ->assertForbidden()+ ->assertSessionMissing('v5.selectedProjectUuid')+ ->assertSessionMissing('v5.selectedEnvironmentUuid');+});++it('serves v5 dev assets from the current request host', function (string $url, string $viteHost) {+ fakeFluxHealth();+ createSharedUserAndTeamTables();+ [$user, $team] = createV5UserWithTeam();++ $hotFile = public_path('hot');+ $originalHotFile = file_exists($hotFile) ? file_get_contents($hotFile) : null;++ file_put_contents($hotFile, 'http://configured-vite-host.test:5173');++ try {+ $response = $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->get($url);++ $response+ ->assertSuccessful()+ ->assertSee("import RefreshRuntime from 'http://{$viteHost}:5173/@react-refresh'", false)+ ->assertSee("src=\"http://{$viteHost}:5173/@vite/client\"", false)+ ->assertSee("src=\"http://{$viteHost}:5173/resources/js/v5/app.tsx\"", false)+ ->assertDontSee('configured-vite-host.test', false);+ } finally {+ if ($originalHotFile === null) {+ @unlink($hotFile);+ } else {+ file_put_contents($hotFile, $originalHotFile);+ }+ }+})->with([+ 'localhost' => ['http://localhost:8000/v5', 'localhost'],+ 'tailscale ip' => ['http://100.64.0.10:8000/v5', '100.64.0.10'],+]);++it('configures the vite dev server for remote v5 access', function () {+ $viteConfig = file_get_contents(base_path('vite.config.js'));++ expect($viteConfig)+ ->toContain('host: "0.0.0.0"')+ ->toContain('allowedHosts: true')+ ->toContain('cors: true')+ ->toContain('const viteHmrHost = env.VITE_HMR_HOST || null;')+ ->toContain('hmr: viteHmrHost')+ ->not->toContain('hmr: viteHost');+});++it('shows when flux is unavailable', function () {+ $this->withoutVite();+ fakeFluxHealth(false, 'Flux socket was not found.');+ createSharedUserAndTeamTables();++ $user = User::withoutEvents(fn () => User::query()->create([+ 'name' => 'Katherine Johnson',+ 'email' => '[email protected]',+ 'email_verified_at' => now(),+ 'password' => 'password',+ ]));+ $team = Team::withoutEvents(fn () => Team::query()->create([+ 'name' => 'Flux Test Team',+ 'description' => null,+ 'personal_team' => false,+ 'show_boarding' => false,+ ]));+ $user->teams()->attach($team, ['role' => 'owner']);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->get('/v5')+ ->assertSuccessful()+ ->assertSee('Unavailable')+ ->assertSee('Flux socket was not found.');+});diff --git a/tests/Feature/V5/DashboardTest.php b/tests/Feature/V5/DashboardTest.phpdeleted file mode 100644index d81153620a..0000000000--- a/tests/Feature/V5/DashboardTest.php+++ /dev/null@@ -1,6127 +0,0 @@-<?php--use App\Actions\V5\Flux\ApplyFluxResourceStatusUpdate;-use App\Events\V5CanvasResourceUpdated;-use App\Events\V5ClusterUpdated;-use App\Events\V5RealtimeTestEvent;-use App\Http\Controllers\V5\DashboardController;-use App\Http\Kernel;-use App\Http\Middleware\CheckForcePasswordReset;-use App\Http\Middleware\DecideWhatToDoWithUser;-use App\Http\Middleware\V5\EnsureCurrentTeam;-use App\Http\Middleware\V5\HandleInertiaRequests;-use App\Jobs\V5BootstrapServerJob;-use App\Models\Environment;-use App\Models\PrivateKey;-use App\Models\Project;-use App\Models\Team;-use App\Models\User;-use App\Models\V5\Application as V5Application;-use App\Models\V5\ApplicationDomain as V5ApplicationDomain;-use App\Models\V5\Cluster;-use App\Models\V5\ContainerStatus;-use App\Models\V5\ResourceConnection;-use App\Models\V5\Server as V5Server;-use App\Services\Flux\FluxClient;-use App\Services\Flux\FluxHealth;-use Database\Seeders\V5DevLimaSeeder;-use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;-use Illuminate\Support\Facades\Artisan;-use Illuminate\Support\Facades\Config;-use Illuminate\Support\Facades\Event;-use Illuminate\Support\Facades\Exceptions;-use Illuminate\Support\Facades\Process;-use Illuminate\Support\Facades\Queue;-use Illuminate\Support\Facades\Route;-use Illuminate\Support\Facades\Schema;-use Mockery\MockInterface;--beforeEach(function () {- Config::set('app.maintenance.store', 'array');- Config::set('broadcasting.default', 'log');- Config::set('cache.default', 'array');-- Schema::dropIfExists('v5_resource_connection_rules');- Schema::dropIfExists('v5_resource_connections');- Schema::dropIfExists('v5_application_domains');- Schema::dropIfExists('v5_applications');- Schema::dropIfExists('v5_container_statuses');- Schema::dropIfExists('v5_servers');- Schema::dropIfExists('v5_clusters');- Schema::dropIfExists('private_keys');- Schema::dropIfExists('team_user');- Schema::dropIfExists('teams');- Schema::dropIfExists('users');-});--it('registers the v5 dashboard route', function () {- expect(Route::has('v5.dashboard'))->toBeTrue()- ->and(Route::has('v5.home'))->toBeFalse()- ->and(Route::has('v5.selection.update'))->toBeTrue()- ->and(Route::has('v5.clusters.index'))->toBeTrue()- ->and(Route::has('v5.clusters.show'))->toBeTrue()- ->and(Route::has('v5.clusters.store'))->toBeTrue()- ->and(Route::has('v5.clusters.destroy'))->toBeTrue()- ->and(Route::has('v5.clusters.servers.store'))->toBeTrue()- ->and(Route::has('v5.clusters.servers.update'))->toBeTrue()- ->and(Route::has('v5.clusters.servers.check'))->toBeTrue()- ->and(Route::has('v5.clusters.servers.coold-logs'))->toBeTrue()- ->and(Route::has('v5.clusters.servers.corrosion-tables'))->toBeTrue()- ->and(Route::has('v5.clusters.servers.bootstrap'))->toBeTrue()- ->and(Route::has('v5.clusters.servers.destroy'))->toBeTrue()- ->and(Route::has('v5.applications.nginx'))->toBeTrue()- ->and(Route::has('v5.applications.refresh'))->toBeTrue()- ->and(Route::has('v5.applications.position'))->toBeTrue()- ->and(Route::has('v5.applications.ingress'))->toBeTrue()- ->and(Route::has('v5.caddy-ingresses.position'))->toBeTrue()- ->and(Route::has('v5.applications.destroy'))->toBeTrue()- ->and(Route::has('v5.resource-connections.store'))->toBeTrue()- ->and(Route::has('v5.resource-connections.update'))->toBeTrue()- ->and(Route::has('v5.resource-connections.destroy'))->toBeTrue()- ->and(Route::has('v5.realtime-test'))->toBeTrue()- ->and(Route::has('v5.realtime-test.broadcast'))->toBeTrue()- ->and(Route::has('v5.coolify.version'))->toBeFalse()- ->and(Route::has('v5.coolify.bootstrap'))->toBeFalse();-});--it('uses separated v5 middleware groups', function () {- $kernel = app(Kernel::class);- $reflection = new ReflectionClass($kernel);- $property = $reflection->getProperty('middlewareGroups');- $property->setAccessible(true);- $groups = $property->getValue($kernel);-- expect($groups)->toHaveKey('v5.web')- ->and($groups)->toHaveKey('v5.authenticated')- ->and($groups['v5.web'])->toContain(HandleInertiaRequests::class)- ->and($groups['v5.web'])->not->toContain(CheckForcePasswordReset::class)- ->and($groups['v5.web'])->not->toContain(DecideWhatToDoWithUser::class)- ->and($groups['v5.authenticated'])->toContain('auth')- ->and($groups['v5.authenticated'])->toContain('verified')- ->and($groups['v5.authenticated'])->toContain(EnsureCurrentTeam::class);-});--it('reuses existing projects instead of creating v5 projects', function () {- expect(file_exists(database_path('migrations/2026_06_04_050157_v5_create_projects_table.php')))->toBeFalse()- ->and(file_exists(app_path('Models/V5/Project.php')))->toBeFalse();-});--it('keeps long v5 application metadata inside the canvas card', function () {- $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));-- expect($dashboardSource)- ->toContain('overflow-hidden')- ->and($dashboardSource)->toContain('grid grid-cols-[auto_minmax(0,1fr)]')- ->and($dashboardSource)->toContain('truncate text-right font-medium')- ->and($dashboardSource)->toContain('truncate text-right font-mono');-});--it('does not render v5 application status messages on dashboard cards', function () {- $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));-- expect($dashboardSource)- ->not->toContain('{application.statusMessage && (')- ->not->toContain('{application.statusMessage}</p>');-});--it('lets users dismiss v5 dashboard notices', function () {- $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));-- expect($dashboardSource)- ->toContain('aria-label="Dismiss notice"')- ->toContain('onClick={() => setNotice(null)}')- ->toContain('<span className="sr-only">Dismiss notice</span>');-});--it('uses the shared dialog and button components for the application ingress modal', function () {- $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));-- expect($dashboardSource)- ->toContain('<Dialog')- ->toContain('open')- ->toContain('<DialogContent')- ->toContain('showCloseButton')- ->toContain('<Button type="submit" variant="coolify"')- ->not->toContain('>Cancel</button>')- ->not->toContain('>Close</button>');-});--it('shows a loading state while toggling application ingress', function () {- $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));-- expect($dashboardSource)- ->toContain('savingIngressApplicationId')- ->toContain("isApplicationIngressSaving ? 'Saving...'")- ->toContain("isSavingIngress ? 'Saving...' : 'Enable ingress'");-});--it('uses v5 resource uuids at http boundaries while keeping database ids internal', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');- $server = V5Server::query()->create([- 'uuid' => 'server-public-uuid',- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.20',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'builder_cpu_quota' => '200%',- 'wireguard_management_ip' => '100.64.0.10',- 'last_bootstrapped_at' => now(),- ]);- $application = V5Application::query()->create([- 'uuid' => 'application-public-uuid',- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-test',- 'status' => 'running',- 'mesh_namespace' => 'default',- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/applications/{$application->uuid}/position", [- 'canvas_x' => 123,- 'canvas_y' => 456,- ])- ->assertSuccessful()- ->assertJsonPath('application.id', $application->uuid);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/applications/{$application->id}/position", [- 'canvas_x' => 789,- 'canvas_y' => 999,- ])- ->assertNotFound();-- $fluxClient = Mockery::mock(FluxClient::class);- $fluxClient->shouldReceive('pullImage')->once()->andReturn('Image pulled.');- $fluxClient->shouldReceive('createContainer')->once()->andReturn('container-id');- $fluxClient->shouldReceive('startContainer')->once()->andReturn('Container started.');- $fluxClient->shouldReceive('inspectContainer')->once()->andReturn(['State' => ['Running' => true]]);- app()->instance(FluxClient::class, $fluxClient);-- $this- ->actingAs($user)- ->withSession([- 'currentTeam' => $team,- 'v5.selected_project' => ['uuid' => $project->uuid, 'name' => $project->name],- 'v5.selected_environment' => ['uuid' => $environment->uuid, 'name' => $environment->name],- ])- ->postJson('/v5/applications/nginx', [- 'server_uuid' => $server->uuid,- 'image' => 'docker.io/library/nginx:alpine',- ])- ->assertSuccessful()- ->assertJsonPath('application.id', fn (string $id): bool => $id !== (string) V5Application::query()->latest('id')->value('id'));-});--it('uses v5 resource uuids for resource connection requests and responses', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.20',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'wireguard_management_ip' => '100.64.0.10',- ]);- $source = V5Application::query()->create([- 'uuid' => 'source-application-uuid',- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'source',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'source-container',- 'status' => 'running',- ]);- $target = V5Application::query()->create([- 'uuid' => 'target-application-uuid',- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'target',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'target-container',- 'status' => 'running',- ]);-- $response = $this- ->actingAs($user)- ->withSession([- 'currentTeam' => $team,- 'v5.selected_project' => ['uuid' => $project->uuid, 'name' => $project->name],- 'v5.selected_environment' => ['uuid' => $environment->uuid, 'name' => $environment->name],- ])- ->postJson('/v5/resource-connections', [- 'resource_one' => ['type' => 'application', 'uuid' => $source->uuid],- 'resource_two' => ['type' => 'application', 'uuid' => $target->uuid],- ])- ->assertCreated()- ->assertJsonPath('connection.fromApplicationId', $source->uuid)- ->assertJsonPath('connection.toApplicationId', $target->uuid);-- $connectionUuid = $response->json('connection.id');-- $fluxClient = Mockery::mock(FluxClient::class);- $fluxClient->shouldReceive('applyFirewallRule')->once()->andReturn('Firewall rule applied.');- app()->instance(FluxClient::class, $fluxClient);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/resource-connections/{$connectionUuid}", [- 'ports_by_direction' => [- "{$source->uuid}->{$target->uuid}" => [8080],- ],- ])- ->assertSuccessful()- ->assertJsonPath("connection.portsByDirection.{$source->uuid}->{$target->uuid}.0", '8080');-- expect(ResourceConnection::query()->first())- ->resource_one_id->toBe($source->id)- ->resource_two_id->toBe($target->id);-});--it('generates http-only caddy routes for application ingress', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.20',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => ['ingress'],- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'builder_cpu_quota' => '200%',- 'wireguard_management_ip' => '100.64.0.10',- 'last_bootstrapped_at' => now(),- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-test',- 'status' => 'running',- 'mesh_namespace' => 'default',- ]);-- $fluxClient = Mockery::mock(FluxClient::class);- $fluxClient- ->shouldReceive('applyIngress')- ->once()- ->with(- '100.64.0.10',- 'caddy',- Mockery::on(fn (string $caddyfile): bool => str_contains($caddyfile, 'import apps/*.caddy')),- Mockery::on(fn (array $apps): bool => count($apps) === 1- && str_contains($apps[0]['config'], 'http://app.example.com {')- && ! str_contains($apps[0]['config'], 'https://')- && str_contains($apps[0]['config'], 'reverse_proxy coolify-v5-nginx-test.default.coolify.internal:3000'))- )- ->andReturn('Caddy ingress applied.');- expectCaddyIngressFirewallRule($fluxClient);- app()->instance(FluxClient::class, $fluxClient);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/applications/{$application->uuid}/ingress", [- 'ingress_enabled' => true,- 'internal_port' => 3000,- 'domains' => ['app.example.com'],- ])- ->assertSuccessful();-});--it('shows a dashboard refresh button next to the center button', function () {- $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));-- expect($dashboardSource)- ->toContain('onClick={() => centerOnCanvasNodes()}')- ->toContain('onClick={() => void refreshApplications()}')- ->toContain("isRefreshing ? 'Refreshing…' : 'Refresh state'");-});--it('subscribes the v5 dashboard canvas to automatic resource status updates', function () {- $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));-- expect($dashboardSource)- ->toContain('currentTeam = null')- ->toContain("channel.listen('.v5.canvas.resource.updated'")- ->toContain('setApplications((currentApplications) =>')- ->toContain('setIngresses((currentIngresses) =>')- ->toContain('Waiting for window.Echo before subscribing to canvas updates')- ->toContain("channel.listen('.v5.canvas.resource.updated'")- ->not->toContain("fetch('/v5/canvas-state'");-});--it('allows zooming the v5 dashboard canvas with buttons and pinch gestures', function () {- $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));-- expect($dashboardSource)- ->toContain('zoom: number;')- ->toContain('MIN_CANVAS_ZOOM')- ->toContain('MAX_CANVAS_ZOOM')- ->toContain('PINCH_CANVAS_ZOOM_STEP')- ->toContain('zoomCanvas(')- ->toContain('zoomCanvas(event.deltaY < 0 ? 1 : -1, PINCH_CANVAS_ZOOM_STEP')- ->toContain('onWheel={handleCanvasWheel}')- ->toContain('event.ctrlKey')- ->toContain('aria-label="Zoom out"')- ->toContain('aria-label="Zoom in"')- ->toContain('Math.round(viewport.zoom * 100)')- ->toContain('scale(${viewport.zoom})');-});--it('renders draggable connector dots on v5 application canvas cards', function () {- $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));-- expect($dashboardSource)- ->toContain("type ConnectorSide = 'top' | 'right' | 'bottom' | 'left';")- ->toContain('application-connector')- ->toContain('data-connector-side={side}')- ->toContain('startConnectionDrag(event, application.id, side)')- ->toContain('<svg className="pointer-events-none absolute inset-0 overflow-visible">')- ->toContain('draftConnection');-});--it('keeps v5 canvas connections selectable unique and shortest-path only', function () {- $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));-- expect($dashboardSource)- ->toContain('type CanvasConnection = V5ResourceConnection;')- ->toContain('resourceConnections: initialResourceConnections = []')- ->toContain('useState<CanvasConnection[]>(initialResourceConnections)')- ->toContain('selectedConnectionId')- ->toContain('clearCanvasSelection')- ->toContain('event.target !== event.currentTarget')- ->toContain('connectionExists')- ->toContain('shortestConnectionPoints')- ->toContain("!['Backspace', 'Delete'].includes(event.key)")- ->toContain('deletePersistedConnection(connectionId)')- ->toContain('onClick={(event) => selectConnection(event, connection.id)}')- ->toContain("selectedConnectionId === connection.id ? 'stroke-destructive' : 'stroke-warning'")- ->toContain('aria-label="Select connection"')- ->toContain('stroke="transparent"')- ->toContain('strokeWidth={12}')- ->toContain('data-application-card="application-card"')- ->toContain("closest<HTMLElement>('[data-application-card]')")- ->toContain('deleteConnection(connection.id)')- ->toContain('Delete connection')- ->toContain('left: (points.from.x + points.to.x) / 2')- ->toContain('top: (points.from.y + points.to.y) / 2')- ->toContain('id="dashboard-connection-arrow"')- ->toContain('markerEnd={selectedConnectionId === connection.id ? \'url(#dashboard-connection-arrow)\' : undefined}')- ->toContain('markerWidth="16"')- ->toContain('markerHeight="16"')- ->toContain('strokeDasharray="6 6"')- ->toContain('persistNewConnection(pointerState.from.applicationId, targetApplicationId)')- ->toContain('persistConnectionPorts(updatedConnection)')- ->toContain('/v5/resource-connections')- ->toContain('ports_by_direction: portsByDirection')- ->toContain('connectionDirectionKey(')- ->toContain('activeConnectionPorts(connection)')- ->toContain('addConnectionPort(connection.id)')- ->toContain('Number.isInteger(portNumber)')- ->toContain('setConnectionPortInput')- ->toContain('Allowed ports')- ->toContain('updateConnectionDirection(')- ->toContain('applicationDirectionLabel(')- ->toContain('application.id.slice(0, 8)')- ->toContain('connection.applicationIds[0]')- ->toContain('connection.applicationIds[1]')- ->toContain('group/application')- ->toContain('opacity-0')- ->toContain('group-hover/application:opacity-100');-});--it('shows v5 application connector dots after selecting a canvas card', function () {- $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));-- expect($dashboardSource)- ->toContain('selectedApplicationId')- ->toContain('setSelectedApplicationId(application.id)')- ->toContain('selectedApplicationId === application.id')- ->toContain('opacity-100');-});--it('keeps side connector geometry aligned with the rendered v5 application card height', function () {- $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));-- expect($dashboardSource)- ->toContain('const APPLICATION_CARD_HEIGHT = 160;')- ->toContain('h-40 w-80');-});--it('shows a loading state on v5 application delete buttons', function () {- $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));-- foreach ([- 'deletingApplicationIds',- 'const isDeletingApplication = deletingApplicationIds.has(application.id)',- 'setDeletingApplicationIds',- 'disabled={isDeletingApplication}',- "{isDeletingApplication ? 'Deleting…' : 'Delete'}",- ] as $expectedSource) {- $this->assertTrue(str_contains($dashboardSource, $expectedSource), "Missing source: {$expectedSource}");- }-});--it('uses a larger mobile touch target for v5 application connector dots', function () {- $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));-- expect($dashboardSource)- ->toContain('size-8')- ->toContain('md:size-3')- ->toContain('group/connector')- ->toContain('group-hover/connector:scale-125')- ->toContain('<span className="size-3 rounded-full border-2 border-card bg-warning shadow ring-2 ring-background transition group-hover/connector:scale-125 group-hover/connector:bg-warning/90" />');-});--it('detects the connection drop target from pointer coordinates for mobile drags', function () {- $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));-- expect($dashboardSource)- ->toContain('connectionTargetFromPointer(event)')- ->toContain('document.elementFromPoint(event.clientX, event.clientY)')- ->toContain('pointer-captured mobile drags')- ->toContain('targetApplicationId !== pointerState.from.applicationId');-});--it('creates v5 cluster tables and lets each server belong to one cluster', function () {- createSharedUserAndTeamTables();- Schema::dropIfExists('v5_servers');- Schema::dropIfExists('v5_clusters');-- $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');- $clusterMigration->up();-- $serverMigration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');- $serverMigration->up();-- expect(Schema::hasTable('v5_clusters'))->toBeTrue()- ->and(Schema::hasColumns('v5_clusters', [- 'id',- 'team_id',- 'created_by_user_id',- 'name',- 'description',- 'wireguard_interface',- 'wireguard_management_pool',- 'wireguard_listen_port',- 'container_network_pool',- 'container_network_prefix',- 'namespaces',- 'default_deny_containers',- 'coold_version',- 'corrosion_version',- 'corrosion_gossip_port',- 'corrosion_api_port',- 'builder_enabled',- 'builder_capacity',- 'builder_cpu_quota',- 'builder_memory_max',- 'builder_timeout_secs',- 'last_cli_action',- 'last_cli_status',- 'last_cli_summary',- 'last_cli_ran_at',- 'created_at',- 'updated_at',- ]))->toBeTrue()- ->and(Schema::hasColumn('v5_servers', 'cluster_id'))->toBeTrue();-});--it('creates v5 server tables in the shared database', function () {- createSharedUserAndTeamTables();-- Schema::dropIfExists('v5_servers');- Schema::dropIfExists('v5_clusters');-- $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');- $clusterMigration->up();-- $migration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');- $migration->up();-- expect(Schema::hasTable('v5_servers'))->toBeTrue()- ->and(Schema::hasColumns('v5_servers', [- 'id',- 'team_id',- 'cluster_id',- 'created_by_user_id',- 'private_key_id',- 'name',- 'host',- 'ssh_user',- 'ssh_port',- 'status',- 'capabilities',- 'builder_enabled',- 'builder_capacity',- 'builder_cpu_quota',- 'node_address',- 'wireguard_listen_port_override',- 'wireguard_endpoint_override',- 'uuid',- 'wireguard_management_ip',- 'wireguard_public_key',- 'container_subnets',- 'last_bootstrapped_at',- 'last_bootstrap_action',- 'last_bootstrap_status',- 'last_bootstrap_output',- 'last_bootstrap_ran_at',- 'last_status_check',- 'last_status_output',- 'last_status_checked_at',- 'created_at',- 'updated_at',- ]))->toBeTrue();-});--it('creates v5 server canvas columns for movable caddy ingress nodes', function () {- createSharedUserAndTeamTables();-- Schema::dropIfExists('v5_servers');- Schema::dropIfExists('v5_clusters');-- $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');- $clusterMigration->up();-- $serverMigration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');- $serverMigration->up();-- expect(Schema::hasColumns('v5_servers', [- 'canvas_x',- 'canvas_y',- ]))->toBeTrue();-});--it('creates v5 server ingress columns', function () {- createSharedUserAndTeamTables();-- Schema::dropIfExists('v5_servers');- Schema::dropIfExists('v5_clusters');-- $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');- $clusterMigration->up();-- $serverMigration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');- $serverMigration->up();-- expect(Schema::hasColumns('v5_servers', [- 'ingress_type',- 'ingress_status',- ]))->toBeTrue();-});--it('creates v5 application tables for dashboard canvas nodes', function () {- createSharedUserAndTeamTables();-- Schema::dropIfExists('v5_application_domains');- Schema::dropIfExists('v5_applications');- Schema::dropIfExists('v5_servers');- Schema::dropIfExists('v5_clusters');-- $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');- $clusterMigration->up();-- $serverMigration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');- $serverMigration->up();-- $applicationMigration = include database_path('migrations/2026_06_19_140000_v5_create_applications_table.php');- $applicationMigration->up();-- expect(Schema::hasTable('v5_applications'))->toBeTrue()- ->and(Schema::hasColumns('v5_applications', [- 'id',- 'team_id',- 'project_id',- 'environment_id',- 'server_id',- 'created_by_user_id',- 'name',- 'image',- 'container_name',- 'status',- 'status_message',- 'runtime_container_id',- 'mesh_namespace',- 'ingress_enabled',- 'internal_port',- 'canvas_x',- 'canvas_y',- 'created_at',- 'updated_at',- ]))->toBeTrue();-});--it('creates v5 application domain tables for zero or more inbound routes', function () {- createSharedUserAndTeamTables();-- Schema::dropIfExists('v5_application_domains');- Schema::dropIfExists('v5_applications');- Schema::dropIfExists('v5_servers');- Schema::dropIfExists('v5_clusters');-- $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');- $clusterMigration->up();-- $serverMigration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');- $serverMigration->up();-- $applicationMigration = include database_path('migrations/2026_06_19_140000_v5_create_applications_table.php');- $applicationMigration->up();-- expect(Schema::hasTable('v5_application_domains'))->toBeTrue()- ->and(Schema::hasColumns('v5_application_domains', [- 'id',- 'application_id',- 'domain',- 'created_at',- 'updated_at',- ]))->toBeTrue()- ->and(Schema::hasColumns('v5_applications', [- 'ingress_enabled',- 'internal_port',- ]))->toBeTrue();-});--it('creates generic v5 resource connection tables', function () {- createSharedUserAndTeamTables();-- Schema::dropIfExists('v5_resource_connection_rules');- Schema::dropIfExists('v5_resource_connections');- Schema::dropIfExists('v5_application_domains');- Schema::dropIfExists('v5_applications');- Schema::dropIfExists('v5_servers');- Schema::dropIfExists('v5_clusters');-- $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');- $clusterMigration->up();-- $serverMigration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');- $serverMigration->up();-- $applicationMigration = include database_path('migrations/2026_06_19_140000_v5_create_applications_table.php');- $applicationMigration->up();-- $connectionMigration = include database_path('migrations/2026_06_19_142000_v5_create_resource_connections_table.php');- $connectionMigration->up();-- expect(Schema::hasTable('v5_resource_connections'))->toBeTrue()- ->and(Schema::hasColumns('v5_resource_connections', [- 'id',- 'team_id',- 'project_id',- 'environment_id',- 'resource_one_type',- 'resource_one_id',- 'resource_two_type',- 'resource_two_id',- 'resource_pair_key',- 'created_by_user_id',- 'created_at',- 'updated_at',- ]))->toBeTrue()- ->and(Schema::hasTable('v5_resource_connection_rules'))->toBeTrue()- ->and(Schema::hasColumns('v5_resource_connection_rules', [- 'id',- 'connection_id',- 'source_resource_type',- 'source_resource_id',- 'target_resource_type',- 'target_resource_id',- 'protocol',- 'port',- 'created_at',- 'updated_at',- ]))->toBeTrue();-});--it('keeps v5 server fields in the initial migration', function () {- createSharedUserAndTeamTables();-- Schema::dropIfExists('v5_servers');- Schema::dropIfExists('v5_clusters');-- $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');- $clusterMigration->up();-- $serverMigration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');- $serverMigration->up();-- expect(Schema::hasColumns('v5_servers', [- 'uuid',- 'ingress_type',- 'ingress_status',- 'builder_cpu_quota',- 'node_address',- 'wireguard_management_ip',- 'container_subnets',- 'canvas_x',- 'canvas_y',- 'last_bootstrap_output',- 'last_status_output',- ]))->toBeTrue();-});--it('includes v5 tables in the dev testing schema', function () {- $schema = file_get_contents(database_path('schema/testing-schema.sql'));-- expect($schema)->toContain('"team_id" INTEGER NOT NULL')- ->and($schema)->toContain('"created_by_user_id" INTEGER NOT NULL')- ->and($schema)->not->toContain('CREATE TABLE IF NOT EXISTS "v5_projects"')- ->and($schema)->not->toContain('2026_06_04_050157_v5_create_projects_table')- ->and($schema)->toContain('CREATE TABLE IF NOT EXISTS "v5_servers"')- ->and($schema)->toContain('CREATE TABLE IF NOT EXISTS "v5_container_statuses"')- ->and($schema)->toContain('CREATE TABLE IF NOT EXISTS "v5_applications"')- ->and($schema)->toContain('CREATE TABLE IF NOT EXISTS "v5_application_domains"')- ->and($schema)->toContain('CREATE TABLE IF NOT EXISTS "v5_resource_connections"')- ->and($schema)->toContain('CREATE TABLE IF NOT EXISTS "v5_resource_connection_rules"')- ->and($schema)->toContain('"domain" TEXT NOT NULL')- ->and($schema)->toContain('"ingress_enabled" INTEGER DEFAULT false NOT NULL')- ->and($schema)->toContain('"internal_port" INTEGER')- ->and($schema)->toContain('"cluster_id" INTEGER')- ->and($schema)->toContain('CREATE TABLE IF NOT EXISTS "v5_clusters"')- ->and($schema)->toContain('"wireguard_interface" TEXT DEFAULT \'wg0\' NOT NULL')- ->and($schema)->toContain('"wireguard_management_pool" TEXT DEFAULT \'100.64.0.0/16\' NOT NULL')- ->and($schema)->toContain('"container_network_pool" TEXT DEFAULT \'10.210.0.0/16\' NOT NULL')- ->and($schema)->toContain('"builder_timeout_secs" INTEGER NOT NULL DEFAULT \'1800\'')- ->and($schema)->toContain('"private_key_id" INTEGER')- ->and($schema)->toContain('"ingress_type" TEXT')- ->and($schema)->toContain('"ingress_status" TEXT')- ->and($schema)->toContain('"builder_cpu_quota" TEXT DEFAULT \'200%\' NOT NULL')- ->and($schema)->toContain('"uuid" TEXT')- ->and($schema)->toContain('"wireguard_management_ip" TEXT')- ->and($schema)->toContain('"container_subnets" JSON')- ->and($schema)->toContain('"canvas_x" INTEGER')- ->and($schema)->toContain('"canvas_y" INTEGER')- ->and($schema)->toContain('"last_bootstrap_output" TEXT')- ->and($schema)->toContain('"last_status_output" TEXT')- ->and($schema)->toContain('2026_06_16_130650_v5_create_servers_table')- ->and($schema)->toContain('2026_06_19_140000_v5_create_applications_table')- ->and($schema)->toContain('2026_06_19_142000_v5_create_resource_connections_table')- ->and($schema)->toContain('2026_06_19_182231_create_container_statuses_table')- ->and($schema)->not->toContain('2026_06_19_141231_add_canvas_position_to_v5_servers_table')- ->and($schema)->not->toContain('2026_06_19_173933_add_ingress_status_to_v5_servers_table')- ->and($schema)->not->toContain('2026_06_20_072818_v5_add_ingress_routing_to_applications_table')- ->and($schema)->not->toContain('2026_06_19_150000_add_mesh_namespace_to_v5_applications_table')- ->and($schema)->toContain('2026_06_16_130649_v5_create_clusters_table')- ->and($schema)->not->toContain('2026_06_16_204644_v5_add_wireguard_cli_configuration_to_clusters_and_servers')- ->and($schema)->not->toContain('2026_06_17_165112_v5_add_builder_cpu_quota_to_servers_table')- ->and($schema)->not->toContain('2026_06_17_172845_add_status_check_fields_to_v5_servers_table')- ->and($schema)->not->toContain('2026_06_19_064539_add_bootstrap_log_fields_to_v5_servers_table')- ->and($schema)->not->toContain('2026_06_19_090217_add_uuid_to_v5_servers_table')- ->and($schema)->not->toContain('2026_06_16_131229_add_cluster_id_to_v5_servers_table')- ->and($schema)->not->toContain('2026_06_16_132000_make_v5_server_private_key_nullable')- ->and($schema)->not->toContain('v5_hosts');-});--it('redirects guests to the shared login', function () {- $this->get('/v5')- ->assertRedirect('/login');-});--it('serves the v5 inertia shell', function () {- app()->detectEnvironment(fn () => 'local');-- $this->withoutVite();- $this->withoutExceptionHandling();- fakeFluxHealth();- createSharedUserAndTeamTables();-- $user = User::withoutEvents(fn () => User::query()->create([- 'name' => 'Ada Lovelace',- 'email' => '[email protected]',- 'email_verified_at' => now(),- 'password' => 'password',- ]));- $team = Team::withoutEvents(fn () => Team::query()->create([- 'name' => 'V5 Shared Team',- 'description' => 'Shared team details',- 'personal_team' => true,- 'show_boarding' => false,- ]));- $user->teams()->attach($team, ['role' => 'owner']);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->get('/v5')- ->assertSuccessful()- ->assertSee('<html lang="en" class="dark">', false)- ->assertSee('coolify-logo-dev-transparent.png', false)- ->assertDontSee('coolify-logo.svg', false)- ->assertSee('js/echo.js', false)- ->assertSee('js/pusher.js', false)- ->assertSee('window.Echo', false)- ->assertSee('v5-app', false)- ->assertSee('Dashboard', false)- ->assertDontSee('Home', false)- ->assertDontSee('v5-ready', false)- ->assertDontSee('This page is served from Laravel through Inertia and React')- ->assertDontSee('Bootstrap server')- ->assertDontSee('privateKeys', false)- ->assertSee('Running')- ->assertSee('Flux is running.')- ->assertDontSee('"clusters":', false)- ->assertDontSee('cooldServers', false)- ->assertDontSee('coold-dev')- ->assertDontSee('Create cluster')- ->assertDontSee('Cluster details')- ->assertDontSee('100.64.0.1')- ->assertDontSee('Current team')- ->assertDontSee('Your teams')- ->assertSee('currentTeam', false)- ->assertSee('"currentTeam":{"id":'.$team->id, false)- ->assertDontSee('teams', false)- ->assertDontSee('V5 Shared Team')- ->assertDontSee('Shared team details');-});--it('serves v5 dashboard applications as canvas nodes', function () {- app()->detectEnvironment(fn () => 'local');-- $this->withoutVite();- fakeFluxHealth();- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- [$otherProject, $otherEnvironment] = createV5ProjectWithEnvironment($team, 'Staging Project', 'Staging');- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- ]);-- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-1',- 'status' => 'running',- 'status_message' => 'Container started.',- 'runtime_container_id' => 'abc123',- 'mesh_namespace' => 'default',- 'canvas_x' => 120,- 'canvas_y' => -80,- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $otherProject->id,- 'environment_id' => $otherEnvironment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'other-nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-other',- 'status' => 'running',- ]);-- $this- ->actingAs($user)- ->withSession([- 'currentTeam' => $team,- 'v5.selectedProjectUuid' => $project->uuid,- 'v5.selectedEnvironmentUuid' => $environment->uuid,- ])- ->get('/v5')- ->assertSuccessful()- ->assertSee('"applications":[', false)- ->assertSee('"name":"nginx-test"', false)- ->assertSee('"serverName":"edge-01"', false)- ->assertSee('"meshNamespace":"default"', false)- ->assertSee('"meshFqdn":"coolify-v5-nginx-1.default.coolify.internal"', false)- ->assertSee('"canvasX":120', false)- ->assertSee('"canvasY":-80', false)- ->assertDontSee('other-nginx-test', false);-});--it('marks v5 application status as unknown when its server is unreachable', function () {- app()->detectEnvironment(fn () => 'local');-- $this->withoutVite();- fakeFluxHealth();- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'unreachable',- 'last_status_output' => 'coold heartbeat timed out.',- 'capabilities' => [],- ]);-- V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-1',- 'status' => 'running',- 'status_message' => 'Container started.',- ]);-- $this- ->actingAs($user)- ->withSession([- 'currentTeam' => $team,- 'v5.selectedProjectUuid' => $project->uuid,- 'v5.selectedEnvironmentUuid' => $environment->uuid,- ])- ->get('/v5')- ->assertSuccessful()- ->assertSee('"status":"running"', false)- ->assertSee('"effectiveStatus":"unknown"', false)- ->assertSee('"effectiveStatusMessage":"coold heartbeat timed out."', false)- ->assertSee('"serverStatus":"unreachable"', false)- ->assertSee('"isServerReachable":false', false);-});--it('shows v5 caddy ingress as unreachable when its server is unreachable', function () {- app()->detectEnvironment(fn () => 'local');-- $this->withoutVite();- fakeFluxHealth();- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-ingress-01',- 'host' => '203.0.113.20',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'unreachable',- 'ingress_status' => 'running',- 'last_status_output' => 'coold heartbeat timed out.',- 'capabilities' => ['ingress'],- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->get('/v5')- ->assertSuccessful()- ->assertSee('"caddyIngresses":[', false)- ->assertSee('"status":"unreachable"', false)- ->assertSee('"statusMessage":"coold heartbeat timed out."', false);-});--it('persists generic v5 resource connections and direction-specific ports', function () {- app()->detectEnvironment(fn () => 'local');-- $this->withoutVite();- fakeFluxHealth();- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- ]);- $source = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-source',- 'status' => 'running',- ]);- $target = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-target',- 'status' => 'running',- ]);-- $response = $this- ->actingAs($user)- ->withSession([- 'currentTeam' => $team,- 'v5.selectedProjectUuid' => $project->uuid,- 'v5.selectedEnvironmentUuid' => $environment->uuid,- '_token' => 'test-csrf-token',- ])- ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')- ->postJson('/v5/resource-connections', [- 'resource_one' => ['type' => 'application', 'uuid' => $source->uuid],- 'resource_two' => ['type' => 'application', 'uuid' => $target->uuid],- ])- ->assertCreated()- ->assertJsonPath('connection.applicationIds.0', $source->uuid)- ->assertJsonPath('connection.applicationIds.1', $target->uuid);-- $connectionId = $response->json('connection.id');-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])- ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')- ->patchJson("/v5/resource-connections/{$connectionId}", [- 'ports_by_direction' => [- "{$source->uuid}->{$target->uuid}" => [80],- "{$target->uuid}->{$source->uuid}" => [443],- ],- ])- ->assertSuccessful()- ->assertJsonPath("connection.portsByDirection.{$source->uuid}->{$target->uuid}.0", '80')- ->assertJsonPath("connection.portsByDirection.{$target->uuid}->{$source->uuid}.0", '443');-- $this- ->actingAs($user)- ->withSession([- 'currentTeam' => $team,- 'v5.selectedProjectUuid' => $project->uuid,- 'v5.selectedEnvironmentUuid' => $environment->uuid,- ])- ->get('/v5')- ->assertSuccessful()- ->assertSee('"resourceConnections":[', false)- ->assertSee("\"id\":\"{$connectionId}\"", false)- ->assertSee("\"{$source->uuid}->{$target->uuid}\":[\"80\"]", false)- ->assertSee("\"{$target->uuid}->{$source->uuid}\":[\"443\"]", false);-});--it('reports flux failures when syncing v5 resource connection firewall rules', function () {- app()->detectEnvironment(fn () => 'local');-- $this->withoutVite();- createSharedUserAndTeamTables();- Exceptions::fake();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'wireguard_management_ip' => '100.64.0.10',- 'capabilities' => [],- ]);- $source = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'api',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-api',- 'mesh_namespace' => 'default',- 'status' => 'running',- ]);- $target = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'postgres',- 'image' => 'docker.io/library/postgres:16',- 'container_name' => 'coolify-v5-postgres',- 'mesh_namespace' => 'default',- 'status' => 'running',- ]);-- $connection = ResourceConnection::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'resource_one_type' => $source->getMorphClass(),- 'resource_one_id' => $source->id,- 'resource_two_type' => $target->getMorphClass(),- 'resource_two_id' => $target->id,- 'resource_pair_key' => "application:{$source->id}|application:{$target->id}",- 'created_by_user_id' => $user->id,- ]);-- $fluxClient = Mockery::mock(FluxClient::class);- $fluxClient- ->shouldReceive('applyFirewallRule')- ->once()- ->andThrow(new RuntimeException('resolve firewall endpoint coolify-v5-api on coolify-default-mesh'));- app()->instance(FluxClient::class, $fluxClient);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])- ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')- ->patchJson("/v5/resource-connections/{$connection->uuid}", [- 'ports_by_direction' => [- "{$source->uuid}->{$target->uuid}" => [5432],- ],- ])- ->assertStatus(502)- ->assertJsonPath('detail', 'resolve firewall endpoint coolify-v5-api on coolify-default-mesh');-- Exceptions::assertReported(fn (RuntimeException $exception): bool => $exception->getMessage() === 'resolve firewall endpoint coolify-v5-api on coolify-default-mesh');-});--it('syncs cross-server v5 resource connection ports on both endpoint hosts', function () {- app()->detectEnvironment(fn () => 'local');-- $this->withoutVite();- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- ]);- $sourceServer = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'wireguard_management_ip' => '100.64.0.10',- 'capabilities' => [],- ]);- $targetServer = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-02',- 'host' => '203.0.113.11',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'wireguard_management_ip' => '100.64.0.11',- 'capabilities' => [],- ]);- $source = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $sourceServer->id,- 'created_by_user_id' => $user->id,- 'name' => 'api',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-api',- 'mesh_namespace' => 'default',- 'status' => 'running',- ]);- $target = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $targetServer->id,- 'created_by_user_id' => $user->id,- 'name' => 'postgres',- 'image' => 'docker.io/library/postgres:16',- 'container_name' => 'coolify-v5-postgres',- 'mesh_namespace' => 'default',- 'status' => 'running',- ]);-- $connection = ResourceConnection::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'resource_one_type' => $source->getMorphClass(),- 'resource_one_id' => $source->id,- 'resource_two_type' => $target->getMorphClass(),- 'resource_two_id' => $target->id,- 'resource_pair_key' => "application:{$source->id}|application:{$target->id}",- 'created_by_user_id' => $user->id,- ]);-- $firewallRuleId = "v5-resource-connection:{$connection->id}:{$source->id}:{$target->id}:tcp:5432";- $expectedRule = [- 'id' => $firewallRuleId,- 'namespace' => 'default',- 'src' => 'coolify-v5-api',- 'dst' => 'coolify-v5-postgres',- 'proto' => 'tcp',- 'port' => 5432,- ];-- $fluxClient = Mockery::mock(FluxClient::class);- $fluxClient- ->shouldReceive('applyFirewallRule')- ->once()- ->with('100.64.0.10', $expectedRule)- ->andReturn('Firewall rule applied on source host.');- $fluxClient- ->shouldReceive('applyFirewallRule')- ->once()- ->with('100.64.0.11', $expectedRule)- ->andReturn('Firewall rule applied on target host.');- app()->instance(FluxClient::class, $fluxClient);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])- ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')- ->patchJson("/v5/resource-connections/{$connection->uuid}", [- 'ports_by_direction' => [- "{$source->uuid}->{$target->uuid}" => [5432],- ],- ])- ->assertSuccessful();-});--it('syncs v5 resource connection ports through flux firewall primitives', function () {- app()->detectEnvironment(fn () => 'local');-- $this->withoutVite();- $this->withoutExceptionHandling();- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'wireguard_management_ip' => '100.64.0.10',- 'capabilities' => [],- ]);- $source = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'api',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-api',- 'mesh_namespace' => 'default',- 'status' => 'running',- ]);- $target = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'postgres',- 'image' => 'docker.io/library/postgres:16',- 'container_name' => 'coolify-v5-postgres',- 'mesh_namespace' => 'default',- 'status' => 'running',- ]);-- $connection = ResourceConnection::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'resource_one_type' => $source->getMorphClass(),- 'resource_one_id' => $source->id,- 'resource_two_type' => $target->getMorphClass(),- 'resource_two_id' => $target->id,- 'resource_pair_key' => "application:{$source->id}|application:{$target->id}",- 'created_by_user_id' => $user->id,- ]);-- $firewallRuleId = "v5-resource-connection:{$connection->id}:{$source->id}:{$target->id}:tcp:5432";-- $fluxClient = Mockery::mock(FluxClient::class);- $fluxClient- ->shouldReceive('applyFirewallRule')- ->once()- ->with('100.64.0.10', [- 'id' => $firewallRuleId,- 'namespace' => 'default',- 'src' => 'coolify-v5-api',- 'dst' => 'coolify-v5-postgres',- 'proto' => 'tcp',- 'port' => 5432,- ])- ->andReturn('rule-api-postgres');- $fluxClient- ->shouldReceive('revokeFirewallRule')- ->once()- ->with('100.64.0.10', $firewallRuleId)- ->andReturn('Firewall rule removed.');- app()->instance(FluxClient::class, $fluxClient);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])- ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')- ->patchJson("/v5/resource-connections/{$connection->uuid}", [- 'ports_by_direction' => [- "{$source->uuid}->{$target->uuid}" => [5432],- ],- ])- ->assertSuccessful();-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])- ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')- ->deleteJson("/v5/resource-connections/{$connection->uuid}")- ->assertNoContent();-});--it('serves enabled v5 caddy ingress servers as canvas nodes', function () {- app()->detectEnvironment(fn () => 'local');-- $this->withoutVite();- fakeFluxHealth();- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- createV5ProjectWithEnvironment($team, 'Production Project', 'Production');-- V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-ingress-01',- 'host' => '203.0.113.20',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'ingress_status' => 'running',- 'capabilities' => ['ingress'],- 'canvas_x' => -160,- 'canvas_y' => 240,- ]);- V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-ingress-02',- 'host' => '203.0.113.22',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'ingress_status' => 'exited',- 'capabilities' => ['ingress'],- ]);- V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-worker-01',- 'host' => '203.0.113.21',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->get('/v5')- ->assertSuccessful()- ->assertSee('"caddyIngresses":[', false)- ->assertSee('"name":"edge-ingress-01"', false)- ->assertSee('"host":"203.0.113.20"', false)- ->assertSee('"type":"caddy"', false)- ->assertSee('"status":"running"', false)- ->assertSee('"name":"edge-ingress-02"', false)- ->assertSee('"status":"exited"', false)- ->assertSee('"canvasX":-160', false)- ->assertSee('"canvasY":240', false);-});--it('creates an nginx v5 application on the first installed team server', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $privateKey->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'last_bootstrapped_at' => now(),- ]);-- fakeSuccessfulNginxFluxDeployment();-- $this- ->actingAs($user)- ->withSession([- 'currentTeam' => $team,- 'v5.selectedProjectUuid' => $project->uuid,- 'v5.selectedEnvironmentUuid' => $environment->uuid,- ])- ->postJson('/v5/applications/nginx')- ->assertCreated()- ->assertJsonPath('application.name', 'nginx-test')- ->assertJsonPath('application.image', 'docker.io/library/nginx:alpine')- ->assertJsonPath('application.status', 'running')- ->assertJsonPath('application.serverName', 'edge-01')- ->assertJsonPath('application.meshNamespace', 'default')- ->assertJsonPath('application.canvasX', 0)- ->assertJsonPath('application.canvasY', 0);-- expect(V5Application::query()- ->where('team_id', $team->id)- ->where('project_id', $project->id)- ->where('environment_id', $environment->id)- ->where('name', 'nginx-test')- ->where('status', 'running')- ->where('runtime_container_id', 'nginx-container-id')- ->exists())->toBeTrue();-});--it('creates an nginx v5 application with a custom image', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'private_key_uuid' => $privateKey->uuid,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'last_bootstrapped_at' => now(),- ]);-- fakeSuccessfulNginxFluxDeployment(image: 'docker.io/library/httpd:alpine');-- $this- ->actingAs($user)- ->withSession([- 'currentTeam' => $team,- 'v5.selectedProjectUuid' => $project->uuid,- 'v5.selectedEnvironmentUuid' => $environment->uuid,- ])- ->postJson('/v5/applications/nginx', [- 'image' => 'docker.io/library/httpd:alpine',- ])- ->assertCreated()- ->assertJsonPath('application.image', 'docker.io/library/httpd:alpine');-- expect(V5Application::query()- ->where('image', 'docker.io/library/httpd:alpine')- ->where('runtime_container_id', 'nginx-container-id')- ->exists())->toBeTrue();-});--it('creates an nginx v5 application on the selected team server', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $privateKey->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'last_bootstrapped_at' => now(),- ]);- $selectedServer = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $privateKey->id,- 'name' => 'edge-02',- 'host' => '203.0.113.11',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'last_bootstrapped_at' => now(),- ]);-- fakeSuccessfulNginxFluxDeployment();-- $this- ->actingAs($user)- ->withSession([- 'currentTeam' => $team,- 'v5.selectedProjectUuid' => $project->uuid,- 'v5.selectedEnvironmentUuid' => $environment->uuid,- ])- ->postJson('/v5/applications/nginx', [- 'server_uuid' => $selectedServer->uuid,- ])- ->assertCreated()- ->assertJsonPath('application.serverName', 'edge-02');-- expect(V5Application::query()- ->where('server_id', $selectedServer->id)- ->where('runtime_container_id', 'nginx-container-id')- ->exists())->toBeTrue();-});--it('places a new nginx v5 application next to existing canvas nodes', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $privateKey->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'last_bootstrapped_at' => now(),- ]);-- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-existing',- 'status' => 'running',- 'status_message' => 'Running.',- 'mesh_namespace' => 'default',- 'canvas_x' => 0,- 'canvas_y' => 0,- ]);-- fakeSuccessfulNginxFluxDeployment();-- $this- ->actingAs($user)- ->withSession([- 'currentTeam' => $team,- 'v5.selectedProjectUuid' => $project->uuid,- 'v5.selectedEnvironmentUuid' => $environment->uuid,- ])- ->postJson('/v5/applications/nginx')- ->assertCreated()- ->assertJsonPath('application.canvasX', 352)- ->assertJsonPath('application.canvasY', 0);-});--it('marks an nginx v5 application failed when the launch command fails', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'private_key_uuid' => $privateKey->uuid,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'last_bootstrapped_at' => now(),- ]);-- $this->mock(FluxClient::class, function (MockInterface $mock): void {- $mock->shouldReceive('pullImage')->once()->andThrow(new RuntimeException('podman failed'));- });-- $this- ->actingAs($user)- ->withSession([- 'currentTeam' => $team,- 'v5.selectedProjectUuid' => $project->uuid,- 'v5.selectedEnvironmentUuid' => $environment->uuid,- ])- ->postJson('/v5/applications/nginx')- ->assertUnprocessable()- ->assertJsonPath('application.status', 'failed')- ->assertJsonPath('application.statusMessage', 'podman failed');-});--it('does not create an nginx v5 application on another teams selected server', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$otherUser, $otherTeam] = createV5UserWithTeam('[email protected]');- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $privateKey = createV5PrivateKey($otherTeam, 'Other SSH Key');- $otherServer = V5Server::query()->create([- 'team_id' => $otherTeam->id,- 'created_by_user_id' => $otherUser->id,- 'private_key_uuid' => $privateKey->uuid,- 'name' => 'other-edge-01',- 'host' => '203.0.113.20',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'last_bootstrapped_at' => now(),- ]);-- $this- ->actingAs($user)- ->withSession([- 'currentTeam' => $team,- 'v5.selectedProjectUuid' => $project->uuid,- 'v5.selectedEnvironmentUuid' => $environment->uuid,- ])- ->postJson('/v5/applications/nginx', [- 'server_id' => $otherServer->id,- ])- ->assertUnprocessable()- ->assertJsonPath('message', 'Add a v5 server before deploying nginx.');-- expect(V5Application::query()->count())->toBe(0);-});--it('does not create an nginx v5 application without a team server', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');-- $this- ->actingAs($user)- ->withSession([- 'currentTeam' => $team,- 'v5.selectedProjectUuid' => $project->uuid,- 'v5.selectedEnvironmentUuid' => $environment->uuid,- ])- ->postJson('/v5/applications/nginx')- ->assertUnprocessable()- ->assertJsonPath('message', 'Add a v5 server before deploying nginx.');-- expect(V5Application::query()->count())->toBe(0);-});--it('deletes a v5 application for the current team', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-1',- 'status' => 'running',- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->deleteJson("/v5/applications/{$application->uuid}")- ->assertNoContent();-- expect(V5Application::query()->whereKey($application->id)->exists())->toBeFalse();-});--it('stops and deletes the nginx container before deleting a v5 application', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $privateKey->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-1',- 'status' => 'running',- 'runtime_container_id' => 'nginx-container-id',- ]);-- Process::fake([- '*' => Process::result(),- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->deleteJson("/v5/applications/{$application->uuid}")- ->assertNoContent();-- Process::assertRan(function ($process): bool {- $command = is_array($process->command) ? implode(' ', $process->command) : $process->command;-- return is_string($command)- && str_contains($command, '203.0.113.10')- && str_contains($command, 'podman rm -f')- && str_contains($command, 'coolify-v5-nginx-1');- });- expect(V5Application::query()->whereKey($application->id)->exists())->toBeFalse();-});--it('does not delete another teams v5 application', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$otherUser, $otherTeam] = createV5UserWithTeam();- [$otherProject, $otherEnvironment] = createV5ProjectWithEnvironment($otherTeam, 'Production Project', 'Production');- $server = V5Server::query()->create([- 'team_id' => $otherTeam->id,- 'created_by_user_id' => $otherUser->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- ]);- $application = V5Application::query()->create([- 'team_id' => $otherTeam->id,- 'project_id' => $otherProject->id,- 'environment_id' => $otherEnvironment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $otherUser->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-1',- 'status' => 'running',- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->deleteJson("/v5/applications/{$application->uuid}")- ->assertNotFound();-- expect(V5Application::query()->whereKey($application->id)->exists())->toBeTrue();-});--it('updates v5 application canvas position for the current team', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-1',- 'status' => 'running',- 'canvas_x' => 0,- 'canvas_y' => 0,- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/applications/{$application->uuid}/position", [- 'canvas_x' => 320,- 'canvas_y' => -160,- ])- ->assertSuccessful()- ->assertJsonPath('application.canvasX', 320)- ->assertJsonPath('application.canvasY', -160);-- expect($application->refresh()->canvas_x)->toBe(320)- ->and($application->canvas_y)->toBe(-160);-});--it('updates v5 caddy ingress canvas position for the current team', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-ingress-01',- 'host' => '203.0.113.20',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => ['ingress'],- 'canvas_x' => -352,- 'canvas_y' => 0,- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/caddy-ingresses/{$server->uuid}/position", [- 'canvas_x' => -160,- 'canvas_y' => 240,- ])- ->assertSuccessful()- ->assertJsonPath('caddyIngress.canvasX', -160)- ->assertJsonPath('caddyIngress.canvasY', 240);-- expect($server->refresh()->canvas_x)->toBe(-160)- ->and($server->canvas_y)->toBe(240);-});--it('applies flux application status updates to the database and broadcasts to the team canvas', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'wireguard_management_ip' => '100.64.0.5',- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-1',- 'status' => 'running',- 'status_message' => 'Container started.',- 'runtime_container_id' => 'nginx-container-id',- 'canvas_x' => 0,- 'canvas_y' => 0,- ]);-- Event::fake([V5CanvasResourceUpdated::class]);-- $resource = ApplyFluxResourceStatusUpdate::run([- 'resource_type' => 'application',- 'host_id' => '100.64.0.5',- 'container_name' => 'coolify-v5-nginx-1',- 'container_id' => 'new-nginx-container-id',- 'status' => 'exited',- 'status_message' => 'Status received from coold through flux.',- ]);-- expect($resource)->toBeInstanceOf(V5Application::class)- ->and($application->refresh()->status)->toBe('exited')- ->and($application->status_message)->toBe('Status received from coold through flux.')- ->and($application->runtime_container_id)->toBe('new-nginx-container-id');-- Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id- && $event->applicationId === $application->id);-});--it('maps generic flux container status updates to v5 applications', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'wireguard_management_ip' => '100.64.0.5',- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-1',- 'status' => 'running',- 'status_message' => 'Container started.',- 'runtime_container_id' => 'nginx-container-id',- ]);-- Event::fake([V5CanvasResourceUpdated::class]);-- $resource = ApplyFluxResourceStatusUpdate::run([- 'resource_type' => 'container',- 'host_id' => '100.64.0.5',- 'container_name' => 'coolify-v5-nginx-1',- 'container_id' => 'nginx-container-id',- 'status' => 'exited',- 'status_message' => 'Container state received from coold.',- ]);-- expect($resource)->toBeInstanceOf(V5Application::class)- ->and($application->refresh()->status)->toBe('exited')- ->and($application->status_message)->toBe('Container state received from coold.');-- Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id- && $event->applicationId === $application->id);-});--it('applies flux ingress server status updates to the database and broadcasts cluster plus canvas updates', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Cluster',- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => ['ingress'],- 'wireguard_management_ip' => '100.64.0.5',- ]);-- Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);-- $resource = ApplyFluxResourceStatusUpdate::run([- 'resource_type' => 'server',- 'host_id' => '100.64.0.5',- 'status' => 'unreachable',- 'message' => 'coold heartbeat timed out.',- ]);-- expect($resource)->toBeInstanceOf(V5Server::class)- ->and($server->refresh()->status)->toBe('unreachable')- ->and($server->last_status_check)->toBe('flux')- ->and($server->last_status_output)->toBe('coold heartbeat timed out.')- ->and($server->last_status_checked_at)->not->toBeNull();-- Event::assertDispatched(V5ClusterUpdated::class, fn (V5ClusterUpdated $event) => $event->teamId === $team->id- && $event->clusterId === $cluster->id);- Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id- && $event->caddyIngressServerId === $server->id);-});--it('broadcasts v5 canvas application updates when a non-ingress server goes unreachable', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Cluster',- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'worker-01',- 'host' => '203.0.113.11',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'wireguard_management_ip' => '100.64.0.6',- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-1',- 'status' => 'running',- 'status_message' => 'Container started.',- ]);-- Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);-- $resource = ApplyFluxResourceStatusUpdate::run([- 'resource_type' => 'server',- 'host_id' => '100.64.0.6',- 'status' => 'unreachable',- 'message' => 'coold heartbeat timed out.',- ]);-- expect($resource)->toBeInstanceOf(V5Server::class)- ->and($server->refresh()->status)->toBe('unreachable');-- Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id- && $event->serverId === $server->id);-- $payload = (new V5CanvasResourceUpdated($team->id, serverId: $server->id))->broadcastWith();- expect($payload['applications'])- ->toHaveCount(1)- ->and($payload['applications'][0])- ->toMatchArray([- 'id' => (string) $application->id,- 'status' => 'running',- 'effectiveStatus' => 'unknown',- 'effectiveStatusMessage' => 'coold heartbeat timed out.',- 'serverStatus' => 'unreachable',- 'isServerReachable' => false,- ]);-});--it('applies flux caddy ingress container status updates without changing server install status', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'ingress_status' => 'running',- 'capabilities' => ['ingress'],- 'wireguard_management_ip' => '100.64.0.5',- ]);-- Event::fake([V5CanvasResourceUpdated::class]);-- $resource = ApplyFluxResourceStatusUpdate::run([- 'resource_type' => 'caddy_ingress',- 'host_id' => '100.64.0.5',- 'container_name' => 'coolify-v5-caddy',- 'status' => 'exited',- 'message' => 'Caddy container exited.',- ]);-- expect($resource)->toBeInstanceOf(V5Server::class)- ->and($server->refresh()->status)->toBe('installed')- ->and($server->ingress_type)->toBe('caddy')- ->and($server->ingress_status)->toBe('exited')- ->and($server->last_status_check)->toBe('flux')- ->and($server->last_status_output)->toBe('Caddy container exited.')- ->and($server->last_status_checked_at)->not->toBeNull();-- Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id- && $event->caddyIngressServerId === $server->id);-});--it('accepts flux status updates for non coolify managed containers', function () {- Config::set('flux.laravel_api_token', 'test-flux-token');- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'wireguard_management_ip' => '100.64.0.5',- ]);-- $this- ->postJson('/api/v1/internal/flux/resource-status', [- 'resource_type' => 'container',- 'host_id' => '100.64.0.5',- 'container_id' => 'external-container-id',- 'container_name' => 'external-container',- 'status' => 'running',- ], [- 'Authorization' => 'Bearer test-flux-token',- ])- ->assertSuccessful()- ->assertJsonPath('message', 'Resource status updated.');-- expect(ContainerStatus::query()- ->where('container_id', 'external-container-id')- ->where('container_name', 'external-container')- ->where('status', 'running')- ->exists())->toBeTrue();-});--it('rejects flux resource status http updates without the shared token', function () {- Config::set('flux.laravel_api_token', 'test-flux-token');-- $this- ->postJson('/api/v1/internal/flux/resource-status', [- 'resource_type' => 'application',- 'status' => 'running',- ])- ->assertUnauthorized();-});--it('accepts flux resource status http updates identified by resource uuids', function () {- createSharedUserAndTeamTables();- Config::set('flux.laravel_api_token', 'test-flux-token');-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $server = V5Server::query()->create([- 'uuid' => 'server-public-uuid',- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'wireguard_management_ip' => '100.64.0.5',- ]);- $application = V5Application::query()->create([- 'uuid' => 'application-public-uuid',- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-1',- 'status' => 'starting',- 'status_message' => 'Container starting.',- ]);-- $this- ->withToken('test-flux-token')- ->postJson('/api/v1/internal/flux/resource-status', [- 'resource_type' => 'application',- 'server_uuid' => $server->uuid,- 'application_uuid' => $application->uuid,- 'container_id' => 'new-container-id',- 'status' => 'running',- 'status_message' => 'Status received from coold through flux.',- ])- ->assertSuccessful()- ->assertJsonPath('message', 'Resource status updated.');-- expect($application->refresh()->status)->toBe('running')- ->and($application->runtime_container_id)->toBe('new-container-id');-});--it('rejects numeric laravel ids in flux resource status http payloads', function () {- Config::set('flux.laravel_api_token', 'test-flux-token');-- $this- ->withToken('test-flux-token')- ->postJson('/api/v1/internal/flux/resource-status', [- 'resource_type' => 'application',- 'server_id' => 1,- 'application_id' => 1,- 'status' => 'running',- ])- ->assertInvalid(['server_id', 'application_id']);-});--it('accepts flux resource status http updates and stores them in the database', function () {- createSharedUserAndTeamTables();- Config::set('flux.laravel_api_token', 'test-flux-token');-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'wireguard_management_ip' => '100.64.0.5',- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-1',- 'status' => 'starting',- 'status_message' => 'Container starting.',- 'runtime_container_id' => 'old-container-id',- ]);-- Event::fake([V5CanvasResourceUpdated::class]);-- $this- ->withToken('test-flux-token')- ->postJson('/api/v1/internal/flux/resource-status', [- 'resource_type' => 'application',- 'host_id' => '100.64.0.5',- 'container_name' => 'coolify-v5-nginx-1',- 'container_id' => 'new-container-id',- 'status' => 'running',- 'status_message' => 'Status received from coold through flux.',- ])- ->assertSuccessful()- ->assertJsonPath('message', 'Resource status updated.');-- expect($application->refresh()->status)->toBe('running')- ->and($application->status_message)->toBe('Status received from coold through flux.')- ->and($application->runtime_container_id)->toBe('new-container-id');-- Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id- && $event->applicationId === $application->id);-});--it('configures flux resource status updates for local http instead of redis', function () {- $configSource = file_get_contents(config_path('flux.php'));-- expect($configSource)- ->toContain('COOLIFY_FLUX_LARAVEL_API_TOKEN')- ->not->toContain('APP_KEY')- ->not->toContain('COOLIFY_FLUX_RESOURCE_STATUS_CHANNEL')- ->not->toContain('resource_status_channel');-});--it('broadcasts v5 canvas resource updates when application state changes', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-1',- 'status' => 'running',- 'status_message' => 'Container started.',- 'runtime_container_id' => 'nginx-container-id',- 'canvas_x' => 0,- 'canvas_y' => 0,- ]);-- Event::fake([V5CanvasResourceUpdated::class]);-- $application->update([- 'status' => 'exited',- 'status_message' => 'Container stopped.',- ]);-- Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id- && $event->applicationId === $application->id);-});--it('broadcasts the full v5 application canvas shape after application state changes', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => ['ingress'],- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-1',- 'status' => 'running',- 'status_message' => 'Container started.',- 'runtime_container_id' => 'nginx-container-id',- 'ingress_enabled' => true,- 'internal_port' => 80,- 'canvas_x' => 0,- 'canvas_y' => 0,- ]);- V5ApplicationDomain::query()->create([- 'application_id' => $application->id,- 'domain' => 'nginx.example.com',- ]);-- $application->update([- 'status' => 'exited',- 'status_message' => 'Container stopped.',- ]);-- $payload = (new V5CanvasResourceUpdated($team->id, $application->id))->broadcastWith();-- expect($payload['application'])- ->toMatchArray([- 'id' => (string) $application->id,- 'status' => 'exited',- 'statusMessage' => 'Container stopped.',- 'effectiveStatus' => 'exited',- 'effectiveStatusMessage' => 'Container stopped.',- 'serverName' => 'edge-01',- 'serverStatus' => 'installed',- 'isServerReachable' => true,- 'serverIngressEnabled' => true,- 'ingressEnabled' => true,- 'internalPort' => 80,- 'domains' => ['nginx.example.com'],- ]);-});--it('broadcasts v5 application status as unknown when its server is unreachable', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'unreachable',- 'last_status_output' => 'coold heartbeat timed out.',- 'capabilities' => ['ingress'],- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-1',- 'status' => 'running',- 'status_message' => 'Container started.',- ]);-- $payload = (new V5CanvasResourceUpdated($team->id, $application->id))->broadcastWith();-- expect($payload['application'])- ->toMatchArray([- 'status' => 'running',- 'effectiveStatus' => 'unknown',- 'effectiveStatusMessage' => 'coold heartbeat timed out.',- 'serverStatus' => 'unreachable',- 'isServerReachable' => false,- ]);-});--it('broadcasts v5 cluster and canvas updates when ingress server state changes', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Cluster',- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => ['ingress'],- ]);-- Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);-- $server->update(['status' => 'unreachable']);-- Event::assertDispatched(V5ClusterUpdated::class, fn (V5ClusterUpdated $event) => $event->teamId === $team->id- && $event->clusterId === $cluster->id);- Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id- && $event->caddyIngressServerId === $server->id);-});--it('refreshes v5 application state from flux container inventory', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'wireguard_management_ip' => '100.64.0.5',- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-1',- 'status' => 'running',- 'status_message' => 'Container started.',- 'runtime_container_id' => 'nginx-container-id',- 'canvas_x' => 0,- 'canvas_y' => 0,- ]);-- $this->mock(FluxClient::class, function (MockInterface $mock): void {- $mock->shouldReceive('listContainers')- ->once()- ->with('100.64.0.5')- ->andReturn([- [- 'id' => 'nginx-container-id',- 'name' => 'coolify-v5-nginx-1',- 'image' => 'docker.io/library/nginx:alpine',- 'state' => 'exited',- 'networks' => ['coolify-default-mesh'],- ],- ]);- });-- $this- ->actingAs($user)- ->withSession([- 'currentTeam' => $team,- 'v5.selectedProjectUuid' => $project->uuid,- 'v5.selectedEnvironmentUuid' => $environment->uuid,- ])- ->postJson('/v5/applications/refresh')- ->assertSuccessful()- ->assertJsonPath('applications.0.id', $application->uuid)- ->assertJsonPath('applications.0.status', 'exited')- ->assertJsonPath('applications.0.statusMessage', 'Container state refreshed from coold.');-- expect($application->refresh()->status)->toBe('exited')- ->and($application->status_message)->toBe('Container state refreshed from coold.');-});--it('refreshes v5 caddy ingress state from flux container inventory', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-ingress-01',- 'host' => '203.0.113.20',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'ingress_status' => 'running',- 'capabilities' => ['ingress'],- 'wireguard_management_ip' => '100.64.0.6',- ]);-- Event::fake([V5CanvasResourceUpdated::class]);-- $this->mock(FluxClient::class, function (MockInterface $mock): void {- $mock->shouldReceive('listContainers')- ->once()- ->with('100.64.0.6')- ->andReturn([- [- 'id' => 'caddy-container-id',- 'name' => 'coolify-v5-caddy',- 'image' => 'docker.io/library/caddy:2-alpine',- 'state' => 'exited',- ],- ]);- });-- $this- ->actingAs($user)- ->withSession([- 'currentTeam' => $team,- 'v5.selectedProjectUuid' => $project->uuid,- 'v5.selectedEnvironmentUuid' => $environment->uuid,- ])- ->postJson('/v5/applications/refresh')- ->assertSuccessful()- ->assertJsonPath('caddyIngresses.0.id', $server->uuid)- ->assertJsonPath('caddyIngresses.0.type', 'caddy')- ->assertJsonPath('caddyIngresses.0.status', 'exited');-- expect($server->refresh()->status)->toBe('installed')- ->and($server->ingress_type)->toBe('caddy')- ->and($server->ingress_status)->toBe('exited')- ->and($server->last_status_check)->toBe('flux')- ->and($server->last_status_output)->toBe('Caddy ingress state refreshed from coold.');-- Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id- && $event->caddyIngressServerId === $server->id);-});--it('broadcasts v5 cluster updates when bootstrap state changes', function () {- createSharedUserAndTeamTables();- Config::set('coold.coolify_cli_bin', '/tmp/coolify');-- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $privateKey->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'added',- 'builder_enabled' => false,- 'builder_capacity' => 0,- ]);-- Queue::fake();- Event::fake([V5ClusterUpdated::class]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/bootstrap")- ->assertAccepted();-- Event::assertDispatched(V5ClusterUpdated::class, fn ($event): bool => $event->clusterId === $cluster->id- && $event->teamId === $team->id);-- Process::fake([- '*' => Process::result(output: "Bootstrap completed\n"),- ]);-- Event::fake([V5ClusterUpdated::class]);-- (new V5BootstrapServerJob($cluster->id, $server->id))->handle();-- expect(Event::dispatched(V5ClusterUpdated::class)->count())->toBeGreaterThanOrEqual(2);-});--it('fetches v5 server coold logs through flux', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'wireguard_management_ip' => '100.64.0.10',- 'node_address' => '203.0.113.10',- ]);-- $this->mock(FluxClient::class, function (MockInterface $mock): void {- $mock->shouldReceive('cooldLogs')- ->once()- ->with('100.64.0.10', 200)- ->andReturn('Jun 22 coold[123]: started');- });-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->getJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/coold-logs?tail=200")- ->assertSuccessful()- ->assertJsonPath('output', 'Jun 22 coold[123]: started')- ->assertJsonStructure(['output', 'fetchedAt']);-});--it('fetches v5 server corrosion tables through flux', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'wireguard_management_ip' => '100.64.0.10',- 'node_address' => '203.0.113.10',- ]);-- $this->mock(FluxClient::class, function (MockInterface $mock): void {- $mock->shouldReceive('corrosionTables')- ->once()- ->with('100.64.0.10', 200)- ->andReturn('{"limit":200,"tables":[{"name":"service_endpoints","columns":["container_name"],"rows":[["coolify-v5-nginx"]]}]}');- });-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->getJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/corrosion-tables?limit=200")- ->assertSuccessful()- ->assertJsonPath('output', '{"limit":200,"tables":[{"name":"service_endpoints","columns":["container_name"],"rows":[["coolify-v5-nginx"]]}]}')- ->assertJsonStructure(['output', 'fetchedAt']);-});--it('fetches v5 server firewall rules through flux', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'wireguard_management_ip' => '100.64.0.10',- 'node_address' => '203.0.113.10',- ]);-- $this->mock(FluxClient::class, function (MockInterface $mock): void {- $mock->shouldReceive('listFirewallRules')- ->once()- ->with('100.64.0.10', '')- ->andReturn([[- 'id' => 'v5-resource-connection:1:1:2:tcp:5432',- 'namespace' => 'default',- 'src' => 'coolify-v5-api',- 'dst' => 'coolify-v5-postgres',- 'proto' => 'tcp',- 'port' => 5432,- ]]);- });-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->getJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/firewall-rules")- ->assertSuccessful()- ->assertJsonPath('rules.0.id', 'v5-resource-connection:1:1:2:tcp:5432')- ->assertJsonPath('rules.0.port', 5432)- ->assertJsonStructure(['rules', 'fetchedAt']);-});--it('renders coold diagnostics actions in the v5 server menu', function () {- $clustersPage = file_get_contents(resource_path('js/v5/Pages/Clusters.tsx'));-- expect($clustersPage)- ->toContain('Coold logs')- ->toContain('Corrosion tables')- ->toContain('Firewall rules')- ->toContain('/coold-logs?tail=200')- ->toContain('/corrosion-tables?limit=200')- ->toContain('/firewall-rules')- ->toContain('Latest journalctl entries')- ->toContain('Corrosion table snapshots')- ->toContain('Defined coold allow rules')- ->toContain('overflow-y-auto overflow-x-hidden')- ->toContain('whitespace-pre-wrap wrap-anywhere');-});--it('renders v5 server status on cluster server cards', function () {- $clustersPage = file_get_contents(resource_path('js/v5/Pages/Clusters.tsx'));-- expect($clustersPage)- ->toContain('server.status')- ->toContain('server.lastStatusOutput')- ->toContain('statusLabel(server.status)')- ->toContain('statusBadgeClass(server.status)');-});--it('returns fresh v5 cluster bootstrap state for realtime fallback refreshes', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'added',- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'last_bootstrap_action' => 'bootstrap',- 'last_bootstrap_status' => 'running',- 'last_bootstrap_output' => 'Starting Coolify CLI bootstrap for prod-01...',- 'last_bootstrap_ran_at' => now(),- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->getJson("/v5/clusters/{$cluster->uuid}")- ->assertSuccessful()- ->assertJsonPath('cluster.id', $cluster->uuid)- ->assertJsonPath('cluster.servers.0.id', $server->uuid)- ->assertJsonPath('cluster.servers.0.lastBootstrapStatus', 'running')- ->assertJsonPath('cluster.servers.0.lastBootstrapOutput', 'Starting Coolify CLI bootstrap for prod-01...');-});--it('broadcasts v5 cluster updates immediately with an explicit echo event name', function () {- $clustersPage = file_get_contents(resource_path('js/v5/Pages/Clusters.tsx'));- $event = new V5ClusterUpdated(1, 1);-- expect($event)->toBeInstanceOf(ShouldBroadcastNow::class)- ->and($event->broadcastAs())->toBe('v5.cluster.updated')- ->and($clustersPage)->toContain("listen('.v5.cluster.updated'")- ->and($clustersPage)->toContain('Waiting for window.Echo before subscribing to cluster updates');-});--it('serves a v5 realtime test page for manual websocket diagnostics', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $page = file_get_contents(resource_path('js/v5/Pages/RealtimeTest.tsx'));-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->get('/v5/realtime-test')- ->assertSuccessful()- ->assertSee('RealtimeTest', false)- ->assertSee((string) $team->id, false);-- expect($page)- ->toContain("listen('.v5.realtime.test'")- ->toContain('Subscribing to private-')- ->toContain('Broadcast event');-});--it('broadcasts manual v5 realtime test events immediately', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();-- Event::fake([V5RealtimeTestEvent::class]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson('/v5/realtime-test', [- 'message' => 'hello socket',- ])- ->assertAccepted()- ->assertJsonPath('message', 'Realtime test event broadcasted.');-- Event::assertDispatched(V5RealtimeTestEvent::class, fn (V5RealtimeTestEvent $event): bool => $event->teamId === $team->id- && $event->message === 'hello socket'- && $event->broadcastAs() === 'v5.realtime.test'- && $event instanceof ShouldBroadcastNow);-});--it('serves the production v5 favicon outside local environments', function () {- app()->detectEnvironment(fn () => 'production');-- $this->withoutVite();- fakeFluxHealth();- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->get('/v5')- ->assertSuccessful()- ->assertSee('coolify-logo.svg', false)- ->assertDontSee('coolify-logo-dev-transparent.png', false);-});--it('shows v5 clusters with their servers on the cluster page', function () {- $this->withoutVite();- fakeFluxHealth();- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Lima Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Development-Lima',- 'description' => 'Local Lima development cluster managed by scripts/dev.sh.',- ]);- V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $privateKey->id,- 'name' => 'coold-dev',- 'host' => 'lima-coold-dev',- 'ssh_user' => 'developer',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => ['builder'],- 'builder_enabled' => true,- 'builder_capacity' => 2,- 'last_bootstrapped_at' => now(),- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->get('/v5/clusters')- ->assertSuccessful()- ->assertSee('Clusters', false)- ->assertSee('"clusters":[', false)- ->assertSee('"privateKeys":[', false)- ->assertSee('"name":"Lima Key"', false)- ->assertSee('"name":"Development-Lima"', false)- ->assertSee('"serversCount":1', false)- ->assertSee('"name":"coold-dev"', false)- ->assertSee('"host":"lima-coold-dev"', false)- ->assertDontSee('"sshUser"', false)- ->assertDontSee('"sshPort"', false)- ->assertSee('"builderEnabled":true', false)- ->assertSee('"builderCapacity":2', false)- ->assertSee('"wireguardInterface":"wg0"', false)- ->assertSee('"wireguardManagementPool":"100.64.0.0\\/16"', false)- ->assertSee('"containerNetworkPool":"10.210.0.0\\/16"', false)- ->assertSee('"namespaces":["default"]', false)- ->assertSee('"defaultDenyContainers":true', false)- ->assertSee('"cooldVersion":"nightly"', false)- ->assertSee('"corrosionVersion":"v1.0.0"', false)- ->assertSee('"builderCpuQuota":"200%"', false)- ->assertSee('"builderMemoryMax":"2G"', false)- ->assertSee('"builderTimeoutSecs":1800', false)- ->assertSee('"lastCliStatus":null', false)- ->assertSee('"privateKeyName":"Lima Key"', false)- ->assertSee('"nodeAddress":null', false)- ->assertSee('"wireguardManagementIp":null', false)- ->assertSee('"containerSubnets":[]', false)- ->assertSee('"lastBootstrappedAt":"', false);-});--it('creates a v5 cluster for the current team', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson('/v5/clusters', [- 'name' => 'Production Mesh',- 'description' => 'Primary production cluster.',- ])- ->assertCreated()- ->assertJsonPath('cluster.name', 'Production Mesh')- ->assertJsonPath('cluster.description', 'Primary production cluster.')- ->assertJsonPath('cluster.wireguardInterface', 'wg0')- ->assertJsonPath('cluster.wireguardManagementPool', '100.64.0.0/16')- ->assertJsonPath('cluster.wireguardListenPort', 51820)- ->assertJsonPath('cluster.containerNetworkPool', '10.210.0.0/16')- ->assertJsonPath('cluster.containerNetworkPrefix', 24)- ->assertJsonPath('cluster.namespaces', ['default'])- ->assertJsonPath('cluster.defaultDenyContainers', true)- ->assertJsonPath('cluster.cooldVersion', 'nightly')- ->assertJsonPath('cluster.corrosionVersion', 'v1.0.0')- ->assertJsonPath('cluster.corrosionGossipPort', 8787)- ->assertJsonPath('cluster.corrosionApiPort', 8080)- ->assertJsonPath('cluster.builderEnabled', true)- ->assertJsonPath('cluster.builderCapacity', 2)- ->assertJsonPath('cluster.builderCpuQuota', '200%')- ->assertJsonPath('cluster.builderMemoryMax', '2G')- ->assertJsonPath('cluster.builderTimeoutSecs', 1800)- ->assertJsonPath('cluster.lastCliAction', null)- ->assertJsonPath('cluster.lastCliStatus', null)- ->assertJsonPath('cluster.lastCliSummary', null)- ->assertJsonPath('cluster.lastCliRanAt', null)- ->assertJsonPath('cluster.serversCount', 0)- ->assertJsonPath('cluster.servers', []);-- expect(Cluster::query()- ->where('team_id', $team->id)- ->where('created_by_user_id', $user->id)- ->where('name', 'Production Mesh')- ->where('description', 'Primary production cluster.')- ->where('wireguard_interface', 'wg0')- ->where('wireguard_management_pool', '100.64.0.0/16')- ->where('container_network_pool', '10.210.0.0/16')- ->exists())->toBeTrue();-});--it('creates a v5 cluster with advanced cli configuration', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson('/v5/clusters', [- 'name' => 'Custom Mesh',- 'description' => null,- 'wireguard_interface' => 'wg-prod',- 'wireguard_management_pool' => '100.65.0.0/16',- 'wireguard_listen_port' => 51830,- 'container_network_pool' => '10.211.0.0/16',- 'container_network_prefix' => 25,- 'namespaces' => ['default', 'preview'],- 'default_deny_containers' => false,- 'coold_version' => 'v0.2.0',- 'corrosion_version' => 'v1.1.0',- 'corrosion_gossip_port' => 8788,- 'corrosion_api_port' => 8081,- 'builder_enabled' => true,- 'builder_capacity' => 4,- 'builder_cpu_quota' => '400%',- 'builder_memory_max' => '4G',- 'builder_timeout_secs' => 2400,- ])- ->assertCreated()- ->assertJsonPath('cluster.wireguardInterface', 'wg-prod')- ->assertJsonPath('cluster.wireguardManagementPool', '100.65.0.0/16')- ->assertJsonPath('cluster.wireguardListenPort', 51830)- ->assertJsonPath('cluster.containerNetworkPool', '10.211.0.0/16')- ->assertJsonPath('cluster.containerNetworkPrefix', 25)- ->assertJsonPath('cluster.namespaces', ['default', 'preview'])- ->assertJsonPath('cluster.defaultDenyContainers', false)- ->assertJsonPath('cluster.cooldVersion', 'v0.2.0')- ->assertJsonPath('cluster.corrosionVersion', 'v1.1.0')- ->assertJsonPath('cluster.builderCapacity', 4)- ->assertJsonPath('cluster.builderCpuQuota', '400%')- ->assertJsonPath('cluster.builderMemoryMax', '4G')- ->assertJsonPath('cluster.builderTimeoutSecs', 2400);-});--it('validates advanced v5 cluster cli configuration', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson('/v5/clusters', [- 'name' => 'Broken Mesh',- 'wireguard_management_pool' => 'not-a-cidr',- 'container_network_pool' => '10.211.0.0',- 'wireguard_listen_port' => 70000,- 'namespaces' => ['Default'],- ])- ->assertUnprocessable()- ->assertJsonValidationErrors([- 'wireguard_management_pool',- 'container_network_pool',- 'wireguard_listen_port',- 'namespaces.0',- ]);-});--it('requires positive v5 cluster builder capacity when builders are enabled', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson('/v5/clusters', [- 'name' => 'Zero Builder Mesh',- 'builder_enabled' => true,- 'builder_capacity' => 0,- ])- ->assertUnprocessable()- ->assertJsonValidationErrors(['builder_capacity']);-});--it('adds a v5 server to a cluster for the current team', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- 'builder_enabled' => true,- 'builder_capacity' => 3,- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson("/v5/clusters/{$cluster->uuid}/servers", [- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'private_key_uuid' => $privateKey->uuid,- 'node_address' => '203.0.113.10',- 'builder_enabled' => true,- 'builder_capacity' => 3,- 'wireguard_listen_port_override' => 51821,- 'wireguard_endpoint_override' => 'prod-01.example.com:51821',- 'coold_version' => 'v9.9.9',- 'corrosion_version' => 'v8.8.8',- ])- ->assertCreated()- ->assertJsonPath('cluster.serversCount', 1)- ->assertJsonPath('cluster.servers.0.name', 'prod-01')- ->assertJsonPath('cluster.servers.0.host', '203.0.113.10')- ->assertJsonMissingPath('cluster.servers.0.sshUser')- ->assertJsonMissingPath('cluster.servers.0.sshPort')- ->assertJsonMissingPath('cluster.servers.0.cooldVersion')- ->assertJsonMissingPath('cluster.servers.0.corrosionVersion')- ->assertJsonPath('cluster.servers.0.privateKeyName', 'Production SSH Key')- ->assertJsonPath('cluster.servers.0.status', 'added')- ->assertJsonPath('cluster.servers.0.nodeAddress', '203.0.113.10')- ->assertJsonPath('cluster.servers.0.builderEnabled', true)- ->assertJsonPath('cluster.servers.0.builderCapacity', 3)- ->assertJsonPath('cluster.servers.0.builderCpuQuota', '200%')- ->assertJsonPath('cluster.servers.0.ingressEnabled', false)- ->assertJsonPath('cluster.servers.0.ingressType', null)- ->assertJsonPath('cluster.servers.0.capabilities', [])- ->assertJsonPath('cluster.servers.0.wireguardListenPortOverride', 51821)- ->assertJsonPath('cluster.servers.0.wireguardEndpointOverride', 'prod-01.example.com:51821')- ->assertJsonPath('cluster.servers.0.wireguardManagementIp', null)- ->assertJsonPath('cluster.servers.0.containerSubnets', []);-- expect(V5Server::query()- ->where('team_id', $team->id)- ->where('cluster_id', $cluster->id)- ->where('created_by_user_id', $user->id)- ->where('name', 'prod-01')- ->where('host', '203.0.113.10')- ->where('ssh_user', 'root')- ->where('ssh_port', 22)- ->where('private_key_id', $privateKey->id)- ->where('node_address', '203.0.113.10')- ->exists())->toBeTrue();-- expect(V5Server::query()->where('name', 'prod-01')->first()->capabilities)- ->toBe([]);-});--it('adds a v5 server with caddy ingress enabled', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson("/v5/clusters/{$cluster->uuid}/servers", [- 'name' => 'edge-01',- 'host' => '203.0.113.20',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'private_key_uuid' => $privateKey->uuid,- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'ingress_enabled' => true,- 'ingress_type' => 'caddy',- ])- ->assertCreated()- ->assertJsonPath('cluster.servers.0.ingressEnabled', true)- ->assertJsonPath('cluster.servers.0.ingressType', 'caddy')- ->assertJsonPath('cluster.servers.0.capabilities', ['ingress']);-- $server = V5Server::query()->where('name', 'edge-01')->first();-- expect($server->capabilities)->toBe(['ingress'])- ->and($server->ingress_type)->toBe('caddy')- ->and($server->isIngress())->toBeTrue();-});--it('keeps added v5 server builder capacity when builder is disabled', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- 'builder_enabled' => true,- 'builder_capacity' => 3,- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson("/v5/clusters/{$cluster->uuid}/servers", [- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'private_key_uuid' => $privateKey->uuid,- 'builder_enabled' => false,- 'builder_capacity' => 3,- ])- ->assertCreated()- ->assertJsonPath('cluster.servers.0.builderEnabled', false)- ->assertJsonPath('cluster.servers.0.builderCapacity', 3)- ->assertJsonPath('cluster.servers.0.capabilities', []);-- $server = V5Server::query()->where('name', 'prod-01')->first();-- expect($server->builder_enabled)->toBeFalse()- ->and($server->builder_capacity)->toBe(3)- ->and($server->capabilities)->toBe([]);-});--it('requires positive v5 server builder capacity when builder is enabled', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson("/v5/clusters/{$cluster->uuid}/servers", [- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'private_key_uuid' => $privateKey->uuid,- 'builder_enabled' => true,- 'builder_capacity' => 0,- ])- ->assertUnprocessable()- ->assertJsonValidationErrors(['builder_capacity']);-});--it('defaults dev Lima wireguard overrides for host docker internal servers', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Testing Host Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Development-Lima',- 'description' => null,- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson("/v5/clusters/{$cluster->uuid}/servers", [- 'name' => 'coolify-naked-test',- 'host' => 'host.docker.internal',- 'ssh_user' => 'root',- 'ssh_port' => 60003,- 'private_key_uuid' => $privateKey->uuid,- ])- ->assertCreated()- ->assertJsonPath('cluster.servers.0.wireguardListenPortOverride', 51823)- ->assertJsonPath('cluster.servers.0.wireguardEndpointOverride', 'host.lima.internal:51823');-});--it('rejects adding a v5 server to another teams cluster', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $otherTeam = Team::withoutEvents(fn () => Team::query()->create([- 'name' => 'Other V5 Team',- 'description' => null,- 'personal_team' => false,- 'show_boarding' => false,- ]));- $cluster = Cluster::query()->create([- 'team_id' => $otherTeam->id,- 'created_by_user_id' => $user->id,- 'name' => 'Other Mesh',- 'description' => null,- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson("/v5/clusters/{$cluster->uuid}/servers", [- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- ])- ->assertForbidden();-});--it('validates v5 server creation input', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson("/v5/clusters/{$cluster->uuid}/servers", [- 'name' => '',- 'host' => '',- 'ssh_user' => '',- 'ssh_port' => 70000,- 'private_key_uuid' => null,- 'wireguard_listen_port_override' => 70000,- ])- ->assertUnprocessable()- ->assertJsonValidationErrors([- 'name',- 'host',- 'ssh_user',- 'ssh_port',- 'private_key_uuid',- 'wireguard_listen_port_override',- ]);-});--it('rejects private keys from another team when adding a v5 server', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $otherTeam = Team::withoutEvents(fn () => Team::query()->create([- 'name' => 'Other V5 Team',- 'description' => null,- 'personal_team' => false,- 'show_boarding' => false,- ]));- $otherPrivateKey = createV5PrivateKey($otherTeam, 'Other SSH Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson("/v5/clusters/{$cluster->uuid}/servers", [- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'private_key_uuid' => $otherPrivateKey->uuid,- ])- ->assertUnprocessable()- ->assertJsonValidationErrors(['private_key_uuid']);-});--it('checks v5 server ssh status without storing diagnostic output', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $privateKey->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'added',- 'builder_enabled' => false,- 'builder_capacity' => 0,- ]);-- Process::fake([- '*' => Process::result(output: "SSH connection OK\nprod-01\nLinux aarch64\n/usr/bin/docker\n"),- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/check")- ->assertSuccessful()- ->assertJsonPath('status', 'reachable')- ->assertJsonPath('output', "SSH connection OK\nprod-01\nLinux aarch64\n/usr/bin/docker")- ->assertJsonPath('checkedAt', fn (?string $value) => $value !== null);-- Process::assertRan(fn ($process) => str_contains(json_encode($process->command), '203.0.113.10'));- Process::assertRan(fn ($process) => in_array('LogLevel=ERROR', $process->command, true));-- $server->refresh();-- expect($server->status)->toBe('added')- ->and($server->last_status_check)->toBeNull()- ->and($server->last_status_output)->toBeNull()- ->and($server->last_status_checked_at)->toBeNull();-});--it('writes quiet ssh options for v5 bootstrap ssh config', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $privateKey->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- ]);- $server->load('privateKey');-- $tempDirectory = storage_path('framework/testing/v5_bootstrap_'.str()->random(8));- mkdir($tempDirectory, 0700, true);-- try {- $controller = app(DashboardController::class);- $reflection = new ReflectionClass($controller);- $method = $reflection->getMethod('writeBootstrapSshConfig');- $method->setAccessible(true);-- $sshConfigLocation = $method->invoke($controller, collect([$server]), $tempDirectory);- $config = file_get_contents($sshConfigLocation);-- expect($config)->toContain(' LogLevel ERROR')- ->and($config)->toContain(' UserKnownHostsFile /dev/null')- ->and($config)->toContain(' StrictHostKeyChecking no');- } finally {- collect(scandir($tempDirectory) ?: [])- ->reject(fn (string $file) => in_array($file, ['.', '..'], true))- ->each(fn (string $file) => @unlink($tempDirectory.'/'.$file));- @rmdir($tempDirectory);- }-});--it('bootstraps a single v5 server with the Coolify CLI', function () {- createSharedUserAndTeamTables();- Config::set('coold.coolify_cli_bin', '/tmp/coolify');-- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- 'namespaces' => ['default', 'preview'],- 'container_network_pool' => '10.211.0.0/16',- 'container_network_prefix' => 25,- 'wireguard_management_pool' => '100.65.0.0/16',- 'wireguard_interface' => 'wg-prod',- 'wireguard_listen_port' => 51830,- 'coold_version' => 'v0.2.0',- 'corrosion_version' => 'v1.1.0',- 'corrosion_gossip_port' => 8788,- 'corrosion_api_port' => 8081,- 'builder_enabled' => true,- 'builder_capacity' => 4,- 'builder_cpu_quota' => '400%',- 'builder_memory_max' => '4G',- 'builder_timeout_secs' => 2400,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $privateKey->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 2222,- 'status' => 'added',- 'capabilities' => ['builder'],- 'builder_enabled' => true,- 'builder_capacity' => 4,- 'wireguard_listen_port_override' => 51831,- 'wireguard_endpoint_override' => 'prod-01.example.com:51831',- ]);-- Queue::fake();-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/bootstrap")- ->assertAccepted()- ->assertJsonPath('message', 'Bootstrap queued.')- ->assertJsonPath('cluster.servers.0.status', 'added')- ->assertJsonPath('cluster.servers.0.lastBootstrapAction', 'bootstrap')- ->assertJsonPath('cluster.servers.0.lastBootstrapStatus', 'queued')- ->assertJsonPath('cluster.servers.0.lastBootstrapOutput', 'Queued Coolify bootstrap for prod-01.');-- Queue::assertPushed(V5BootstrapServerJob::class);-- Process::fake([- '*' => Process::result(output: "Bootstrap completed\n"),- ]);-- Event::fake([V5ClusterUpdated::class]);-- (new V5BootstrapServerJob($cluster->id, $server->id))->handle();-- $server->refresh();-- Process::assertRan(function ($process): bool {- $command = $process->command;- $node = cliFlagValue($command, '--nodes');-- return $command[0] === '/tmp/coolify'- && in_array('init', $command, true)- && in_array('bootstrap', $command, true)- && in_array('--ssh-config', $command, true)- && is_string($node)- && str_starts_with($node, 'v5-server-')- && cliFlagValue($command, '--namespaces') === 'default,preview'- && cliFlagValue($command, '--container-pool') === '10.211.0.0/16'- && cliFlagValue($command, '--wg-mgmt-pool') === '100.65.0.0/16'- && cliFlagValue($command, '--wg-interface') === 'wg-prod'- && cliFlagValue($command, '--coold-version') === 'v0.2.0'- && cliFlagValue($command, '--corrosion-version') === 'v1.1.0'- && cliFlagValue($command, '--wg-listen-port-overrides') === $node.'=51831'- && cliFlagValue($command, '--wg-endpoint-overrides') === $node.'=prod-01.example.com:51831'- && ! in_array('--enable-builder', $command, true)- && in_array('--yes', $command, true)- && ! in_array('--new-nodes', $command, true);- });-- $cluster->refresh();-- expect($server->status)->toBe('installed')- ->and($server->last_bootstrap_status)->toBe('succeeded')- ->and($server->last_bootstrap_output)->toBe('Bootstrap completed')- ->and($server->last_bootstrapped_at)->not->toBeNull();-});--it('does not run a macOS development Coolify CLI binary from Docker during v5 server bootstrap', function () {- createSharedUserAndTeamTables();- Config::set('coold.coolify_cli_bin', '/usr/local/bin/coolify');-- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $privateKey->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'added',- 'builder_enabled' => false,- 'builder_capacity' => 0,- ]);-- Queue::fake();-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/bootstrap")- ->assertAccepted();-- Process::fake([- '*' => Process::result(output: "Bootstrap completed\n"),- ]);-- Event::fake([V5ClusterUpdated::class]);-- (new V5BootstrapServerJob($cluster->id, $server->id))->handle();-- Process::assertRan(fn ($process): bool => $process->command[0] === '/usr/local/bin/coolify');-});--it('keeps a v5 server added when Coolify CLI bootstrap fails', function () {- createSharedUserAndTeamTables();- Config::set('coold.coolify_cli_bin', '/tmp/coolify');-- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $privateKey->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'added',- 'builder_enabled' => false,- 'builder_capacity' => 0,- ]);-- Queue::fake();-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/bootstrap")- ->assertAccepted()- ->assertJsonPath('cluster.servers.0.status', 'added')- ->assertJsonPath('cluster.servers.0.lastBootstrappedAt', null)- ->assertJsonPath('cluster.servers.0.lastBootstrapStatus', 'queued');-- Process::fake([- '*' => Process::result(errorOutput: "bootstrap failed\n", exitCode: 1),- ]);-- Event::fake([V5ClusterUpdated::class]);-- (new V5BootstrapServerJob($cluster->id, $server->id))->handle();-- $server->refresh();-- expect($server->status)->toBe('added')- ->and($server->last_bootstrap_status)->toBe('failed')- ->and($server->last_bootstrap_output)->toBe('bootstrap failed')- ->and($server->last_bootstrapped_at)->toBeNull();-});--it('extends a v5 cluster when bootstrapping a new server', function () {- createSharedUserAndTeamTables();- Config::set('coold.coolify_cli_bin', '/tmp/coolify');-- [$user, $team] = createV5UserWithTeam();- $oldPrivateKey = createV5PrivateKey($team, 'Old SSH Key');- $newPrivateKey = createV5PrivateKey($team, 'New SSH Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- 'coold_version' => 'v0.3.0',- 'corrosion_version' => 'v1.2.0',- ]);- $oldServer = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $oldPrivateKey->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'ubuntu',- 'ssh_port' => 2222,- 'status' => 'installed',- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'last_bootstrapped_at' => now()->subDay(),- ]);- $newServer = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $newPrivateKey->id,- 'name' => 'prod-02',- 'host' => '203.0.113.11',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'added',- 'builder_enabled' => false,- 'builder_capacity' => 0,- ]);-- Queue::fake();-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson("/v5/clusters/{$cluster->uuid}/servers/{$newServer->uuid}/bootstrap")- ->assertAccepted()- ->assertJsonPath('cluster.servers.1.lastBootstrapAction', 'extend')- ->assertJsonPath('cluster.servers.1.lastBootstrapStatus', 'queued');-- Process::fake([- '*' => Process::result(output: "Extend completed\n"),- ]);-- Event::fake([V5ClusterUpdated::class]);-- (new V5BootstrapServerJob($cluster->id, $newServer->id))->handle();-- Process::assertRan(function ($process) use ($oldServer, $newServer): bool {- $command = $process->command;- $oldNode = "v5-server-{$oldServer->uuid}";- $newNode = "v5-server-{$newServer->uuid}";-- return in_array('extend', $command, true)- && in_array("{$oldNode},{$newNode}", $command, true)- && in_array('--new-nodes', $command, true)- && in_array($newNode, $command, true)- && in_array('--ssh-config', $command, true)- && cliFlagValue($command, '--coold-version') === 'v0.3.0'- && cliFlagValue($command, '--corrosion-version') === 'v1.2.0';- });-- $oldServer->refresh();- $newServer->refresh();-- expect($oldServer->status)->toBe('installed')- ->and($newServer->status)->toBe('installed')- ->and($newServer->last_bootstrap_status)->toBe('succeeded')- ->and($newServer->last_bootstrap_output)->toBe('Extend completed')- ->and($newServer->last_bootstrapped_at)->not->toBeNull();-});--it('adopts a re-added v5 server that is already bootstrapped for the same cluster', function () {- createSharedUserAndTeamTables();- Config::set('coold.coolify_cli_bin', '/tmp/coolify');-- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $privateKey->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'added',- 'builder_enabled' => false,- 'builder_capacity' => 0,- ]);-- Process::fake([- '*' => Process::result(output: json_encode([- 'cluster_id' => $cluster->id,- 'server_uuid' => 'server-previous-uuid',- 'wireguard_management_ip' => '100.64.0.10',- 'wireguard_public_key' => 'public-key',- 'container_subnets' => ['default' => '10.210.0.0/24'],- ], JSON_THROW_ON_ERROR)."\n"),- ]);-- Event::fake([V5ClusterUpdated::class]);-- (new V5BootstrapServerJob($cluster->id, $server->id))->handle();-- Process::assertNotRan(fn ($process): bool => $process->command[0] === '/tmp/coolify');-- $server->refresh();-- expect($server->status)->toBe('installed')- ->and($server->uuid)->toBe('server-previous-uuid')- ->and($server->wireguard_management_ip)->toBe('100.64.0.10')- ->and($server->wireguard_public_key)->toBe('public-key')- ->and($server->container_subnets)->toBe(['default' => '10.210.0.0/24'])- ->and($server->last_bootstrap_status)->toBe('succeeded')- ->and($server->last_bootstrap_output)->toBe('Adopted existing Coolify bootstrap state for this cluster.')- ->and($server->last_bootstrapped_at)->not->toBeNull();-});--it('blocks bootstrapping a v5 server that belongs to another cluster', function () {- createSharedUserAndTeamTables();- Config::set('coold.coolify_cli_bin', '/tmp/coolify');-- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Production SSH Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $privateKey->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'added',- 'builder_enabled' => false,- 'builder_capacity' => 0,- ]);-- Process::fake([- '*' => Process::result(output: json_encode([- 'cluster_id' => $cluster->id + 100,- 'server_uuid' => 'server-other-uuid',- ], JSON_THROW_ON_ERROR)."\n"),- ]);-- Event::fake([V5ClusterUpdated::class]);-- (new V5BootstrapServerJob($cluster->id, $server->id))->handle();-- Process::assertNotRan(fn ($process): bool => $process->command[0] === '/tmp/coolify');-- $server->refresh();-- expect($server->status)->toBe('added')- ->and($server->last_bootstrap_status)->toBe('failed')- ->and($server->last_bootstrap_output)->toContain('already bootstrapped for another cluster')- ->and($server->last_bootstrapped_at)->toBeNull();-});--it('deletes an unbootstrapped v5 server from a cluster', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'added',- 'builder_enabled' => false,- 'builder_capacity' => 0,- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->deleteJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}")- ->assertSuccessful()- ->assertJsonPath('cluster.serversCount', 0)- ->assertJsonPath('cluster.servers', []);-- expect(V5Server::query()->whereKey($server->id)->exists())->toBeFalse();-});--it('deletes a bootstrapped v5 server from a cluster', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'last_bootstrapped_at' => now(),- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->deleteJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}")- ->assertSuccessful()- ->assertJsonPath('cluster.serversCount', 0)- ->assertJsonPath('cluster.servers', []);-- expect(V5Server::query()->whereKey($server->id)->exists())->toBeFalse();-});--it('updates editable v5 server builder details without changing networking', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'builder_cpu_quota' => '100%',- 'node_address' => '10.0.0.10',- 'wireguard_listen_port_override' => 51821,- 'wireguard_endpoint_override' => 'prod-01.example.com:51821',- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}", [- 'builder_enabled' => true,- 'builder_capacity' => 5,- 'builder_cpu_quota' => '350%',- 'host' => '198.51.100.99',- 'ssh_user' => 'admin',- 'ssh_port' => 2222,- 'node_address' => '10.0.0.99',- 'wireguard_endpoint_override' => 'changed.example.com:51821',- ])- ->assertSuccessful()- ->assertJsonPath('cluster.servers.0.builderEnabled', true)- ->assertJsonPath('cluster.servers.0.builderCapacity', 5)- ->assertJsonPath('cluster.servers.0.builderCpuQuota', '350%')- ->assertJsonPath('cluster.servers.0.ingressEnabled', false)- ->assertJsonPath('cluster.servers.0.host', '203.0.113.10')- ->assertJsonMissingPath('cluster.servers.0.sshUser')- ->assertJsonMissingPath('cluster.servers.0.sshPort')- ->assertJsonPath('cluster.servers.0.nodeAddress', '10.0.0.10')- ->assertJsonPath('cluster.servers.0.wireguardEndpointOverride', 'prod-01.example.com:51821');-- $server->refresh();-- expect($server->builder_enabled)->toBeTrue()- ->and($server->builder_capacity)->toBe(5)- ->and($server->builder_cpu_quota)->toBe('350%')- ->and($server->capabilities)->toBe([])- ->and($server->host)->toBe('203.0.113.10')- ->and($server->ssh_user)->toBe('root')- ->and($server->ssh_port)->toBe(22)- ->and($server->node_address)->toBe('10.0.0.10')- ->and($server->wireguard_endpoint_override)->toBe('prod-01.example.com:51821');-});--it('updates editable v5 server caddy ingress capability independently from builder', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.20',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'added',- 'capabilities' => ['builder'],- 'builder_enabled' => true,- 'builder_capacity' => 2,- 'builder_cpu_quota' => '200%',- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}", [- 'builder_enabled' => false,- 'builder_capacity' => 2,- 'builder_cpu_quota' => '200%',- 'ingress_enabled' => true,- 'ingress_type' => 'caddy',- ])- ->assertSuccessful()- ->assertJsonPath('cluster.servers.0.builderEnabled', false)- ->assertJsonPath('cluster.servers.0.ingressEnabled', true)- ->assertJsonPath('cluster.servers.0.ingressType', 'caddy')- ->assertJsonPath('cluster.servers.0.capabilities', ['ingress']);-- $server->refresh();-- expect($server->capabilities)->toBe(['ingress'])- ->and($server->ingress_type)->toBe('caddy')- ->and($server->builder_enabled)->toBeFalse()- ->and($server->isIngress())->toBeTrue();-});--it('rejects application ingress when server ingress is disabled', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'app-01',- 'host' => '203.0.113.21',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'builder_cpu_quota' => '200%',- 'wireguard_management_ip' => '100.64.0.11',- 'last_bootstrapped_at' => now(),- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'private-app',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-private-app',- 'status' => 'running',- 'mesh_namespace' => 'default',- ]);-- $fluxClient = Mockery::mock(FluxClient::class);- $fluxClient->shouldNotReceive('applyIngress');- app()->instance(FluxClient::class, $fluxClient);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/applications/{$application->uuid}/ingress", [- 'ingress_enabled' => true,- 'internal_port' => 3000,- 'domains' => ['app.example.com'],- ])- ->assertUnprocessable()- ->assertJsonPath('message', 'Enable ingress on the server before enabling app ingress.');-- expect($application->refresh()->ingress_enabled)->toBeFalse()- ->and($application->domains()->count())->toBe(0);-});--it('enables application ingress without publishing domains by default', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.20',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => ['ingress'],- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'builder_cpu_quota' => '200%',- 'wireguard_management_ip' => '100.64.0.10',- 'last_bootstrapped_at' => now(),- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-test',- 'status' => 'running',- 'mesh_namespace' => 'default',- ]);- V5ApplicationDomain::query()->create([- 'application_id' => $application->id,- 'domain' => 'kept.example.com',- ]);-- $fluxClient = Mockery::mock(FluxClient::class);- $fluxClient- ->shouldReceive('applyIngress')- ->once()- ->with(- '100.64.0.10',- 'caddy',- Mockery::on(fn (string $caddyfile): bool => str_contains($caddyfile, 'import apps/*.caddy')),- []- )- ->andReturn('Caddy ingress applied.');- expectCaddyIngressFirewallRule($fluxClient);- app()->instance(FluxClient::class, $fluxClient);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/applications/{$application->uuid}/ingress", [- 'ingress_enabled' => false,- 'internal_port' => 8080,- ])- ->assertSuccessful()- ->assertJsonPath('application.ingressEnabled', false)- ->assertJsonPath('application.internalPort', 8080)- ->assertJsonPath('application.domains.0', 'kept.example.com');-- expect($application->refresh()->ingress_enabled)->toBeFalse();-});--it('validates application ingress domains', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.20',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => ['ingress'],- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'builder_cpu_quota' => '200%',- 'wireguard_management_ip' => '100.64.0.10',- 'last_bootstrapped_at' => now(),- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-test',- 'status' => 'running',- 'mesh_namespace' => 'default',- ]);-- $fluxClient = Mockery::mock(FluxClient::class);- $fluxClient->shouldNotReceive('applyIngress');- app()->instance(FluxClient::class, $fluxClient);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/applications/{$application->uuid}/ingress", [- 'ingress_enabled' => true,- 'internal_port' => 3000,- 'domains' => ['https://bad.example.com'],- ])- ->assertUnprocessable()- ->assertInvalid(['domains.0']);-- expect($application->refresh()->ingress_enabled)->toBeFalse();-});--it('enables application ingress with explicit domains and port', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.20',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => ['ingress'],- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'builder_cpu_quota' => '200%',- 'wireguard_management_ip' => '100.64.0.10',- 'last_bootstrapped_at' => now(),- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-test',- 'status' => 'running',- 'mesh_namespace' => 'default',- ]);-- $fluxClient = Mockery::mock(FluxClient::class);- $fluxClient- ->shouldReceive('applyIngress')- ->once()- ->with(- '100.64.0.10',- 'caddy',- Mockery::on(fn (string $caddyfile): bool => str_contains($caddyfile, 'import apps/*.caddy')),- Mockery::on(fn (array $apps): bool => count($apps) === 1- && str_contains($apps[0]['config'], 'http://app.example.com {')- && str_contains($apps[0]['config'], 'reverse_proxy coolify-v5-nginx-test.default.coolify.internal:3000'))- )- ->andReturn('Caddy ingress applied.');- expectCaddyIngressFirewallRule($fluxClient);- app()->instance(FluxClient::class, $fluxClient);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/applications/{$application->uuid}/ingress", [- 'ingress_enabled' => true,- 'internal_port' => 3000,- 'domains' => ['app.example.com'],- ])- ->assertSuccessful()- ->assertJsonPath('application.ingressEnabled', true)- ->assertJsonPath('application.internalPort', 3000)- ->assertJsonPath('application.domains.0', 'app.example.com');-- expect($application->refresh()->ingress_enabled)->toBeTrue()- ->and($application->internal_port)->toBe(3000)- ->and($application->domains()->pluck('domain')->all())->toBe(['app.example.com']);-});--it('returns flux error details when application ingress sync fails', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.20',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => ['ingress'],- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'builder_cpu_quota' => '200%',- 'wireguard_management_ip' => '100.64.0.10',- 'last_bootstrapped_at' => now(),- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-test',- 'status' => 'running',- 'mesh_namespace' => 'default',- ]);-- $fluxClient = Mockery::mock(FluxClient::class);- $fluxClient- ->shouldReceive('applyIngress')- ->once()- ->andThrow(new RuntimeException('start Caddy ingress: podman exited with status 125'));- app()->instance(FluxClient::class, $fluxClient);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/applications/{$application->uuid}/ingress", [- 'ingress_enabled' => true,- 'internal_port' => 3000,- 'domains' => ['app.example.com'],- ])- ->assertStatus(502)- ->assertJsonPath('message', 'Could not start Caddy ingress on the server. Check that Podman is running and port 80 is available.')- ->assertJsonPath('detail', 'start Caddy ingress: podman exited with status 125');-});--it('syncs caddy ingress routes through flux when enabling ingress on an installed server', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.20',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'builder_cpu_quota' => '200%',- 'wireguard_management_ip' => '100.64.0.10',- 'last_bootstrapped_at' => now(),- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-test',- 'status' => 'running',- 'mesh_namespace' => 'default',- 'ingress_enabled' => true,- 'internal_port' => 8080,- ]);- V5ApplicationDomain::query()->create([- 'application_id' => $application->id,- 'domain' => 'nginx.example.com',- ]);- V5ApplicationDomain::query()->create([- 'application_id' => $application->id,- 'domain' => 'www.nginx.example.com',- ]);-- $fluxClient = Mockery::mock(FluxClient::class);- $fluxClient- ->shouldReceive('applyIngress')- ->once()- ->with(- '100.64.0.10',- 'caddy',- Mockery::on(fn (string $caddyfile): bool => str_contains($caddyfile, 'import apps/*.caddy')),- Mockery::on(fn (array $apps): bool => count($apps) === 1- && str_contains($apps[0]['config'], 'http://nginx.example.com {')- && str_contains($apps[0]['config'], 'http://www.nginx.example.com {')- && str_contains($apps[0]['config'], 'reverse_proxy coolify-v5-nginx-test.default.coolify.internal:8080'))- )- ->andReturn('Caddy ingress applied.');- expectCaddyIngressFirewallRule($fluxClient);- app()->instance(FluxClient::class, $fluxClient);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}", [- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'builder_cpu_quota' => '200%',- 'ingress_enabled' => true,- 'ingress_type' => 'caddy',- ])- ->assertSuccessful()- ->assertJsonPath('cluster.servers.0.ingressEnabled', true)- ->assertJsonPath('cluster.servers.0.ingressType', 'caddy');-- expect($server->refresh()->ingress_type)->toBe('caddy')- ->and($server->ingress_status)->toBe('running');-});--it('returns flux error details when server ingress activation fails', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'edge-01',- 'host' => '203.0.113.20',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'builder_cpu_quota' => '200%',- 'wireguard_management_ip' => '100.64.0.10',- 'last_bootstrapped_at' => now(),- ]);- $application = V5Application::query()->create([- 'team_id' => $team->id,- 'project_id' => $project->id,- 'environment_id' => $environment->id,- 'server_id' => $server->id,- 'created_by_user_id' => $user->id,- 'name' => 'nginx-test',- 'image' => 'docker.io/library/nginx:alpine',- 'container_name' => 'coolify-v5-nginx-test',- 'status' => 'running',- 'mesh_namespace' => 'default',- 'ingress_enabled' => true,- 'internal_port' => 8080,- ]);- V5ApplicationDomain::query()->create([- 'application_id' => $application->id,- 'domain' => 'nginx.example.com',- ]);-- $fluxClient = Mockery::mock(FluxClient::class);- $fluxClient- ->shouldReceive('applyIngress')- ->once()- ->andThrow(new RuntimeException('validate Caddyfile: unrecognized directive'));- app()->instance(FluxClient::class, $fluxClient);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}", [- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'builder_cpu_quota' => '200%',- 'ingress_enabled' => true,- 'ingress_type' => 'caddy',- ])- ->assertStatus(502)- ->assertJsonPath('message', 'Caddy rejected the generated ingress configuration. Check the domains and internal port, then try again.')- ->assertJsonPath('detail', 'validate Caddyfile: unrecognized directive');-});--it('keeps editable v5 server builder capacity when disabling builder', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => ['builder'],- 'builder_enabled' => true,- 'builder_capacity' => 5,- 'builder_cpu_quota' => '350%',- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}", [- 'builder_enabled' => false,- 'builder_capacity' => 5,- 'builder_cpu_quota' => '350%',- ])- ->assertSuccessful()- ->assertJsonPath('cluster.servers.0.builderEnabled', false)- ->assertJsonPath('cluster.servers.0.builderCapacity', 5);-- $server->refresh();-- expect($server->builder_enabled)->toBeFalse()- ->and($server->builder_capacity)->toBe(5)- ->and($server->builder_cpu_quota)->toBe('350%')- ->and($server->capabilities)->toBe([]);-});--it('validates editable v5 server builder details', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => ['builder'],- 'builder_enabled' => true,- 'builder_capacity' => 2,- 'builder_cpu_quota' => '200%',- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}", [- 'builder_enabled' => true,- 'builder_capacity' => 1001,- 'builder_cpu_quota' => str_repeat('a', 33),- ])- ->assertUnprocessable()- ->assertJsonValidationErrors(['builder_capacity', 'builder_cpu_quota']);-});--it('requires positive editable v5 server builder capacity when builder is enabled', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);- $server = V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'prod-01',- 'host' => '203.0.113.10',- 'ssh_user' => 'root',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => [],- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'builder_cpu_quota' => '200%',- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->patchJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}", [- 'builder_enabled' => true,- 'builder_capacity' => 0,- 'builder_cpu_quota' => '200%',- ])- ->assertUnprocessable()- ->assertJsonValidationErrors(['builder_capacity']);-});--it('validates v5 cluster creation input', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson('/v5/clusters', [- 'name' => '',- 'description' => str_repeat('a', 1001),- ])- ->assertUnprocessable()- ->assertJsonValidationErrors(['name', 'description']);-});--it('rejects duplicate v5 cluster names in the same team', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Production Mesh',- 'description' => null,- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson('/v5/clusters', [- 'name' => 'Production Mesh',- 'description' => null,- ])- ->assertUnprocessable()- ->assertJsonValidationErrors(['name']);-});--it('deletes an empty v5 cluster in the current team', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Empty Mesh',- 'description' => null,- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->deleteJson('/v5/clusters/'.$cluster->uuid)- ->assertNoContent();-- expect(Cluster::query()->whereKey($cluster->id)->exists())->toBeFalse();-});--it('does not delete a v5 cluster that has servers', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Lima Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Development-Lima',- 'description' => null,- ]);- V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $privateKey->id,- 'name' => 'coold-dev',- 'host' => 'lima-coold-dev',- 'ssh_user' => 'developer',- 'ssh_port' => 22,- 'status' => 'installed',- 'capabilities' => ['builder'],- 'builder_enabled' => true,- 'builder_capacity' => 2,- 'last_bootstrapped_at' => now(),- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->deleteJson('/v5/clusters/'.$cluster->uuid)- ->assertUnprocessable()- ->assertJsonPath('message', 'Only empty clusters can be deleted.');-- expect(Cluster::query()->whereKey($cluster->id)->exists())->toBeTrue();-});--it('does not delete a v5 cluster outside the current team', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $otherTeam = Team::withoutEvents(fn () => Team::query()->create([- 'name' => 'Other V5 Team',- 'description' => null,- 'personal_team' => false,- 'show_boarding' => false,- ]));- $otherUser = User::withoutEvents(fn () => User::query()->create([- 'name' => 'Other User',- 'email' => '[email protected]',- 'email_verified_at' => now(),- 'password' => 'password',- ]));- $cluster = Cluster::query()->create([- 'team_id' => $otherTeam->id,- 'created_by_user_id' => $otherUser->id,- 'name' => 'Other Mesh',- 'description' => null,- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->deleteJson('/v5/clusters/'.$cluster->uuid)- ->assertNotFound();-- expect(Cluster::query()->whereKey($cluster->id)->exists())->toBeTrue();-});--it('allows the same v5 cluster name in another team without leaking it', function () {- $this->withoutVite();- fakeFluxHealth();- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $otherTeam = Team::withoutEvents(fn () => Team::query()->create([- 'name' => 'Other V5 Team',- 'description' => null,- 'personal_team' => false,- 'show_boarding' => false,- ]));- $otherUser = User::withoutEvents(fn () => User::query()->create([- 'name' => 'Other User',- 'email' => '[email protected]',- 'email_verified_at' => now(),- 'password' => 'password',- ]));- Cluster::query()->create([- 'team_id' => $otherTeam->id,- 'created_by_user_id' => $otherUser->id,- 'name' => 'Production Mesh',- 'description' => 'Other team cluster.',- ]);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson('/v5/clusters', [- 'name' => 'Production Mesh',- 'description' => 'Current team cluster.',- ])- ->assertCreated()- ->assertJsonPath('cluster.description', 'Current team cluster.');-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->get('/v5/clusters')- ->assertSuccessful()- ->assertSee('Current team cluster.')- ->assertDontSee('Other team cluster.');-});--it('shares existing projects and environments with the v5 dashboard page', function () {- $this->withoutVite();- fakeFluxHealth();- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- [$project, $environment] = createV5ProjectWithEnvironment($team, 'gravy-truck', 'production');- createV5ProjectWithEnvironment($team, 'rocket-bike', 'staging');- $otherTeam = Team::withoutEvents(fn () => Team::query()->create([- 'name' => 'Other V5 Team',- 'description' => null,- 'personal_team' => false,- 'show_boarding' => false,- ]));- [$otherProject, $otherEnvironment] = createV5ProjectWithEnvironment($otherTeam, 'secret-saucer', 'private');-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->get('/v5')- ->assertSuccessful()- ->assertSee('"projects":[', false)- ->assertSee('"name":"gravy-truck"', false)- ->assertSee('"uuid":"'.$project->uuid.'"', false)- ->assertSee('"environments":[', false)- ->assertSee('"name":"production"', false)- ->assertSee('"uuid":"'.$environment->uuid.'"', false)- ->assertSee('"selectedProjectUuid":"'.$project->uuid.'"', false)- ->assertSee('"selectedEnvironmentUuid":"'.$environment->uuid.'"', false)- ->assertDontSee('"id":"'.$project->id.'","uuid":"'.$project->uuid.'"', false)- ->assertDontSee('"id":"'.$environment->id.'","uuid":"'.$environment->uuid.'"', false)- ->assertDontSee($otherProject->name)- ->assertDontSee($otherProject->uuid)- ->assertDontSee($otherEnvironment->name)- ->assertDontSee($otherEnvironment->uuid);-});--it('persists the selected v5 project and environment in the session', function () {- $this->withoutVite();- fakeFluxHealth();- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- createV5ProjectWithEnvironment($team, 'alpha-project', 'production');- [$selectedProject, $selectedEnvironment] = createV5ProjectWithEnvironment($team, 'zebra-project', 'staging');-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson('/v5/selection', [- 'project_uuid' => $selectedProject->uuid,- 'environment_uuid' => $selectedEnvironment->uuid,- ])- ->assertNoContent()- ->assertSessionHas('v5.selectedProjectUuid', $selectedProject->uuid)- ->assertSessionHas('v5.selectedEnvironmentUuid', $selectedEnvironment->uuid);-- $this- ->actingAs($user)- ->get('/v5')- ->assertSuccessful()- ->assertSee('"selectedProjectUuid":"'.$selectedProject->uuid.'"', false)- ->assertSee('"selectedEnvironmentUuid":"'.$selectedEnvironment->uuid.'"', false);-});--it('rejects persisted v5 selections outside the current team', function () {- createSharedUserAndTeamTables();-- [$user, $team] = createV5UserWithTeam();- $otherTeam = Team::withoutEvents(fn () => Team::query()->create([- 'name' => 'Other V5 Team',- 'description' => null,- 'personal_team' => false,- 'show_boarding' => false,- ]));- [$otherProject, $otherEnvironment] = createV5ProjectWithEnvironment($otherTeam, 'secret-saucer', 'private');-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->postJson('/v5/selection', [- 'project_uuid' => $otherProject->uuid,- 'environment_uuid' => $otherEnvironment->uuid,- ])- ->assertForbidden()- ->assertSessionMissing('v5.selectedProjectUuid')- ->assertSessionMissing('v5.selectedEnvironmentUuid');-});--it('defines the v5 dashboard page as a shadcn styled canvas shell', function () {- $dashboardPage = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));- $app = file_get_contents(resource_path('js/v5/app.tsx'));- $navbarPath = resource_path('js/v5/components/app-navbar.tsx');-- expect(file_exists($navbarPath))->toBeTrue();-- $navbar = file_get_contents($navbarPath);- $sheetPath = resource_path('js/v5/components/ui/sheet.tsx');-- expect(file_exists($sheetPath))->toBeTrue();-- expect($app)- ->toContain('progress: {')- ->toContain('delay: 10')- ->toContain("color: '#fcd452'")- ->toContain('showSpinner: false')- ->not->toContain('TopNavigationLoadingIndicator')- ->not->toContain('withApp:');-- expect($dashboardPage)- ->toContain('Dashboard')- ->toContain("import { AppNavbar } from '@/components/app-navbar';")- ->not->toContain('function csrfToken()')- ->toContain("import { csrfToken } from '@/lib/csrf';")- ->toContain("import { Button } from '@/components/ui/button';")- ->toContain("import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from '@/components/ui/sheet';")- ->toContain("import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';")- ->not->toContain("fetch('/v5/clusters'")- ->toContain('<AppNavbar')- ->toContain('bg-background text-foreground')- ->toContain('h-dvh overflow-hidden bg-background text-foreground')- ->toContain('relative h-full min-h-0 overflow-hidden pt-16')- ->toContain('Deploy')- ->not->toContain('Add nginx')- ->toContain('Select nginx server')- ->toContain('selectedNginxServerId')- ->toContain('nginxImage')- ->toContain('docker.io/library/nginx:alpine')- ->toContain('server_uuid: selectedNginxServerId || null')- ->toContain('image: nginxImage.trim() || DEFAULT_NGINX_IMAGE')- ->toContain('Center')- ->toContain('Delete')- ->toContain('App configuration')- ->toContain('openApplicationInspector')- ->toContain('selectedInspectorApplication')- ->toContain('onDoubleClick={(event) => openApplicationInspector(event, application)}')- ->toContain('open={selectedInspectorApplication !== null}')- ->toContain('<SheetContent side="right" className="w-full overflow-hidden bg-background sm:rounded-l-xl sm:border data-[side=right]:sm:!inset-y-4 data-[side=right]:sm:!h-auto data-[side=right]:sm:!w-[45vw] data-[side=right]:sm:!max-w-[45vw]"')- ->toContain('showCloseButton blurOverlay={false}')- ->toContain('<SheetHeader className="p-6 pb-4">')- ->toContain('<div className="flex flex-1 flex-col gap-6 px-6 pb-6">')- ->toContain('<Tabs defaultValue="overview"')- ->toContain('<TabsList className="w-full justify-start" variant="line">')- ->toContain('<TabsTrigger value="overview">Overview</TabsTrigger>')- ->toContain('<TabsTrigger value="networking">Networking</TabsTrigger>')- ->toContain('<TabsTrigger value="advanced">Advanced</TabsTrigger>')- ->toContain('Double-click an application card to open configuration.')- ->toContain("method: 'DELETE'")- ->toContain('removeApplication')- ->toContain('useEffect(() => {')- ->toContain('setApplications(settledResources.applications);')- ->toContain('centerOnCanvasNodes(settledResources.applications, settledResources.ingresses);')- ->toContain('Caddy ingress')- ->toContain('persistCaddyIngressPosition')- ->toContain('startIngressDrag')- ->toContain('fetch(`/v5/caddy-ingresses/${ingress.id}/position`')- ->toContain("fetch('/v5/applications/nginx'")- ->toContain('nginxServers = []')- ->toContain('fetch(`/v5/applications/${application.id}/position`')- ->not->toContain('<header')- ->not->toContain('h-[calc(100dvh-4rem)]')- ->not->toContain('flex h-dvh flex-col overflow-hidden bg-background text-foreground')- ->toContain('No applications on this canvas yet.')- ->not->toContain("import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';")- ->not->toContain("fetch('/v5/selection'");-- expect(file_get_contents($sheetPath))- ->toContain('blurOverlay = true')- ->toContain('<SheetOverlay blur={blurOverlay} />');-- expect($navbar)- ->toContain("import { Link, router, usePage } from '@inertiajs/react';")- ->toContain("import { cn } from '@/lib/utils';")- ->toContain("import { Sheet, SheetClose, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet';")- ->toContain("import { csrfToken } from '@/lib/csrf';")- ->not->toContain('function csrfToken()')- ->toContain('export function AppNavbar')- ->toContain('/coolify-logo.svg')- ->toContain('<Link')- ->toContain('className="fixed inset-x-0 top-0 z-40 border-b border-border bg-background"')- ->not->toContain('className="sticky top-0 z-40 shrink-0 border-b border-border bg-background"')- ->toContain('hover:bg-muted')- ->toContain('text-muted-foreground')- ->toContain('SelectGroup')- ->toContain('variant="ghost"')- ->toContain('position="popper"')- ->toContain('sideOffset={4}')- ->toContain('Select a project')- ->toContain('Select an environment')- ->toContain('const { url } = usePage();')- ->toContain("const isClustersPage = url.startsWith('/v5/clusters');")- ->toContain('href="/v5"')- ->toContain('href="/v5/clusters"')- ->toContain('Clusters')- ->toContain('className="relative flex h-16 items-center gap-3 px-4 sm:px-6"')- ->toContain('className="absolute left-1/2 flex min-w-0 -translate-x-1/2 items-center justify-center gap-1 md:static md:flex-1 md:translate-x-0 md:justify-start md:gap-2"')- ->toContain('className="max-w-[38vw] md:max-w-[10rem]"')- ->toContain('className="max-w-[30vw] md:max-w-[10rem]"')- ->toContain('aria-label="Open mobile menu"')- ->toContain('<Sheet>')- ->toContain('<SheetTrigger')- ->toContain('<SheetContent side="right" className="w-72 max-w-[85vw] bg-background"')- ->toContain('<SheetHeader>')- ->toContain('<SheetTitle>Coolify</SheetTitle>')- ->toContain('<SheetDescription className="sr-only">')- ->toContain('<SheetClose')- ->toContain('Move between Coolify v5 pages.')- ->not->toContain('<SheetTitle className="sr-only">Navigation</SheetTitle>')- ->toContain('className="hidden rounded-md px-3 py-1 text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground md:inline-flex"')- ->toContain('className="inline-flex rounded-md p-2 text-warning transition-colors hover:bg-muted hover:text-warning md:hidden"')- ->toContain('Dashboard')- ->not->toContain('Home')- ->toContain("fetch('/v5/selection'")- ->toContain('router.reload({')- ->toContain("only: ['applications', 'selectedProjectUuid', 'selectedEnvironmentUuid']")- ->toContain('void persistSelection(nextProjectUuid, nextEnvironmentUuid).then(refreshCurrentPageSelection);')- ->toContain('void persistSelection(projectUuid, nextEnvironmentUuid).then(refreshCurrentPageSelection);')- ->toContain("'X-CSRF-TOKEN': csrfToken()")- ->not->toContain('isMobileMenuOpen')- ->not->toContain('setIsMobileMenuOpen')- ->not->toContain('isProjectEnvironmentMenuOpen')- ->not->toContain('setIsProjectEnvironmentMenuOpen')- ->not->toContain('Open project and environment selector')- ->not->toContain('Close project and environment selector')- ->not->toContain('DropdownMenu')- ->not->toContain('fixed inset-0 bg-black/80')- ->not->toContain('fixed inset-y-0 right-0')- ->not->toContain('<a')- ->not->toContain("import { Button } from '@/components/ui/button';")- ->not->toContain('<Button')- ->not->toContain("import { Separator } from '@/components/ui/separator';")- ->not->toContain('<Separator')- ->not->toContain('min-h-[calc(100vh-4rem)]')- ->not->toContain('py-10')- ->not->toContain('bg-background/95')- ->not->toContain('backdrop-blur')- ->not->toContain('supports-[backdrop-filter]')- ->not->toContain('border-coolgray')- ->not->toContain('className="w-[12rem]"')- ->not->toContain('<h1>Coolify v5</h1>')- ->not->toContain('<h2 id="clusters-heading">Clusters</h2>');-- expect(file_exists(resource_path('js/v5/components/top-navigation-loading-indicator.tsx')))->toBeFalse();-});--it('tracks v5 server actions with reusable per-id loading state', function () {- $clustersPage = file_get_contents(resource_path('js/v5/Pages/Clusters.tsx'));- $pendingIdsHook = file_get_contents(resource_path('js/v5/lib/use-pending-ids.ts'));-- expect($clustersPage)- ->toContain("import { usePendingIds } from '@/lib/use-pending-ids';")- ->toContain('const checkingServers = usePendingIds<string>()')- ->toContain('const isCheckingServer = checkingServers.has(server.id)')- ->toContain('checkingServers.start(server.id)')- ->toContain('checkingServers.finish(server.id)')- ->not->toContain('const [checkingServerId, setCheckingServerId] = useState<string | null>(null)')- ->not->toContain('setCheckingServerId(server.id)')- ->not->toContain('setCheckingServerId(null)');-- expect($pendingIdsHook)- ->toContain('export function usePendingIds')- ->toContain('const [pendingIds, setPendingIds] = useState<Set<T>>(() => new Set())')- ->toContain('start')- ->toContain('finish')- ->toContain('has')- ->toContain('hasAny');-});--it('defines the v5 cluster management page and create cluster form', function () {- $clustersPagePath = resource_path('js/v5/Pages/Clusters.tsx');- $clustersPage = file_get_contents($clustersPagePath);- $buttonComponent = file_get_contents(resource_path('js/v5/components/ui/button.tsx'));- $dialogComponent = file_get_contents(resource_path('js/v5/components/ui/dialog.tsx'));- $types = file_get_contents(resource_path('js/v5/types.ts'));-- expect(file_exists($clustersPagePath))->toBeTrue();-- preg_match('/<Button\s+type="button"\s+variant="coolify"\s+aria-label="Add server to cluster"/m', $clustersPage, $addServerButtonMatches);-- expect($addServerButtonMatches)->not->toBeEmpty();-- expect($clustersPage)- ->toContain("import { Button } from '@/components/ui/button';")- ->toContain("} from '@/components/ui/dialog';")- ->toContain("} from '@/components/ui/dropdown-menu';")- ->toContain("import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';")- ->toContain("import { csrfToken } from '@/lib/csrf';")- ->toContain("fetch('/v5/clusters'")- ->toContain('aria-label="Select a cluster"')- ->toContain('Cluster state')- ->not->toContain('Last run')- ->not->toContain('selectedCluster.lastCliStatus')- ->not->toContain('selectedCluster.lastCliSummary')- ->toContain('Generated mesh values are saved after bootstrap or extend runs.')- ->not->toContain('CLI state')- ->not->toContain('CLI-generated mesh values')- ->toContain('Select a cluster')- ->toContain('setSelectedClusterId(value)')- ->toContain('aria-label="Create cluster"')- ->toContain('setIsCreateDialogOpen(true)')- ->toContain('Add cluster')- ->toContain('variant="coolify"')- ->not->toContain('border-warning bg-warning/10 text-foreground')- ->not->toContain('border-primary bg-primary/10 text-foreground')- ->toContain('<Dialog')- ->toContain('<DialogTitle>Create cluster</DialogTitle>')- ->toContain('<DialogDescription>')- ->toContain('<DialogFooter>')- ->not->toContain('<DialogClose')- ->toContain('Cancel')- ->toContain('<DialogContent className="max-w-md" showCloseButton={false}>')- ->toContain('<DialogTitle>Confirm deletion</DialogTitle>')- ->toContain('variant="delete"')- ->toContain('aria-label="Add server to cluster"')- ->toContain('setIsAddServerDialogOpen(true)')- ->toContain('Add server')- ->toContain('className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between"')- ->toContain('<DialogTitle>Add server</DialogTitle>')- ->toContain('DialogContent className="max-w-3xl"')- ->toContain('DialogContent className="max-w-2xl"')- ->not->toContain('DialogContent className="max-h-[90dvh] max-w-3xl overflow-y-auto"')- ->not->toContain('DialogContent className="max-h-[90dvh] max-w-2xl overflow-y-auto"')- ->toContain('fetch(`/v5/clusters/${selectedCluster.id}/servers/${server.id}/bootstrap`')- ->toContain('fetch(`/v5/clusters/${selectedCluster.id}`')- ->toContain('hasBootstrapInProgress')- ->toContain('Bootstrap')- ->toContain('lastBootstrapOutput')- ->toContain('Unable to queue bootstrap for this server.')- ->toContain('border-destructive/30')- ->toContain('fetch(`/v5/clusters/${selectedCluster.id}/servers`')- ->toContain('fetch(`/v5/clusters/${selectedCluster.id}/servers/${editingServer.id}`')- ->toContain('fetch(`/v5/clusters/${selectedCluster.id}/servers/${server.id}/check`')- ->toContain('fetch(`/v5/clusters/${cluster.id}/servers/${server.id}`')- ->toContain("method: 'PATCH'")- ->toContain("method: 'DELETE'")- ->toContain('<DropdownMenu>')- ->toContain('<DropdownMenuTrigger')- ->toContain("import { DotsThreeIcon } from '@phosphor-icons/react';")- ->toContain('variant="ghost"')- ->toContain('size="icon-sm"')- ->toContain('aria-label="Server actions"')- ->toContain('<DotsThreeIcon data-icon="inline-start" weight="bold" />')- ->not->toContain('>Server actions</DropdownMenuTrigger>')- ->toContain('<DropdownMenuGroup>')- ->toContain('<DropdownMenuSeparator />')- ->toContain('Check connection')- ->not->toContain('Check SSH')- ->toContain('Not initialized')- ->toContain('role="group"')- ->toContain('aria-label="Server initialization"')- ->toContain('rounded-l-md border border-r-0 border-destructive/30 bg-destructive/10')- ->toContain('variant="coolify"')- ->toContain('className="rounded-r-md"')- ->toContain('onClick={() => void bootstrapServer(server)}')- ->not->toContain('<DropdownMenuItem- disabled={isBootstrappingServer}')- ->not->toContain('Bootstrap: {serverStatusLabel(server.status)}')- ->not->toContain('Last bootstrap')- ->not->toContain('{formatDate(server.lastBootstrappedAt)}')- ->toContain('Latest SSH check: {latestSshCheck.status}')- ->toContain('const notInitializedServers = selectedCluster?.servers.filter((server) => server.lastBootstrappedAt === null) ?? []')- ->toContain('const initializedServers = selectedCluster?.servers.filter((server) => server.lastBootstrappedAt !== null) ?? []')- ->toContain('Not initialized servers')- ->toContain('{notInitializedServers.map(renderServerCard)}')- ->toContain('{initializedServers.map(renderServerCard)}')- ->toContain('{!isServerInitialized ? (')- ->toContain('Show install logs')- ->toContain('{canShowBootstrapLogs ? (')- ->not->toContain('{!isServerInitialized && isBootstrapLogVisible ? (')- ->toContain('Delete server')- ->toContain('This removes it from this cluster inventory so you can add it again later.')- ->not->toContain('<Button\n type="button"\n variant="outline"\n size="sm"\n disabled={isCheckingServer}')- ->toContain('<DialogTitle>Edit server</DialogTitle>')- ->toContain('Edit server')- ->toContain('Save server')- ->toContain('editServerBuilderCapacity')- ->toContain('editServerBuilderCpuQuota')- ->toContain('Networking and bootstrap settings stay locked after creation.')- ->toContain('Bootstrap SSH user')- ->toContain('Bootstrap SSH port')- ->not->toContain('{server.sshUser}@{server.host}:{server.sshPort}')- ->toContain('showAdvancedServerConfiguration')- ->toContain('Node address override')- ->toContain('Defaults to server IP')- ->not->toContain('CLI node address')- ->toContain('wireguardListenPortOverride')- ->toContain('wireguardEndpointOverride')- ->toContain('privateKeys')- ->toContain('selectedPrivateKeyId')- ->toContain('Private key')- ->toContain('Select a private key')- ->toContain('appearance-none')- ->toContain('backgroundImage: `url("data:image/svg+xml')- ->not->toContain('No private key')- ->toContain('Create cluster')- ->toContain('Cluster details')- ->toContain('Servers in this cluster')- ->toContain('selectedCluster')- ->toContain('Server IP')- ->toContain('{server.host}')- ->not->toContain('<dt className="text-muted-foreground">CLI node</dt>')- ->not->toContain('CLI node')- ->not->toContain('{server.nodeAddress ?? server.host}')- ->toContain('builderCapacity')- ->toContain('{server.builderEnabled ? (')- ->toContain('<dt className="text-muted-foreground">Builder CPU quota</dt>')- ->toContain('server.builderCpuQuota')- ->toContain(') : null}')- ->toContain('privateKeyName')- ->toContain('lastBootstrappedAt')- ->toContain('This removes it from this cluster inventory so you can add it again later.')- ->toContain('deleteCluster')- ->toContain('fetch(`/v5/clusters/${cluster.id}`')- ->toContain("method: 'DELETE'")- ->toContain('Delete cluster')- ->toContain('selectedCluster.serversCount === 0')- ->not->toContain("selectedCluster.serversCount === 1 ? 'server' : 'servers'")- ->toContain('Only empty clusters can be deleted.')- ->toContain('min-h-dvh overflow-y-auto bg-background text-foreground lg:h-dvh lg:overflow-hidden')- ->toContain('flex min-h-dvh overflow-visible px-4 pt-16 lg:h-full lg:min-h-0 lg:overflow-hidden lg:px-6')- ->toContain('flex w-full flex-col gap-4 py-4 lg:min-h-0 lg:py-6')- ->toContain('rounded-lg border border-border bg-card p-4')- ->toContain('flex items-start justify-between gap-3')- ->toContain('min-w-0 flex-1')- ->toContain('flex shrink-0 items-center justify-end gap-2 sm:flex-wrap')- ->toContain('aria-label="Select a cluster"')- ->toContain('setSelectedClusterId(value)')- ->not->toContain('flex max-h-80 flex-col rounded-lg border border-border bg-card lg:max-h-none lg:min-h-0')- ->toContain('overflow-visible rounded-lg border border-border bg-card lg:min-h-0 lg:overflow-y-auto')- ->not->toContain('flex w-full flex-col items-stretch gap-2 sm:w-auto sm:flex-row sm:flex-wrap sm:items-center sm:justify-end')- ->toContain('mt-4 grid grid-cols-1 gap-3 text-xs sm:grid-cols-2')- ->not->toContain('lg:grid-cols-[20rem_minmax(0,1fr)]')- ->not->toContain('lg:grid-cols-[20rem_minmax(0,1fr)_22rem]')- ->not->toContain('New cluster')- ->not->toContain('<aside className="rounded-lg border border-border bg-card p-5">')- ->not->toContain('This is where the magic happens.');-- expect(substr_count($clustersPage, 'variant="coolify"'))->toBe(6)- ->and($buttonComponent)- ->toContain('coolify:')- ->toContain('bg-coollabs-50')- ->toContain('hover:bg-coollabs')- ->toContain('delete:');-- expect($dialogComponent)- ->toContain('@base-ui/react/dialog')- ->toContain('z-50')- ->toContain('max-h-[calc(100dvh-2rem)]')- ->toContain('overflow-y-auto')- ->toContain('top-1/2')- ->toContain('-translate-y-1/2')- ->not->toContain('top-4 bottom-4')- ->not->toContain('top-1/2 w-[calc(100%-2rem)] max-w-lg -translate-x-1/2 -translate-y-1/2')- ->toContain('showCloseButton = true')- ->toContain('aria-label="Close dialog"')- ->toContain('<XIcon />')- ->toContain('DialogTitle')- ->toContain('DialogDescription')- ->toContain("'mt-6 flex justify-end gap-2'");-- $v5Css = file_get_contents(resource_path('css/v5/app.css'));-- expect($v5Css)- ->toContain('--color-warning: var(--warning);')- ->toContain('--warning: #fcd452;')- ->not->toContain('--ring: oklch(0.705 0.015 286.067);')- ->not->toContain('--ring: oklch(0.552 0.016 285.938);');-- expect(substr_count($v5Css, '--ring: var(--warning);'))->toBe(2);-- expect($types)- ->not->toContain('sshUser: string;')- ->not->toContain('sshPort: number;')- ->toContain('builderEnabled: boolean;')- ->toContain('builderCapacity: number;')- ->toContain('builderCpuQuota: string;')- ->toContain('privateKeyName: string | null;')- ->toContain('lastBootstrappedAt: string | null;')- ->toContain('lastBootstrapStatus: string | null;')- ->toContain('lastStatusOutput: string | null;');-});--it('uses the standard button size for the v5 delete cluster action', function () {- $clustersPage = file_get_contents(resource_path('js/v5/Pages/Clusters.tsx'));-- expect($clustersPage)- ->toContain("variant=\"delete\"\n size=\"default\"\n onClick={openDeleteClusterDialog}")- ->not->toContain("variant=\"delete\"\n size=\"sm\"\n onClick={openDeleteClusterDialog}");-});--it('defines a ghost variant for compact v5 select triggers', function () {- $select = file_get_contents(resource_path('js/v5/components/ui/select.tsx'));-- expect($select)- ->toContain('@base-ui/react/select')- ->not->toContain('radix-ui')- ->toContain("variant = 'default'")- ->toContain("variant === 'default'")- ->toContain("variant === 'ghost'")- ->toContain('border-transparent')- ->toContain('h-auto')- ->toContain('text-sm')- ->toContain("position === 'popper' ? false : true");-});--it('provides reusable v5 form field primitives with reserved validation error space', function () {- $fieldPath = resource_path('js/v5/components/ui/field.tsx');- $inputPath = resource_path('js/v5/components/ui/input.tsx');- $textareaPath = resource_path('js/v5/components/ui/textarea.tsx');- $clustersPage = file_get_contents(resource_path('js/v5/Pages/Clusters.tsx'));-- expect(file_exists($fieldPath))->toBeTrue()- ->and(file_exists($inputPath))->toBeTrue()- ->and(file_exists($textareaPath))->toBeTrue();-- $field = file_get_contents($fieldPath);- $input = file_get_contents($inputPath);- $textarea = file_get_contents($textareaPath);-- expect($field)- ->toContain('function Field(')- ->toContain('function FieldLabel(')- ->toContain('function FieldError(')- ->toContain('min-h-4')- ->toContain('aria-live="polite"')- ->toContain('message ? undefined : true')- ->toContain('export { Field, FieldError, FieldLabel }');-- expect($input)- ->toContain('function Input(')- ->toContain('aria-invalid:border-destructive')- ->toContain('export { Input };');-- expect($textarea)- ->toContain('function Textarea(')- ->toContain('aria-invalid:border-destructive')- ->toContain('export { Textarea };');-- expect($clustersPage)- ->toContain("import { Field, FieldError, FieldLabel } from '@/components/ui/field';")- ->toContain("import { Input } from '@/components/ui/input';")- ->toContain("import { Textarea } from '@/components/ui/textarea';")- ->toContain('<FieldError message={errors.name?.[0]} />')- ->toContain('<FieldError message={serverErrors.private_key_uuid?.[0]} />')- ->not->toContain('{errors.name ? <span className="text-xs text-destructive">{errors.name[0]}</span> : null}')- ->not->toContain('{serverErrors.name ? (');-});--it('uses the requested shadcn preset configuration for v5', function () {- $components = json_decode(file_get_contents(base_path('components.json')), true);- $css = file_get_contents(resource_path('css/v5/app.css'));-- expect($components['style'])- ->toBe('base-lyra')- ->and($components['tsx'])->toBeTrue()- ->and($components['iconLibrary'])->toBe('phosphor')- ->and($components['tailwind']['css'])->toBe('resources/css/v5/app.css')- ->and($components['tailwind']['baseColor'])->toBe('zinc')- ->and($css)->toContain('@import "@fontsource-variable/geist";')- ->and($css)->toContain('--foreground: oklch(0.141 0.005 285.823);')- ->and($css)->toContain('--background: #101010;')- ->and($css)->toContain('button:not(:disabled)');-});--it('sizes the v5 app root with the dynamic mobile viewport', function () {- $css = file_get_contents(resource_path('css/v5/app.css'));-- expect($css)- ->toContain('min-height: 100dvh;')- ->not->toContain('min-height: 100vh;');-});--it('selects a shared team when the session has no current team', function () {- $this->withoutVite();- fakeFluxHealth();- createSharedUserAndTeamTables();-- $user = User::withoutEvents(fn () => User::query()->create([- 'name' => 'Grace Hopper',- 'email' => '[email protected]',- 'email_verified_at' => now(),- 'password' => 'password',- ]));- $team = Team::withoutEvents(fn () => Team::query()->create([- 'name' => 'Auto Selected Team',- 'description' => null,- 'personal_team' => false,- 'show_boarding' => false,- ]));- $user->teams()->attach($team, ['role' => 'admin']);-- $this- ->actingAs($user)- ->get('/v5')- ->assertSuccessful()- ->assertSessionHas('currentTeam')- ->assertDontSee('Auto Selected Team')- ->assertDontSee('admin');-});--it('serves v5 dev assets from the current request host', function (string $url, string $viteHost) {- fakeFluxHealth();- createSharedUserAndTeamTables();- [$user, $team] = createV5UserWithTeam();-- $hotFile = public_path('hot');- $originalHotFile = file_exists($hotFile) ? file_get_contents($hotFile) : null;-- file_put_contents($hotFile, 'http://configured-vite-host.test:5173');-- try {- $response = $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->get($url);-- $response- ->assertSuccessful()- ->assertSee("import RefreshRuntime from 'http://{$viteHost}:5173/@react-refresh'", false)- ->assertSee("src=\"http://{$viteHost}:5173/@vite/client\"", false)- ->assertSee("src=\"http://{$viteHost}:5173/resources/js/v5/app.tsx\"", false)- ->assertDontSee('configured-vite-host.test', false);- } finally {- if ($originalHotFile === null) {- @unlink($hotFile);- } else {- file_put_contents($hotFile, $originalHotFile);- }- }-})->with([- 'localhost' => ['http://localhost:8000/v5', 'localhost'],- 'tailscale ip' => ['http://100.64.0.10:8000/v5', '100.64.0.10'],-]);--it('configures the vite dev server for remote v5 access', function () {- $viteConfig = file_get_contents(base_path('vite.config.js'));-- expect($viteConfig)- ->toContain('host: "0.0.0.0"')- ->toContain('allowedHosts: true')- ->toContain('cors: true')- ->toContain('const viteHmrHost = env.VITE_HMR_HOST || null;')- ->toContain('hmr: viteHmrHost')- ->not->toContain('hmr: viteHost');-});--it('shows when flux is unavailable', function () {- $this->withoutVite();- fakeFluxHealth(false, 'Flux socket was not found.');- createSharedUserAndTeamTables();-- $user = User::withoutEvents(fn () => User::query()->create([- 'name' => 'Katherine Johnson',- 'email' => '[email protected]',- 'email_verified_at' => now(),- 'password' => 'password',- ]));- $team = Team::withoutEvents(fn () => Team::query()->create([- 'name' => 'Flux Test Team',- 'description' => null,- 'personal_team' => false,- 'show_boarding' => false,- ]));- $user->teams()->attach($team, ['role' => 'owner']);-- $this- ->actingAs($user)- ->withSession(['currentTeam' => $team])- ->get('/v5')- ->assertSuccessful()- ->assertSee('Unavailable')- ->assertSee('Flux socket was not found.');-});--it('does not include coolify version controls on the v5 dashboard page', function () {- $dashboardPage = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));-- expect($dashboardPage)- ->not->toContain('Check coolify version')- ->not->toContain('/v5/coolify/version')- ->not->toContain('Installed version:');-});--it('does not render flux status in the v5 navbar', function () {- $navbar = file_get_contents(resource_path('js/v5/components/app-navbar.tsx'));-- expect($navbar)- ->not->toContain('Flux: {flux?.label ??')- ->not->toContain('title={flux?.socket ?? flux?.message ?? undefined}')- ->not->toContain('{clusters.length} clusters')- ->not->toContain('<h2 id="flux-status-heading">Flux status</h2>')- ->not->toContain('<p>{flux.message}</p>')- ->not->toContain('Socket: {flux.socket}');-});--it('syncs dev Lima VMs into v5 clusters and servers', function () {- createSharedUserAndTeamTables();- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Dev Lima Key');-- $exitCode = Artisan::call('v5:sync-dev-lima-servers', [- '--team-id' => $team->id,- '--user-id' => $user->id,- '--cluster' => 'Development-Lima',- '--server' => [- 'coold-dev|host.docker.internal|developer|61332|100.64.0.1',- 'coold-dev-2|host.docker.internal|developer|61379|100.64.0.2',- ],- ]);-- expect($exitCode)->toBe(0)- ->and(Cluster::query()->where('name', 'Development-Lima')->count())->toBe(1)- ->and(V5Server::query()->where('name', 'coold-dev')->where('host', 'host.docker.internal')->where('node_address', '100.64.0.1')->where('wireguard_management_ip', '100.64.0.1')->where('ssh_port', 61332)->where('private_key_id', $privateKey->id)->exists())->toBeTrue()- ->and(V5Server::query()->where('name', 'coold-dev-2')->where('host', 'host.docker.internal')->where('node_address', '100.64.0.2')->where('wireguard_management_ip', '100.64.0.2')->where('ssh_port', 61379)->where('private_key_id', $privateKey->id)->exists())->toBeTrue();-});--it('updates legacy dev Lima hostnames to Docker reachable SSH endpoints', function () {- createSharedUserAndTeamTables();- [$user, $team] = createV5UserWithTeam();- $privateKey = createV5PrivateKey($team, 'Dev Lima Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Development-Lima',- 'description' => 'Local Lima development cluster managed by scripts/dev.sh.',- ]);-- V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'private_key_id' => $privateKey->id,- 'name' => 'coold-dev',- 'host' => 'lima-coold-dev',- 'ssh_user' => 'developer',- 'ssh_port' => 22,- 'status' => 'installed',- 'builder_enabled' => true,- 'builder_capacity' => 2,- 'last_bootstrapped_at' => now(),- ]);-- $exitCode = Artisan::call('v5:sync-dev-lima-servers', [- '--team-id' => $team->id,- '--user-id' => $user->id,- '--cluster' => 'Development-Lima',- '--server' => [- 'coold-dev|host.docker.internal|developer|61332',- ],- ]);-- expect($exitCode)->toBe(0)- ->and(V5Server::query()->where('name', 'coold-dev')->count())->toBe(1)- ->and(V5Server::query()->where('name', 'coold-dev')->where('host', 'host.docker.internal')->where('ssh_port', 61332)->exists())->toBeTrue()- ->and(V5Server::query()->where('host', 'lima-coold-dev')->exists())->toBeFalse();-});--it('seeds dev Lima VMs into v5 clusters and servers idempotently', function () {- createSharedUserAndTeamTables();- [$user, $team] = createV5UserWithTeam();- createV5PrivateKey($team, 'Dev Lima Key');-- (new V5DevLimaSeeder)->run();- (new V5DevLimaSeeder)->run();-- $cluster = Cluster::query()->where('name', 'Development-Lima')->sole();-- expect($cluster->team_id)->toBe($team->id)- ->and($cluster->created_by_user_id)->toBe($user->id)- ->and($cluster->description)->toBe('Local Lima development cluster managed by scripts/dev.sh.')- ->and(V5Server::query()->count())->toBe(2)- ->and(V5Server::query()->where('name', 'coold-dev')->where('host', 'coold-dev.local')->where('ssh_user', 'coolify')->where('ssh_port', 22)->exists())->toBeTrue()- ->and(V5Server::query()->where('name', 'coold-dev-2')->where('host', 'coold-dev-2.local')->where('ssh_user', 'coolify')->where('ssh_port', 22)->exists())->toBeTrue()- ->and(V5Server::query()->where('name', 'coold-dev')->where('node_address', '100.64.0.1')->where('wireguard_management_ip', '100.64.0.1')->exists())->toBeTrue()- ->and(V5Server::query()->where('name', 'coold-dev-2')->where('node_address', '100.64.0.2')->where('wireguard_management_ip', '100.64.0.2')->exists())->toBeTrue()- ->and(V5Server::query()->where('status', 'installed')->count())->toBe(2)- ->and(V5Server::query()->where('builder_enabled', false)->where('builder_capacity', 0)->count())->toBe(2)- ->and(V5Server::query()->where('cluster_id', $cluster->id)->count())->toBe(2);-});--it('seeds dev Lima VMs by updating existing named servers', function () {- createSharedUserAndTeamTables();- [$user, $team] = createV5UserWithTeam();- createV5PrivateKey($team, 'Dev Lima Key');- $cluster = Cluster::query()->create([- 'team_id' => $team->id,- 'created_by_user_id' => $user->id,- 'name' => 'Development-Lima',- 'description' => 'Local Lima development cluster managed by scripts/dev.sh.',- ]);-- V5Server::query()->create([- 'team_id' => $team->id,- 'cluster_id' => $cluster->id,- 'created_by_user_id' => $user->id,- 'name' => 'coold-dev',- 'host' => 'old-host.local',- 'ssh_user' => 'developer',- 'ssh_port' => 22,- 'status' => 'installed',- 'builder_enabled' => false,- 'builder_capacity' => 0,- 'last_bootstrapped_at' => now()->subDay(),- ]);-- (new V5DevLimaSeeder)->run();-- expect(V5Server::query()->where('name', 'coold-dev')->count())->toBe(1)- ->and(V5Server::query()->where('name', 'coold-dev')->where('host', 'coold-dev.local')->where('ssh_port', 22)->exists())->toBeTrue()- ->and(V5Server::query()->count())->toBe(2);-});--function fakeFluxHealth(bool $available = true, string $message = 'Flux is running.'): void-{- app()->instance(FluxHealth::class, Mockery::mock(FluxHealth::class, function (MockInterface $mock) use ($available, $message) {- $mock->shouldReceive('check')- ->once()- ->andReturn([- 'available' => $available,- 'label' => $available ? 'Running' : 'Unavailable',- 'message' => $message,- 'socket' => '/run/coolify/flux.sock',- ]);- }));-}--function fakeSuccessfulNginxFluxDeployment(string $image = 'docker.io/library/nginx:alpine'): void-{- $mock = Mockery::mock(FluxClient::class, function (MockInterface $mock) use ($image): void {- $mock->shouldReceive('pullImage')- ->once()- ->with(Mockery::type('string'), $image)- ->andReturn('Image pulled.');- $mock->shouldReceive('createContainer')- ->once()- ->with(Mockery::type('string'), Mockery::on(fn (array $spec): bool => ($spec['image'] ?? null) === $image- && ($spec['networks'] ?? []) === ['coolify-default-mesh']- && ($spec['dns_search'] ?? []) === ['default.coolify.internal']- && in_array($spec['name'] ?? '', $spec['network_aliases'] ?? [], true)))- ->andReturn('nginx-container-id');- $mock->shouldReceive('startContainer')- ->once()- ->with(Mockery::type('string'), 'nginx-container-id')- ->andReturn('Container started.');- $mock->shouldReceive('inspectContainer')- ->once()- ->with(Mockery::type('string'), 'nginx-container-id')- ->andReturn(['State' => ['Running' => true]]);- });-- app()->instance(FluxClient::class, $mock);-}--function expectCaddyIngressFirewallRule(mixed $fluxClient): void-{- $fluxClient- ->shouldReceive('applyFirewallRule')- ->once()- ->with('100.64.0.10', [- 'id' => 'v5-caddy-ingress:80',- 'namespace' => 'default',- 'src' => '0.0.0.0/0',- 'dst' => 'coolify-v5-caddy',- 'proto' => 'tcp',- 'port' => 80,- ])- ->andReturn('Firewall rule applied.');- $fluxClient- ->shouldReceive('applyFirewallRule')- ->once()- ->with('100.64.0.10', [- 'id' => 'v5-caddy-ingress:443',- 'namespace' => 'default',- 'src' => '0.0.0.0/0',- 'dst' => 'coolify-v5-caddy',- 'proto' => 'tcp',- 'port' => 443,- ])- ->andReturn('Firewall rule applied.');-}--function createSharedUserAndTeamTables(): void-{- Schema::create('users', function ($table) {- $table->id();- $table->string('name')->default('Anonymous');- $table->string('email');- $table->timestamp('email_verified_at')->nullable();- $table->string('password')->nullable();- $table->rememberToken();- $table->timestamps();- });-- Schema::create('teams', function ($table) {- $table->id();- $table->string('name');- $table->string('description')->nullable();- $table->boolean('personal_team')->default(false);- $table->boolean('show_boarding')->default(false);- $table->timestamps();- });-- Schema::create('private_keys', function ($table) {- $table->id();- $table->string('uuid')->unique();- $table->string('name');- $table->string('description')->nullable();- $table->longText('private_key');- $table->string('fingerprint')->nullable();- $table->boolean('is_git_related')->default(false);- $table->foreignId('team_id');- $table->timestamps();- });-- Schema::create('projects', function ($table) {- $table->id();- $table->string('uuid');- $table->string('name');- $table->text('description')->nullable();- $table->foreignId('team_id');- $table->timestamps();- });-- Schema::create('environments', function ($table) {- $table->id();- $table->string('name');- $table->foreignId('project_id');- $table->timestamps();- $table->text('description')->nullable();- $table->string('uuid');- });-- Schema::create('v5_clusters', function ($table) {- $table->id();- $table->string('uuid')->nullable()->unique();- $table->foreignId('team_id');- $table->foreignId('created_by_user_id');- $table->string('name');- $table->text('description')->nullable();- $table->string('wireguard_interface')->default('wg0');- $table->string('wireguard_management_pool')->default('100.64.0.0/16');- $table->unsignedInteger('wireguard_listen_port')->default(51820);- $table->string('container_network_pool')->default('10.210.0.0/16');- $table->unsignedTinyInteger('container_network_prefix')->default(24);- $table->json('namespaces')->nullable();- $table->boolean('default_deny_containers')->default(true);- $table->string('coold_version')->default('nightly');- $table->string('corrosion_version')->default('v1.0.0');- $table->unsignedInteger('corrosion_gossip_port')->default(8787);- $table->unsignedInteger('corrosion_api_port')->default(8080);- $table->boolean('builder_enabled')->default(true);- $table->unsignedInteger('builder_capacity')->default(2);- $table->string('builder_cpu_quota')->default('200%');- $table->string('builder_memory_max')->default('2G');- $table->unsignedInteger('builder_timeout_secs')->default(1800);- $table->string('last_cli_action')->nullable();- $table->string('last_cli_status')->nullable();- $table->text('last_cli_summary')->nullable();- $table->timestamp('last_cli_ran_at')->nullable();- $table->timestamps();- });-- Schema::create('v5_servers', function ($table) {- $table->id();- $table->string('uuid')->nullable()->unique();- $table->foreignId('team_id');- $table->foreignId('cluster_id')->nullable();- $table->foreignId('created_by_user_id');- $table->foreignId('private_key_id')->nullable();- $table->string('name');- $table->string('host');- $table->string('ssh_user');- $table->unsignedInteger('ssh_port');- $table->string('status')->default('installed');- $table->string('ingress_type')->nullable();- $table->string('ingress_status')->nullable();- $table->json('capabilities')->nullable();- $table->boolean('builder_enabled')->default(false);- $table->unsignedInteger('builder_capacity')->default(0);- $table->string('builder_cpu_quota')->default('200%');- $table->string('node_address')->nullable();- $table->unsignedInteger('wireguard_listen_port_override')->nullable();- $table->string('wireguard_endpoint_override')->nullable();- $table->string('wireguard_management_ip')->nullable();- $table->string('wireguard_public_key')->nullable();- $table->json('container_subnets')->nullable();- $table->integer('canvas_x')->nullable();- $table->integer('canvas_y')->nullable();- $table->timestamp('last_bootstrapped_at')->nullable();- $table->string('last_bootstrap_action')->nullable();- $table->string('last_bootstrap_status')->nullable();- $table->text('last_bootstrap_output')->nullable();- $table->timestamp('last_bootstrap_ran_at')->nullable();- $table->string('last_status_check')->nullable();- $table->text('last_status_output')->nullable();- $table->timestamp('last_status_checked_at')->nullable();- $table->timestamps();- });-- Schema::create('v5_container_statuses', function ($table) {- $table->id();- $table->foreignId('team_id');- $table->foreignId('server_id');- $table->string('container_id');- $table->string('container_name')->nullable();- $table->string('image')->nullable();- $table->string('status')->default('unknown');- $table->text('status_message')->nullable();- $table->timestamp('last_seen_at')->nullable();- $table->timestamps();-- $table->unique(['server_id', 'container_id']);- });-- Schema::create('v5_applications', function ($table) {- $table->id();- $table->string('uuid')->nullable()->unique();- $table->foreignId('team_id');- $table->foreignId('project_id');- $table->foreignId('environment_id');- $table->foreignId('server_id')->nullable();- $table->foreignId('created_by_user_id');- $table->string('name');- $table->string('image');- $table->string('container_name')->unique();- $table->string('status')->default('creating');- $table->text('status_message')->nullable();- $table->string('runtime_container_id')->nullable();- $table->string('mesh_namespace')->default('default');- $table->boolean('ingress_enabled')->default(false);- $table->unsignedSmallInteger('internal_port')->nullable();- $table->integer('canvas_x')->default(0);- $table->integer('canvas_y')->default(0);- $table->timestamps();- });-- Schema::create('v5_application_domains', function ($table) {- $table->id();- $table->foreignId('application_id');- $table->string('domain');- $table->timestamps();-- $table->unique(['application_id', 'domain']);- });-- Schema::create('v5_resource_connections', function ($table) {- $table->id();- $table->string('uuid')->nullable()->unique();- $table->foreignId('team_id');- $table->foreignId('project_id');- $table->foreignId('environment_id');- $table->string('resource_one_type');- $table->unsignedBigInteger('resource_one_id');- $table->string('resource_two_type');- $table->unsignedBigInteger('resource_two_id');- $table->string('resource_pair_key');- $table->foreignId('created_by_user_id');- $table->timestamps();-- $table->unique(['team_id', 'resource_pair_key']);- });-- Schema::create('v5_resource_connection_rules', function ($table) {- $table->id();- $table->foreignId('connection_id');- $table->string('source_resource_type');- $table->unsignedBigInteger('source_resource_id');- $table->string('target_resource_type');- $table->unsignedBigInteger('target_resource_id');- $table->string('protocol')->default('tcp');- $table->unsignedSmallInteger('port');- $table->timestamps();- });-- Schema::create('team_user', function ($table) {- $table->id();- $table->foreignId('team_id');- $table->foreignId('user_id');- $table->string('role')->default('member');- $table->timestamps();-- $table->unique(['team_id', 'user_id']);- });-}--/**- * @return array{0: Project, 1: Environment}- */-/**- * @param array<int, string> $command- */-function cliFlagValue(array $command, string $flag): ?string-{- $index = array_search($flag, $command, true);-- if ($index === false || ! isset($command[$index + 1])) {- return null;- }-- return $command[$index + 1];-}--function createV5ProjectWithEnvironment(Team $team, string $projectName, string $environmentName): array-{- $project = Project::withoutEvents(fn () => Project::query()->forceCreate([- 'uuid' => str($projectName)->slug().'-uuid',- 'name' => $projectName,- 'description' => null,- 'team_id' => $team->id,- ]));-- $environment = Environment::withoutEvents(fn () => Environment::query()->forceCreate([- 'uuid' => str($environmentName)->slug().'-uuid',- 'name' => $environmentName,- 'description' => null,- 'project_id' => $project->id,- ]));-- return [$project, $environment];-}--function createV5PrivateKey(Team $team, string $name): PrivateKey-{- return PrivateKey::withoutEvents(fn () => PrivateKey::query()->forceCreate([- 'uuid' => str($name)->slug().'-uuid',- 'name' => $name,- 'description' => null,- 'private_key' => "-----BEGIN OPENSSH PRIVATE KEY-----\ntest-key\n-----END OPENSSH PRIVATE KEY-----\n",- 'fingerprint' => str($name)->slug()->toString(),- 'is_git_related' => false,- 'team_id' => $team->id,- ]));-}--/**- * @return array{0: User, 1: Team}- */-function createV5UserWithTeam(string $email = '[email protected]'): array-{- $user = User::withoutEvents(fn () => User::query()->create([- 'name' => 'Margaret Hamilton',- 'email' => $email,- 'email_verified_at' => now(),- 'password' => 'password',- ]));- $team = Team::withoutEvents(fn () => Team::query()->create([- 'name' => 'V5 Tooling Team',- 'description' => null,- 'personal_team' => false,- 'show_boarding' => false,- ]));- $user->teams()->attach($team, ['role' => 'owner']);-- return [$user, $team];-}--it('configures v5 dev lima host resolver for coolify internal dns', function () {- $script = file_get_contents(base_path('scripts/coold-vm.sh'));-- expect($script)- ->toContain('configure_system_resolved')- ->toContain('ensure_mesh_dns_anchor')- ->toContain('coolify-v5-mesh-dns-anchor')- ->toContain('resolvectl dns podman1 "$CONTAINER_GATEWAY"')- ->toContain("resolvectl domain podman1 '~coolify.internal'")- ->toContain('resolvectl default-route podman1 false');-});diff --git a/tests/Feature/V5/EnsureCurrentTeamTest.php b/tests/Feature/V5/EnsureCurrentTeamTest.phpnew file mode 100644index 0000000000..31eb0123df--- /dev/null+++ b/tests/Feature/V5/EnsureCurrentTeamTest.php@@ -0,0 +1,153 @@+<?php++use App\Http\Middleware\V5\EnsureCurrentTeam;+use App\Models\Team;+use App\Models\User;+use Illuminate\Http\Request;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Schema;+use Symfony\Component\HttpFoundation\Response;+use Symfony\Component\HttpKernel\Exception\HttpException;++beforeEach(function () {+ Config::set('cache.default', 'array');++ Schema::dropIfExists('team_user');+ Schema::dropIfExists('teams');+ Schema::dropIfExists('users');++ Schema::create('users', function ($table) {+ $table->id();+ $table->string('name')->default('Anonymous');+ $table->string('email');+ $table->timestamp('email_verified_at')->nullable();+ $table->string('password')->nullable();+ $table->rememberToken();+ $table->timestamps();+ });++ Schema::create('teams', function ($table) {+ $table->id();+ $table->string('name');+ $table->string('description')->nullable();+ $table->boolean('personal_team')->default(false);+ $table->boolean('show_boarding')->default(false);+ $table->timestamps();+ });++ Schema::create('team_user', function ($table) {+ $table->id();+ $table->foreignId('team_id');+ $table->foreignId('user_id');+ $table->string('role')->default('member');+ $table->timestamps();++ $table->unique(['team_id', 'user_id']);+ });+});++function createEnsureCurrentTeamUser(string $email = '[email protected]'): User+{+ return User::withoutEvents(fn () => User::query()->create([+ 'name' => 'Margaret Hamilton',+ 'email' => $email,+ 'email_verified_at' => now(),+ 'password' => 'password',+ ]));+}++function createEnsureCurrentTeamTeam(string $name = 'V5 Tooling Team'): Team+{+ return Team::withoutEvents(fn () => Team::query()->create([+ 'name' => $name,+ 'description' => 'The team that ships v5.',+ 'personal_team' => false,+ 'show_boarding' => false,+ ]));+}++/**+ * Runs the middleware against a request the way the v5.authenticated group+ * would: an authenticated user with an active session store.+ *+ * @return array{0: Response, 1: Request}+ */+function runEnsureCurrentTeam(?User $user): array+{+ $request = Request::create('/v5', 'GET');+ $request->setLaravelSession(app('session.store'));+ $request->setUserResolver(fn () => $user);++ $response = (new EnsureCurrentTeam)->handle($request, fn () => response()->noContent());++ return [$response, $request];+}++it('aborts 403 when the user belongs to no team', function () {+ $user = createEnsureCurrentTeamUser();++ expect(fn () => runEnsureCurrentTeam($user))+ ->toThrow(fn (HttpException $exception) => expect($exception->getStatusCode())->toBe(403));+});++it('falls back to first team when the session team is no longer a member', function () {+ $user = createEnsureCurrentTeamUser();+ $memberTeam = createEnsureCurrentTeamTeam('Member Team');+ $foreignTeam = createEnsureCurrentTeamTeam('Foreign Team');+ $user->teams()->attach($memberTeam, ['role' => 'owner']);++ session(['currentTeam' => $foreignTeam]);++ [, $request] = runEnsureCurrentTeam($user);++ expect($request->attributes->get('v5.currentTeam')->id)->toBe($memberTeam->id)+ ->and(session('currentTeam'))->toBeInstanceOf(Team::class)+ ->and(session('currentTeam')->id)->toBe($memberTeam->id)+ ->and(session('currentTeam')->name)->toBe('Member Team');+});++it('stores the full team model so v4 session reads keep working', function () {+ $user = createEnsureCurrentTeamUser();+ $team = createEnsureCurrentTeamTeam();+ $user->teams()->attach($team, ['role' => 'owner']);++ runEnsureCurrentTeam($user);++ $sessionTeam = session('currentTeam');++ // v4 reads columns beyond id/name/description/personal_team off the+ // session team (e.g. show_boarding, custom limits), so the stored model+ // must not be a partial select.+ expect($sessionTeam)->toBeInstanceOf(Team::class)+ ->and($sessionTeam->getAttributes())->toHaveKeys([+ 'id',+ 'name',+ 'description',+ 'personal_team',+ 'show_boarding',+ 'created_at',+ 'updated_at',+ ])+ ->and($sessionTeam->created_at)->not->toBeNull()+ ->and((bool) $sessionTeam->show_boarding)->toBeFalse();+});++it('does not rewrite the session when the team is unchanged', function () {+ $user = createEnsureCurrentTeamUser();+ $team = createEnsureCurrentTeamTeam();+ $user->teams()->attach($team, ['role' => 'owner']);++ // Prime the session with the same team but a sentinel attribute; if the+ // middleware skips the redundant write, the sentinel survives the request.+ $sessionTeam = Team::query()->findOrFail($team->id);+ $sessionTeam->name = 'Session Sentinel';+ session(['currentTeam' => $sessionTeam]);++ [, $request] = runEnsureCurrentTeam($user);++ expect($request->attributes->get('v5.currentTeam'))->toBeInstanceOf(Team::class)+ ->and($request->attributes->get('v5.currentTeam')->id)->toBe($team->id)+ ->and($request->attributes->get('v5.currentTeam')->name)->toBe('V5 Tooling Team')+ ->and(session('currentTeam'))->toBe($sessionTeam)+ ->and(session('currentTeam')->name)->toBe('Session Sentinel');+});diff --git a/tests/Feature/V5/FluxGenerateKeysTest.php b/tests/Feature/V5/FluxGenerateKeysTest.phpnew file mode 100644index 0000000000..82985f807c--- /dev/null+++ b/tests/Feature/V5/FluxGenerateKeysTest.php@@ -0,0 +1,81 @@+<?php++use App\Services\Flux\AgentTokenIssuer;+use Firebase\JWT\JWT;+use Firebase\JWT\Key;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\File;++beforeEach(function () {+ $this->keyDir = storage_path('framework/testing/flux-keygen-'.bin2hex(random_bytes(4)));+ $this->privateKeyPath = $this->keyDir.'/jwt.priv';+ $this->publicKeyPath = $this->keyDir.'/jwt.pub';++ Config::set('flux.jwt_private_key_path', $this->privateKeyPath);+ Config::set('flux.jwt_public_key_path', $this->publicKeyPath);+});++afterEach(function () {+ File::deleteDirectory($this->keyDir);+});++/**+ * @return string octal file/dir mode, e.g. "0600"+ */+function fluxKeyMode(string $path): string+{+ clearstatcache();++ return sprintf('%04o', fileperms($path) & 0777);+}++it('generates a working ES256 keypair at the configured paths with strict perms', function () {+ $this->artisan('v5:flux-generate-keys')->assertSuccessful();++ expect(File::exists($this->privateKeyPath))->toBeTrue()+ ->and(File::exists($this->publicKeyPath))->toBeTrue()+ ->and(fluxKeyMode($this->privateKeyPath))->toBe('0600')+ ->and(fluxKeyMode($this->publicKeyPath))->toBe('0644')+ ->and(fluxKeyMode($this->keyDir))->toBe('0700');++ // The generated private key must be usable by the real issuer...+ $token = app(AgentTokenIssuer::class)->issue('100.64.0.10');++ expect(substr_count($token, '.'))->toBe(2);++ // ...and verifiable with the generated public key (proves the pair matches).+ $claims = JWT::decode($token, new Key(File::get($this->publicKeyPath), 'ES256'));++ expect($claims->sub)->toBe('100.64.0.10');+});++it('refuses to overwrite an existing private key without --force', function () {+ File::ensureDirectoryExists($this->keyDir);+ File::put($this->privateKeyPath, 'SENTINEL-PRIVATE-KEY');++ $this->artisan('v5:flux-generate-keys')+ ->expectsOutputToContain('already exists')+ ->assertSuccessful();++ expect(File::get($this->privateKeyPath))->toBe('SENTINEL-PRIVATE-KEY');+});++it('overwrites an existing private key with --force and produces a valid keypair', function () {+ File::ensureDirectoryExists($this->keyDir);+ File::put($this->privateKeyPath, 'SENTINEL-PRIVATE-KEY');++ $this->artisan('v5:flux-generate-keys --force')->assertSuccessful();++ expect(File::get($this->privateKeyPath))->not->toBe('SENTINEL-PRIVATE-KEY')+ ->and(fluxKeyMode($this->privateKeyPath))->toBe('0600');++ $token = app(AgentTokenIssuer::class)->issue('100.64.0.10');++ expect(substr_count($token, '.'))->toBe(2);+});++it('prints the public key when --show-public is passed', function () {+ $this->artisan('v5:flux-generate-keys --show-public')+ ->expectsOutputToContain('BEGIN PUBLIC KEY')+ ->assertSuccessful();+});diff --git a/tests/Feature/V5/FluxInboundTokenTest.php b/tests/Feature/V5/FluxInboundTokenTest.phpnew file mode 100644index 0000000000..b6bdb2705a--- /dev/null+++ b/tests/Feature/V5/FluxInboundTokenTest.php@@ -0,0 +1,72 @@+<?php++use App\Models\V5\Server as V5Server;+use Illuminate\Support\Facades\Config;+use Illuminate\Testing\TestResponse;+use Tests\Support\V5TestSchema;++beforeEach(function () {+ Config::set('broadcasting.default', 'log');+ Config::set('cache.default', 'array');++ V5TestSchema::dropAllTables();+ V5TestSchema::createAllTables();++ V5Server::query()->create([+ 'team_id' => 1,+ 'created_by_user_id' => 1,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'wireguard_management_ip' => '100.64.0.5',+ ]);+});++afterEach(function () {+ V5TestSchema::dropAllTables();+});++function postFluxContainerStatus(string $bearer): TestResponse+{+ return test()->postJson('/api/v1/internal/flux/resource-status', [+ 'resource_type' => 'container',+ 'host_id' => '100.64.0.5',+ 'container_id' => 'external-container-id',+ 'container_name' => 'external-container',+ 'status' => 'running',+ ], [+ 'Authorization' => 'Bearer '.$bearer,+ ]);+}++it('accepts an inbound token listed in the rotatable token array', function () {+ Config::set('flux.laravel_api_token', null);+ Config::set('flux.laravel_api_tokens', ['old-token', 'new-token']);++ postFluxContainerStatus('new-token')->assertSuccessful();+ postFluxContainerStatus('old-token')->assertSuccessful();+});++it('still accepts the single fallback token alongside the array', function () {+ Config::set('flux.laravel_api_token', 'single-token');+ Config::set('flux.laravel_api_tokens', ['array-token']);++ postFluxContainerStatus('single-token')->assertSuccessful();+ postFluxContainerStatus('array-token')->assertSuccessful();+});++it('rejects a token that is in neither the array nor the fallback', function () {+ Config::set('flux.laravel_api_token', 'single-token');+ Config::set('flux.laravel_api_tokens', ['array-token']);++ postFluxContainerStatus('unknown-token')->assertUnauthorized();+});++it('rejects an empty bearer token even when no tokens are configured', function () {+ Config::set('flux.laravel_api_token', null);+ Config::set('flux.laravel_api_tokens', []);++ postFluxContainerStatus('')->assertUnauthorized();+});diff --git a/tests/Feature/V5/FluxStatusIngestionTest.php b/tests/Feature/V5/FluxStatusIngestionTest.phpnew file mode 100644index 0000000000..b07a183519--- /dev/null+++ b/tests/Feature/V5/FluxStatusIngestionTest.php@@ -0,0 +1,341 @@+<?php++use App\Actions\V5\Flux\ApplyFluxResourceStatusUpdate;+use App\Enums\V5\ApplicationStatus;+use App\Enums\V5\ContainerState;+use App\Enums\V5\ServerStatus;+use App\Events\V5CanvasResourceUpdated;+use App\Events\V5ClusterUpdated;+use App\Models\V5\Application as V5Application;+use App\Models\V5\ContainerStatus;+use App\Models\V5\Server as V5Server;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Event;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Facades\Schema;+use Tests\Support\V5TestSchema;++beforeEach(function () {+ Config::set('broadcasting.default', 'log');+ Config::set('cache.default', 'array');++ Schema::dropIfExists('v5_applications');+ Schema::dropIfExists('v5_container_statuses');+ Schema::dropIfExists('v5_servers');++ V5TestSchema::createServersTable();+ V5TestSchema::createApplicationsTable();+ V5TestSchema::createContainerStatusesTable();+});++afterEach(function () {+ Schema::dropIfExists('v5_applications');+ Schema::dropIfExists('v5_container_statuses');+ Schema::dropIfExists('v5_servers');+});++/**+ * @param array<string, mixed> $overrides+ */+function createFluxIngestionServer(array $overrides = []): V5Server+{+ return V5Server::query()->create([+ 'team_id' => 1,+ 'created_by_user_id' => 1,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => ServerStatus::Installed->value,+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.5',+ ...$overrides,+ ]);+}++/**+ * @param array<string, mixed> $overrides+ */+function createFluxIngestionApplication(V5Server $server, array $overrides = []): V5Application+{+ return V5Application::query()->create([+ 'team_id' => $server->team_id,+ 'project_id' => 1,+ 'environment_id' => 1,+ 'server_id' => $server->id,+ 'created_by_user_id' => 1,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => ApplicationStatus::Running->value,+ 'status_message' => 'Container started.',+ 'runtime_container_id' => 'nginx-container-id',+ ...$overrides,+ ]);+}++it('maps unknown flux application status values to unknown and logs a warning', function () {+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);+ Log::spy();++ $server = createFluxIngestionServer();+ $application = createFluxIngestionApplication($server);++ ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'application',+ 'host_id' => '100.64.0.5',+ 'container_name' => 'coolify-v5-nginx-1',+ 'container_id' => 'nginx-container-id',+ 'status' => 'Exploded',+ ]);++ expect($application->refresh()->status)->toBe(ApplicationStatus::Unknown->value);++ Log::shouldHaveReceived('warning')+ ->withArgs(fn (string $message, array $context = []): bool => str_contains($message, 'unknown flux resource status')+ && ($context['raw_status'] ?? null) === 'Exploded'+ && ($context['status_enum'] ?? null) === ApplicationStatus::class)+ ->once();+});++it('maps unknown flux container states to unknown when upserting container statuses', function () {+ Log::spy();++ $server = createFluxIngestionServer();++ $resource = ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'container',+ 'host_id' => '100.64.0.5',+ 'container_id' => 'external-container-id',+ 'container_name' => 'external-container',+ 'status' => 'levitating',+ ]);++ expect($resource)->toBeInstanceOf(ContainerStatus::class)+ ->and($resource->status)->toBe(ContainerState::Unknown->value);++ Log::shouldHaveReceived('warning')+ ->withArgs(fn (string $message, array $context = []): bool => ($context['raw_status'] ?? null) === 'levitating'+ && ($context['status_enum'] ?? null) === ContainerState::class)+ ->once();+});++it('still applies known statuses case insensitively without warnings', function () {+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);+ Log::spy();++ $server = createFluxIngestionServer();+ $application = createFluxIngestionApplication($server);++ ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'application',+ 'host_id' => '100.64.0.5',+ 'container_name' => 'coolify-v5-nginx-1',+ 'container_id' => 'nginx-container-id',+ 'status' => 'EXITED',+ ]);++ expect($application->refresh()->status)->toBe(ApplicationStatus::Exited->value);++ Log::shouldNotHaveReceived('warning');+});++it('drops flux application status updates that are older than the persisted observation', function () {+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);+ Log::spy();++ $server = createFluxIngestionServer();+ $application = createFluxIngestionApplication($server, [+ 'status_observed_at' => '2026-07-05T12:00:00Z',+ ]);++ $resource = ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'application',+ 'host_id' => '100.64.0.5',+ 'container_name' => 'coolify-v5-nginx-1',+ 'container_id' => 'nginx-container-id',+ 'status' => 'exited',+ 'observed_at' => '2026-07-05T11:00:00Z',+ ]);++ expect($resource)->toBeInstanceOf(V5Application::class)+ ->and($application->refresh()->status)->toBe(ApplicationStatus::Running->value)+ ->and($application->status_observed_at->toIso8601String())->toBe('2026-07-05T12:00:00+00:00');++ Log::shouldHaveReceived('debug')+ ->withArgs(fn (string $message): bool => str_contains($message, 'stale flux application status'))+ ->once();++ Event::assertNotDispatched(V5CanvasResourceUpdated::class);+});++it('applies flux application status updates with a newer observation and persists the timestamp', function () {+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $server = createFluxIngestionServer();+ $application = createFluxIngestionApplication($server, [+ 'status_observed_at' => '2026-07-05T10:00:00Z',+ ]);++ ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'application',+ 'host_id' => '100.64.0.5',+ 'container_name' => 'coolify-v5-nginx-1',+ 'container_id' => 'nginx-container-id',+ 'status' => 'exited',+ 'status_message' => 'Container exited.',+ 'observed_at' => '2026-07-05T12:00:00Z',+ ]);++ expect($application->refresh()->status)->toBe(ApplicationStatus::Exited->value)+ ->and($application->status_message)->toBe('Container exited.')+ ->and($application->status_observed_at->toIso8601String())->toBe('2026-07-05T12:00:00+00:00');++ Event::assertDispatched(V5CanvasResourceUpdated::class);+});++it('keeps applying flux application status updates that carry no observation timestamp', function () {+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $server = createFluxIngestionServer();+ $application = createFluxIngestionApplication($server, [+ 'status_observed_at' => '2026-07-05T12:00:00Z',+ ]);++ ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'application',+ 'host_id' => '100.64.0.5',+ 'container_name' => 'coolify-v5-nginx-1',+ 'container_id' => 'nginx-container-id',+ 'status' => 'exited',+ ]);++ expect($application->refresh()->status)->toBe(ApplicationStatus::Exited->value)+ ->and($application->status_observed_at->toIso8601String())->toBe('2026-07-05T12:00:00+00:00');+});++it('drops stale flux server status updates but applies newer observations', function () {+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);+ Log::spy();++ $server = createFluxIngestionServer([+ 'status_observed_at' => '2026-07-05T12:00:00Z',+ ]);++ ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'server',+ 'host_id' => '100.64.0.5',+ 'status' => 'unreachable',+ 'observed_at' => '2026-07-05T11:59:59Z',+ ]);++ expect($server->refresh()->status)->toBe(ServerStatus::Installed->value);++ Log::shouldHaveReceived('debug')+ ->withArgs(fn (string $message): bool => str_contains($message, 'stale flux server status'))+ ->once();++ ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'server',+ 'host_id' => '100.64.0.5',+ 'status' => 'unreachable',+ 'observed_at' => '2026-07-05T12:00:01Z',+ ]);++ expect($server->refresh()->status)->toBe(ServerStatus::Unreachable->value)+ ->and($server->status_observed_at->toIso8601String())->toBe('2026-07-05T12:00:01+00:00');+});++it('drops stale flux container status updates that are older than the persisted observation', function () {+ Log::spy();++ $server = createFluxIngestionServer();+ ContainerStatus::query()->create([+ 'team_id' => $server->team_id,+ 'server_id' => $server->id,+ 'container_id' => 'external-container-id',+ 'container_name' => 'external-container',+ 'status' => ContainerState::Running->value,+ 'status_observed_at' => '2026-07-05T12:00:00Z',+ ]);++ $resource = ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'container',+ 'host_id' => '100.64.0.5',+ 'container_id' => 'external-container-id',+ 'container_name' => 'external-container',+ 'status' => 'exited',+ 'observed_at' => '2026-07-05T11:00:00Z',+ ]);++ expect($resource)->toBeInstanceOf(ContainerStatus::class)+ ->and($resource->status)->toBe(ContainerState::Running->value);++ Log::shouldHaveReceived('debug')+ ->withArgs(fn (string $message): bool => str_contains($message, 'stale flux container status'))+ ->once();+});++it('logs a warning when a flux host id matches multiple v5 servers', function () {+ Log::spy();++ $serverOne = createFluxIngestionServer();+ $serverTwo = createFluxIngestionServer([+ 'name' => 'edge-02',+ 'host' => '203.0.113.11',+ ]);++ $resource = ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'server',+ 'host_id' => '100.64.0.5',+ 'status' => 'unreachable',+ ]);++ expect($resource)->toBeNull()+ ->and($serverOne->refresh()->status)->toBe(ServerStatus::Installed->value)+ ->and($serverTwo->refresh()->status)->toBe(ServerStatus::Installed->value);++ Log::shouldHaveReceived('warning')+ ->withArgs(fn (string $message, array $context = []): bool => str_contains($message, 'matches multiple v5 servers')+ && ($context['host_id'] ?? null) === '100.64.0.5'+ && ($context['server_ids'] ?? null) === [$serverOne->id, $serverTwo->id])+ ->once();+});++it('accepts flux resource status http payloads with a valid observed_at timestamp', function () {+ Config::set('flux.laravel_api_token', 'test-flux-token');+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $server = createFluxIngestionServer();+ $application = createFluxIngestionApplication($server);++ $this+ ->withToken('test-flux-token')+ ->postJson('/api/v1/internal/flux/resource-status', [+ 'resource_type' => 'application',+ 'host_id' => '100.64.0.5',+ 'container_name' => 'coolify-v5-nginx-1',+ 'container_id' => 'nginx-container-id',+ 'status' => 'exited',+ 'observed_at' => '2026-07-05T12:00:00Z',+ ])+ ->assertSuccessful()+ ->assertJsonPath('message', 'Resource status updated.');++ expect($application->refresh()->status)->toBe(ApplicationStatus::Exited->value)+ ->and($application->status_observed_at->toIso8601String())->toBe('2026-07-05T12:00:00+00:00');+});++it('rejects flux resource status http payloads with an invalid observed_at value', function () {+ Config::set('flux.laravel_api_token', 'test-flux-token');++ $this+ ->withToken('test-flux-token')+ ->postJson('/api/v1/internal/flux/resource-status', [+ 'resource_type' => 'application',+ 'host_id' => '100.64.0.5',+ 'status' => 'exited',+ 'observed_at' => 'not-a-timestamp',+ ])+ ->assertInvalid(['observed_at']);+});diff --git a/tests/Feature/V5/HorizonReconcileQueueTest.php b/tests/Feature/V5/HorizonReconcileQueueTest.phpnew file mode 100644index 0000000000..eb93c1205c--- /dev/null+++ b/tests/Feature/V5/HorizonReconcileQueueTest.php@@ -0,0 +1,36 @@+<?php++/**+ * @param string|array<int, string> $queue+ * @return array<int, string>+ */+function horizonSupervisorQueues(string|array $queue): array+{+ $queues = is_array($queue) ? $queue : explode(',', $queue);++ return array_map('trim', $queues);+}++it('defines a horizon supervisor that consumes the v5-reconcile queue', function () {+ $supervisors = config('horizon.defaults');++ $handlesReconcile = collect($supervisors)->contains(+ fn (array $config): bool => in_array('v5-reconcile', horizonSupervisorQueues($config['queue'] ?? ''), true)+ );++ expect($handlesReconcile)->toBeTrue();+});++it('provisions the v5-reconcile supervisor in both production and local environments', function () {+ expect(config('horizon.environments.production.v5reconcile'))->toBeArray()+ ->and(config('horizon.environments.local.v5reconcile'))->toBeArray()+ ->and(config('horizon.defaults.v5reconcile.queue'))->toBe('v5-reconcile');+});++it('keeps the v5-reconcile supervisor isolated from the user-facing deploy queues', function () {+ $reconcileQueues = horizonSupervisorQueues(config('horizon.defaults.v5reconcile.queue'));++ expect($reconcileQueues)->not->toContain('high')+ ->and($reconcileQueues)->not->toContain('default')+ ->and(config('horizon.defaults.v5reconcile.nice'))->toBeGreaterThan(0);+});diff --git a/tests/Feature/V5/ModelHygieneTest.php b/tests/Feature/V5/ModelHygieneTest.phpnew file mode 100644index 0000000000..c0c0729a98--- /dev/null+++ b/tests/Feature/V5/ModelHygieneTest.php@@ -0,0 +1,295 @@+<?php++use App\Jobs\V5ReconcileServersJob;+use App\Jobs\V5ReconcileServerStateJob;+use App\Models\Application;+use App\Models\V5\Application as V5Application;+use App\Models\V5\ApplicationDomain;+use App\Models\V5\ContainerStatus;+use App\Models\V5\ResourceConnection;+use App\Models\V5\ResourceConnectionRule;+use App\Models\V5\Server as V5Server;+use Illuminate\Database\Eloquent\Relations\Relation;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Facades\Schema;+use Tests\Support\V5TestSchema;++beforeEach(function () {+ Config::set('broadcasting.default', 'log');+ Config::set('cache.default', 'array');++ dropModelHygieneTables();+ createModelHygieneTables();+});++afterEach(function () {+ dropModelHygieneTables();+});++it('registers the v5 application morph alias without enforcing a global morph map', function () {+ expect((new V5Application)->getMorphClass())->toBe('v5.application')+ ->and(Relation::getMorphedModel('v5.application'))->toBe(V5Application::class)+ // v4 models keep storing FQCNs — the map must not be enforced.+ ->and((new Application)->getMorphClass())->toBe(Application::class);+});++it('stores v5 resource connections with the morph alias and resolves it back', function () {+ $source = createModelHygieneApplication('api');+ $target = createModelHygieneApplication('postgres');++ $connection = ResourceConnection::query()->create([+ 'team_id' => 1,+ 'project_id' => 1,+ 'environment_id' => 1,+ 'resource_one_type' => $source->getMorphClass(),+ 'resource_one_id' => $source->id,+ 'resource_two_type' => $target->getMorphClass(),+ 'resource_two_id' => $target->id,+ 'resource_pair_key' => collect([+ $source->getMorphClass().':'.$source->getKey(),+ $target->getMorphClass().':'.$target->getKey(),+ ])->sort()->implode('|'),+ 'created_by_user_id' => 1,+ ]);++ $storedRow = DB::table('v5_resource_connections')->where('id', $connection->id)->first();++ expect($storedRow->resource_one_type)->toBe('v5.application')+ ->and($storedRow->resource_two_type)->toBe('v5.application')+ ->and($storedRow->resource_pair_key)->toBe("v5.application:{$source->id}|v5.application:{$target->id}")+ ->and($connection->refresh()->resourceOne)->toBeInstanceOf(V5Application::class)+ ->and($connection->resourceOne->id)->toBe($source->id)+ ->and($connection->resourceTwo->id)->toBe($target->id);+});++it('rewrites legacy fqcn morph rows to the v5 application alias', function () {+ $fqcn = 'App\Models\V5\Application';++ DB::table('v5_resource_connections')->insert([+ 'uuid' => 'legacy-connection',+ 'team_id' => 1,+ 'project_id' => 1,+ 'environment_id' => 1,+ 'resource_one_type' => $fqcn,+ 'resource_one_id' => 1,+ 'resource_two_type' => $fqcn,+ 'resource_two_id' => 2,+ 'resource_pair_key' => "{$fqcn}:1|{$fqcn}:2",+ 'created_by_user_id' => 1,+ 'created_at' => now(),+ 'updated_at' => now(),+ ]);+ DB::table('v5_resource_connection_rules')->insert([+ 'connection_id' => 1,+ 'source_resource_type' => $fqcn,+ 'source_resource_id' => 1,+ 'target_resource_type' => $fqcn,+ 'target_resource_id' => 2,+ 'protocol' => 'tcp',+ 'port' => 5432,+ 'created_at' => now(),+ 'updated_at' => now(),+ ]);++ $migration = include database_path('migrations/2026_07_06_090000_v5_convert_resource_connection_morphs_to_aliases.php');+ $migration->up();++ $connection = DB::table('v5_resource_connections')->where('uuid', 'legacy-connection')->first();+ $rule = DB::table('v5_resource_connection_rules')->first();++ expect($connection->resource_one_type)->toBe('v5.application')+ ->and($connection->resource_two_type)->toBe('v5.application')+ ->and($connection->resource_pair_key)->toBe('v5.application:1|v5.application:2')+ ->and($rule->source_resource_type)->toBe('v5.application')+ ->and($rule->target_resource_type)->toBe('v5.application');+});++it('maps the capabilities array onto the indexed booleans', function () {+ $server = new V5Server(['capabilities' => ['ingress']]);++ expect($server->is_ingress)->toBeTrue()+ ->and($server->has_coold)->toBeFalse()+ ->and($server->isIngress())->toBeTrue()+ ->and($server->hasCapability('ingress'))->toBeTrue()+ ->and($server->hasCapability('coold'))->toBeFalse()+ ->and($server->hasCapability('builder'))->toBeFalse()+ ->and($server->capabilities)->toBe(['ingress']);++ $server->has_coold = true;++ expect($server->capabilities)->toBe(['coold', 'ingress']);++ $server->capabilities = [];++ expect($server->has_coold)->toBeFalse()+ ->and($server->is_ingress)->toBeFalse()+ ->and($server->capabilities)->toBe([]);+});++it('persists capabilities writes into the boolean columns', function () {+ $server = createModelHygieneServer(['capabilities' => ['coold']]);++ $storedRow = DB::table('v5_servers')->where('id', $server->id)->first();++ expect((bool) $storedRow->has_coold)->toBeTrue()+ ->and((bool) $storedRow->is_ingress)->toBeFalse()+ ->and($server->fresh()->capabilities)->toBe(['coold']);+});++it('backfills the capability booleans from the legacy json column', function () {+ Schema::dropIfExists('v5_servers');+ Schema::create('v5_servers', function ($table) {+ $table->id();+ $table->string('uuid')->nullable()->unique();+ $table->string('name');+ $table->json('capabilities')->nullable();+ $table->timestamps();+ });++ DB::table('v5_servers')->insert([+ ['name' => 'full', 'capabilities' => json_encode(['coold', 'ingress'])],+ ['name' => 'ingress-only', 'capabilities' => json_encode(['ingress'])],+ ['name' => 'unknown-only', 'capabilities' => json_encode(['builder'])],+ ['name' => 'empty', 'capabilities' => null],+ ]);++ $migration = include database_path('migrations/2026_07_06_090100_v5_convert_server_capabilities_to_booleans.php');+ $migration->up();++ $serversByName = DB::table('v5_servers')->get()->keyBy('name');++ expect(Schema::hasColumn('v5_servers', 'capabilities'))->toBeFalse()+ ->and((bool) $serversByName['full']->has_coold)->toBeTrue()+ ->and((bool) $serversByName['full']->is_ingress)->toBeTrue()+ ->and((bool) $serversByName['ingress-only']->has_coold)->toBeFalse()+ ->and((bool) $serversByName['ingress-only']->is_ingress)->toBeTrue()+ ->and((bool) $serversByName['unknown-only']->has_coold)->toBeFalse()+ ->and((bool) $serversByName['unknown-only']->is_ingress)->toBeFalse()+ ->and((bool) $serversByName['empty']->has_coold)->toBeFalse()+ ->and((bool) $serversByName['empty']->is_ingress)->toBeFalse();+});++it('selects reconcile-eligible servers through the indexed has_coold column', function () {+ Queue::fake();++ $eligible = createModelHygieneServer(['name' => 'coold-node', 'host' => '203.0.113.10', 'has_coold' => true]);+ createModelHygieneServer(['name' => 'plain-node', 'host' => '203.0.113.11', 'has_coold' => false]);++ DB::enableQueryLog();+ (new V5ReconcileServersJob)->handle();+ $queries = collect(DB::getQueryLog())->pluck('query')->implode(' ');+ DB::disableQueryLog();+ DB::flushQueryLog();++ expect($queries)->toContain('has_coold');+ Queue::assertPushed(V5ReconcileServerStateJob::class, 1);+ Queue::assertPushed(+ V5ReconcileServerStateJob::class,+ fn (V5ReconcileServerStateJob $job) => $job->serverId === $eligible->id,+ );+});++it('generates uuids only for models whose tables have a uuid column', function () {+ $server = createModelHygieneServer();++ expect($server->uuid)->not->toBeNull()+ ->and($server->getRouteKeyName())->toBe('uuid');++ // v5_container_statuses has no uuid column: the insert would fail if the+ // base model still tried to assign one.+ $containerStatus = ContainerStatus::query()->create([+ 'team_id' => 1,+ 'server_id' => $server->id,+ 'container_id' => 'abc123',+ 'status' => 'running',+ ]);++ expect($containerStatus->getAttribute('uuid'))->toBeNull()+ ->and($containerStatus->getRouteKeyName())->toBe('id')+ ->and((new ApplicationDomain)->getRouteKeyName())->toBe('id')+ ->and((new ResourceConnectionRule)->getRouteKeyName())->toBe('id');+});++it('keeps explicitly provided uuids', function () {+ $server = createModelHygieneServer(['uuid' => 'chosen-uuid']);++ expect($server->uuid)->toBe('chosen-uuid');+});++it('regenerates a colliding public id before inserting', function () {+ createModelHygieneServer(['uuid' => 'taken-uuid']);++ $colliding = new class extends V5Server+ {+ /** @var array<int, string> */+ public array $candidates = ['taken-uuid', 'fresh-uuid'];++ protected function newPublicIdCandidate(): string+ {+ return array_shift($this->candidates);+ }+ };++ $colliding->forceFill([+ 'team_id' => 1,+ 'created_by_user_id' => 1,+ 'name' => 'collision-node',+ 'host' => '203.0.113.99',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ ])->save();++ expect($colliding->uuid)->toBe('fresh-uuid');+});++function dropModelHygieneTables(): void+{+ Schema::dropIfExists('v5_resource_connection_rules');+ Schema::dropIfExists('v5_resource_connections');+ Schema::dropIfExists('v5_application_domains');+ Schema::dropIfExists('v5_applications');+ Schema::dropIfExists('v5_container_statuses');+ Schema::dropIfExists('v5_servers');+}++function createModelHygieneTables(): void+{+ V5TestSchema::createServersTable();+ V5TestSchema::createContainerStatusesTable();+ V5TestSchema::createApplicationsTable();+ V5TestSchema::createApplicationDomainsTable();+ V5TestSchema::createResourceConnectionsTable();+ V5TestSchema::createResourceConnectionRulesTable();+}++/**+ * @param array<string, mixed> $overrides+ */+function createModelHygieneServer(array $overrides = []): V5Server+{+ return V5Server::query()->create([+ 'team_id' => 1,+ 'created_by_user_id' => 1,+ 'name' => 'edge-01',+ 'host' => '203.0.113.'.random_int(2, 250),+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ ...$overrides,+ ]);+}++function createModelHygieneApplication(string $name): V5Application+{+ return V5Application::query()->create([+ 'team_id' => 1,+ 'project_id' => 1,+ 'environment_id' => 1,+ 'created_by_user_id' => 1,+ 'name' => $name,+ 'image' => "docker.io/library/{$name}:latest",+ 'container_name' => "coolify-v5-{$name}",+ ]);+}diff --git a/tests/Feature/V5/ReconcileServerStateTest.php b/tests/Feature/V5/ReconcileServerStateTest.phpnew file mode 100644index 0000000000..f47537968f--- /dev/null+++ b/tests/Feature/V5/ReconcileServerStateTest.php@@ -0,0 +1,397 @@+<?php++use App\Actions\V5\Flux\ApplyFluxResourceStatusUpdate;+use App\Events\V5CanvasResourceUpdated;+use App\Events\V5ClusterUpdated;+use App\Jobs\V5ReconcileServersJob;+use App\Jobs\V5ReconcileServerStateJob;+use App\Models\V5\Application as V5Application;+use App\Models\V5\ContainerStatus;+use App\Models\V5\Server as V5Server;+use App\Services\Flux\FluxClient;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Event;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Facades\Schema;+use Tests\Support\V5TestSchema;++beforeEach(function () {+ Config::set('broadcasting.default', 'log');+ Config::set('cache.default', 'array');++ Schema::dropIfExists('v5_applications');+ Schema::dropIfExists('v5_container_statuses');+ Schema::dropIfExists('v5_servers');+});++function createReconcileV5Tables(): void+{+ V5TestSchema::createServersTable();+ V5TestSchema::createContainerStatusesTable();+ V5TestSchema::createApplicationsTable();+}++/**+ * @param array<string, mixed> $attributes+ */+function createReconcileServer(array $attributes = []): V5Server+{+ return V5Server::query()->create([+ 'team_id' => 1,+ 'created_by_user_id' => 1,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['coold'],+ 'wireguard_management_ip' => '100.64.0.10',+ ...$attributes,+ ]);+}++/**+ * @param array<string, mixed> $attributes+ */+function createReconcileApplication(V5Server $server, array $attributes = []): V5Application+{+ return V5Application::query()->create([+ 'team_id' => $server->team_id,+ 'project_id' => 1,+ 'environment_id' => 1,+ 'server_id' => $server->id,+ 'created_by_user_id' => 1,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-test',+ 'status' => 'running',+ 'runtime_container_id' => 'container-live',+ ...$attributes,+ ]);+}++it('marks a stale running application exited when its container is gone', function () {+ createReconcileV5Tables();+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $server = createReconcileServer();+ $application = createReconcileApplication($server);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('listContainers')->once()->with($server->fluxHostId())->andReturn([]);++ (new V5ReconcileServerStateJob($server->id))->handle($fluxClient);++ expect($application->refresh())+ ->status->toBe('exited')+ ->status_message->toBe('Container not found on server during reconcile.');+ expect($server->refresh())+ ->status->toBe('installed')+ ->last_status_check->toBe('reconcile')+ ->last_status_checked_at->not->toBeNull();++ Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->applicationId === $application->id);+});++it('updates application status from the observed container state and refreshes container statuses', function () {+ createReconcileV5Tables();+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $server = createReconcileServer();+ $application = createReconcileApplication($server, ['runtime_container_id' => null]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('listContainers')->once()->andReturn([+ [+ 'id' => 'container-live',+ 'name' => 'coolify-v5-nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'state' => 'Restarting',+ ],+ ]);++ (new V5ReconcileServerStateJob($server->id))->handle($fluxClient);++ expect($application->refresh())+ ->status->toBe('restarting')+ ->runtime_container_id->toBe('container-live');++ $containerStatus = ContainerStatus::query()+ ->where('server_id', $server->id)+ ->where('container_id', 'container-live')+ ->first();++ expect($containerStatus)->not->toBeNull()+ ->and($containerStatus->status)->toBe('restarting')+ ->and($containerStatus->last_seen_at)->not->toBeNull();+});++it('leaves a creating application without a container id alone during reconcile', function () {+ createReconcileV5Tables();+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $server = createReconcileServer();+ $application = createReconcileApplication($server, [+ 'status' => 'creating',+ 'runtime_container_id' => null,+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('listContainers')->once()->andReturn([]);++ (new V5ReconcileServerStateJob($server->id))->handle($fluxClient);++ expect($application->refresh())->status->toBe('creating');+});++it('marks an installed server unreachable when the node cannot be reached', function () {+ createReconcileV5Tables();+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $server = createReconcileServer();+ $application = createReconcileApplication($server);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('listContainers')->once()->andThrow(new RuntimeException('Flux did not return a response before the timeout.'));++ (new V5ReconcileServerStateJob($server->id))->handle($fluxClient);++ expect($server->refresh())+ ->status->toBe('unreachable')+ ->last_status_check->toBe('reconcile')+ ->last_status_output->toContain('Flux did not return a response');+ expect($application->refresh())->status->toBe('running');++ Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->serverId === $server->id);+});++it('does not mark a failed server unreachable when the node cannot be reached', function () {+ createReconcileV5Tables();+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $server = createReconcileServer(['status' => 'failed']);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('listContainers')->once()->andThrow(new RuntimeException('boom'));++ (new V5ReconcileServerStateJob($server->id))->handle($fluxClient);++ expect($server->refresh())+ ->status->toBe('failed')+ ->last_status_check->toBe('reconcile');+});++it('restores an unreachable server to installed on a successful reconcile', function () {+ createReconcileV5Tables();+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $server = createReconcileServer(['status' => 'unreachable']);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('listContainers')->once()->andReturn([]);++ (new V5ReconcileServerStateJob($server->id))->handle($fluxClient);++ expect($server->refresh())+ ->status->toBe('installed')+ ->last_status_check->toBe('reconcile');++ Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->serverId === $server->id);+});++it('dispatches per-server reconcile jobs only for managed servers', function () {+ createReconcileV5Tables();+ Queue::fake();++ $managed = createReconcileServer(['host' => '203.0.113.10', 'wireguard_management_ip' => '100.64.0.10']);+ $unreachable = createReconcileServer([+ 'name' => 'edge-02',+ 'host' => '203.0.113.11',+ 'wireguard_management_ip' => '100.64.0.11',+ 'status' => 'unreachable',+ ]);+ $withoutCoold = createReconcileServer([+ 'name' => 'edge-03',+ 'host' => '203.0.113.12',+ 'wireguard_management_ip' => '100.64.0.12',+ 'capabilities' => [],+ ]);+ $notInstalled = createReconcileServer([+ 'name' => 'edge-04',+ 'host' => '203.0.113.13',+ 'wireguard_management_ip' => '100.64.0.13',+ 'status' => 'added',+ ]);++ (new V5ReconcileServersJob)->handle();++ Queue::assertPushed(V5ReconcileServerStateJob::class, 2);+ Queue::assertPushed(V5ReconcileServerStateJob::class, fn (V5ReconcileServerStateJob $job) => $job->serverId === $managed->id);+ Queue::assertPushed(V5ReconcileServerStateJob::class, fn (V5ReconcileServerStateJob $job) => $job->serverId === $unreachable->id);+ Queue::assertNotPushed(V5ReconcileServerStateJob::class, fn (V5ReconcileServerStateJob $job) => $job->serverId === $withoutCoold->id);+ Queue::assertNotPushed(V5ReconcileServerStateJob::class, fn (V5ReconcileServerStateJob $job) => $job->serverId === $notInstalled->id);+});++it('drops a reconcile write when the stored observation is newer than the snapshot', function () {+ createReconcileV5Tables();+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $server = createReconcileServer();+ $application = createReconcileApplication($server, [+ 'status' => 'running',+ 'runtime_container_id' => 'container-live',+ // A fresher webhook already advanced the watermark past this pull.+ 'status_observed_at' => now()->addMinutes(5),+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('listContainers')->once()->andReturn([+ ['id' => 'container-live', 'name' => 'coolify-v5-nginx-test', 'state' => 'exited'],+ ]);++ (new V5ReconcileServerStateJob($server->id))->handle($fluxClient);++ expect($application->refresh())+ ->status->toBe('running')+ ->status_observed_at->not->toBeNull();++ Event::assertNotDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->applicationId === $application->id);+});++it('advances status_observed_at when reconcile writes an application status', function () {+ createReconcileV5Tables();+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $server = createReconcileServer();+ $application = createReconcileApplication($server, [+ 'status' => 'running',+ 'runtime_container_id' => 'container-live',+ 'status_observed_at' => null,+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('listContainers')->once()->andReturn([+ ['id' => 'container-live', 'name' => 'coolify-v5-nginx-test', 'state' => 'restarting'],+ ]);++ (new V5ReconcileServerStateJob($server->id))->handle($fluxClient);++ expect($application->refresh())+ ->status->toBe('restarting')+ ->status_observed_at->not->toBeNull();+});++it('normalizes the coold configured state to a valid status on reconcile', function () {+ createReconcileV5Tables();+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $server = createReconcileServer();+ $application = createReconcileApplication($server);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('listContainers')->once()->andReturn([+ ['id' => 'container-live', 'name' => 'coolify-v5-nginx-test', 'state' => 'configured'],+ ]);++ (new V5ReconcileServerStateJob($server->id))->handle($fluxClient);++ expect($application->refresh()->status)->toBe('configured');++ $containerStatus = ContainerStatus::query()+ ->where('server_id', $server->id)+ ->where('container_id', 'container-live')+ ->first();++ expect($containerStatus)->not->toBeNull()+ ->and($containerStatus->status)->toBe('configured');+});++it('normalizes the coold configured state on the flux webhook path', function () {+ createReconcileV5Tables();+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $server = createReconcileServer();+ $application = createReconcileApplication($server, ['runtime_container_id' => 'container-live']);++ ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'application',+ 'server_uuid' => $server->uuid,+ 'application_uuid' => $application->uuid,+ 'status' => 'configured',+ 'runtime_container_id' => 'container-live',+ ]);++ expect($application->refresh()->status)->toBe('configured');+});++it('does not broadcast when reconcile finds the application status unchanged', function () {+ createReconcileV5Tables();+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $server = createReconcileServer();+ $application = createReconcileApplication($server, [+ 'status' => 'running',+ 'runtime_container_id' => 'container-live',+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('listContainers')->once()->andReturn([+ ['id' => 'container-live', 'name' => 'coolify-v5-nginx-test', 'state' => 'running'],+ ]);++ (new V5ReconcileServerStateJob($server->id))->handle($fluxClient);++ expect($application->refresh()->status)->toBe('running');++ Event::assertNotDispatched(V5CanvasResourceUpdated::class);+});++it('runs the reconcile jobs on the dedicated v5-reconcile queue', function () {+ expect((new V5ReconcileServersJob)->queue)->toBe('v5-reconcile')+ ->and((new V5ReconcileServerStateJob(1))->queue)->toBe('v5-reconcile');+});++it('prunes stale and orphaned container statuses but keeps fresh and live rows', function () {+ createReconcileV5Tables();+ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);+ Queue::fake();++ $server = createReconcileServer();+ createReconcileApplication($server, ['runtime_container_id' => 'container-live']);++ $staleRow = ContainerStatus::query()->create([+ 'team_id' => 1,+ 'server_id' => $server->id,+ 'container_id' => 'container-stale',+ 'status' => 'running',+ 'last_seen_at' => now()->subHours(V5ReconcileServersJob::CONTAINER_STATUS_TTL_HOURS + 1),+ ]);+ $staleButLiveRow = ContainerStatus::query()->create([+ 'team_id' => 1,+ 'server_id' => $server->id,+ 'container_id' => 'container-live',+ 'status' => 'running',+ 'last_seen_at' => now()->subHours(V5ReconcileServersJob::CONTAINER_STATUS_TTL_HOURS + 1),+ ]);+ $freshRow = ContainerStatus::query()->create([+ 'team_id' => 1,+ 'server_id' => $server->id,+ 'container_id' => 'container-fresh',+ 'status' => 'running',+ 'last_seen_at' => now()->subHour(),+ ]);+ $orphanedServerRow = ContainerStatus::query()->create([+ 'team_id' => 1,+ 'server_id' => $server->id + 999,+ 'container_id' => 'container-orphaned',+ 'status' => 'running',+ 'last_seen_at' => now()->subHour(),+ ]);++ (new V5ReconcileServersJob)->handle();++ expect(ContainerStatus::query()->find($staleRow->id))->toBeNull()+ ->and(ContainerStatus::query()->find($orphanedServerRow->id))->toBeNull()+ ->and(ContainerStatus::query()->find($staleButLiveRow->id))->not->toBeNull()+ ->and(ContainerStatus::query()->find($freshRow->id))->not->toBeNull();+});diff --git a/tests/Feature/V5/RemoveBootstrapMarkerTest.php b/tests/Feature/V5/RemoveBootstrapMarkerTest.phpnew file mode 100644index 0000000000..ef1bf2ff47--- /dev/null+++ b/tests/Feature/V5/RemoveBootstrapMarkerTest.php@@ -0,0 +1,111 @@+<?php++use App\Actions\V5\Server\RemoveBootstrapMarker;+use App\Models\V5\Server as V5Server;+use Illuminate\Support\Facades\Process;++beforeEach(function () {+ resetV5DashboardTestState();+ createSharedUserAndTeamTables();+});++/**+ * @param array<string, mixed> $attributes+ */+function createRemoveMarkerServer(array $attributes = []): V5Server+{+ [$user, $team] = createV5UserWithTeam();++ return V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 2222,+ 'status' => 'installed',+ ...$attributes,+ ]);+}++/**+ * @param array<int, mixed> $command+ */+function removeMarkerSshKeyPath(array $command): ?string+{+ $index = array_search('-i', $command, true);++ return $index === false ? null : ($command[$index + 1] ?? null);+}++it('returns false and runs no ssh command when the server has no private key', function () {+ Process::fake();++ $server = createRemoveMarkerServer(['private_key_id' => null]);++ expect(RemoveBootstrapMarker::run($server))->toBeFalse();++ Process::assertNothingRan();+});++it('removes the on-host bootstrap identity over ssh and deletes the temporary key file', function () {+ Process::fake(['*' => Process::result(output: '')]);++ $server = createRemoveMarkerServer();+ $privateKey = createV5PrivateKey($server->team, 'Marker Removal Key');+ $server->update(['private_key_id' => $privateKey->id]);++ expect(RemoveBootstrapMarker::run($server->fresh()))->toBeTrue();++ $keyPath = null;++ Process::assertRan(function ($process) use (&$keyPath): bool {+ $command = $process->command;++ if (! is_array($command) || ($command[0] ?? null) !== 'ssh') {+ return false;+ }++ $script = end($command);++ if (! str_contains($script, '$SUDO rm -f /etc/coolify/v5-node.json /etc/coolify/host-jwt /etc/systemd/system/coold.service.d/10-flux.conf')) {+ return false;+ }++ if (! in_array('[email protected]', $command, true) || ! in_array('2222', $command, true)) {+ return false;+ }++ $keyPath = removeMarkerSshKeyPath($command);++ return true;+ });++ expect($keyPath)->not->toBeNull()+ ->and(file_exists($keyPath))->toBeFalse();+});++it('returns false but still deletes the temporary key file when the ssh command fails', function () {+ Process::fake(['*' => Process::result(errorOutput: 'connection refused', exitCode: 255)]);++ $server = createRemoveMarkerServer();+ $privateKey = createV5PrivateKey($server->team, 'Marker Removal Key');+ $server->update(['private_key_id' => $privateKey->id]);++ expect(RemoveBootstrapMarker::run($server->fresh()))->toBeFalse();++ $keyPath = null;++ Process::assertRan(function ($process) use (&$keyPath): bool {+ if (! is_array($process->command) || ($process->command[0] ?? null) !== 'ssh') {+ return false;+ }++ $keyPath = removeMarkerSshKeyPath($process->command);++ return true;+ });++ expect($keyPath)->not->toBeNull()+ ->and(file_exists($keyPath))->toBeFalse();+});diff --git a/tests/Feature/V5/ResourceConnectionControllerTest.php b/tests/Feature/V5/ResourceConnectionControllerTest.phpnew file mode 100644index 0000000000..21a0557766--- /dev/null+++ b/tests/Feature/V5/ResourceConnectionControllerTest.php@@ -0,0 +1,626 @@+<?php++use App\Models\V5\Application as V5Application;+use App\Models\V5\Cluster;+use App\Models\V5\ResourceConnection;+use App\Models\V5\Server as V5Server;+use App\Services\Flux\FluxClient;+use Illuminate\Support\Facades\Exceptions;++beforeEach(function () {+ resetV5DashboardTestState();+});++it('uses v5 resource uuids for resource connection requests and responses', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.10',+ ]);+ $source = V5Application::query()->create([+ 'uuid' => 'source-application-uuid',+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'source',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'source-container',+ 'status' => 'running',+ ]);+ $target = V5Application::query()->create([+ 'uuid' => 'target-application-uuid',+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'target',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'target-container',+ 'status' => 'running',+ ]);++ $response = $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ ])+ ->postJson('/v5/resource-connections', [+ 'resource_one' => ['type' => 'application', 'uuid' => $source->uuid],+ 'resource_two' => ['type' => 'application', 'uuid' => $target->uuid],+ ])+ ->assertCreated()+ ->assertJsonPath('connection.fromApplicationId', $source->uuid)+ ->assertJsonPath('connection.toApplicationId', $target->uuid);++ $connectionUuid = $response->json('connection.id');++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('applyFirewallRule')->once()->andReturn('Firewall rule applied.');+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/resource-connections/{$connectionUuid}", [+ 'ports_by_direction' => [+ "{$source->uuid}->{$target->uuid}" => [8080],+ ],+ ])+ ->assertSuccessful()+ ->assertJsonPath("connection.portsByDirection.{$source->uuid}->{$target->uuid}.0", '8080');++ expect(ResourceConnection::query()->first())+ ->resource_one_id->toBe($source->id)+ ->resource_two_id->toBe($target->id);+});++it('persists generic v5 resource connections and direction-specific ports', function () {+ app()->detectEnvironment(fn () => 'local');++ $this->withoutVite();+ fakeFluxHealth();+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.10',+ ]);+ $source = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-source',+ 'status' => 'running',+ ]);+ $target = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-target',+ 'status' => 'running',+ ]);++ $response = $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ '_token' => 'test-csrf-token',+ ])+ ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')+ ->postJson('/v5/resource-connections', [+ 'resource_one' => ['type' => 'application', 'uuid' => $source->uuid],+ 'resource_two' => ['type' => 'application', 'uuid' => $target->uuid],+ ])+ ->assertCreated()+ ->assertJsonPath('connection.applicationIds.0', $source->uuid)+ ->assertJsonPath('connection.applicationIds.1', $target->uuid);++ $connectionId = $response->json('connection.id');++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('applyFirewallRule')->twice()->andReturn('Firewall rule applied.');+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])+ ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')+ ->patchJson("/v5/resource-connections/{$connectionId}", [+ 'ports_by_direction' => [+ "{$source->uuid}->{$target->uuid}" => [80],+ "{$target->uuid}->{$source->uuid}" => [443],+ ],+ ])+ ->assertSuccessful()+ ->assertJsonPath("connection.portsByDirection.{$source->uuid}->{$target->uuid}.0", '80')+ ->assertJsonPath("connection.portsByDirection.{$target->uuid}->{$source->uuid}.0", '443');++ $this+ ->actingAs($user)+ ->withSession([+ 'currentTeam' => $team,+ 'v5.selectedProjectUuid' => $project->uuid,+ 'v5.selectedEnvironmentUuid' => $environment->uuid,+ ])+ ->get('/v5')+ ->assertSuccessful()+ ->assertSee('"resourceConnections":[', false)+ ->assertSee("\"id\":\"{$connectionId}\"", false)+ ->assertSee("\"{$source->uuid}->{$target->uuid}\":[\"80\"]", false)+ ->assertSee("\"{$target->uuid}->{$source->uuid}\":[\"443\"]", false);+});++it('reports flux failures when syncing v5 resource connection firewall rules', function () {+ app()->detectEnvironment(fn () => 'local');++ $this->withoutVite();+ createSharedUserAndTeamTables();+ Exceptions::fake();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'wireguard_management_ip' => '100.64.0.10',+ 'capabilities' => [],+ ]);+ $source = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'api',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-api',+ 'mesh_namespace' => 'default',+ 'status' => 'running',+ ]);+ $target = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'postgres',+ 'image' => 'docker.io/library/postgres:16',+ 'container_name' => 'coolify-v5-postgres',+ 'mesh_namespace' => 'default',+ 'status' => 'running',+ ]);++ $connection = ResourceConnection::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'resource_one_type' => $source->getMorphClass(),+ 'resource_one_id' => $source->id,+ 'resource_two_type' => $target->getMorphClass(),+ 'resource_two_id' => $target->id,+ 'resource_pair_key' => "application:{$source->id}|application:{$target->id}",+ 'created_by_user_id' => $user->id,+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient+ ->shouldReceive('applyFirewallRule')+ ->once()+ ->andThrow(new RuntimeException('resolve firewall endpoint coolify-v5-api on coolify-default-mesh'));+ // The compensation pass rolls the node back by revoking the attempted rule.+ $fluxClient+ ->shouldReceive('revokeFirewallRule')+ ->once()+ ->with(Mockery::type('string'), "v5-resource-connection:{$connection->id}:{$source->id}:{$target->id}:tcp:5432")+ ->andReturn('Firewall rule removed.');+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])+ ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')+ ->patchJson("/v5/resource-connections/{$connection->uuid}", [+ 'ports_by_direction' => [+ "{$source->uuid}->{$target->uuid}" => [5432],+ ],+ ])+ ->assertStatus(502)+ ->assertJsonPath('message', 'Could not sync firewall rules through Flux.')+ ->assertJsonPath('detail', 'The previous rules were restored. Check the server diagnostics and try again.');++ expect($connection->rules()->count())->toBe(0);++ // The raw Flux/coold error is never leaked to the client, only reported server-side.+ Exceptions::assertReported(fn (RuntimeException $exception): bool => $exception->getMessage() === 'resolve firewall endpoint coolify-v5-api on coolify-default-mesh');+});++it('syncs cross-server v5 resource connection ports on both endpoint hosts', function () {+ app()->detectEnvironment(fn () => 'local');++ $this->withoutVite();+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ ]);+ $sourceServer = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'wireguard_management_ip' => '100.64.0.10',+ 'capabilities' => [],+ ]);+ $targetServer = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-02',+ 'host' => '203.0.113.11',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'wireguard_management_ip' => '100.64.0.11',+ 'capabilities' => [],+ ]);+ $source = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $sourceServer->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'api',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-api',+ 'mesh_namespace' => 'default',+ 'status' => 'running',+ ]);+ $target = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $targetServer->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'postgres',+ 'image' => 'docker.io/library/postgres:16',+ 'container_name' => 'coolify-v5-postgres',+ 'mesh_namespace' => 'default',+ 'status' => 'running',+ ]);++ $connection = ResourceConnection::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'resource_one_type' => $source->getMorphClass(),+ 'resource_one_id' => $source->id,+ 'resource_two_type' => $target->getMorphClass(),+ 'resource_two_id' => $target->id,+ 'resource_pair_key' => "application:{$source->id}|application:{$target->id}",+ 'created_by_user_id' => $user->id,+ ]);++ $firewallRuleId = "v5-resource-connection:{$connection->id}:{$source->id}:{$target->id}:tcp:5432";+ $expectedRule = [+ 'id' => $firewallRuleId,+ 'namespace' => 'default',+ 'src' => 'coolify-v5-api',+ 'dst' => 'coolify-v5-postgres',+ 'proto' => 'tcp',+ 'port' => 5432,+ ];++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient+ ->shouldReceive('applyFirewallRule')+ ->once()+ ->with(Mockery::type('string'), $expectedRule)+ ->andReturn('Firewall rule applied on source host.');+ $fluxClient+ ->shouldReceive('applyFirewallRule')+ ->once()+ ->with(Mockery::type('string'), $expectedRule)+ ->andReturn('Firewall rule applied on target host.');+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])+ ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')+ ->patchJson("/v5/resource-connections/{$connection->uuid}", [+ 'ports_by_direction' => [+ "{$source->uuid}->{$target->uuid}" => [5432],+ ],+ ])+ ->assertSuccessful();+});++it('syncs v5 resource connection ports through flux firewall primitives', function () {+ app()->detectEnvironment(fn () => 'local');++ $this->withoutVite();+ $this->withoutExceptionHandling();+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'wireguard_management_ip' => '100.64.0.10',+ 'capabilities' => [],+ ]);+ $source = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'api',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-api',+ 'mesh_namespace' => 'default',+ 'status' => 'running',+ ]);+ $target = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'postgres',+ 'image' => 'docker.io/library/postgres:16',+ 'container_name' => 'coolify-v5-postgres',+ 'mesh_namespace' => 'default',+ 'status' => 'running',+ ]);++ $connection = ResourceConnection::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'resource_one_type' => $source->getMorphClass(),+ 'resource_one_id' => $source->id,+ 'resource_two_type' => $target->getMorphClass(),+ 'resource_two_id' => $target->id,+ 'resource_pair_key' => "application:{$source->id}|application:{$target->id}",+ 'created_by_user_id' => $user->id,+ ]);++ $firewallRuleId = "v5-resource-connection:{$connection->id}:{$source->id}:{$target->id}:tcp:5432";++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient+ ->shouldReceive('applyFirewallRule')+ ->once()+ ->with(Mockery::type('string'), [+ 'id' => $firewallRuleId,+ 'namespace' => 'default',+ 'src' => 'coolify-v5-api',+ 'dst' => 'coolify-v5-postgres',+ 'proto' => 'tcp',+ 'port' => 5432,+ ])+ ->andReturn('rule-api-postgres');+ $fluxClient+ ->shouldReceive('revokeFirewallRule')+ ->once()+ ->with(Mockery::type('string'), $firewallRuleId)+ ->andReturn('Firewall rule removed.');+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])+ ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')+ ->patchJson("/v5/resource-connections/{$connection->uuid}", [+ 'ports_by_direction' => [+ "{$source->uuid}->{$target->uuid}" => [5432],+ ],+ ])+ ->assertSuccessful();++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])+ ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')+ ->deleteJson("/v5/resource-connections/{$connection->uuid}")+ ->assertNoContent();+});++it('rejects firewall sync when a connected application has no server host id', function () {+ createSharedUserAndTeamTables();+ Exceptions::fake();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ ]);+ $source = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'api',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-api',+ 'status' => 'running',+ ]);+ $target = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'postgres',+ 'image' => 'docker.io/library/postgres:16',+ 'container_name' => 'coolify-v5-postgres',+ 'status' => 'running',+ ]);+ $connection = ResourceConnection::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'resource_one_type' => $source->getMorphClass(),+ 'resource_one_id' => $source->id,+ 'resource_two_type' => $target->getMorphClass(),+ 'resource_two_id' => $target->id,+ 'resource_pair_key' => "application:{$source->id}|application:{$target->id}",+ 'created_by_user_id' => $user->id,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])+ ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')+ ->patchJson("/v5/resource-connections/{$connection->uuid}", [+ 'ports_by_direction' => [+ "{$source->uuid}->{$target->uuid}" => [5432],+ ],+ ])+ ->assertStatus(502)+ ->assertJsonPath('detail', 'The previous rules were restored. Check the server diagnostics and try again.');++ expect($connection->rules()->count())->toBe(0);+});++it('still deletes a v5 resource connection whose endpoint lost its server host id', function () {+ createSharedUserAndTeamTables();+ Exceptions::fake();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ ]);+ $source = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'api',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-api',+ 'status' => 'running',+ ]);+ $target = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'postgres',+ 'image' => 'docker.io/library/postgres:16',+ 'container_name' => 'coolify-v5-postgres',+ 'status' => 'running',+ ]);+ $connection = ResourceConnection::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'resource_one_type' => $source->getMorphClass(),+ 'resource_one_id' => $source->id,+ 'resource_two_type' => $target->getMorphClass(),+ 'resource_two_id' => $target->id,+ 'resource_pair_key' => "application:{$source->id}|application:{$target->id}",+ 'created_by_user_id' => $user->id,+ ]);+ $connection->rules()->create([+ 'source_resource_type' => $source->getMorphClass(),+ 'source_resource_id' => $source->id,+ 'target_resource_type' => $target->getMorphClass(),+ 'target_resource_id' => $target->id,+ 'protocol' => 'tcp',+ 'port' => 5432,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])+ ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')+ ->deleteJson("/v5/resource-connections/{$connection->uuid}")+ ->assertNoContent();++ expect(ResourceConnection::query()->whereKey($connection->id)->exists())->toBeFalse();+});diff --git a/tests/Feature/V5/ResourceConnectionFirewallConsistencyTest.php b/tests/Feature/V5/ResourceConnectionFirewallConsistencyTest.phpnew file mode 100644index 0000000000..a3d234f12a--- /dev/null+++ b/tests/Feature/V5/ResourceConnectionFirewallConsistencyTest.php@@ -0,0 +1,370 @@+<?php++use App\Exceptions\V5\UnsupportedCooldVerb;+use App\Models\Team;+use App\Models\User;+use App\Models\V5\Application as V5Application;+use App\Models\V5\ResourceConnection;+use App\Models\V5\Server as V5Server;+use App\Services\Flux\FluxClient;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Exceptions;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Facades\Schema;+use Tests\Support\V5TestSchema;++beforeEach(function () {+ Config::set('broadcasting.default', 'log');+ Config::set('cache.default', 'array');++ dropConnectionFirewallConsistencyTables();+ createConnectionFirewallConsistencyTables();+});++it('restores db rules and rolls back node firewall when flux fails after the db write', function () {+ Exceptions::fake();++ $context = createConnectionFirewallConsistencyContext();+ ['user' => $user, 'team' => $team, 'source' => $source, 'target' => $target, 'connection' => $connection] = $context;++ $connection->rules()->create([+ 'source_resource_type' => $source->getMorphClass(),+ 'source_resource_id' => $source->id,+ 'target_resource_type' => $target->getMorphClass(),+ 'target_resource_id' => $target->id,+ 'protocol' => 'tcp',+ 'port' => 5432,+ ]);++ $oldRuleId = "v5-resource-connection:{$connection->id}:{$source->id}:{$target->id}:tcp:5432";+ $newRuleId = "v5-resource-connection:{$connection->id}:{$source->id}:{$target->id}:tcp:6379";+ $oldRule = connectionFirewallConsistencyRule($oldRuleId, 5432);+ $newRule = connectionFirewallConsistencyRule($newRuleId, 6379);++ $fluxClient = Mockery::mock(FluxClient::class);+ // Forward sync: revoke the removed old rule, then fail applying the new one.+ $fluxClient->shouldReceive('revokeFirewallRule')->once()->with(Mockery::type('string'), $oldRuleId)->andReturn('Firewall rule removed.');+ $fluxClient->shouldReceive('applyFirewallRule')->once()->with(Mockery::type('string'), $newRule)->andThrow(new RuntimeException('apply firewall rule: nft exited with status 1'));+ // Compensation: revoke the attempted new rule and re-apply the restored old rule.+ $fluxClient->shouldReceive('revokeFirewallRule')->once()->with(Mockery::type('string'), $newRuleId)->andReturn('Firewall rule removed.');+ $fluxClient->shouldReceive('applyFirewallRule')->once()->with(Mockery::type('string'), $oldRule)->andReturn('Firewall rule applied.');+ app()->instance(FluxClient::class, $fluxClient);++ patchConnectionFirewallConsistency($this, $user, $team, $connection, [+ "{$source->uuid}->{$target->uuid}" => [6379],+ ])+ ->assertStatus(502)+ ->assertJsonPath('message', 'Could not sync firewall rules through Flux.')+ ->assertJsonPath('detail', 'The previous rules were restored. Check the server diagnostics and try again.');++ expect($connection->rules()->pluck('port')->all())->toBe([5432]);++ Exceptions::assertReported(fn (RuntimeException $exception): bool => $exception->getMessage() === 'apply firewall rule: nft exited with status 1');+});++it('keeps committed db rules and succeeds when the node coold lacks firewall support', function () {+ $context = createConnectionFirewallConsistencyContext();+ ['user' => $user, 'team' => $team, 'source' => $source, 'target' => $target, 'connection' => $connection] = $context;++ $connection->rules()->create([+ 'source_resource_type' => $source->getMorphClass(),+ 'source_resource_id' => $source->id,+ 'target_resource_type' => $target->getMorphClass(),+ 'target_resource_id' => $target->id,+ 'protocol' => 'tcp',+ 'port' => 5432,+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('revokeFirewallRule')->once()->andThrow(new UnsupportedCooldVerb('firewall.revoke', 'primitive firewall.revoke is not supported by host'));+ $fluxClient->shouldReceive('applyFirewallRule')->once()->andThrow(new UnsupportedCooldVerb('firewall.allow', 'primitive firewall.allow is not supported by host'));+ app()->instance(FluxClient::class, $fluxClient);++ patchConnectionFirewallConsistency($this, $user, $team, $connection, [+ "{$source->uuid}->{$target->uuid}" => [6379],+ ])+ ->assertSuccessful()+ ->assertJsonPath("connection.portsByDirection.{$source->uuid}->{$target->uuid}.0", '6379');++ expect($connection->rules()->pluck('port')->all())->toBe([6379]);+});++it('still surfaces the original flux error when the firewall rollback also fails', function () {+ Exceptions::fake();+ Log::spy();++ $context = createConnectionFirewallConsistencyContext();+ ['user' => $user, 'team' => $team, 'source' => $source, 'target' => $target, 'connection' => $connection] = $context;++ $connection->rules()->create([+ 'source_resource_type' => $source->getMorphClass(),+ 'source_resource_id' => $source->id,+ 'target_resource_type' => $target->getMorphClass(),+ 'target_resource_id' => $target->id,+ 'protocol' => 'tcp',+ 'port' => 5432,+ ]);++ $oldRuleId = "v5-resource-connection:{$connection->id}:{$source->id}:{$target->id}:tcp:5432";+ $newRuleId = "v5-resource-connection:{$connection->id}:{$source->id}:{$target->id}:tcp:6379";+ $newRule = connectionFirewallConsistencyRule($newRuleId, 6379);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('revokeFirewallRule')->once()->with(Mockery::type('string'), $oldRuleId)->andReturn('Firewall rule removed.');+ $fluxClient->shouldReceive('applyFirewallRule')->once()->with(Mockery::type('string'), $newRule)->andThrow(new RuntimeException('apply firewall rule: nft exited with status 1'));+ $fluxClient->shouldReceive('revokeFirewallRule')->once()->with(Mockery::type('string'), $newRuleId)->andThrow(new RuntimeException('revoke firewall rule: coold connection reset'));+ app()->instance(FluxClient::class, $fluxClient);++ patchConnectionFirewallConsistency($this, $user, $team, $connection, [+ "{$source->uuid}->{$target->uuid}" => [6379],+ ])+ ->assertStatus(502)+ ->assertJsonPath('detail', 'The previous rules were restored. Check the server diagnostics and try again.');++ expect($connection->rules()->pluck('port')->all())->toBe([5432]);++ Log::shouldHaveReceived('warning')+ ->withArgs(fn (string $message): bool => str_contains($message, 'firewall rollback failed'))+ ->once();+});++it('does not delete the connection when revoking firewall rules fails with a real error', function () {+ Exceptions::fake();++ $context = createConnectionFirewallConsistencyContext();+ ['user' => $user, 'team' => $team, 'source' => $source, 'target' => $target, 'connection' => $connection] = $context;++ $connection->rules()->create([+ 'source_resource_type' => $source->getMorphClass(),+ 'source_resource_id' => $source->id,+ 'target_resource_type' => $target->getMorphClass(),+ 'target_resource_id' => $target->id,+ 'protocol' => 'tcp',+ 'port' => 5432,+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('revokeFirewallRule')->once()->andThrow(new RuntimeException('revoke firewall rule: nft exited with status 1'));+ app()->instance(FluxClient::class, $fluxClient);++ deleteConnectionFirewallConsistency($this, $user, $team, $connection)+ ->assertStatus(502)+ ->assertJsonPath('detail', 'The connection was not deleted. Check the server diagnostics and try again.');++ expect(ResourceConnection::query()->whereKey($connection->id)->exists())->toBeTrue()+ ->and($connection->rules()->count())->toBe(1);++ Exceptions::assertReported(fn (RuntimeException $exception): bool => $exception->getMessage() === 'revoke firewall rule: nft exited with status 1');+});++it('reports but tolerates an unbuildable firewall snapshot when deleting the connection', function () {+ Exceptions::fake();++ $context = createConnectionFirewallConsistencyContext(sourceServerless: true);+ ['user' => $user, 'team' => $team, 'source' => $source, 'target' => $target, 'connection' => $connection] = $context;++ $connection->rules()->create([+ 'source_resource_type' => $source->getMorphClass(),+ 'source_resource_id' => $source->id,+ 'target_resource_type' => $target->getMorphClass(),+ 'target_resource_id' => $target->id,+ 'protocol' => 'tcp',+ 'port' => 5432,+ ]);++ // The node cannot be addressed without a host id, so no flux call may happen.+ $fluxClient = Mockery::mock(FluxClient::class);+ app()->instance(FluxClient::class, $fluxClient);++ deleteConnectionFirewallConsistency($this, $user, $team, $connection)+ ->assertNoContent();++ expect(ResourceConnection::query()->whereKey($connection->id)->exists())->toBeFalse();++ Exceptions::assertReported(fn (RuntimeException $exception): bool => str_contains($exception->getMessage(), 'has no reachable server host id'));+});++it('deletes the connection when the node coold lacks firewall revoke support', function () {+ $context = createConnectionFirewallConsistencyContext();+ ['user' => $user, 'team' => $team, 'source' => $source, 'target' => $target, 'connection' => $connection] = $context;++ $connection->rules()->create([+ 'source_resource_type' => $source->getMorphClass(),+ 'source_resource_id' => $source->id,+ 'target_resource_type' => $target->getMorphClass(),+ 'target_resource_id' => $target->id,+ 'protocol' => 'tcp',+ 'port' => 5432,+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('revokeFirewallRule')->once()->andThrow(new UnsupportedCooldVerb('firewall.revoke', 'primitive firewall.revoke is not supported by host'));+ app()->instance(FluxClient::class, $fluxClient);++ deleteConnectionFirewallConsistency($this, $user, $team, $connection)+ ->assertNoContent();++ expect(ResourceConnection::query()->whereKey($connection->id)->exists())->toBeFalse();+});++/**+ * @param array<string, array<int, int>> $portsByDirection+ */+function patchConnectionFirewallConsistency(mixed $test, User $user, Team $team, ResourceConnection $connection, array $portsByDirection): mixed+{+ return $test+ ->actingAs($user)+ ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])+ ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')+ ->patchJson("/v5/resource-connections/{$connection->uuid}", [+ 'ports_by_direction' => $portsByDirection,+ ]);+}++function deleteConnectionFirewallConsistency(mixed $test, User $user, Team $team, ResourceConnection $connection): mixed+{+ return $test+ ->actingAs($user)+ ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])+ ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')+ ->deleteJson("/v5/resource-connections/{$connection->uuid}");+}++/**+ * @return array{id: string, namespace: string, src: string, dst: string, proto: string, port: int}+ */+function connectionFirewallConsistencyRule(string $ruleId, int $port): array+{+ return [+ 'id' => $ruleId,+ 'namespace' => 'default',+ 'src' => 'coolify-v5-consistency-api',+ 'dst' => 'coolify-v5-consistency-postgres',+ 'proto' => 'tcp',+ 'port' => $port,+ ];+}++/**+ * @return array{user: User, team: Team, source: V5Application, target: V5Application, connection: ResourceConnection}+ */+function createConnectionFirewallConsistencyContext(bool $sourceServerless = false): array+{+ $user = User::withoutEvents(fn () => User::query()->create([+ 'name' => 'Margaret Hamilton',+ 'email' => '[email protected]',+ 'email_verified_at' => now(),+ 'password' => 'password',+ ]));+ $team = Team::withoutEvents(fn () => Team::query()->create([+ 'name' => 'V5 Firewall Team',+ 'description' => null,+ 'personal_team' => false,+ 'show_boarding' => false,+ ]));+ $user->teams()->attach($team, ['role' => 'owner']);++ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'wireguard_management_ip' => '100.64.0.10',+ ]);++ $source = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => 1,+ 'environment_id' => 1,+ 'server_id' => $sourceServerless ? null : $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'api',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-consistency-api',+ 'mesh_namespace' => 'default',+ 'status' => 'running',+ ]);+ $target = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => 1,+ 'environment_id' => 1,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'postgres',+ 'image' => 'docker.io/library/postgres:16',+ 'container_name' => 'coolify-v5-consistency-postgres',+ 'mesh_namespace' => 'default',+ 'status' => 'running',+ ]);++ $connection = ResourceConnection::query()->create([+ 'team_id' => $team->id,+ 'project_id' => 1,+ 'environment_id' => 1,+ 'resource_one_type' => $source->getMorphClass(),+ 'resource_one_id' => $source->id,+ 'resource_two_type' => $target->getMorphClass(),+ 'resource_two_id' => $target->id,+ 'resource_pair_key' => "application:{$source->id}|application:{$target->id}",+ 'created_by_user_id' => $user->id,+ ]);++ return [+ 'user' => $user,+ 'team' => $team,+ 'source' => $source,+ 'target' => $target,+ 'connection' => $connection,+ ];+}++function createConnectionFirewallConsistencyTables(): void+{+ Schema::create('users', function ($table) {+ $table->id();+ $table->string('name')->default('Anonymous');+ $table->string('email');+ $table->timestamp('email_verified_at')->nullable();+ $table->string('password')->nullable();+ $table->rememberToken();+ $table->timestamps();+ });++ Schema::create('teams', function ($table) {+ $table->id();+ $table->string('name');+ $table->string('description')->nullable();+ $table->boolean('personal_team')->default(false);+ $table->boolean('show_boarding')->default(false);+ $table->timestamps();+ });++ Schema::create('team_user', function ($table) {+ $table->id();+ $table->foreignId('team_id');+ $table->foreignId('user_id');+ $table->string('role')->default('member');+ $table->timestamps();++ $table->unique(['team_id', 'user_id']);+ });++ V5TestSchema::createServersTable();+ V5TestSchema::createApplicationsTable();+ V5TestSchema::createResourceConnectionsTable();+ V5TestSchema::createResourceConnectionRulesTable();+}++function dropConnectionFirewallConsistencyTables(): void+{+ Schema::dropIfExists('v5_resource_connection_rules');+ Schema::dropIfExists('v5_resource_connections');+ Schema::dropIfExists('v5_applications');+ Schema::dropIfExists('v5_servers');+ Schema::dropIfExists('team_user');+ Schema::dropIfExists('teams');+ Schema::dropIfExists('users');+}diff --git a/tests/Feature/V5/ServerControllerTest.php b/tests/Feature/V5/ServerControllerTest.phpnew file mode 100644index 0000000000..b7f9f9b303--- /dev/null+++ b/tests/Feature/V5/ServerControllerTest.php@@ -0,0 +1,1459 @@+<?php++use App\Models\Team;+use App\Models\V5\Application as V5Application;+use App\Models\V5\ApplicationDomain as V5ApplicationDomain;+use App\Models\V5\Cluster;+use App\Models\V5\Server as V5Server;+use App\Services\Flux\FluxClient;+use Illuminate\Support\Facades\Process;+use Illuminate\Support\Facades\Queue;+use Mockery\MockInterface;++beforeEach(function () {+ resetV5DashboardTestState();+});++it('updates v5 caddy ingress canvas position for the current team', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-ingress-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['ingress'],+ 'canvas_x' => -352,+ 'canvas_y' => 0,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/caddy-ingresses/{$server->uuid}/position", [+ 'canvas_x' => -160,+ 'canvas_y' => 240,+ ])+ ->assertSuccessful()+ ->assertJsonPath('caddyIngress.canvasX', -160)+ ->assertJsonPath('caddyIngress.canvasY', 240);++ expect($server->refresh()->canvas_x)->toBe(-160)+ ->and($server->canvas_y)->toBe(240);+});++it('fetches v5 server coold logs through flux', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'wireguard_management_ip' => '100.64.0.10',+ 'node_address' => '203.0.113.10',+ ]);++ $this->mock(FluxClient::class, function (MockInterface $mock): void {+ $mock->shouldReceive('cooldLogs')+ ->once()+ ->with(Mockery::type('string'), 200)+ ->andReturn('Jun 22 coold[123]: started');+ });++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->getJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/coold-logs?tail=200")+ ->assertSuccessful()+ ->assertJsonPath('output', 'Jun 22 coold[123]: started')+ ->assertJsonStructure(['output', 'fetchedAt']);+});++it('falls back to ssh for v5 server coold logs when the host is not connected to flux', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'wireguard_management_ip' => '100.64.0.10',+ 'node_address' => '203.0.113.10',+ ]);++ $this->mock(FluxClient::class, function (MockInterface $mock): void {+ $mock->shouldReceive('cooldLogs')+ ->once()+ ->with(Mockery::type('string'), 50)+ ->andThrow(new RuntimeException('host is not connected'));+ });++ Process::fake([+ '*' => Process::result(output: "Jul 06 coold[123]: reconnecting\n"),+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->getJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/coold-logs?tail=50")+ ->assertSuccessful()+ ->assertJsonPath('output', 'Jul 06 coold[123]: reconnecting')+ ->assertJsonPath('source', 'ssh')+ ->assertJsonStructure(['output', 'source', 'fetchedAt']);++ Process::assertRan(function ($process): bool {+ $command = implode(' ', array_map(fn ($part) => is_string($part) ? $part : json_encode($part), $process->command));++ return str_contains($command, 'sudo -n journalctl -u coold -n 50 --no-pager -q')+ && str_contains($command, '203.0.113.10')+ && in_array('LogLevel=ERROR', $process->command, true);+ });+});++it('falls back to ssh for v5 server coold logs when flux itself is unavailable', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'wireguard_management_ip' => '100.64.0.10',+ 'node_address' => '203.0.113.10',+ ]);++ $this->mock(FluxClient::class, function (MockInterface $mock): void {+ $mock->shouldReceive('cooldLogs')+ ->once()+ ->with(Mockery::type('string'), 200)+ ->andThrow(new RuntimeException('Flux socket was not found.'));+ });++ Process::fake([+ '*' => Process::result(output: "Jul 06 coold[123]: no flux socket\n"),+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->getJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/coold-logs")+ ->assertSuccessful()+ ->assertJsonPath('output', 'Jul 06 coold[123]: no flux socket')+ ->assertJsonPath('source', 'ssh');+});++it('fetches v5 server corrosion tables through flux', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'wireguard_management_ip' => '100.64.0.10',+ 'node_address' => '203.0.113.10',+ ]);++ $this->mock(FluxClient::class, function (MockInterface $mock): void {+ $mock->shouldReceive('corrosionTables')+ ->once()+ ->with(Mockery::type('string'), 200)+ ->andReturn('{"limit":200,"tables":[{"name":"service_endpoints","columns":["container_name"],"rows":[["coolify-v5-nginx"]]}]}');+ });++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->getJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/corrosion-tables?limit=200")+ ->assertSuccessful()+ ->assertJsonPath('output', '{"limit":200,"tables":[{"name":"service_endpoints","columns":["container_name"],"rows":[["coolify-v5-nginx"]]}]}')+ ->assertJsonStructure(['output', 'fetchedAt']);+});++it('falls back to ssh for v5 server corrosion tables when flux fails', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'wireguard_management_ip' => '100.64.0.10',+ 'node_address' => '203.0.113.10',+ ]);++ $this->mock(FluxClient::class, function (MockInterface $mock): void {+ $mock->shouldReceive('corrosionTables')+ ->once()+ ->with(Mockery::type('string'), 200)+ ->andThrow(new RuntimeException('host not connected'));+ });++ Process::fake([+ '*' => Process::result(output: '{"limit":200,"tables":[{"name":"service_endpoints","columns":["container_name"],"rows":[["coolify-v5-nginx"]]}]}'),+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->getJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/corrosion-tables?limit=200")+ ->assertSuccessful()+ ->assertJsonPath('output', '{"limit":200,"tables":[{"name":"service_endpoints","columns":["container_name"],"rows":[["coolify-v5-nginx"]]}]}')+ ->assertJsonPath('source', 'ssh');++ Process::assertRan(function ($process): bool {+ $command = implode(' ', array_map(fn ($part) => is_string($part) ? $part : json_encode($part), $process->command));++ return str_contains($command, '127.0.0.1:8080/v1/queries')+ && str_contains($command, 'sqlite_schema')+ && str_contains($command, '203.0.113.10')+ && in_array('LogLevel=ERROR', $process->command, true);+ });+});++it('fetches v5 server firewall rules through flux', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'wireguard_management_ip' => '100.64.0.10',+ 'node_address' => '203.0.113.10',+ ]);++ $this->mock(FluxClient::class, function (MockInterface $mock): void {+ $mock->shouldReceive('listFirewallRules')+ ->once()+ ->with(Mockery::type('string'), '')+ ->andReturn([[+ 'id' => 'v5-resource-connection:1:1:2:tcp:5432',+ 'namespace' => 'default',+ 'src' => 'coolify-v5-api',+ 'dst' => 'coolify-v5-postgres',+ 'proto' => 'tcp',+ 'port' => 5432,+ ]]);+ });++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->getJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/firewall-rules")+ ->assertSuccessful()+ ->assertJsonPath('rules.0.id', 'v5-resource-connection:1:1:2:tcp:5432')+ ->assertJsonPath('rules.0.port', 5432)+ ->assertJsonStructure(['rules', 'fetchedAt']);+});++it('adds a v5 server to a cluster for the current team', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ 'builder_enabled' => true,+ 'builder_capacity' => 3,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers", [+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'private_key_uuid' => $privateKey->uuid,+ 'node_address' => '203.0.113.10',+ 'builder_enabled' => true,+ 'builder_capacity' => 3,+ 'wireguard_listen_port_override' => 51821,+ 'wireguard_endpoint_override' => 'prod-01.example.com:51821',+ 'coold_version' => 'v9.9.9',+ 'corrosion_version' => 'v8.8.8',+ ])+ ->assertCreated()+ ->assertJsonPath('cluster.serversCount', 1)+ ->assertJsonPath('cluster.servers.0.name', 'prod-01')+ ->assertJsonPath('cluster.servers.0.host', '203.0.113.10')+ ->assertJsonMissingPath('cluster.servers.0.sshUser')+ ->assertJsonMissingPath('cluster.servers.0.sshPort')+ ->assertJsonMissingPath('cluster.servers.0.cooldVersion')+ ->assertJsonMissingPath('cluster.servers.0.corrosionVersion')+ ->assertJsonPath('cluster.servers.0.privateKeyName', 'Production SSH Key')+ ->assertJsonPath('cluster.servers.0.status', 'added')+ ->assertJsonPath('cluster.servers.0.nodeAddress', '203.0.113.10')+ ->assertJsonPath('cluster.servers.0.builderEnabled', true)+ ->assertJsonPath('cluster.servers.0.builderCapacity', 3)+ ->assertJsonPath('cluster.servers.0.builderCpuQuota', '200%')+ ->assertJsonPath('cluster.servers.0.ingressEnabled', false)+ ->assertJsonPath('cluster.servers.0.ingressType', null)+ ->assertJsonPath('cluster.servers.0.capabilities', [])+ ->assertJsonPath('cluster.servers.0.wireguardListenPortOverride', 51821)+ ->assertJsonPath('cluster.servers.0.wireguardEndpointOverride', 'prod-01.example.com:51821')+ ->assertJsonPath('cluster.servers.0.wireguardManagementIp', null)+ ->assertJsonPath('cluster.servers.0.containerSubnets', []);++ expect(V5Server::query()+ ->where('team_id', $team->id)+ ->where('cluster_id', $cluster->id)+ ->where('created_by_user_id', $user->id)+ ->where('name', 'prod-01')+ ->where('host', '203.0.113.10')+ ->where('ssh_user', 'root')+ ->where('ssh_port', 22)+ ->where('private_key_id', $privateKey->id)+ ->where('node_address', '203.0.113.10')+ ->exists())->toBeTrue();++ expect(V5Server::query()->where('name', 'prod-01')->first()->capabilities)+ ->toBe([]);+});++it('adds a v5 server with caddy ingress enabled', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers", [+ 'name' => 'edge-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'private_key_uuid' => $privateKey->uuid,+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'ingress_enabled' => true,+ 'ingress_type' => 'caddy',+ ])+ ->assertCreated()+ ->assertJsonPath('cluster.servers.0.ingressEnabled', true)+ ->assertJsonPath('cluster.servers.0.ingressType', 'caddy')+ ->assertJsonPath('cluster.servers.0.capabilities', ['ingress']);++ $server = V5Server::query()->where('name', 'edge-01')->first();++ expect($server->capabilities)->toBe(['ingress'])+ ->and($server->ingress_type)->toBe('caddy')+ ->and($server->isIngress())->toBeTrue();+});++it('keeps added v5 server builder capacity when builder is disabled', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ 'builder_enabled' => true,+ 'builder_capacity' => 3,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers", [+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'private_key_uuid' => $privateKey->uuid,+ 'builder_enabled' => false,+ 'builder_capacity' => 3,+ ])+ ->assertCreated()+ ->assertJsonPath('cluster.servers.0.builderEnabled', false)+ ->assertJsonPath('cluster.servers.0.builderCapacity', 3)+ ->assertJsonPath('cluster.servers.0.capabilities', []);++ $server = V5Server::query()->where('name', 'prod-01')->first();++ expect($server->builder_enabled)->toBeFalse()+ ->and($server->builder_capacity)->toBe(3)+ ->and($server->capabilities)->toBe([]);+});++it('requires positive v5 server builder capacity when builder is enabled', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers", [+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'private_key_uuid' => $privateKey->uuid,+ 'builder_enabled' => true,+ 'builder_capacity' => 0,+ ])+ ->assertUnprocessable()+ ->assertJsonValidationErrors(['builder_capacity']);+});++it('defaults dev Lima wireguard overrides for host docker internal servers', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Testing Host Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Development-Lima',+ 'description' => null,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers", [+ 'name' => 'coolify-naked-test',+ 'host' => 'host.docker.internal',+ 'ssh_user' => 'root',+ 'ssh_port' => 60003,+ 'private_key_uuid' => $privateKey->uuid,+ ])+ ->assertCreated()+ ->assertJsonPath('cluster.servers.0.wireguardListenPortOverride', 51823)+ ->assertJsonPath('cluster.servers.0.wireguardEndpointOverride', 'host.lima.internal:51823');+});++it('rejects adding a v5 server to another teams cluster', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $otherTeam = Team::withoutEvents(fn () => Team::query()->create([+ 'name' => 'Other V5 Team',+ 'description' => null,+ 'personal_team' => false,+ 'show_boarding' => false,+ ]));+ $cluster = Cluster::query()->create([+ 'team_id' => $otherTeam->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Other Mesh',+ 'description' => null,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers", [+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ ])+ ->assertForbidden();+});++it('validates v5 server creation input', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers", [+ 'name' => '',+ 'host' => '',+ 'ssh_user' => '',+ 'ssh_port' => 70000,+ 'private_key_uuid' => null,+ 'wireguard_listen_port_override' => 70000,+ ])+ ->assertUnprocessable()+ ->assertJsonValidationErrors([+ 'name',+ 'host',+ 'ssh_user',+ 'ssh_port',+ 'private_key_uuid',+ 'wireguard_listen_port_override',+ ]);+});++it('rejects unsafe v5 server host and wireguard endpoint input', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers", [+ 'name' => 'prod-01',+ 'host' => "203.0.113.10\nProxyCommand sh -c whoami",+ 'ssh_user' => "root\nUser attacker",+ 'ssh_port' => 22,+ 'private_key_uuid' => $privateKey->uuid,+ 'node_address' => "100.64.0.10\nHost *",+ 'wireguard_endpoint_override' => 'not a host port',+ ])+ ->assertUnprocessable()+ ->assertJsonValidationErrors([+ 'host',+ 'ssh_user',+ 'node_address',+ 'wireguard_endpoint_override',+ ]);+});++it('accepts bracketed IPv6 wireguard endpoint overrides for v5 servers', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers", [+ 'name' => 'prod-ipv6',+ 'host' => '2001:db8::10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'private_key_uuid' => $privateKey->uuid,+ 'wireguard_endpoint_override' => '[2001:db8::10]:51820',+ ])+ ->assertCreated()+ ->assertJsonPath('cluster.servers.0.wireguardEndpointOverride', '[2001:db8::10]:51820');+});++it('rejects private keys from another team when adding a v5 server', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $otherTeam = Team::withoutEvents(fn () => Team::query()->create([+ 'name' => 'Other V5 Team',+ 'description' => null,+ 'personal_team' => false,+ 'show_boarding' => false,+ ]));+ $otherPrivateKey = createV5PrivateKey($otherTeam, 'Other SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers", [+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'private_key_uuid' => $otherPrivateKey->uuid,+ ])+ ->assertUnprocessable()+ ->assertJsonValidationErrors(['private_key_uuid']);+});++it('checks v5 server ssh status without storing diagnostic output', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ ]);++ Process::fake([+ '*' => Process::result(output: "SSH connection OK\nprod-01\nLinux aarch64\n/usr/bin/docker\n"),+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/check")+ ->assertSuccessful()+ ->assertJsonPath('status', 'reachable')+ ->assertJsonPath('output', "SSH connection OK\nprod-01\nLinux aarch64\n/usr/bin/docker")+ ->assertJsonPath('checkedAt', fn (?string $value) => $value !== null);++ Process::assertRan(fn ($process) => str_contains(json_encode($process->command), '203.0.113.10'));+ Process::assertRan(fn ($process) => in_array('LogLevel=ERROR', $process->command, true));++ $server->refresh();++ expect($server->status)->toBe('added')+ ->and($server->last_status_check)->toBeNull()+ ->and($server->last_status_output)->toBeNull()+ ->and($server->last_status_checked_at)->toBeNull();+});++it('blocks starting a second v5 server bootstrap while another cluster bootstrap is active', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'last_bootstrap_status' => 'running',+ 'last_bootstrap_ran_at' => now()->subMinutes(5),+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-02',+ 'host' => '203.0.113.11',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ ]);++ Queue::fake();++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/bootstrap")+ ->assertConflict()+ ->assertJsonPath('message', 'Another server bootstrap is already queued or running for this cluster.');++ Queue::assertNothingPushed();+ expect($server->refresh()->last_bootstrap_status)->toBeNull();+});++it('deletes an unbootstrapped v5 server from a cluster', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->deleteJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}")+ ->assertSuccessful()+ ->assertJsonPath('cluster.serversCount', 0)+ ->assertJsonPath('cluster.servers', []);++ expect(V5Server::query()->whereKey($server->id)->exists())->toBeFalse();+});++it('deletes a bootstrapped v5 server from a cluster', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'last_bootstrapped_at' => now(),+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->deleteJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}")+ ->assertSuccessful()+ ->assertJsonPath('cluster.serversCount', 0)+ ->assertJsonPath('cluster.servers', []);++ expect(V5Server::query()->whereKey($server->id)->exists())->toBeFalse();+});++it('removes the bootstrap marker over ssh when deleting a bootstrapped v5 server', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'last_bootstrapped_at' => now(),+ ]);++ Process::fake([+ '*' => Process::result(output: "cleaned\n"),+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->deleteJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}")+ ->assertSuccessful()+ ->assertJsonMissingPath('warning');++ Process::assertRan(function ($process): bool {+ $command = implode(' ', array_map(fn ($part) => is_string($part) ? $part : json_encode($part), $process->command));++ return str_contains($command, 'rm -f /etc/coolify/v5-node.json /etc/coolify/host-jwt');+ });++ expect(V5Server::query()->whereKey($server->id)->exists())->toBeFalse();+});++it('still deletes a bootstrapped v5 server when the ssh cleanup fails', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'last_bootstrapped_at' => now(),+ ]);++ Process::fake([+ '*' => Process::result(errorOutput: "ssh failed\n", exitCode: 255),+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->deleteJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}")+ ->assertSuccessful()+ ->assertJsonPath('warning', 'Could not clean up the server over SSH. Remove /etc/coolify/v5-node.json manually before re-adding this server.');++ expect(V5Server::query()->whereKey($server->id)->exists())->toBeFalse();+});++it('rejects adding a v5 server beyond the cluster network pool capacity', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'namespaces' => ['default', 'preview'],+ 'container_network_pool' => '10.211.0.0/24',+ 'container_network_prefix' => 25,+ ]);+ V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])+ ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')+ ->postJson("/v5/clusters/{$cluster->uuid}/servers", [+ 'name' => 'prod-02',+ 'host' => '203.0.113.11',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'private_key_uuid' => $privateKey->uuid,+ ])+ ->assertUnprocessable()+ ->assertJsonPath('message', "This cluster's network pools are full (1 server(s) max). Grow the pools or remove a server first.");++ expect($cluster->servers()->count())->toBe(1);+});++it('rejects duplicate v5 server node addresses within a team', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ ]);+ V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'node_address' => '10.0.0.5',+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team, '_token' => 'test-csrf-token'])+ ->withHeader('X-CSRF-TOKEN', 'test-csrf-token')+ ->postJson("/v5/clusters/{$cluster->uuid}/servers", [+ 'name' => 'prod-02',+ 'host' => '203.0.113.11',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'private_key_uuid' => $privateKey->uuid,+ 'node_address' => '10.0.0.5',+ ])+ ->assertUnprocessable()+ ->assertJsonValidationErrors(['node_address']);+});++it('blocks deleting a v5 server that still has applications', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'last_bootstrapped_at' => now(),+ ]);+ V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'api',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-api',+ 'status' => 'running',+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->deleteJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}")+ ->assertUnprocessable()+ ->assertJsonPath('message', 'Delete or move applications from this server before deleting it.');++ expect(V5Server::query()->whereKey($server->id)->exists())->toBeTrue();+});++it('updates editable v5 server builder details without changing networking', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '100%',+ 'node_address' => '10.0.0.10',+ 'wireguard_listen_port_override' => 51821,+ 'wireguard_endpoint_override' => 'prod-01.example.com:51821',+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}", [+ 'builder_enabled' => true,+ 'builder_capacity' => 5,+ 'builder_cpu_quota' => '350%',+ 'host' => '198.51.100.99',+ 'ssh_user' => 'admin',+ 'ssh_port' => 2222,+ 'node_address' => '10.0.0.99',+ 'wireguard_endpoint_override' => 'changed.example.com:51821',+ ])+ ->assertSuccessful()+ ->assertJsonPath('cluster.servers.0.builderEnabled', true)+ ->assertJsonPath('cluster.servers.0.builderCapacity', 5)+ ->assertJsonPath('cluster.servers.0.builderCpuQuota', '350%')+ ->assertJsonPath('cluster.servers.0.ingressEnabled', false)+ ->assertJsonPath('cluster.servers.0.host', '203.0.113.10')+ ->assertJsonMissingPath('cluster.servers.0.sshUser')+ ->assertJsonMissingPath('cluster.servers.0.sshPort')+ ->assertJsonPath('cluster.servers.0.nodeAddress', '10.0.0.10')+ ->assertJsonPath('cluster.servers.0.wireguardEndpointOverride', 'prod-01.example.com:51821');++ $server->refresh();++ expect($server->builder_enabled)->toBeTrue()+ ->and($server->builder_capacity)->toBe(5)+ ->and($server->builder_cpu_quota)->toBe('350%')+ ->and($server->capabilities)->toBe([])+ ->and($server->host)->toBe('203.0.113.10')+ ->and($server->ssh_user)->toBe('root')+ ->and($server->ssh_port)->toBe(22)+ ->and($server->node_address)->toBe('10.0.0.10')+ ->and($server->wireguard_endpoint_override)->toBe('prod-01.example.com:51821');+});++it('updates editable v5 server caddy ingress capability independently from builder', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'capabilities' => ['builder'],+ 'builder_enabled' => true,+ 'builder_capacity' => 2,+ 'builder_cpu_quota' => '200%',+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}", [+ 'builder_enabled' => false,+ 'builder_capacity' => 2,+ 'builder_cpu_quota' => '200%',+ 'ingress_enabled' => true,+ 'ingress_type' => 'caddy',+ ])+ ->assertSuccessful()+ ->assertJsonPath('cluster.servers.0.builderEnabled', false)+ ->assertJsonPath('cluster.servers.0.ingressEnabled', true)+ ->assertJsonPath('cluster.servers.0.ingressType', 'caddy')+ ->assertJsonPath('cluster.servers.0.capabilities', ['ingress']);++ $server->refresh();++ expect($server->capabilities)->toBe(['ingress'])+ ->and($server->ingress_type)->toBe('caddy')+ ->and($server->builder_enabled)->toBeFalse()+ ->and($server->isIngress())->toBeTrue();+});++it('syncs caddy ingress routes through flux when enabling ingress on an installed server', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '200%',+ 'wireguard_management_ip' => '100.64.0.10',+ 'last_bootstrapped_at' => now(),+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-test',+ 'status' => 'running',+ 'mesh_namespace' => 'default',+ 'ingress_enabled' => true,+ 'internal_port' => 8080,+ ]);+ V5ApplicationDomain::query()->create([+ 'application_id' => $application->id,+ 'domain' => 'nginx.example.com',+ ]);+ V5ApplicationDomain::query()->create([+ 'application_id' => $application->id,+ 'domain' => 'www.nginx.example.com',+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient+ ->shouldReceive('applyIngress')+ ->once()+ ->with(+ Mockery::type('string'),+ 'caddy',+ Mockery::on(fn (string $caddyfile): bool => str_contains($caddyfile, 'import apps/*.caddy')),+ Mockery::on(fn (array $apps): bool => count($apps) === 1+ && str_contains($apps[0]['config'], 'http://nginx.example.com {')+ && str_contains($apps[0]['config'], 'http://www.nginx.example.com {')+ && str_contains($apps[0]['config'], 'reverse_proxy coolify-v5-nginx-test.default.coolify.internal:8080'))+ )+ ->andReturn('Caddy ingress applied.');+ expectCaddyIngressFirewallRule($fluxClient);+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}", [+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '200%',+ 'ingress_enabled' => true,+ 'ingress_type' => 'caddy',+ ])+ ->assertSuccessful()+ ->assertJsonPath('cluster.servers.0.ingressEnabled', true)+ ->assertJsonPath('cluster.servers.0.ingressType', 'caddy');++ expect($server->refresh()->ingress_type)->toBe('caddy')+ ->and($server->ingress_status)->toBe('running');+});++it('returns flux error details when server ingress activation fails', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Project', 'production');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.20',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '200%',+ 'wireguard_management_ip' => '100.64.0.10',+ 'last_bootstrapped_at' => now(),+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-test',+ 'status' => 'running',+ 'mesh_namespace' => 'default',+ 'ingress_enabled' => true,+ 'internal_port' => 8080,+ ]);+ V5ApplicationDomain::query()->create([+ 'application_id' => $application->id,+ 'domain' => 'nginx.example.com',+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient+ ->shouldReceive('applyIngress')+ ->once()+ ->andThrow(new RuntimeException('validate Caddyfile: unrecognized directive'));+ app()->instance(FluxClient::class, $fluxClient);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}", [+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '200%',+ 'ingress_enabled' => true,+ 'ingress_type' => 'caddy',+ ])+ ->assertStatus(502)+ ->assertJsonPath('message', 'Caddy rejected the generated ingress configuration. Check the domains and internal port, then try again.')+ ->assertJsonPath('detail', 'validate Caddyfile: unrecognized directive');++ expect($server->refresh()->capabilities)->toBe([])+ ->and($server->ingress_type)->toBeNull()+ ->and($server->ingress_status)->toBeNull();+});++it('keeps editable v5 server builder capacity when disabling builder', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['builder'],+ 'builder_enabled' => true,+ 'builder_capacity' => 5,+ 'builder_cpu_quota' => '350%',+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}", [+ 'builder_enabled' => false,+ 'builder_capacity' => 5,+ 'builder_cpu_quota' => '350%',+ ])+ ->assertSuccessful()+ ->assertJsonPath('cluster.servers.0.builderEnabled', false)+ ->assertJsonPath('cluster.servers.0.builderCapacity', 5);++ $server->refresh();++ expect($server->builder_enabled)->toBeFalse()+ ->and($server->builder_capacity)->toBe(5)+ ->and($server->builder_cpu_quota)->toBe('350%')+ ->and($server->capabilities)->toBe([]);+});++it('validates editable v5 server builder details', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['builder'],+ 'builder_enabled' => true,+ 'builder_capacity' => 2,+ 'builder_cpu_quota' => '200%',+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}", [+ 'builder_enabled' => true,+ 'builder_capacity' => 1001,+ 'builder_cpu_quota' => str_repeat('a', 33),+ ])+ ->assertUnprocessable()+ ->assertJsonValidationErrors(['builder_capacity', 'builder_cpu_quota']);+});++it('requires positive editable v5 server builder capacity when builder is enabled', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '200%',+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}", [+ 'builder_enabled' => true,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '200%',+ ])+ ->assertUnprocessable()+ ->assertJsonValidationErrors(['builder_capacity']);+});diff --git a/tests/Feature/V5/V5BootstrapServerJobTest.php b/tests/Feature/V5/V5BootstrapServerJobTest.phpnew file mode 100644index 0000000000..784e48869b--- /dev/null+++ b/tests/Feature/V5/V5BootstrapServerJobTest.php@@ -0,0 +1,920 @@+<?php++use App\Events\V5ClusterUpdated;+use App\Jobs\V5BootstrapServerJob;+use App\Models\V5\Cluster;+use App\Models\V5\Server as V5Server;+use App\Services\Flux\AgentTokenIssuer;+use App\Services\Flux\FluxClient;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Event;+use Illuminate\Support\Facades\Process;+use Illuminate\Support\Facades\Queue;++beforeEach(function () {+ resetV5DashboardTestState();+});++it('broadcasts v5 cluster updates when bootstrap state changes', function () {+ createSharedUserAndTeamTables();+ Config::set('coold.coolify_cli_bin', '/tmp/coolify');++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ ]);++ Queue::fake();+ Event::fake([V5ClusterUpdated::class]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/bootstrap")+ ->assertAccepted();++ Event::assertDispatched(V5ClusterUpdated::class, fn ($event): bool => $event->clusterId === $cluster->id+ && $event->teamId === $team->id);++ Process::fake([+ '*' => Process::result(output: "Bootstrap completed\n"),+ ]);++ Event::fake([V5ClusterUpdated::class]);++ (new V5BootstrapServerJob($cluster->id, $server->id))->handle();++ expect(Event::dispatched(V5ClusterUpdated::class)->count())->toBeGreaterThanOrEqual(2);+});++it('writes quiet ssh options for v5 bootstrap ssh config', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ ]);+ $server->load('privateKey');++ $tempDirectory = storage_path('framework/testing/v5_bootstrap_'.str()->random(8));+ mkdir($tempDirectory, 0700, true);++ try {+ $job = new V5BootstrapServerJob($cluster->id, $server->id);+ $reflection = new ReflectionClass($job);+ $method = $reflection->getMethod('writeBootstrapSshConfig');+ $method->setAccessible(true);++ $sshConfigLocation = $method->invoke($job, collect([$server]), $tempDirectory);+ $config = file_get_contents($sshConfigLocation);++ expect($config)->toContain(' LogLevel ERROR')+ ->and($config)->toContain(' UserKnownHostsFile /dev/null')+ ->and($config)->toContain(' StrictHostKeyChecking no');+ } finally {+ collect(scandir($tempDirectory) ?: [])+ ->reject(fn (string $file) => in_array($file, ['.', '..'], true))+ ->each(fn (string $file) => @unlink($tempDirectory.'/'.$file));+ @rmdir($tempDirectory);+ }+});++it('bootstraps a single v5 server with the Coolify CLI', function () {+ createSharedUserAndTeamTables();+ Config::set('coold.coolify_cli_bin', '/tmp/coolify');+ Config::set('coold.flux_url', 'http://coolify.example.com:6443');+ fakeAgentTokenIssuer();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ 'namespaces' => ['default', 'preview'],+ 'container_network_pool' => '10.211.0.0/16',+ 'container_network_prefix' => 25,+ 'wireguard_management_pool' => '100.65.0.0/16',+ 'wireguard_interface' => 'wg-prod',+ 'wireguard_listen_port' => 51830,+ 'coold_version' => 'v0.2.0',+ 'corrosion_version' => 'v1.1.0',+ 'corrosion_gossip_port' => 8788,+ 'corrosion_api_port' => 8081,+ 'builder_enabled' => true,+ 'builder_capacity' => 4,+ 'builder_cpu_quota' => '400%',+ 'builder_memory_max' => '4G',+ 'builder_timeout_secs' => 2400,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 2222,+ 'status' => 'added',+ 'capabilities' => ['builder'],+ 'builder_enabled' => true,+ 'builder_capacity' => 4,+ 'wireguard_listen_port_override' => 51831,+ 'wireguard_endpoint_override' => 'prod-01.example.com:51831',+ ]);++ Queue::fake();++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/bootstrap")+ ->assertAccepted()+ ->assertJsonPath('message', 'Bootstrap queued.')+ ->assertJsonPath('cluster.servers.0.status', 'added')+ ->assertJsonPath('cluster.servers.0.lastBootstrapAction', 'bootstrap')+ ->assertJsonPath('cluster.servers.0.lastBootstrapStatus', 'queued')+ ->assertJsonPath('cluster.servers.0.lastBootstrapOutput', 'Queued Coolify bootstrap for prod-01.');++ Queue::assertPushed(V5BootstrapServerJob::class);++ Process::fake([+ '*' => Process::result(output: "Bootstrap completed\n"),+ ]);++ Event::fake([V5ClusterUpdated::class]);++ (new V5BootstrapServerJob($cluster->id, $server->id))->handle();++ $server->refresh();++ Process::assertRan(function ($process): bool {+ $command = $process->command;+ $node = cliFlagValue($command, '--nodes');++ return $command[0] === '/tmp/coolify'+ && in_array('init', $command, true)+ && in_array('bootstrap', $command, true)+ && cliFlagValue($command, '--format') === 'json'+ && in_array('--ssh-config', $command, true)+ && cliFlagValue($command, '--ssh-user') === 'root'+ && is_string($node)+ && str_starts_with($node, 'v5-server-')+ && cliFlagValue($command, '--namespaces') === 'default,preview'+ && cliFlagValue($command, '--container-pool') === '10.211.0.0/16'+ && cliFlagValue($command, '--wg-mgmt-pool') === '100.65.0.0/16'+ && cliFlagValue($command, '--wg-interface') === 'wg-prod'+ && cliFlagValue($command, '--coold-version') === 'v0.2.0'+ && cliFlagValue($command, '--corrosion-version') === 'v1.1.0'+ && cliFlagValue($command, '--wg-listen-port-overrides') === $node.'=51831'+ && cliFlagValue($command, '--wg-endpoint-overrides') === $node.'=prod-01.example.com:51831'+ && ! in_array('--enable-builder', $command, true)+ && in_array('--yes', $command, true)+ && ! in_array('--new-nodes', $command, true);+ });+ Process::assertRan(fn ($process): bool => in_array('bootstrap', $process->command, true) && $process->timeout === 7200);++ $cluster->refresh();++ expect($server->status)->toBe('installed')+ ->and($server->last_bootstrap_status)->toBe('succeeded')+ ->and($server->last_bootstrap_output)->toContain('Bootstrap completed')+ ->and($server->last_bootstrapped_at)->not->toBeNull();+});++it('does not run a macOS development Coolify CLI binary from Docker during v5 server bootstrap', function () {+ createSharedUserAndTeamTables();+ Config::set('coold.coolify_cli_bin', '/usr/local/bin/coolify');++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ ]);++ Queue::fake();++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/bootstrap")+ ->assertAccepted();++ Process::fake([+ '*' => Process::result(output: "Bootstrap completed\n"),+ ]);++ Event::fake([V5ClusterUpdated::class]);++ (new V5BootstrapServerJob($cluster->id, $server->id))->handle();++ Process::assertRan(fn ($process): bool => $process->command[0] === '/usr/local/bin/coolify');+});++it('keeps a v5 server added when Coolify CLI bootstrap fails', function () {+ createSharedUserAndTeamTables();+ Config::set('coold.coolify_cli_bin', '/tmp/coolify');++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ ]);++ Queue::fake();++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/bootstrap")+ ->assertAccepted()+ ->assertJsonPath('cluster.servers.0.status', 'added')+ ->assertJsonPath('cluster.servers.0.lastBootstrappedAt', null)+ ->assertJsonPath('cluster.servers.0.lastBootstrapStatus', 'queued');++ Process::fake([+ '*' => Process::result(errorOutput: "bootstrap failed\n", exitCode: 1),+ ]);++ Event::fake([V5ClusterUpdated::class]);++ (new V5BootstrapServerJob($cluster->id, $server->id))->handle();++ $server->refresh();++ expect($server->status)->toBe('added')+ ->and($server->last_bootstrap_status)->toBe('failed')+ ->and($server->last_bootstrap_output)->toBe('bootstrap failed')+ ->and($server->last_bootstrapped_at)->toBeNull();+});++it('persists v5 bootstrap mesh assignments and enrolls coold into flux', function () {+ createSharedUserAndTeamTables();+ Config::set('coold.coolify_cli_bin', '/tmp/coolify');+ Config::set('coold.flux_url', 'http://coolify.example.com:6443');++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ 'namespaces' => ['default', 'preview'],+ 'wireguard_management_pool' => '100.65.0.0/16',+ 'container_network_pool' => '10.211.0.0/16',+ 'container_network_prefix' => 25,+ 'coold_version' => 'v0.9.9',+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'ubuntu',+ 'ssh_port' => 2222,+ 'status' => 'added',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'last_bootstrap_status' => 'queued',+ 'last_bootstrap_ran_at' => now(),+ ]);++ $issuer = Mockery::mock(AgentTokenIssuer::class);+ $issuer+ ->shouldReceive('issueForServer')+ ->once()+ ->with(Mockery::on(fn (V5Server $server): bool => $server->wireguard_management_ip === '100.65.0.1'))+ ->andReturn('signed-host-jwt');+ app()->instance(AgentTokenIssuer::class, $issuer);++ Process::fake([+ '*' => Process::sequence()+ ->push(Process::result(output: ''))+ ->push(Process::result(output: json_encode([+ 'results' => [],+ 'verified' => [[+ 'host' => "v5-server-{$server->uuid}",+ 'wireguard_ip' => '100.65.0.1',+ 'peer_count' => 0,+ 'status' => 'ok',+ ]],+ ], JSON_THROW_ON_ERROR)."\n"))+ ->push(Process::result(output: "public-key\n"))+ ->push(Process::result(output: "default=10.211.0.0/25\npreview=10.211.0.128/25\n"))+ ->push(Process::result(output: "marker written\n"))+ ->push(Process::result(output: "coold restarted\n")),+ ]);++ Event::fake([V5ClusterUpdated::class]);++ (new V5BootstrapServerJob($cluster->id, $server->id))->handle();++ $server->refresh();++ expect($server->wireguard_management_ip)->toBe('100.65.0.1')+ ->and($server->wireguard_public_key)->toBe('public-key')+ ->and($server->container_subnets)->toBe([+ 'default' => '10.211.0.0/25',+ 'preview' => '10.211.0.128/25',+ ])+ ->and($server->node_address)->toBe('100.65.0.1')+ ->and($server->status)->toBe('installed')+ ->and($server->coold_version)->toBe('v0.9.9')+ ->and($server->last_bootstrapped_at)->not->toBeNull();++ Process::assertRan(function ($process) use ($server): bool {+ $command = implode(' ', array_map(fn ($part) => is_string($part) ? $part : json_encode($part), $process->command));++ return str_contains($command, 'COOLIFY_COOLD_FLUX_URL=http://coolify.example.com:6443')+ && str_contains($command, 'COOLIFY_COOLD_HOST_ID='.$server->uuid)+ && str_contains($command, 'COOLIFY_COOLD_HOST_JWT_PATH=/etc/coolify/host-jwt')+ && str_contains($command, 'signed-host-jwt')+ && str_contains($command, 'chmod 600 /etc/coolify/host-jwt')+ && str_contains($command, 'systemctl restart coold.service');+ });++ Process::assertRan(function ($process): bool {+ $command = implode(' ', array_map(fn ($part) => is_string($part) ? $part : json_encode($part), $process->command));++ return str_contains($command, 'wg show')+ && str_contains($command, "if [ \"$(id -u)\" != \"0\" ]; then SUDO='sudo'; fi");+ });++ Process::assertRan(function ($process): bool {+ $command = implode(' ', array_map(fn ($part) => is_string($part) ? $part : json_encode($part), $process->command));++ return str_contains($command, 'podman network inspect "coolify-${ns}-mesh"')+ && str_contains($command, "if [ \"$(id -u)\" != \"0\" ]; then SUDO='sudo'; fi");+ });+});++it('waits for the bootstrapped host to connect to flux before marking the server installed', function () {+ createSharedUserAndTeamTables();+ Config::set('coold.coolify_cli_bin', '/tmp/coolify');+ Config::set('coold.flux_url', 'http://coolify.example.com:6443');+ Config::set('flux.bootstrap_host_connection_timeout_seconds', 1);++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'wireguard_management_pool' => '100.65.0.0/16',+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'ubuntu',+ 'ssh_port' => 2222,+ 'status' => 'added',+ 'last_bootstrap_status' => 'queued',+ 'last_bootstrap_ran_at' => now(),+ ]);++ fakeAgentTokenIssuer();+ $this->mock(FluxClient::class, function ($mock) use ($server): void {+ $mock->shouldReceive('cooldLogs')+ ->once()+ ->with($server->uuid, 1)+ ->andReturn('coold connected');+ });++ Process::fake([+ '*' => Process::sequence()+ ->push(Process::result(output: ''))+ ->push(Process::result(output: json_encode([+ 'verified' => [[+ 'host' => "v5-server-{$server->uuid}",+ 'wireguard_ip' => '100.65.0.1',+ ]],+ ], JSON_THROW_ON_ERROR)."\n"))+ ->push(Process::result(output: "public-key\n"))+ ->push(Process::result(output: "default=10.211.0.0/25\n"))+ ->push(Process::result(output: "marker written\n"))+ ->push(Process::result(output: "coold restarted\n")),+ ]);++ Event::fake([V5ClusterUpdated::class]);++ (new V5BootstrapServerJob($cluster->id, $server->id))->handle();++ $server->refresh();++ expect($server->status)->toBe('installed')+ ->and($server->last_bootstrap_status)->toBe('succeeded')+ ->and($server->wireguard_management_ip)->toBe('100.65.0.1');+});++it('reads the WireGuard management IP from the host when bootstrap output does not include it', function () {+ createSharedUserAndTeamTables();+ Config::set('coold.coolify_cli_bin', '/tmp/coolify');+ Config::set('coold.flux_url', 'http://coolify.example.com:6443');++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'wireguard_interface' => 'wg-prod',+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'ubuntu',+ 'ssh_port' => 2222,+ 'status' => 'added',+ 'node_address' => '203.0.113.10',+ 'last_bootstrap_status' => 'queued',+ 'last_bootstrap_ran_at' => now(),+ ]);++ $issuer = Mockery::mock(AgentTokenIssuer::class);+ $issuer+ ->shouldReceive('issueForServer')+ ->once()+ ->with(Mockery::on(fn (V5Server $server): bool => $server->wireguard_management_ip === '100.65.0.1'))+ ->andReturn('signed-host-jwt');+ app()->instance(AgentTokenIssuer::class, $issuer);++ Process::fake([+ '*' => Process::sequence()+ ->push(Process::result(output: ''))+ ->push(Process::result(output: json_encode([+ 'results' => [],+ 'verified' => [],+ ], JSON_THROW_ON_ERROR)."\n"))+ ->push(Process::result(output: "100.65.0.1\n"))+ ->push(Process::result(output: "public-key\n"))+ ->push(Process::result(output: "default=10.211.0.0/25\n"))+ ->push(Process::result(output: "marker written\n"))+ ->push(Process::result(output: "coold restarted\n")),+ ]);++ Event::fake([V5ClusterUpdated::class]);++ (new V5BootstrapServerJob($cluster->id, $server->id))->handle();++ $server->refresh();++ expect($server->wireguard_management_ip)->toBe('100.65.0.1')+ ->and($server->node_address)->toBe('100.65.0.1')+ ->and($server->status)->toBe('installed');++ Process::assertRan(function ($process): bool {+ $command = implode(' ', array_map(fn ($part) => is_string($part) ? $part : json_encode($part), $process->command));++ return str_contains($command, 'ip -4 -o addr show dev')+ && str_contains($command, 'wg-prod');+ });+});++it('fails the bootstrap when the flux url is not configured', function () {+ createSharedUserAndTeamTables();+ Config::set('coold.coolify_cli_bin', '/tmp/coolify');+ Config::set('coold.flux_url', '');++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'last_bootstrap_status' => 'queued',+ 'last_bootstrap_ran_at' => now(),+ ]);++ Process::fake([+ '*' => Process::result(output: "Bootstrap completed\n"),+ ]);++ Event::fake([V5ClusterUpdated::class]);++ (new V5BootstrapServerJob($cluster->id, $server->id))->handle();++ $server->refresh();++ expect($server->status)->toBe('added')+ ->and($server->last_bootstrap_status)->toBe('failed')+ ->and($server->last_bootstrap_output)->toContain('COOLIFY_COOLD_FLUX_URL')+ ->and($server->last_bootstrapped_at)->toBeNull();+});++it('writes the bootstrap marker before flux enrollment so a failed enrollment can resume', function () {+ createSharedUserAndTeamTables();+ Config::set('coold.coolify_cli_bin', '/tmp/coolify');+ Config::set('coold.flux_url', 'http://coolify.example.com:6443');+ fakeAgentTokenIssuer();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'last_bootstrap_status' => 'queued',+ 'last_bootstrap_ran_at' => now(),+ ]);++ Process::fake([+ '*systemctl restart coold*' => Process::result(errorOutput: "enrollment boom\n", exitCode: 1),+ '*' => Process::result(output: "Bootstrap completed\n"),+ ]);++ Event::fake([V5ClusterUpdated::class]);++ (new V5BootstrapServerJob($cluster->id, $server->id))->handle();++ $server->refresh();++ expect($server->status)->toBe('added')+ ->and($server->last_bootstrap_status)->toBe('failed')+ ->and($server->last_bootstrap_output)->toContain('enrollment boom')+ ->and($server->last_bootstrap_output)->toContain('retrying this bootstrap is safe')+ ->and($server->last_bootstrapped_at)->toBeNull();++ Process::assertRan(function ($process): bool {+ $command = implode(' ', array_map(fn ($part) => is_string($part) ? $part : json_encode($part), $process->command));++ return str_contains($command, 'v5-node.json') && str_contains($command, 'base64 -d');+ });+});++it('exits the bootstrap job when its claim was superseded', function () {+ createSharedUserAndTeamTables();+ Config::set('coold.coolify_cli_bin', '/tmp/coolify');++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'last_bootstrap_status' => 'failed',+ 'last_bootstrap_ran_at' => now(),+ ]);++ Process::fake();++ (new V5BootstrapServerJob($cluster->id, $server->id))->handle();++ Process::assertNothingRan();+ expect($server->refresh()->last_bootstrap_status)->toBe('failed');+});++it('recovers a stale queued v5 bootstrap claim', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ ]);+ $staleServer = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'last_bootstrap_status' => 'queued',+ 'last_bootstrap_ran_at' => now()->subMinutes(20),+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-02',+ 'host' => '203.0.113.11',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ ]);++ Queue::fake();++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers/{$server->uuid}/bootstrap")+ ->assertAccepted()+ ->assertJsonPath('message', 'Bootstrap queued.');++ Queue::assertPushed(V5BootstrapServerJob::class);++ expect($staleServer->refresh()->last_bootstrap_status)->toBe('failed')+ ->and($staleServer->last_bootstrap_output)->toContain('timed out or its worker died')+ ->and($server->refresh()->last_bootstrap_status)->toBe('queued');+});++it('extends a v5 cluster when bootstrapping a new server', function () {+ createSharedUserAndTeamTables();+ Config::set('coold.coolify_cli_bin', '/tmp/coolify');+ Config::set('coold.flux_url', 'http://coolify.example.com:6443');+ fakeAgentTokenIssuer();++ [$user, $team] = createV5UserWithTeam();+ $oldPrivateKey = createV5PrivateKey($team, 'Old SSH Key');+ $newPrivateKey = createV5PrivateKey($team, 'New SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ 'coold_version' => 'v0.3.0',+ 'corrosion_version' => 'v1.2.0',+ ]);+ $oldServer = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $oldPrivateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'ubuntu',+ 'ssh_port' => 2222,+ 'status' => 'installed',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'last_bootstrapped_at' => now()->subDay(),+ ]);+ $newServer = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $newPrivateKey->id,+ 'name' => 'prod-02',+ 'host' => '203.0.113.11',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ ]);++ Queue::fake();++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->postJson("/v5/clusters/{$cluster->uuid}/servers/{$newServer->uuid}/bootstrap")+ ->assertAccepted()+ ->assertJsonPath('cluster.servers.1.lastBootstrapAction', 'extend')+ ->assertJsonPath('cluster.servers.1.lastBootstrapStatus', 'queued');++ Process::fake([+ '*' => Process::result(output: "Extend completed\n"),+ ]);++ Event::fake([V5ClusterUpdated::class]);++ (new V5BootstrapServerJob($cluster->id, $newServer->id))->handle();++ Process::assertRan(function ($process) use ($oldServer, $newServer): bool {+ $command = $process->command;+ $oldNode = "v5-server-{$oldServer->uuid}";+ $newNode = "v5-server-{$newServer->uuid}";++ return in_array('extend', $command, true)+ && in_array("{$oldNode},{$newNode}", $command, true)+ && in_array('--new-nodes', $command, true)+ && in_array($newNode, $command, true)+ && cliFlagValue($command, '--ssh-user') === 'root'+ && in_array('--ssh-config', $command, true)+ && cliFlagValue($command, '--coold-version') === 'v0.3.0'+ && cliFlagValue($command, '--corrosion-version') === 'v1.2.0';+ });++ $oldServer->refresh();+ $newServer->refresh();++ expect($oldServer->status)->toBe('installed')+ ->and($newServer->status)->toBe('installed')+ ->and($newServer->last_bootstrap_status)->toBe('succeeded')+ ->and($newServer->last_bootstrap_output)->toContain('Extend completed')+ ->and($newServer->last_bootstrapped_at)->not->toBeNull();+});++it('adopts a re-added v5 server that is already bootstrapped for the same cluster', function () {+ createSharedUserAndTeamTables();+ Config::set('coold.coolify_cli_bin', '/tmp/coolify');+ Config::set('coold.flux_url', 'http://coolify.example.com:6443');+ fakeAgentTokenIssuer();++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'last_bootstrap_status' => 'queued',+ 'last_bootstrap_ran_at' => now(),+ ]);++ Process::fake([+ '*' => Process::result(output: json_encode([+ 'cluster_id' => $cluster->id,+ 'cluster_uuid' => $cluster->uuid,+ 'server_uuid' => 'server-previous-uuid',+ 'wireguard_management_ip' => '100.64.0.10',+ 'wireguard_public_key' => 'public-key',+ 'container_subnets' => ['default' => '10.210.0.0/24'],+ ], JSON_THROW_ON_ERROR)."\n"),+ ]);++ Event::fake([V5ClusterUpdated::class]);++ (new V5BootstrapServerJob($cluster->id, $server->id))->handle();++ Process::assertNotRan(fn ($process): bool => $process->command[0] === '/tmp/coolify');++ $server->refresh();++ expect($server->status)->toBe('installed')+ ->and($server->uuid)->toBe('server-previous-uuid')+ ->and($server->wireguard_management_ip)->toBe('100.64.0.10')+ ->and($server->wireguard_public_key)->toBe('public-key')+ ->and($server->container_subnets)->toBe(['default' => '10.210.0.0/24'])+ ->and($server->last_bootstrap_status)->toBe('succeeded')+ ->and($server->last_bootstrap_output)->toBe('Adopted existing Coolify bootstrap state for this cluster.')+ ->and($server->last_bootstrapped_at)->not->toBeNull();+});++it('blocks bootstrapping a v5 server that belongs to another cluster', function () {+ createSharedUserAndTeamTables();+ Config::set('coold.coolify_cli_bin', '/tmp/coolify');++ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Production SSH Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'added',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'last_bootstrap_status' => 'queued',+ 'last_bootstrap_ran_at' => now(),+ ]);++ Process::fake([+ '*' => Process::result(output: json_encode([+ 'cluster_id' => $cluster->id + 100,+ 'server_uuid' => 'server-other-uuid',+ ], JSON_THROW_ON_ERROR)."\n"),+ ]);++ Event::fake([V5ClusterUpdated::class]);++ (new V5BootstrapServerJob($cluster->id, $server->id))->handle();++ Process::assertNotRan(fn ($process): bool => $process->command[0] === '/tmp/coolify');++ $server->refresh();++ expect($server->status)->toBe('added')+ ->and($server->last_bootstrap_status)->toBe('failed')+ ->and($server->last_bootstrap_output)->toContain('already bootstrapped for another cluster')+ ->and($server->last_bootstrapped_at)->toBeNull();+});diff --git a/tests/Feature/V5/V5CanvasBroadcastTest.php b/tests/Feature/V5/V5CanvasBroadcastTest.phpnew file mode 100644index 0000000000..67862c7751--- /dev/null+++ b/tests/Feature/V5/V5CanvasBroadcastTest.php@@ -0,0 +1,292 @@+<?php++use App\Events\V5CanvasResourceUpdated;+use App\Events\V5ClusterUpdated;+use App\Models\V5\Application as V5Application;+use App\Models\V5\ApplicationDomain as V5ApplicationDomain;+use App\Models\V5\Cluster;+use App\Models\V5\Server as V5Server;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Event;++beforeEach(function () {+ resetV5DashboardTestState();+});++it('broadcasts v5 canvas resource updates when application state changes', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ 'status_message' => 'Container started.',+ 'runtime_container_id' => 'nginx-container-id',+ 'canvas_x' => 0,+ 'canvas_y' => 0,+ ]);++ Event::fake([V5CanvasResourceUpdated::class]);++ $application->update([+ 'status' => 'exited',+ 'status_message' => 'Container stopped.',+ ]);++ Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id+ && $event->applicationId === $application->id);+});++it('broadcasts the full v5 application canvas shape after application state changes', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['ingress'],+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ 'status_message' => 'Container started.',+ 'runtime_container_id' => 'nginx-container-id',+ 'ingress_enabled' => true,+ 'internal_port' => 80,+ 'canvas_x' => 0,+ 'canvas_y' => 0,+ ]);+ V5ApplicationDomain::query()->create([+ 'application_id' => $application->id,+ 'domain' => 'nginx.example.com',+ ]);++ $application->update([+ 'status' => 'exited',+ 'status_message' => 'Container stopped.',+ ]);++ $payload = (new V5CanvasResourceUpdated($team->id, $application->id))->broadcastWith();++ expect($payload['application'])+ ->toMatchArray([+ 'id' => $application->uuid,+ 'status' => 'exited',+ 'statusMessage' => 'Container stopped.',+ 'effectiveStatus' => 'exited',+ 'effectiveStatusMessage' => 'Container stopped.',+ 'serverName' => 'edge-01',+ 'serverStatus' => 'installed',+ 'isServerReachable' => true,+ 'serverIngressEnabled' => true,+ 'ingressEnabled' => true,+ 'internalPort' => 80,+ 'domains' => ['nginx.example.com'],+ ]);+});++it('broadcasts v5 application status as unknown when its server is unreachable', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'unreachable',+ 'last_status_output' => 'coold heartbeat timed out.',+ 'capabilities' => ['ingress'],+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ 'status_message' => 'Container started.',+ ]);++ $payload = (new V5CanvasResourceUpdated($team->id, $application->id))->broadcastWith();++ expect($payload['application'])+ ->toMatchArray([+ 'status' => 'running',+ 'effectiveStatus' => 'unknown',+ 'effectiveStatusMessage' => 'coold heartbeat timed out.',+ 'serverStatus' => 'unreachable',+ 'isServerReachable' => false,+ ]);+});++it('broadcasts v5 cluster and canvas updates when ingress server state changes', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Cluster',+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['ingress'],+ ]);++ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $server->update(['status' => 'unreachable']);++ Event::assertDispatched(V5ClusterUpdated::class, fn (V5ClusterUpdated $event) => $event->teamId === $team->id+ && $event->clusterId === $cluster->id);+ Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id+ && $event->caddyIngressServerId === $server->id);+});++it('broadcasts v5 cluster updates with uuid identifiers and the full server shape', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'uuid' => 'cluster-public-uuid',+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Mesh',+ 'description' => null,+ ]);+ $server = V5Server::query()->create([+ 'uuid' => 'server-public-uuid',+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['ingress'],+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'ingress_type' => 'caddy',+ 'last_status_output' => 'coold heartbeat ok.',+ 'last_status_checked_at' => now(),+ ]);++ $payload = (new V5ClusterUpdated($team->id, $cluster->id))->broadcastWith();++ expect($payload['cluster']['id'])+ ->toBe($cluster->uuid)+ ->and($payload['cluster']['id'])->not->toBe((string) $cluster->id)+ ->and($payload['cluster']['servers'][0]['id'])->not->toBe((string) $server->id)+ ->and($payload['cluster']['servers'][0])->toMatchArray([+ 'id' => $server->uuid,+ 'uuid' => $server->uuid,+ 'ingressEnabled' => true,+ 'ingressType' => 'caddy',+ 'lastStatusOutput' => 'coold heartbeat ok.',+ ])+ ->and($payload['cluster']['servers'][0])->toHaveKey('lastStatusCheckedAt');+});++it('resolves an empty v5 canvas broadcast payload when the models are deleted before the queued broadcast runs', function () {+ createSharedUserAndTeamTables();++ $payload = (new V5CanvasResourceUpdated(1, 999, 998, 997))->broadcastWith();++ expect($payload)->toBe([+ 'application' => null,+ 'applications' => [],+ 'caddyIngress' => null,+ ]);+});++it('resolves a null v5 cluster broadcast payload when the cluster is deleted before the queued broadcast runs', function () {+ createSharedUserAndTeamTables();++ $payload = (new V5ClusterUpdated(1, 999))->broadcastWith();++ expect($payload)->toBe(['cluster' => null]);+});++it('broadcasts v5 canvas updates only after the database transaction commits', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'creating',+ ]);++ Event::fake([V5CanvasResourceUpdated::class]);++ DB::transaction(function () use ($application): void {+ $application->update(['status' => 'running']);++ Event::assertNotDispatched(V5CanvasResourceUpdated::class);+ });++ Event::assertDispatched(V5CanvasResourceUpdated::class);+});diff --git a/tests/Feature/V5/V5DevLimaSeederTest.php b/tests/Feature/V5/V5DevLimaSeederTest.phpnew file mode 100644index 0000000000..b6f1e14921--- /dev/null+++ b/tests/Feature/V5/V5DevLimaSeederTest.php@@ -0,0 +1,139 @@+<?php++use App\Models\V5\Cluster;+use App\Models\V5\Server as V5Server;+use Database\Seeders\V5DevLimaSeeder;+use Illuminate\Support\Facades\Artisan;++beforeEach(function () {+ resetV5DashboardTestState();+});++it('syncs dev Lima VMs into v5 clusters and servers', function () {+ createSharedUserAndTeamTables();+ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Dev Lima Key');++ $exitCode = Artisan::call('v5:sync-dev-lima-servers', [+ '--team-id' => $team->id,+ '--user-id' => $user->id,+ '--cluster' => 'Development-Lima',+ '--server' => [+ 'coold-dev|host.docker.internal|developer|61332|100.64.0.1',+ 'coold-dev-2|host.docker.internal|developer|61379|100.64.0.2',+ ],+ ]);++ expect($exitCode)->toBe(0)+ ->and(Cluster::query()->where('name', 'Development-Lima')->count())->toBe(1)+ ->and(V5Server::query()->where('name', 'coold-dev')->where('host', 'host.docker.internal')->where('node_address', '100.64.0.1')->where('wireguard_management_ip', '100.64.0.1')->where('ssh_port', 61332)->where('private_key_id', $privateKey->id)->exists())->toBeTrue()+ ->and(V5Server::query()->where('name', 'coold-dev-2')->where('host', 'host.docker.internal')->where('node_address', '100.64.0.2')->where('wireguard_management_ip', '100.64.0.2')->where('ssh_port', 61379)->where('private_key_id', $privateKey->id)->exists())->toBeTrue();+});++it('updates legacy dev Lima hostnames to Docker reachable SSH endpoints', function () {+ createSharedUserAndTeamTables();+ [$user, $team] = createV5UserWithTeam();+ $privateKey = createV5PrivateKey($team, 'Dev Lima Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Development-Lima',+ 'description' => 'Local Lima development cluster managed by scripts/dev.sh.',+ ]);++ V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'coold-dev',+ 'host' => 'lima-coold-dev',+ 'ssh_user' => 'developer',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'builder_enabled' => true,+ 'builder_capacity' => 2,+ 'last_bootstrapped_at' => now(),+ ]);++ $exitCode = Artisan::call('v5:sync-dev-lima-servers', [+ '--team-id' => $team->id,+ '--user-id' => $user->id,+ '--cluster' => 'Development-Lima',+ '--server' => [+ 'coold-dev|host.docker.internal|developer|61332',+ ],+ ]);++ expect($exitCode)->toBe(0)+ ->and(V5Server::query()->where('name', 'coold-dev')->count())->toBe(1)+ ->and(V5Server::query()->where('name', 'coold-dev')->where('host', 'host.docker.internal')->where('ssh_port', 61332)->exists())->toBeTrue()+ ->and(V5Server::query()->where('host', 'lima-coold-dev')->exists())->toBeFalse();+});++it('seeds dev Lima VMs into v5 clusters and servers idempotently', function () {+ createSharedUserAndTeamTables();+ [$user, $team] = createV5UserWithTeam();+ createV5PrivateKey($team, 'Dev Lima Key');++ (new V5DevLimaSeeder)->run();+ (new V5DevLimaSeeder)->run();++ $cluster = Cluster::query()->where('name', 'Development-Lima')->sole();++ expect($cluster->team_id)->toBe($team->id)+ ->and($cluster->created_by_user_id)->toBe($user->id)+ ->and($cluster->description)->toBe('Local Lima development cluster managed by scripts/dev.sh.')+ ->and(V5Server::query()->count())->toBe(2)+ ->and(V5Server::query()->where('name', 'coold-dev')->where('host', 'coold-dev.local')->where('ssh_user', 'coolify')->where('ssh_port', 22)->exists())->toBeTrue()+ ->and(V5Server::query()->where('name', 'coold-dev-2')->where('host', 'coold-dev-2.local')->where('ssh_user', 'coolify')->where('ssh_port', 22)->exists())->toBeTrue()+ ->and(V5Server::query()->where('name', 'coold-dev')->where('node_address', '100.64.0.1')->where('wireguard_management_ip', '100.64.0.1')->exists())->toBeTrue()+ ->and(V5Server::query()->where('name', 'coold-dev-2')->where('node_address', '100.64.0.2')->where('wireguard_management_ip', '100.64.0.2')->exists())->toBeTrue()+ ->and(V5Server::query()->where('status', 'installed')->count())->toBe(2)+ ->and(V5Server::query()->where('builder_enabled', false)->where('builder_capacity', 0)->count())->toBe(2)+ ->and(V5Server::query()->where('cluster_id', $cluster->id)->count())->toBe(2);+});++it('seeds dev Lima VMs by updating existing named servers', function () {+ createSharedUserAndTeamTables();+ [$user, $team] = createV5UserWithTeam();+ createV5PrivateKey($team, 'Dev Lima Key');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Development-Lima',+ 'description' => 'Local Lima development cluster managed by scripts/dev.sh.',+ ]);++ V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'coold-dev',+ 'host' => 'old-host.local',+ 'ssh_user' => 'developer',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'last_bootstrapped_at' => now()->subDay(),+ ]);++ (new V5DevLimaSeeder)->run();++ expect(V5Server::query()->where('name', 'coold-dev')->count())->toBe(1)+ ->and(V5Server::query()->where('name', 'coold-dev')->where('host', 'coold-dev.local')->where('ssh_port', 22)->exists())->toBeTrue()+ ->and(V5Server::query()->count())->toBe(2);+});++it('configures v5 dev lima host resolver for coolify internal dns', function () {+ $script = file_get_contents(base_path('scripts/coold-vm.sh'));++ expect($script)+ ->toContain('configure_system_resolved')+ ->toContain('ensure_mesh_dns_anchor')+ ->toContain('coolify-v5-mesh-dns-anchor')+ ->toContain('resolvectl dns podman1 "$CONTAINER_GATEWAY"')+ ->toContain("resolvectl domain podman1 '~coolify.internal'")+ ->toContain('resolvectl default-route podman1 false');+});diff --git a/tests/Feature/V5/V5FluxStatusUpdateTest.php b/tests/Feature/V5/V5FluxStatusUpdateTest.phpnew file mode 100644index 0000000000..bec1407a42--- /dev/null+++ b/tests/Feature/V5/V5FluxStatusUpdateTest.php@@ -0,0 +1,639 @@+<?php++use App\Actions\V5\Flux\ApplyFluxResourceStatusUpdate;+use App\Events\V5CanvasResourceUpdated;+use App\Events\V5ClusterUpdated;+use App\Models\Team;+use App\Models\V5\Application as V5Application;+use App\Models\V5\Cluster;+use App\Models\V5\ContainerStatus;+use App\Models\V5\Server as V5Server;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Event;++beforeEach(function () {+ resetV5DashboardTestState();+});++it('applies flux application status updates to the database and broadcasts to the team canvas', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.5',+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ 'status_message' => 'Container started.',+ 'runtime_container_id' => 'nginx-container-id',+ 'canvas_x' => 0,+ 'canvas_y' => 0,+ ]);++ Event::fake([V5CanvasResourceUpdated::class]);++ $resource = ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'application',+ 'host_id' => '100.64.0.5',+ 'container_name' => 'coolify-v5-nginx-1',+ 'container_id' => 'nginx-container-id',+ 'status' => 'exited',+ 'status_message' => 'Status received from coold through flux.',+ ]);++ expect($resource)->toBeInstanceOf(V5Application::class)+ ->and($application->refresh()->status)->toBe('exited')+ ->and($application->status_message)->toBe('Status received from coold through flux.')+ ->and($application->runtime_container_id)->toBe('nginx-container-id');++ Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id+ && $event->applicationId === $application->id);+});++it('ignores stale flux status updates for a superseded container', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.5',+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ 'status_message' => 'Container started.',+ 'runtime_container_id' => 'new-container-id',+ ]);++ Event::fake([V5CanvasResourceUpdated::class]);++ ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'application',+ 'host_id' => '100.64.0.5',+ 'container_name' => 'coolify-v5-nginx-1',+ 'container_id' => 'old-container-id',+ 'status' => 'exited',+ 'status_message' => 'Stale event for the old container.',+ ]);++ expect($application->refresh()->status)->toBe('running')+ ->and($application->runtime_container_id)->toBe('new-container-id');++ Event::assertNotDispatched(V5CanvasResourceUpdated::class);+});++it('scopes flux application status updates to the reporting server', function () {+ createSharedUserAndTeamTables();++ [$userA, $teamA] = createV5UserWithTeam();+ [$userB, $teamB] = createV5UserWithTeam('[email protected]');+ [$projectA, $environmentA] = createV5ProjectWithEnvironment($teamA, 'Project A', 'Production');+ [$projectB, $environmentB] = createV5ProjectWithEnvironment($teamB, 'Project B', 'Production');+ $serverA = V5Server::query()->create([+ 'team_id' => $teamA->id,+ 'created_by_user_id' => $userA->id,+ 'name' => 'edge-a',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.5',+ ]);+ $serverB = V5Server::query()->create([+ 'team_id' => $teamB->id,+ 'created_by_user_id' => $userB->id,+ 'name' => 'edge-b',+ 'host' => '203.0.113.11',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.6',+ ]);+ $applicationA = V5Application::query()->create([+ 'team_id' => $teamA->id,+ 'project_id' => $projectA->id,+ 'environment_id' => $environmentA->id,+ 'server_id' => $serverA->id,+ 'created_by_user_id' => $userA->id,+ 'name' => 'api',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-api-a',+ 'status' => 'running',+ ]);+ $applicationB = V5Application::query()->create([+ 'uuid' => $applicationA->uuid.'-b',+ 'team_id' => $teamB->id,+ 'project_id' => $projectB->id,+ 'environment_id' => $environmentB->id,+ 'server_id' => $serverB->id,+ 'created_by_user_id' => $userB->id,+ 'name' => 'api',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-api-b',+ 'status' => 'running',+ ]);++ // An update reported by team A's host must never resolve to team B's app,+ // even when the payload carries team B's application uuid.+ $resource = ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'application',+ 'host_id' => '100.64.0.5',+ 'application_uuid' => $applicationB->uuid,+ 'status' => 'exited',+ ]);++ expect($resource)->toBeNull()+ ->and($applicationA->refresh()->status)->toBe('running')+ ->and($applicationB->refresh()->status)->toBe('running');+});++it('ignores flux application status updates whose host does not resolve to a server', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.5',+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ ]);++ $resource = ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'application',+ 'host_id' => '100.99.99.99',+ 'application_uuid' => $application->uuid,+ 'status' => 'exited',+ ]);++ expect($resource)->toBeNull()+ ->and($application->refresh()->status)->toBe('running');+});++it('maps generic flux container status updates to v5 applications', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.5',+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ 'status_message' => 'Container started.',+ 'runtime_container_id' => 'nginx-container-id',+ ]);++ Event::fake([V5CanvasResourceUpdated::class]);++ $resource = ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'container',+ 'host_id' => '100.64.0.5',+ 'container_name' => 'coolify-v5-nginx-1',+ 'container_id' => 'nginx-container-id',+ 'status' => 'exited',+ 'status_message' => 'Container state received from coold.',+ ]);++ expect($resource)->toBeInstanceOf(V5Application::class)+ ->and($application->refresh()->status)->toBe('exited')+ ->and($application->status_message)->toBe('Container state received from coold.');++ Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id+ && $event->applicationId === $application->id);+});++it('applies flux ingress server status updates to the database and broadcasts cluster plus canvas updates', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Cluster',+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => ['ingress'],+ 'wireguard_management_ip' => '100.64.0.5',+ ]);++ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $resource = ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'server',+ 'host_id' => '100.64.0.5',+ 'status' => 'unreachable',+ 'message' => 'coold heartbeat timed out.',+ ]);++ expect($resource)->toBeInstanceOf(V5Server::class)+ ->and($server->refresh()->status)->toBe('unreachable')+ ->and($server->last_status_check)->toBe('flux')+ ->and($server->last_status_output)->toBe('coold heartbeat timed out.')+ ->and($server->last_status_checked_at)->not->toBeNull();++ Event::assertDispatched(V5ClusterUpdated::class, fn (V5ClusterUpdated $event) => $event->teamId === $team->id+ && $event->clusterId === $cluster->id);+ Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id+ && $event->caddyIngressServerId === $server->id);+});++it('ignores flux server status updates when a host id matches multiple v5 servers', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Cluster',+ ]);+ $serverOne = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'wireguard_management_ip' => '100.64.0.5',+ ]);+ $serverTwo = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-02',+ 'host' => '203.0.113.11',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'wireguard_management_ip' => '100.64.0.5',+ ]);++ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $resource = ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'server',+ 'host_id' => '100.64.0.5',+ 'status' => 'unreachable',+ 'message' => 'ambiguous host id.',+ ]);++ expect($resource)->toBeNull()+ ->and($serverOne->refresh()->status)->toBe('installed')+ ->and($serverTwo->refresh()->status)->toBe('installed');++ Event::assertNotDispatched(V5ClusterUpdated::class);+ Event::assertNotDispatched(V5CanvasResourceUpdated::class);+});++it('broadcasts v5 canvas application updates when a non-ingress server goes unreachable', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $cluster = Cluster::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'Production Cluster',+ ]);+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'cluster_id' => $cluster->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'worker-01',+ 'host' => '203.0.113.11',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.6',+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'running',+ 'status_message' => 'Container started.',+ ]);++ Event::fake([V5CanvasResourceUpdated::class, V5ClusterUpdated::class]);++ $resource = ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'server',+ 'host_id' => '100.64.0.6',+ 'status' => 'unreachable',+ 'message' => 'coold heartbeat timed out.',+ ]);++ expect($resource)->toBeInstanceOf(V5Server::class)+ ->and($server->refresh()->status)->toBe('unreachable');++ Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id+ && $event->serverId === $server->id);++ $payload = (new V5CanvasResourceUpdated($team->id, serverId: $server->id))->broadcastWith();+ expect($payload['applications'])+ ->toHaveCount(1)+ ->and($payload['applications'][0])+ ->toMatchArray([+ 'id' => $application->uuid,+ 'status' => 'running',+ 'effectiveStatus' => 'unknown',+ 'effectiveStatusMessage' => 'coold heartbeat timed out.',+ 'serverStatus' => 'unreachable',+ 'isServerReachable' => false,+ ]);+});++it('applies flux caddy ingress container status updates without changing server install status', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'ingress_status' => 'running',+ 'capabilities' => ['ingress'],+ 'wireguard_management_ip' => '100.64.0.5',+ ]);++ Event::fake([V5CanvasResourceUpdated::class]);++ $resource = ApplyFluxResourceStatusUpdate::run([+ 'resource_type' => 'caddy_ingress',+ 'host_id' => '100.64.0.5',+ 'container_name' => 'coolify-v5-caddy',+ 'status' => 'exited',+ 'message' => 'Caddy container exited.',+ ]);++ expect($resource)->toBeInstanceOf(V5Server::class)+ ->and($server->refresh()->status)->toBe('installed')+ ->and($server->ingress_type)->toBe('caddy')+ ->and($server->ingress_status)->toBe('exited')+ ->and($server->last_status_check)->toBe('flux')+ ->and($server->last_status_output)->toBe('Caddy container exited.')+ ->and($server->last_status_checked_at)->not->toBeNull();++ Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id+ && $event->caddyIngressServerId === $server->id);+});++it('accepts flux status updates for non coolify managed containers', function () {+ Config::set('flux.laravel_api_token', 'test-flux-token');+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'wireguard_management_ip' => '100.64.0.5',+ ]);++ $this+ ->postJson('/api/v1/internal/flux/resource-status', [+ 'resource_type' => 'container',+ 'host_id' => '100.64.0.5',+ 'container_id' => 'external-container-id',+ 'container_name' => 'external-container',+ 'status' => 'running',+ ], [+ 'Authorization' => 'Bearer test-flux-token',+ ])+ ->assertSuccessful()+ ->assertJsonPath('message', 'Resource status updated.');++ expect(ContainerStatus::query()+ ->where('container_id', 'external-container-id')+ ->where('container_name', 'external-container')+ ->where('status', 'running')+ ->exists())->toBeTrue();+});++it('rejects flux resource status http updates without the shared token', function () {+ Config::set('flux.laravel_api_token', 'test-flux-token');++ $this+ ->postJson('/api/v1/internal/flux/resource-status', [+ 'resource_type' => 'application',+ 'status' => 'running',+ ])+ ->assertUnauthorized();+});++it('accepts flux resource status http updates identified by resource uuids', function () {+ createSharedUserAndTeamTables();+ Config::set('flux.laravel_api_token', 'test-flux-token');++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'uuid' => 'server-public-uuid',+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.5',+ ]);+ $application = V5Application::query()->create([+ 'uuid' => 'application-public-uuid',+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'starting',+ 'status_message' => 'Container starting.',+ ]);++ $this+ ->withToken('test-flux-token')+ ->postJson('/api/v1/internal/flux/resource-status', [+ 'resource_type' => 'application',+ 'server_uuid' => $server->uuid,+ 'application_uuid' => $application->uuid,+ 'container_id' => 'new-container-id',+ 'status' => 'running',+ 'status_message' => 'Status received from coold through flux.',+ ])+ ->assertSuccessful()+ ->assertJsonPath('message', 'Resource status updated.');++ expect($application->refresh()->status)->toBe('running')+ ->and($application->runtime_container_id)->toBe('new-container-id');+});++it('rejects numeric laravel ids in flux resource status http payloads', function () {+ Config::set('flux.laravel_api_token', 'test-flux-token');++ $this+ ->withToken('test-flux-token')+ ->postJson('/api/v1/internal/flux/resource-status', [+ 'resource_type' => 'application',+ 'server_id' => 1,+ 'application_id' => 1,+ 'status' => 'running',+ ])+ ->assertInvalid(['server_id', 'application_id']);+});++it('accepts flux resource status http updates and stores them in the database', function () {+ createSharedUserAndTeamTables();+ Config::set('flux.laravel_api_token', 'test-flux-token');++ [$user, $team] = createV5UserWithTeam();+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Production Project', 'Production');+ $server = V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'capabilities' => [],+ 'wireguard_management_ip' => '100.64.0.5',+ ]);+ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-1',+ 'status' => 'starting',+ 'status_message' => 'Container starting.',+ 'runtime_container_id' => 'old-container-id',+ ]);++ Event::fake([V5CanvasResourceUpdated::class]);++ $this+ ->withToken('test-flux-token')+ ->postJson('/api/v1/internal/flux/resource-status', [+ 'resource_type' => 'application',+ 'host_id' => '100.64.0.5',+ 'container_name' => 'coolify-v5-nginx-1',+ 'container_id' => 'old-container-id',+ 'status' => 'running',+ 'status_message' => 'Status received from coold through flux.',+ ])+ ->assertSuccessful()+ ->assertJsonPath('message', 'Resource status updated.');++ expect($application->refresh()->status)->toBe('running')+ ->and($application->status_message)->toBe('Status received from coold through flux.')+ ->and($application->runtime_container_id)->toBe('old-container-id');++ Event::assertDispatched(V5CanvasResourceUpdated::class, fn (V5CanvasResourceUpdated $event) => $event->teamId === $team->id+ && $event->applicationId === $application->id);+});++it('configures flux resource status updates for local http instead of redis', function () {+ $configSource = file_get_contents(config_path('flux.php'));++ expect($configSource)+ ->toContain('COOLIFY_FLUX_LARAVEL_API_TOKEN')+ ->not->toContain('APP_KEY')+ ->not->toContain('COOLIFY_FLUX_RESOURCE_STATUS_CHANNEL')+ ->not->toContain('resource_status_channel');+});diff --git a/tests/Feature/V5/V5FrontendSourceContractTest.php b/tests/Feature/V5/V5FrontendSourceContractTest.phpnew file mode 100644index 0000000000..c2914fbcc1--- /dev/null+++ b/tests/Feature/V5/V5FrontendSourceContractTest.php@@ -0,0 +1,932 @@+<?php++use App\Events\V5ClusterUpdated;+use Illuminate\Contracts\Broadcasting\ShouldBroadcast;+use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;++beforeEach(function () {+ resetV5DashboardTestState();+});++it('keeps long v5 application metadata inside the canvas card', function () {+ $applicationCardSource = file_get_contents(resource_path('js/v5/components/canvas/application-card.tsx'));+ $caddyIngressCardSource = file_get_contents(resource_path('js/v5/components/canvas/caddy-ingress-card.tsx'));++ expect($caddyIngressCardSource)+ ->toContain('overflow-hidden')+ ->and($applicationCardSource)->toContain('grid grid-cols-[auto_minmax(0,1fr)]')+ ->and($applicationCardSource)->toContain('truncate text-right font-medium')+ ->and($applicationCardSource)->toContain('truncate text-right font-mono');+});++it('does not render v5 application status messages on dashboard cards', function () {+ $applicationCardSource = file_get_contents(resource_path('js/v5/components/canvas/application-card.tsx'));++ expect($applicationCardSource)+ ->not->toContain('{application.statusMessage && (')+ ->not->toContain('{application.statusMessage}</p>');+});++it('lets users dismiss v5 dashboard notices', function () {+ $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));+ $noticeSource = file_get_contents(resource_path('js/v5/components/canvas/canvas-notice.tsx'));++ expect($noticeSource)+ ->toContain('aria-label="Dismiss notice"')+ ->toContain('onClick={onDismiss}')+ ->toContain('<span className="sr-only">Dismiss notice</span>')+ ->toContain('bg-card')+ ->not->toContain('bg-destructive/10')+ ->not->toContain('bg-emerald-500/10')+ ->not->toContain('bg-blue-500/10');++ expect($dashboardSource)->toContain('onDismiss={dismissNotice}');+});++it('uses the shared dialog and button components for the application ingress modal', function () {+ $ingressDialogSource = file_get_contents(resource_path('js/v5/components/canvas/ingress-dialog.tsx'));++ expect($ingressDialogSource)+ ->toContain('<Dialog')+ ->toContain('open')+ ->toContain('<DialogContent')+ ->toContain('showCloseButton')+ ->toContain('<Button type="submit" variant="coolify"')+ ->not->toContain('>Cancel</button>')+ ->not->toContain('>Close</button>');+});++it('shows a loading state while toggling application ingress', function () {+ $ingressHookSource = file_get_contents(resource_path('js/v5/lib/use-application-ingress.ts'));+ $ingressButtonSource = file_get_contents(resource_path('js/v5/components/canvas/application-ingress-button.tsx'));+ $ingressDialogSource = file_get_contents(resource_path('js/v5/components/canvas/ingress-dialog.tsx'));++ expect($ingressHookSource)+ ->toContain('const savingIngressApplications = usePendingIds<string>()')+ ->toContain('savingIngressApplications.start(application.id)')+ ->toContain('savingIngressApplications.finish(application.id)');++ expect($ingressButtonSource)->toContain("isSaving ? 'Saving...'");++ expect($ingressDialogSource)->toContain("isSaving ? 'Saving...' : 'Enable ingress'");+});++it('shows a dashboard refresh button next to the center button', function () {+ $toolbarSource = file_get_contents(resource_path('js/v5/components/canvas/canvas-toolbar.tsx'));+ $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));++ expect($toolbarSource)+ ->toContain('onClick={onCenter}')+ ->toContain('onClick={onRefresh}')+ ->toContain("isRefreshing ? 'Refreshing…' : 'Refresh state'");++ expect($dashboardSource)+ ->toContain('centerOnCanvasNodes(applications, ingresses)')+ ->toContain('void refreshApplications()');+});++it('subscribes the v5 dashboard canvas to automatic resource status updates', function () {+ $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));+ $channelHookSource = file_get_contents(resource_path('js/v5/lib/use-canvas-channel.ts'));+ $teamChannelSource = file_get_contents(resource_path('js/v5/lib/use-team-channel.ts'));++ $mergeHookSource = file_get_contents(resource_path('js/v5/lib/use-canvas-resource-merge.ts'));++ expect($dashboardSource)+ ->toContain('currentTeam = null')+ ->toContain('useCanvasResourceMerge({')+ ->toContain('teamId: currentTeam?.id ?? null')+ ->not->toContain("fetch('/v5/canvas-state'");++ expect($mergeHookSource)+ ->toContain('setApplications((currentApplications) =>')+ ->toContain('setIngresses((currentIngresses) =>')+ ->toContain('useCanvasResourceChannel(teamId, handleCanvasResourceEvent)');++ expect($channelHookSource)+ ->toContain("useTeamChannel(teamId, '.v5.canvas.resource.updated'");++ expect($teamChannelSource)+ ->toContain('channel.listen(eventName')+ ->toContain('Waiting for window.Echo before subscribing to ${eventName} updates');+});++it('allows zooming the v5 dashboard canvas with buttons and pinch gestures', function () {+ $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));+ $viewportHookSource = file_get_contents(resource_path('js/v5/lib/use-canvas-viewport.ts'));+ $toolbarSource = file_get_contents(resource_path('js/v5/components/canvas/canvas-toolbar.tsx'));++ expect($viewportHookSource)+ ->toContain('zoom: number;')+ ->toContain('MIN_CANVAS_ZOOM')+ ->toContain('MAX_CANVAS_ZOOM')+ ->toContain('PINCH_CANVAS_ZOOM_STEP')+ ->toContain('zoomCanvas(')+ ->toContain('zoomCanvas(event.deltaY < 0 ? 1 : -1, PINCH_CANVAS_ZOOM_STEP')+ ->toContain('event.ctrlKey');++ expect($toolbarSource)+ ->toContain('aria-label="Zoom out"')+ ->toContain('aria-label="Zoom in"')+ ->toContain('Math.round(zoom * 100)');++ expect($dashboardSource)+ ->toContain('onWheel={handleCanvasWheel}')+ ->toContain('scale(${viewport.zoom})');+});++it('renders draggable connector dots on v5 application canvas cards', function () {+ $geometrySource = file_get_contents(resource_path('js/v5/lib/canvas-geometry.ts'));+ $applicationCardSource = file_get_contents(resource_path('js/v5/components/canvas/application-card.tsx'));+ $connectionLinesSource = file_get_contents(resource_path('js/v5/components/canvas/connection-lines.tsx'));+ $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));++ expect($geometrySource)->toContain("export type ConnectorSide = 'top' | 'right' | 'bottom' | 'left';");++ expect($applicationCardSource)+ ->toContain('application-connector')+ ->toContain('data-connector-side={side}')+ ->toContain('onConnectorPointerDown(event, application.id, side)');++ expect($connectionLinesSource)->toContain('<svg className="pointer-events-none absolute inset-0 overflow-visible">');++ expect($dashboardSource)+ ->toContain('onConnectorPointerDown={startConnectionDrag}')+ ->toContain('draftConnection');+});++it('keeps v5 canvas connections selectable unique and shortest-path only', function () {+ $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));+ $connectionsHookSource = file_get_contents(resource_path('js/v5/lib/use-canvas-connections.ts'));+ $geometrySource = file_get_contents(resource_path('js/v5/lib/canvas-geometry.ts'));+ $connectionLinesSource = file_get_contents(resource_path('js/v5/components/canvas/connection-lines.tsx'));+ $portsEditorSource = file_get_contents(resource_path('js/v5/components/canvas/connection-ports-editor.tsx'));+ $applicationCardSource = file_get_contents(resource_path('js/v5/components/canvas/application-card.tsx'));++ expect($dashboardSource)+ ->toContain('resourceConnections: initialResourceConnections = []')+ ->toContain('selectedConnectionId')+ ->toContain('clearCanvasSelection')+ ->toContain('event.target !== event.currentTarget')+ ->toContain('connectionExists')+ ->toContain("closest<HTMLElement>('[data-application-card]')")+ ->toContain('persistNewConnection(pointerState.from.applicationId, targetApplicationId)');++ expect($connectionsHookSource)+ ->toContain('type CanvasConnection = V5ResourceConnection;')+ ->toContain('useState<CanvasConnection[]>(initialConnections)')+ ->toContain("!['Backspace', 'Delete'].includes(event.key)")+ ->toContain('rollback: () =>')+ ->toContain('persistConnectionPorts(updatedConnection, connection)')+ ->toContain('/v5/resource-connections')+ ->toContain('ports_by_direction: portsByDirection')+ ->toContain('connectionDirectionKey(')+ ->toContain('pruneConnectionPortsByDirection(')+ ->toContain('Number.isInteger(portNumber)')+ ->toContain('setConnectionPortInput');++ expect($geometrySource)->toContain('shortestConnectionPoints');++ expect($connectionLinesSource)+ ->toContain('onClick={(event) => onSelect(event, connection.id)}')+ ->toContain("isSelected ? 'stroke-destructive' : 'stroke-warning'")+ ->toContain('aria-label="Select connection"')+ ->toContain('stroke="transparent"')+ ->toContain('strokeWidth={12}')+ ->toContain('id="dashboard-connection-arrow"')+ ->toContain('markerEnd={isSelected ? \'url(#dashboard-connection-arrow)\' : undefined}')+ ->toContain('markerWidth="16"')+ ->toContain('markerHeight="16"')+ ->toContain('strokeDasharray="6 6"');++ expect($portsEditorSource)+ ->toContain('activeConnectionPorts(connection)')+ ->toContain('onAddPort(connection.id)')+ ->toContain('Allowed ports')+ ->toContain('onUpdateDirection(')+ ->toContain('applicationDirectionLabel(')+ ->toContain('application.id.slice(0, 8)')+ ->toContain('connection.applicationIds[0]')+ ->toContain('connection.applicationIds[1]')+ ->toContain('left: (points.from.x + points.to.x) / 2')+ ->toContain('top: (points.from.y + points.to.y) / 2')+ ->toContain('onDelete(connection.id)')+ ->toContain('Delete connection');++ expect($applicationCardSource)+ ->toContain('data-application-card="application-card"')+ ->toContain('group/application')+ ->toContain('opacity-0')+ ->toContain('group-hover/application:opacity-100');+});++it('shows v5 application connector dots after selecting a canvas card', function () {+ $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));+ $applicationCardSource = file_get_contents(resource_path('js/v5/components/canvas/application-card.tsx'));++ expect($dashboardSource)+ ->toContain('selectedApplicationId')+ ->toContain('setSelectedApplicationId(application.id)')+ ->toContain('selectedApplicationId === application.id');++ expect($applicationCardSource)->toContain('opacity-100');+});++it('keeps side connector geometry aligned with the rendered v5 application card height', function () {+ $geometrySource = file_get_contents(resource_path('js/v5/lib/canvas-geometry.ts'));+ $applicationCardSource = file_get_contents(resource_path('js/v5/components/canvas/application-card.tsx'));++ expect($geometrySource)->toContain('const APPLICATION_CARD_HEIGHT = 160;');++ expect($applicationCardSource)->toContain('h-40 w-80');+});++it('shows a loading state on v5 application delete buttons', function () {+ $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));+ $applicationCardSource = file_get_contents(resource_path('js/v5/components/canvas/application-card.tsx'));++ foreach ([+ 'const deletingApplications = usePendingIds<string>()',+ 'deletingApplications.start(application.id)',+ 'deletingApplications.finish(application.id)',+ 'isDeleting={deletingApplications.pendingIds.has(application.id)}',+ ] as $expectedSource) {+ $this->assertTrue(str_contains($dashboardSource, $expectedSource), "Missing source: {$expectedSource}");+ }++ foreach ([+ 'disabled={isDeleting}',+ "{isDeleting ? 'Deleting…' : 'Delete'}",+ ] as $expectedSource) {+ $this->assertTrue(str_contains($applicationCardSource, $expectedSource), "Missing source: {$expectedSource}");+ }+});++it('uses a larger mobile touch target for v5 application connector dots', function () {+ $applicationCardSource = file_get_contents(resource_path('js/v5/components/canvas/application-card.tsx'));++ expect($applicationCardSource)+ ->toContain('size-8')+ ->toContain('md:size-3')+ ->toContain('group/connector')+ ->toContain('group-hover/connector:scale-125')+ ->toContain('<span className="size-3 rounded-full border-2 border-card bg-warning shadow ring-2 ring-background transition group-hover/connector:scale-125 group-hover/connector:bg-warning/90" />');+});++it('detects the connection drop target from pointer coordinates for mobile drags', function () {+ $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));++ expect($dashboardSource)+ ->toContain('connectionTargetFromPointer(event)')+ ->toContain('document.elementFromPoint(event.clientX, event.clientY)')+ ->toContain('pointer-captured mobile drags')+ ->toContain('targetApplicationId !== pointerState.from.applicationId');+});++it('renders coold diagnostics actions in the v5 server menu', function () {+ $clustersPage = file_get_contents(resource_path('js/v5/Pages/Clusters.tsx'));++ expect($clustersPage)+ ->toContain('Coold logs')+ ->toContain('Corrosion tables')+ ->toContain('Firewall rules')+ ->toContain('/coold-logs?tail=200')+ ->toContain('/corrosion-tables?limit=200')+ ->toContain('/firewall-rules')+ ->toContain("source: 'flux' | 'ssh';")+ ->toContain('setCooldLogsSource(payload?.source ?? null)')+ ->toContain('setCorrosionTablesSource(payload?.source ?? null)')+ ->toContain('Source: {diagnosticsSourceLabel(cooldLogsSource)}')+ ->toContain('Source: {diagnosticsSourceLabel(corrosionTablesSource)}')+ ->toContain('Latest journalctl entries')+ ->toContain('Corrosion table snapshots')+ ->toContain('Defined coold allow rules')+ ->toContain('overflow-y-auto overflow-x-hidden')+ ->toContain('whitespace-pre-wrap wrap-anywhere');+});++it('renders v5 server status on cluster server cards', function () {+ $clustersPage = file_get_contents(resource_path('js/v5/Pages/Clusters.tsx'));++ expect($clustersPage)+ ->toContain('server.status')+ ->toContain('server.lastStatusOutput')+ ->toContain('statusLabel(server.status)')+ ->toContain('statusBadgeClass(server.status)');+});++it('broadcasts v5 cluster updates from the queue with an explicit echo event name', function () {+ $clustersPage = file_get_contents(resource_path('js/v5/Pages/Clusters.tsx'));+ $teamChannelSource = file_get_contents(resource_path('js/v5/lib/use-team-channel.ts'));+ $event = new V5ClusterUpdated(1, 1);++ expect($event)->toBeInstanceOf(ShouldBroadcast::class)+ ->not->toBeInstanceOf(ShouldBroadcastNow::class)+ ->and($event->broadcastAs())->toBe('v5.cluster.updated')+ ->and($clustersPage)->toContain("useTeamChannel(currentTeam?.id ?? null, '.v5.cluster.updated'")+ ->and($teamChannelSource)->toContain('Waiting for window.Echo before subscribing to ${eventName} updates');+});++it('serves a v5 realtime test page for manual websocket diagnostics', function () {+ createSharedUserAndTeamTables();++ [$user, $team] = createV5UserWithTeam();+ $page = file_get_contents(resource_path('js/v5/Pages/RealtimeTest.tsx'));++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->get('/v5/realtime-test')+ ->assertSuccessful()+ ->assertSee('RealtimeTest', false)+ ->assertSee((string) $team->id, false);++ expect($page)+ ->toContain('useTeamChannel(')+ ->toContain("'.v5.realtime.test',")+ ->toContain('{ onDebug: addLog, onError: addLog }')+ ->toContain('Broadcast event');++ expect(file_get_contents(resource_path('js/v5/lib/use-team-channel.ts')))+ ->toContain('Subscribing to private-');+});++it('defines the v5 dashboard page as a shadcn styled canvas shell', function () {+ $dashboardPage = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));+ $canvasApi = file_get_contents(resource_path('js/v5/lib/canvas-api.ts'));+ $toolbar = file_get_contents(resource_path('js/v5/components/canvas/canvas-toolbar.tsx'));+ $applicationCard = file_get_contents(resource_path('js/v5/components/canvas/application-card.tsx'));+ $caddyIngressCard = file_get_contents(resource_path('js/v5/components/canvas/caddy-ingress-card.tsx'));+ $inspectorSheet = file_get_contents(resource_path('js/v5/components/canvas/application-inspector-sheet.tsx'));+ $ingressDialog = file_get_contents(resource_path('js/v5/components/canvas/ingress-dialog.tsx'));+ $app = file_get_contents(resource_path('js/v5/app.tsx'));+ $navbarPath = resource_path('js/v5/components/app-navbar.tsx');++ expect(file_exists($navbarPath))->toBeTrue();++ $navbar = file_get_contents($navbarPath);+ $sheetPath = resource_path('js/v5/components/ui/sheet.tsx');++ expect(file_exists($sheetPath))->toBeTrue();++ expect($app)+ ->toContain('progress: {')+ ->toContain('delay: 10')+ ->toContain("color: '#fcd452'")+ ->toContain('showSpinner: false')+ ->not->toContain('TopNavigationLoadingIndicator')+ ->not->toContain('withApp:');++ expect($dashboardPage)+ ->toContain('Dashboard')+ ->toContain("import { AppNavbar } from '@/components/app-navbar';")+ ->not->toContain('function csrfToken()')+ ->toContain("import { canvasRequest } from '@/lib/canvas-api';")+ ->toContain("import { ApplicationInspectorSheet } from '@/components/canvas/application-inspector-sheet';")+ ->toContain("import { IngressDialog } from '@/components/canvas/ingress-dialog';")+ ->not->toContain("fetch('/v5/clusters'")+ ->toContain('<AppNavbar')+ ->toContain('bg-background text-foreground')+ ->toContain('h-dvh overflow-hidden bg-background text-foreground')+ ->toContain('relative h-full min-h-0 overflow-hidden pt-16')+ ->not->toContain('Add nginx')+ ->toContain('selectedNginxServerId')+ ->toContain('nginxImage')+ ->toContain('docker.io/library/nginx:alpine')+ ->toContain('server_uuid: selectedNginxServerId || null')+ ->toContain('image: nginxImage.trim() || DEFAULT_NGINX_IMAGE')+ ->toContain('openApplicationInspector')+ ->toContain('selectedInspectorApplication')+ ->toContain('application={selectedInspectorApplication}')+ ->toContain("method: 'DELETE'")+ ->toContain('removeApplication')+ ->toContain('useEffect(() => {')+ ->toContain('setApplications(settledResources.applications);')+ ->toContain('centerOnCanvasNodes(settledResources.applications, settledResources.ingresses);')+ ->toContain('persistCaddyIngressPosition')+ ->toContain('startIngressDrag')+ ->toContain('canvasRequest(`/v5/caddy-ingresses/${ingress.id}/position`')+ ->toContain("canvasRequest('/v5/applications/nginx'")+ ->toContain('nginxServers = []')+ ->toContain('canvasRequest(`/v5/applications/${application.id}/position`')+ ->not->toContain('<header')+ ->not->toContain('h-[calc(100dvh-4rem)]')+ ->not->toContain('flex h-dvh flex-col overflow-hidden bg-background text-foreground')+ ->toContain('No applications on this canvas yet.')+ ->not->toContain("import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';")+ ->not->toContain("fetch('/v5/selection'");++ expect($canvasApi)+ ->not->toContain('function csrfToken()')+ ->toContain("import { csrfToken } from '@/lib/csrf';");++ expect($toolbar)+ ->toContain('Deploy')+ ->toContain('Select nginx server')+ ->toContain('Center');++ expect($applicationCard)+ ->toContain('Delete')+ ->toContain('onDoubleClick={(event) => onOpenInspector(event, application)}');++ expect($caddyIngressCard)->toContain('Caddy ingress');++ expect($inspectorSheet)+ ->toContain("import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from '@/components/ui/sheet';")+ ->toContain("import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';")+ ->toContain('App configuration')+ ->toContain('open={application !== null}')+ ->toContain('<SheetContent side="right" className="w-full overflow-hidden bg-background sm:rounded-l-xl sm:border data-[side=right]:sm:!inset-y-4 data-[side=right]:sm:!h-auto data-[side=right]:sm:!w-[45vw] data-[side=right]:sm:!max-w-[45vw]"')+ ->toContain('showCloseButton blurOverlay={false}')+ ->toContain('<SheetHeader className="p-6 pb-4">')+ ->toContain('<div className="flex flex-1 flex-col gap-6 px-6 pb-6">')+ ->toContain('<Tabs defaultValue="overview"')+ ->toContain('<TabsList className="w-full justify-start" variant="line">')+ ->toContain('<TabsTrigger value="overview">Overview</TabsTrigger>')+ ->toContain('<TabsTrigger value="networking">Networking</TabsTrigger>')+ ->toContain('<TabsTrigger value="advanced">Advanced</TabsTrigger>')+ ->toContain('Double-click an application card to open configuration.');++ expect($ingressDialog)->toContain("import { Button } from '@/components/ui/button';");++ expect(file_get_contents($sheetPath))+ ->toContain('blurOverlay = true')+ ->toContain('<SheetOverlay blur={blurOverlay} />');++ expect($navbar)+ ->toContain("import { Link, router, usePage } from '@inertiajs/react';")+ ->toContain("import { cn } from '@/lib/utils';")+ ->toContain("import { Sheet, SheetClose, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet';")+ ->toContain("import { csrfToken } from '@/lib/csrf';")+ ->not->toContain('function csrfToken()')+ ->toContain('export function AppNavbar')+ ->toContain('/coolify-logo.svg')+ ->toContain('<Link')+ ->toContain('className="fixed inset-x-0 top-0 z-40 border-b border-border bg-background"')+ ->not->toContain('className="sticky top-0 z-40 shrink-0 border-b border-border bg-background"')+ ->toContain('hover:bg-muted')+ ->toContain('text-muted-foreground')+ ->toContain('SelectGroup')+ ->toContain('variant="ghost"')+ ->toContain('position="popper"')+ ->toContain('sideOffset={4}')+ ->toContain('Select a project')+ ->toContain('Select an environment')+ ->toContain('const { url } = usePage();')+ ->toContain("const isClustersPage = url.startsWith('/v5/clusters');")+ ->toContain('href="/v5"')+ ->toContain('href="/v5/clusters"')+ ->toContain('Clusters')+ ->toContain('className="relative flex h-16 items-center gap-3 px-4 sm:px-6"')+ ->toContain('className="absolute left-1/2 flex min-w-0 -translate-x-1/2 items-center justify-center gap-1 md:static md:flex-1 md:translate-x-0 md:justify-start md:gap-2"')+ ->toContain('className="max-w-[38vw] md:max-w-[10rem]"')+ ->toContain('className="max-w-[30vw] md:max-w-[10rem]"')+ ->toContain('aria-label="Open mobile menu"')+ ->toContain('<Sheet>')+ ->toContain('<SheetTrigger')+ ->toContain('<SheetContent side="right" className="w-72 max-w-[85vw] bg-background"')+ ->toContain('<SheetHeader>')+ ->toContain('<SheetTitle>Coolify</SheetTitle>')+ ->toContain('<SheetDescription className="sr-only">')+ ->toContain('<SheetClose')+ ->toContain('Move between Coolify v5 pages.')+ ->not->toContain('<SheetTitle className="sr-only">Navigation</SheetTitle>')+ ->toContain('className="hidden rounded-md px-3 py-1 text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground md:inline-flex"')+ ->toContain('className="inline-flex rounded-md p-2 text-warning transition-colors hover:bg-muted hover:text-warning md:hidden"')+ ->toContain('Dashboard')+ ->not->toContain('Home')+ ->toContain("fetch('/v5/selection'")+ ->toContain('router.reload({')+ ->toContain("'applications',")+ ->toContain("'caddyIngresses',")+ ->toContain("'resourceConnections',")+ ->toContain("'nginxServers',")+ ->toContain("'selectedProjectUuid',")+ ->toContain("'selectedEnvironmentUuid',")+ ->toContain('void persistSelection(nextProjectUuid, nextEnvironmentUuid).then((persisted) => {')+ ->toContain('void persistSelection(projectUuid, nextEnvironmentUuid).then((persisted) => {')+ ->toContain('refreshCurrentPageSelection();')+ ->toContain("'X-CSRF-TOKEN': csrfToken()")+ ->not->toContain('isMobileMenuOpen')+ ->not->toContain('setIsMobileMenuOpen')+ ->not->toContain('isProjectEnvironmentMenuOpen')+ ->not->toContain('setIsProjectEnvironmentMenuOpen')+ ->not->toContain('Open project and environment selector')+ ->not->toContain('Close project and environment selector')+ ->not->toContain('DropdownMenu')+ ->not->toContain('fixed inset-0 bg-black/80')+ ->not->toContain('fixed inset-y-0 right-0')+ ->not->toContain('<a')+ ->not->toContain("import { Button } from '@/components/ui/button';")+ ->not->toContain('<Button')+ ->not->toContain("import { Separator } from '@/components/ui/separator';")+ ->not->toContain('<Separator')+ ->not->toContain('min-h-[calc(100vh-4rem)]')+ ->not->toContain('py-10')+ ->not->toContain('bg-background/95')+ ->not->toContain('backdrop-blur')+ ->not->toContain('supports-[backdrop-filter]')+ ->not->toContain('border-coolgray')+ ->not->toContain('className="w-[12rem]"')+ ->not->toContain('<h1>Coolify v5</h1>')+ ->not->toContain('<h2 id="clusters-heading">Clusters</h2>');++ expect(file_exists(resource_path('js/v5/components/top-navigation-loading-indicator.tsx')))->toBeFalse();+});++it('tracks v5 server actions with reusable per-id loading state', function () {+ $clustersPage = file_get_contents(resource_path('js/v5/Pages/Clusters.tsx'));+ $pendingIdsHook = file_get_contents(resource_path('js/v5/lib/use-pending-ids.ts'));++ expect($clustersPage)+ ->toContain("import { usePendingIds } from '@/lib/use-pending-ids';")+ ->toContain('const checkingServers = usePendingIds<string>()')+ ->toContain('const isCheckingServer = checkingServers.has(server.id)')+ ->toContain('checkingServers.start(server.id)')+ ->toContain('checkingServers.finish(server.id)')+ ->not->toContain('const [checkingServerId, setCheckingServerId] = useState<string | null>(null)')+ ->not->toContain('setCheckingServerId(server.id)')+ ->not->toContain('setCheckingServerId(null)');++ expect($pendingIdsHook)+ ->toContain('export function usePendingIds')+ ->toContain('const [pendingIds, setPendingIds] = useState<Set<T>>(() => new Set())')+ ->toContain('start')+ ->toContain('finish')+ ->toContain('has')+ ->toContain('hasAny');+});++it('defines the v5 cluster management page and create cluster form', function () {+ $clustersPagePath = resource_path('js/v5/Pages/Clusters.tsx');+ $clustersPage = file_get_contents($clustersPagePath);+ $buttonComponent = file_get_contents(resource_path('js/v5/components/ui/button.tsx'));+ $dialogComponent = file_get_contents(resource_path('js/v5/components/ui/dialog.tsx'));+ $types = file_get_contents(resource_path('js/v5/types.ts'));++ expect(file_exists($clustersPagePath))->toBeTrue();++ preg_match('/<Button\s+type="button"\s+variant="coolify"\s+aria-label="Add server to cluster"/m', $clustersPage, $addServerButtonMatches);++ expect($addServerButtonMatches)->not->toBeEmpty();++ expect($clustersPage)+ ->toContain("import { Button } from '@/components/ui/button';")+ ->toContain("} from '@/components/ui/dialog';")+ ->toContain("} from '@/components/ui/dropdown-menu';")+ ->toContain("import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';")+ ->toContain("import { apiRequest } from '@/lib/api';")+ ->toContain("apiRequest('/v5/clusters'")+ ->toContain('aria-label="Select a cluster"')+ ->toContain('Cluster state')+ ->not->toContain('Last run')+ ->not->toContain('selectedCluster.lastCliStatus')+ ->not->toContain('selectedCluster.lastCliSummary')+ ->toContain('Generated mesh values are saved after bootstrap or extend runs.')+ ->not->toContain('CLI state')+ ->not->toContain('CLI-generated mesh values')+ ->toContain('Select a cluster')+ ->toContain('setSelectedClusterId(value)')+ ->toContain('aria-label="Create cluster"')+ ->toContain('setIsCreateDialogOpen(true)')+ ->toContain('Add cluster')+ ->toContain('variant="coolify"')+ ->not->toContain('border-warning bg-warning/10 text-foreground')+ ->not->toContain('border-primary bg-primary/10 text-foreground')+ ->toContain('<Dialog')+ ->toContain('<DialogTitle>Create cluster</DialogTitle>')+ ->toContain('<DialogDescription>')+ ->toContain('<DialogFooter>')+ ->not->toContain('<DialogClose')+ ->toContain('Cancel')+ ->toContain('<DialogContent className="max-w-md" showCloseButton={false}>')+ ->toContain('<DialogTitle>Confirm deletion</DialogTitle>')+ ->toContain('variant="delete"')+ ->toContain('aria-label="Add server to cluster"')+ ->toContain('setIsAddServerDialogOpen(true)')+ ->toContain('Add server')+ ->toContain('className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between"')+ ->toContain('<DialogTitle>Add server</DialogTitle>')+ ->toContain('DialogContent className="max-w-3xl"')+ ->toContain('DialogContent className="max-w-2xl"')+ ->not->toContain('DialogContent className="max-h-[90dvh] max-w-3xl overflow-y-auto"')+ ->not->toContain('DialogContent className="max-h-[90dvh] max-w-2xl overflow-y-auto"')+ ->toContain('apiRequest(`/v5/clusters/${selectedCluster.id}/servers/${server.id}/bootstrap`')+ ->toContain('apiRequest(`/v5/clusters/${selectedCluster.id}`')+ ->toContain('hasBootstrapInProgress')+ ->toContain('Bootstrap')+ ->toContain('lastBootstrapOutput')+ ->toContain('Unable to queue bootstrap for this server.')+ ->toContain('border-destructive/30')+ ->toContain('apiRequest(`/v5/clusters/${selectedCluster.id}/servers`')+ ->toContain('apiRequest(`/v5/clusters/${selectedCluster.id}/servers/${editingServer.id}`')+ ->toContain('apiRequest(`/v5/clusters/${selectedCluster.id}/servers/${server.id}/check`')+ ->toContain('apiRequest(`/v5/clusters/${cluster.id}/servers/${server.id}`')+ ->toContain("method: 'PATCH'")+ ->toContain("method: 'DELETE'")+ ->toContain('<DropdownMenu>')+ ->toContain('<DropdownMenuTrigger')+ ->toContain("import { DotsThreeIcon } from '@phosphor-icons/react';")+ ->toContain('variant="ghost"')+ ->toContain('size="icon-sm"')+ ->toContain('aria-label="Server actions"')+ ->toContain('<DotsThreeIcon data-icon="inline-start" weight="bold" />')+ ->not->toContain('>Server actions</DropdownMenuTrigger>')+ ->toContain('<DropdownMenuGroup>')+ ->toContain('<DropdownMenuSeparator />')+ ->toContain('Check connection')+ ->not->toContain('Check SSH')+ ->toContain('Not initialized')+ ->toContain('role="group"')+ ->toContain('aria-label="Server initialization"')+ ->toContain('rounded-l-md border border-r-0 border-destructive/30 bg-destructive/10')+ ->toContain('variant="coolify"')+ ->toContain('className="rounded-r-md"')+ ->toContain('onClick={() => void bootstrapServer(server)}')+ ->not->toContain('<DropdownMenuItem+ disabled={isBootstrappingServer}')+ ->not->toContain('Bootstrap: {serverStatusLabel(server.status)}')+ ->not->toContain('Last bootstrap')+ ->not->toContain('{formatDate(server.lastBootstrappedAt)}')+ ->toContain("import { CanvasNotice } from '@/components/canvas/canvas-notice';")+ ->toContain('const [serverConnectionNotice, setServerConnectionNotice] = useState<ServerConnectionNotice | null>(null)')+ ->toContain('setServerConnectionNotice({')+ ->toContain('<CanvasNotice')+ ->toContain('variant={serverConnectionNotice.variant}')+ ->toContain('onDismiss={() => setServerConnectionNotice(null)}')+ ->not->toContain('aria-label="Dismiss server connection notification"')+ ->not->toContain('Latest SSH check: {latestSshCheck.status}')+ ->toContain('const notInitializedServers = selectedCluster?.servers.filter((server) => server.lastBootstrappedAt === null) ?? []')+ ->toContain('const initializedServers = selectedCluster?.servers.filter((server) => server.lastBootstrappedAt !== null) ?? []')+ ->toContain('Not initialized servers')+ ->toContain('{notInitializedServers.map(renderServerCard)}')+ ->toContain('{initializedServers.map(renderServerCard)}')+ ->toContain('{!isServerInitialized ? (')+ ->toContain('const [isBootstrapLogsDialogOpen, setIsBootstrapLogsDialogOpen] = useState(false)')+ ->toContain('const [bootstrapLogsServerId, setBootstrapLogsServerId] = useState<string | null>(null)')+ ->toContain('openBootstrapLogs(server)')+ ->toContain('View install logs')+ ->toContain('<DialogTitle>Install logs</DialogTitle>')+ ->toContain('const parsedBootstrapLogs = parseBootstrapOutput(bootstrapLogsServer?.lastBootstrapOutput ?? null)')+ ->toContain('parsedBootstrapLogs.summary.length > 0')+ ->toContain('parsedBootstrapLogs.visibleOutput')+ ->toContain('visibleOutput: hideRawBootstrapPlan(remainingOutput)')+ ->toContain("line.trim() === 'Plan:'")+ ->toContain('Action results')+ ->toContain('max-h-[70dvh]')+ ->toContain('{canShowBootstrapLogs ? (')+ ->not->toContain('Show install logs')+ ->not->toContain('{!isServerInitialized && isBootstrapLogVisible ? (')+ ->not->toContain('setVisibleBootstrapLogs')+ ->toContain('Delete server')+ ->toContain('This removes it from this cluster inventory so you can add it again later.')+ ->not->toContain('<Button\n type="button"\n variant="outline"\n size="sm"\n disabled={isCheckingServer}')+ ->toContain('<DialogTitle>Edit server</DialogTitle>')+ ->toContain('Edit server')+ ->toContain('Save server')+ ->toContain('editServerBuilderCapacity')+ ->toContain('editServerBuilderCpuQuota')+ ->toContain('Networking and bootstrap settings stay locked after creation.')+ ->toContain('Bootstrap SSH user')+ ->toContain('Bootstrap SSH port')+ ->not->toContain('{server.sshUser}@{server.host}:{server.sshPort}')+ ->toContain('showAdvancedServerConfiguration')+ ->toContain('Node address override')+ ->toContain('Defaults to server IP')+ ->not->toContain('CLI node address')+ ->toContain('wireguardListenPortOverride')+ ->toContain('wireguardEndpointOverride')+ ->toContain('privateKeys')+ ->toContain('selectedPrivateKeyId')+ ->toContain('Private key')+ ->toContain('Select a private key')+ ->toContain('appearance-none')+ ->toContain('backgroundImage: `url("data:image/svg+xml')+ ->not->toContain('No private key')+ ->toContain('Create cluster')+ ->toContain('Cluster details')+ ->toContain('Servers in this cluster')+ ->toContain('selectedCluster')+ ->toContain('Server IP')+ ->toContain('{server.host}')+ ->not->toContain('<dt className="text-muted-foreground">CLI node</dt>')+ ->not->toContain('CLI node')+ ->not->toContain('{server.nodeAddress ?? server.host}')+ ->toContain('builderCapacity')+ ->toContain('{server.builderEnabled ? (')+ ->toContain('<dt className="text-muted-foreground">Builder CPU quota</dt>')+ ->toContain('server.builderCpuQuota')+ ->toContain(') : null}')+ ->toContain('privateKeyName')+ ->toContain('lastBootstrappedAt')+ ->toContain('This removes it from this cluster inventory so you can add it again later.')+ ->toContain('deleteCluster')+ ->toContain('apiRequest(`/v5/clusters/${cluster.id}`')+ ->toContain("method: 'DELETE'")+ ->toContain('Delete cluster')+ ->toContain('selectedCluster.serversCount === 0')+ ->not->toContain("selectedCluster.serversCount === 1 ? 'server' : 'servers'")+ ->toContain('Only empty clusters can be deleted.')+ ->toContain('min-h-dvh overflow-y-auto bg-background text-foreground lg:h-dvh lg:overflow-hidden')+ ->toContain('flex min-h-dvh overflow-visible px-4 pt-16 lg:h-full lg:min-h-0 lg:overflow-hidden lg:px-6')+ ->toContain('flex w-full flex-col gap-4 py-4 lg:min-h-0 lg:py-6')+ ->toContain('rounded-lg border border-border bg-card p-4')+ ->toContain('flex items-start justify-between gap-3')+ ->toContain('min-w-0 flex-1')+ ->toContain('flex shrink-0 items-center justify-end gap-2 sm:flex-wrap')+ ->toContain('aria-label="Select a cluster"')+ ->toContain('setSelectedClusterId(value)')+ ->not->toContain('flex max-h-80 flex-col rounded-lg border border-border bg-card lg:max-h-none lg:min-h-0')+ ->toContain('overflow-visible rounded-lg border border-border bg-card lg:min-h-0 lg:overflow-y-auto')+ ->not->toContain('flex w-full flex-col items-stretch gap-2 sm:w-auto sm:flex-row sm:flex-wrap sm:items-center sm:justify-end')+ ->toContain('mt-4 grid grid-cols-1 gap-3 text-xs sm:grid-cols-2')+ ->not->toContain('lg:grid-cols-[20rem_minmax(0,1fr)]')+ ->not->toContain('lg:grid-cols-[20rem_minmax(0,1fr)_22rem]')+ ->not->toContain('New cluster')+ ->not->toContain('<aside className="rounded-lg border border-border bg-card p-5">')+ ->not->toContain('This is where the magic happens.');++ expect(substr_count($clustersPage, 'variant="coolify"'))->toBe(6)+ ->and($buttonComponent)+ ->toContain('coolify:')+ ->toContain('bg-coollabs-50')+ ->toContain('hover:bg-coollabs')+ ->toContain('delete:');++ expect($dialogComponent)+ ->toContain('@base-ui/react/dialog')+ ->toContain('z-50')+ ->toContain('max-h-[calc(100dvh-2rem)]')+ ->toContain('overflow-y-auto')+ ->toContain('top-1/2')+ ->toContain('-translate-y-1/2')+ ->not->toContain('top-4 bottom-4')+ ->not->toContain('top-1/2 w-[calc(100%-2rem)] max-w-lg -translate-x-1/2 -translate-y-1/2')+ ->toContain('showCloseButton = true')+ ->toContain('aria-label="Close dialog"')+ ->toContain('<XIcon />')+ ->toContain('DialogTitle')+ ->toContain('DialogDescription')+ ->toContain("'mt-6 flex justify-end gap-2'");++ $v5Css = file_get_contents(resource_path('css/v5/app.css'));++ expect($v5Css)+ ->toContain('--color-warning: var(--warning);')+ ->toContain('--warning: #fcd452;')+ ->not->toContain('--ring: oklch(0.705 0.015 286.067);')+ ->not->toContain('--ring: oklch(0.552 0.016 285.938);');++ expect(substr_count($v5Css, '--ring: var(--warning);'))->toBe(2);++ expect($types)+ ->not->toContain('sshUser: string;')+ ->not->toContain('sshPort: number;')+ ->toContain('builderEnabled: boolean;')+ ->toContain('builderCapacity: number;')+ ->toContain('builderCpuQuota: string;')+ ->toContain('privateKeyName: string | null;')+ ->toContain('lastBootstrappedAt: string | null;')+ ->toContain('lastBootstrapStatus: string | null;')+ ->toContain('lastStatusOutput: string | null;');+});++it('uses the standard button size for the v5 delete cluster action', function () {+ $clustersPage = file_get_contents(resource_path('js/v5/Pages/Clusters.tsx'));++ expect($clustersPage)+ ->toContain("variant=\"delete\"\n size=\"default\"\n onClick={openDeleteClusterDialog}")+ ->not->toContain("variant=\"delete\"\n size=\"sm\"\n onClick={openDeleteClusterDialog}");+});++it('shows the v5 server delete validation error in the confirmation dialog', function () {+ $clustersPage = file_get_contents(resource_path('js/v5/Pages/Clusters.tsx'));++ expect($clustersPage)+ ->toContain('const payload = (await response?.json().catch(() => null)) as { message?: string } | null;')+ ->toContain('response?.status === 422')+ ->toContain("'Delete or move applications from this server before deleting it.'")+ ->toContain("'Unable to delete this server. Please try again.'")+ ->toContain('role="alert"')+ ->toContain('border-destructive/30 bg-destructive/10')+ ->toContain('setDeleteClusterError(null);');+});++it('defines a ghost variant for compact v5 select triggers', function () {+ $select = file_get_contents(resource_path('js/v5/components/ui/select.tsx'));++ expect($select)+ ->toContain('@base-ui/react/select')+ ->not->toContain('radix-ui')+ ->toContain("variant = 'default'")+ ->toContain("variant === 'default'")+ ->toContain("variant === 'ghost'")+ ->toContain('border-transparent')+ ->toContain('h-auto')+ ->toContain('text-sm')+ ->toContain("position === 'popper' ? false : true");+});++it('provides reusable v5 form field primitives with reserved validation error space', function () {+ $fieldPath = resource_path('js/v5/components/ui/field.tsx');+ $inputPath = resource_path('js/v5/components/ui/input.tsx');+ $textareaPath = resource_path('js/v5/components/ui/textarea.tsx');+ $clustersPage = file_get_contents(resource_path('js/v5/Pages/Clusters.tsx'));++ expect(file_exists($fieldPath))->toBeTrue()+ ->and(file_exists($inputPath))->toBeTrue()+ ->and(file_exists($textareaPath))->toBeTrue();++ $field = file_get_contents($fieldPath);+ $input = file_get_contents($inputPath);+ $textarea = file_get_contents($textareaPath);++ expect($field)+ ->toContain('function Field(')+ ->toContain('function FieldLabel(')+ ->toContain('function FieldError(')+ ->toContain('min-h-4')+ ->toContain('aria-live="polite"')+ ->toContain('message ? undefined : true')+ ->toContain('export { Field, FieldError, FieldLabel }');++ expect($input)+ ->toContain('function Input(')+ ->toContain('aria-invalid:border-destructive')+ ->toContain('export { Input };');++ expect($textarea)+ ->toContain('function Textarea(')+ ->toContain('aria-invalid:border-destructive')+ ->toContain('export { Textarea };');++ expect($clustersPage)+ ->toContain("import { Field, FieldError, FieldLabel } from '@/components/ui/field';")+ ->toContain("import { Input } from '@/components/ui/input';")+ ->toContain("import { Textarea } from '@/components/ui/textarea';")+ ->toContain('<FieldError message={errors.name?.[0]} />')+ ->toContain('<FieldError message={serverErrors.private_key_uuid?.[0]} />')+ ->not->toContain('{errors.name ? <span className="text-xs text-destructive">{errors.name[0]}</span> : null}')+ ->not->toContain('{serverErrors.name ? (');+});++it('uses the requested shadcn preset configuration for v5', function () {+ $components = json_decode(file_get_contents(base_path('components.json')), true);+ $css = file_get_contents(resource_path('css/v5/app.css'));++ expect($components['style'])+ ->toBe('base-lyra')+ ->and($components['tsx'])->toBeTrue()+ ->and($components['iconLibrary'])->toBe('phosphor')+ ->and($components['tailwind']['css'])->toBe('resources/css/v5/app.css')+ ->and($components['tailwind']['baseColor'])->toBe('zinc')+ ->and($css)->toContain('@import "@fontsource-variable/geist";')+ ->and($css)->toContain('--foreground: oklch(0.141 0.005 285.823);')+ ->and($css)->toContain('--background: #101010;')+ ->and($css)->toContain('button:not(:disabled)');+});++it('sizes the v5 app root with the dynamic mobile viewport', function () {+ $css = file_get_contents(resource_path('css/v5/app.css'));++ expect($css)+ ->toContain('min-height: 100dvh;')+ ->not->toContain('min-height: 100vh;');+});++it('does not include coolify version controls on the v5 dashboard page', function () {+ $dashboardPage = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));++ expect($dashboardPage)+ ->not->toContain('Check coolify version')+ ->not->toContain('/v5/coolify/version')+ ->not->toContain('Installed version:');+});++it('does not render flux status in the v5 navbar', function () {+ $navbar = file_get_contents(resource_path('js/v5/components/app-navbar.tsx'));++ expect($navbar)+ ->not->toContain('Flux: {flux?.label ??')+ ->not->toContain('title={flux?.socket ?? flux?.message ?? undefined}')+ ->not->toContain('{clusters.length} clusters')+ ->not->toContain('<h2 id="flux-status-heading">Flux status</h2>')+ ->not->toContain('<p>{flux.message}</p>')+ ->not->toContain('Socket: {flux.socket}');+});++it('hardens v5 dashboard fetches and websocket merges against failures', function () {+ $dashboardSource = file_get_contents(resource_path('js/v5/Pages/Dashboard.tsx'));+ $canvasApiSource = file_get_contents(resource_path('js/v5/lib/canvas-api.ts'));+ $statusBadgeSource = file_get_contents(resource_path('js/v5/components/canvas/status-badge.ts'));++ expect($canvasApiSource)->toContain('AbortSignal.timeout(30_000)');++ expect($statusBadgeSource)->toContain("'starting'");++ expect($dashboardSource)->toContain('Could not save the card position.');++ $addNginxSource = substr($dashboardSource, strpos($dashboardSource, 'addNginx'));++ expect(strpos($addNginxSource, '!response.ok'))->not->toBeFalse();+});diff --git a/tests/Feature/V5/V5MigrationSchemaTest.php b/tests/Feature/V5/V5MigrationSchemaTest.phpnew file mode 100644index 0000000000..9be2f16539--- /dev/null+++ b/tests/Feature/V5/V5MigrationSchemaTest.php@@ -0,0 +1,343 @@+<?php++use Illuminate\Support\Facades\Schema;++beforeEach(function () {+ resetV5DashboardTestState();+});++it('reuses existing projects instead of creating v5 projects', function () {+ expect(file_exists(database_path('migrations/2026_06_04_050157_v5_create_projects_table.php')))->toBeFalse()+ ->and(file_exists(app_path('Models/V5/Project.php')))->toBeFalse();+});++it('creates v5 cluster tables and lets each server belong to one cluster', function () {+ createSharedUserAndTeamTables();+ Schema::dropIfExists('v5_servers');+ Schema::dropIfExists('v5_clusters');++ $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');+ $clusterMigration->up();++ $serverMigration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');+ $serverMigration->up();++ expect(Schema::hasTable('v5_clusters'))->toBeTrue()+ ->and(Schema::hasColumns('v5_clusters', [+ 'id',+ 'team_id',+ 'created_by_user_id',+ 'name',+ 'description',+ 'wireguard_interface',+ 'wireguard_management_pool',+ 'wireguard_listen_port',+ 'container_network_pool',+ 'container_network_prefix',+ 'namespaces',+ 'default_deny_containers',+ 'coold_version',+ 'corrosion_version',+ 'corrosion_gossip_port',+ 'corrosion_api_port',+ 'builder_enabled',+ 'builder_capacity',+ 'builder_cpu_quota',+ 'builder_memory_max',+ 'builder_timeout_secs',+ 'last_cli_action',+ 'last_cli_status',+ 'last_cli_summary',+ 'last_cli_ran_at',+ 'created_at',+ 'updated_at',+ ]))->toBeTrue()+ ->and(Schema::hasColumn('v5_servers', 'cluster_id'))->toBeTrue();+});++it('creates v5 server tables in the shared database', function () {+ createSharedUserAndTeamTables();++ Schema::dropIfExists('v5_servers');+ Schema::dropIfExists('v5_clusters');++ $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');+ $clusterMigration->up();++ $migration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');+ $migration->up();++ expect(Schema::hasTable('v5_servers'))->toBeTrue()+ ->and(Schema::hasColumns('v5_servers', [+ 'id',+ 'team_id',+ 'cluster_id',+ 'created_by_user_id',+ 'private_key_id',+ 'name',+ 'host',+ 'ssh_user',+ 'ssh_port',+ 'status',+ 'capabilities',+ 'builder_enabled',+ 'builder_capacity',+ 'builder_cpu_quota',+ 'node_address',+ 'wireguard_listen_port_override',+ 'wireguard_endpoint_override',+ 'uuid',+ 'wireguard_management_ip',+ 'wireguard_public_key',+ 'container_subnets',+ 'last_bootstrapped_at',+ 'last_bootstrap_action',+ 'last_bootstrap_status',+ 'last_bootstrap_output',+ 'last_bootstrap_ran_at',+ 'last_status_check',+ 'last_status_output',+ 'last_status_checked_at',+ 'created_at',+ 'updated_at',+ ]))->toBeTrue();+});++it('creates v5 server canvas columns for movable caddy ingress nodes', function () {+ createSharedUserAndTeamTables();++ Schema::dropIfExists('v5_servers');+ Schema::dropIfExists('v5_clusters');++ $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');+ $clusterMigration->up();++ $serverMigration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');+ $serverMigration->up();++ expect(Schema::hasColumns('v5_servers', [+ 'canvas_x',+ 'canvas_y',+ ]))->toBeTrue();+});++it('creates v5 server ingress columns', function () {+ createSharedUserAndTeamTables();++ Schema::dropIfExists('v5_servers');+ Schema::dropIfExists('v5_clusters');++ $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');+ $clusterMigration->up();++ $serverMigration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');+ $serverMigration->up();++ expect(Schema::hasColumns('v5_servers', [+ 'ingress_type',+ 'ingress_status',+ ]))->toBeTrue();+});++it('creates v5 application tables for dashboard canvas nodes', function () {+ createSharedUserAndTeamTables();++ Schema::dropIfExists('v5_application_domains');+ Schema::dropIfExists('v5_applications');+ Schema::dropIfExists('v5_servers');+ Schema::dropIfExists('v5_clusters');++ $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');+ $clusterMigration->up();++ $serverMigration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');+ $serverMigration->up();++ $applicationMigration = include database_path('migrations/2026_06_19_140000_v5_create_applications_table.php');+ $applicationMigration->up();++ expect(Schema::hasTable('v5_applications'))->toBeTrue()+ ->and(Schema::hasColumns('v5_applications', [+ 'id',+ 'team_id',+ 'project_id',+ 'environment_id',+ 'server_id',+ 'created_by_user_id',+ 'name',+ 'image',+ 'container_name',+ 'status',+ 'status_message',+ 'runtime_container_id',+ 'mesh_namespace',+ 'ingress_enabled',+ 'internal_port',+ 'canvas_x',+ 'canvas_y',+ 'created_at',+ 'updated_at',+ ]))->toBeTrue();+});++it('creates v5 application domain tables for zero or more inbound routes', function () {+ createSharedUserAndTeamTables();++ Schema::dropIfExists('v5_application_domains');+ Schema::dropIfExists('v5_applications');+ Schema::dropIfExists('v5_servers');+ Schema::dropIfExists('v5_clusters');++ $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');+ $clusterMigration->up();++ $serverMigration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');+ $serverMigration->up();++ $applicationMigration = include database_path('migrations/2026_06_19_140000_v5_create_applications_table.php');+ $applicationMigration->up();++ expect(Schema::hasTable('v5_application_domains'))->toBeTrue()+ ->and(Schema::hasColumns('v5_application_domains', [+ 'id',+ 'application_id',+ 'domain',+ 'created_at',+ 'updated_at',+ ]))->toBeTrue()+ ->and(Schema::hasColumns('v5_applications', [+ 'ingress_enabled',+ 'internal_port',+ ]))->toBeTrue();+});++it('creates generic v5 resource connection tables', function () {+ createSharedUserAndTeamTables();++ Schema::dropIfExists('v5_resource_connection_rules');+ Schema::dropIfExists('v5_resource_connections');+ Schema::dropIfExists('v5_application_domains');+ Schema::dropIfExists('v5_applications');+ Schema::dropIfExists('v5_servers');+ Schema::dropIfExists('v5_clusters');++ $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');+ $clusterMigration->up();++ $serverMigration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');+ $serverMigration->up();++ $applicationMigration = include database_path('migrations/2026_06_19_140000_v5_create_applications_table.php');+ $applicationMigration->up();++ $connectionMigration = include database_path('migrations/2026_06_19_142000_v5_create_resource_connections_table.php');+ $connectionMigration->up();++ expect(Schema::hasTable('v5_resource_connections'))->toBeTrue()+ ->and(Schema::hasColumns('v5_resource_connections', [+ 'id',+ 'team_id',+ 'project_id',+ 'environment_id',+ 'resource_one_type',+ 'resource_one_id',+ 'resource_two_type',+ 'resource_two_id',+ 'resource_pair_key',+ 'created_by_user_id',+ 'created_at',+ 'updated_at',+ ]))->toBeTrue()+ ->and(Schema::hasTable('v5_resource_connection_rules'))->toBeTrue()+ ->and(Schema::hasColumns('v5_resource_connection_rules', [+ 'id',+ 'connection_id',+ 'source_resource_type',+ 'source_resource_id',+ 'target_resource_type',+ 'target_resource_id',+ 'protocol',+ 'port',+ 'created_at',+ 'updated_at',+ ]))->toBeTrue();+});++it('keeps v5 server fields in the initial migration', function () {+ createSharedUserAndTeamTables();++ Schema::dropIfExists('v5_servers');+ Schema::dropIfExists('v5_clusters');++ $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');+ $clusterMigration->up();++ $serverMigration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');+ $serverMigration->up();++ expect(Schema::hasColumns('v5_servers', [+ 'uuid',+ 'ingress_type',+ 'ingress_status',+ 'builder_cpu_quota',+ 'node_address',+ 'wireguard_management_ip',+ 'container_subnets',+ 'canvas_x',+ 'canvas_y',+ 'last_bootstrap_output',+ 'last_status_output',+ ]))->toBeTrue();+});++it('includes v5 tables in the dev testing schema', function () {+ $schema = file_get_contents(database_path('schema/testing-schema.sql'));++ expect($schema)->toContain('"team_id" INTEGER NOT NULL')+ ->and($schema)->toContain('"created_by_user_id" INTEGER NOT NULL')+ ->and($schema)->not->toContain('CREATE TABLE IF NOT EXISTS "v5_projects"')+ ->and($schema)->not->toContain('2026_06_04_050157_v5_create_projects_table')+ ->and($schema)->toContain('CREATE TABLE IF NOT EXISTS "v5_servers"')+ ->and($schema)->toContain('CREATE TABLE IF NOT EXISTS "v5_container_statuses"')+ ->and($schema)->toContain('CREATE TABLE IF NOT EXISTS "v5_applications"')+ ->and($schema)->toContain('CREATE TABLE IF NOT EXISTS "v5_application_domains"')+ ->and($schema)->toContain('CREATE TABLE IF NOT EXISTS "v5_resource_connections"')+ ->and($schema)->toContain('CREATE TABLE IF NOT EXISTS "v5_resource_connection_rules"')+ ->and($schema)->toContain('"domain" TEXT NOT NULL')+ ->and($schema)->toContain('"ingress_enabled" INTEGER DEFAULT false NOT NULL')+ ->and($schema)->toContain('"internal_port" INTEGER')+ ->and($schema)->toContain('"cluster_id" INTEGER')+ ->and($schema)->toContain('CREATE TABLE IF NOT EXISTS "v5_clusters"')+ ->and($schema)->toContain('"wireguard_interface" TEXT DEFAULT \'wg0\' NOT NULL')+ ->and($schema)->toContain('"wireguard_management_pool" TEXT DEFAULT \'100.64.0.0/16\' NOT NULL')+ ->and($schema)->toContain('"container_network_pool" TEXT DEFAULT \'10.210.0.0/16\' NOT NULL')+ ->and($schema)->toContain('"builder_timeout_secs" INTEGER NOT NULL DEFAULT \'1800\'')+ ->and($schema)->toContain('"private_key_id" INTEGER')+ ->and($schema)->toContain('"ingress_type" TEXT')+ ->and($schema)->toContain('"ingress_status" TEXT')+ ->and($schema)->toContain('"builder_cpu_quota" TEXT DEFAULT \'200%\' NOT NULL')+ ->and($schema)->toContain('"uuid" TEXT')+ ->and($schema)->toContain('"wireguard_management_ip" TEXT')+ ->and($schema)->toContain('"container_subnets" JSON')+ ->and($schema)->toContain('"canvas_x" INTEGER')+ ->and($schema)->toContain('"canvas_y" INTEGER')+ ->and($schema)->toContain('"last_bootstrap_output" TEXT')+ ->and($schema)->toContain('"last_status_output" TEXT')+ ->and($schema)->toContain('2026_06_16_130650_v5_create_servers_table')+ ->and($schema)->toContain('2026_06_19_140000_v5_create_applications_table')+ ->and($schema)->toContain('2026_06_19_142000_v5_create_resource_connections_table')+ ->and($schema)->toContain('2026_06_19_182231_create_container_statuses_table')+ ->and($schema)->not->toContain('2026_06_19_141231_add_canvas_position_to_v5_servers_table')+ ->and($schema)->not->toContain('2026_06_19_173933_add_ingress_status_to_v5_servers_table')+ ->and($schema)->not->toContain('2026_06_20_072818_v5_add_ingress_routing_to_applications_table')+ ->and($schema)->not->toContain('2026_06_19_150000_add_mesh_namespace_to_v5_applications_table')+ ->and($schema)->toContain('2026_06_16_130649_v5_create_clusters_table')+ ->and($schema)->not->toContain('2026_06_16_204644_v5_add_wireguard_cli_configuration_to_clusters_and_servers')+ ->and($schema)->not->toContain('2026_06_17_165112_v5_add_builder_cpu_quota_to_servers_table')+ ->and($schema)->not->toContain('2026_06_17_172845_add_status_check_fields_to_v5_servers_table')+ ->and($schema)->not->toContain('2026_06_19_064539_add_bootstrap_log_fields_to_v5_servers_table')+ ->and($schema)->not->toContain('2026_06_19_090217_add_uuid_to_v5_servers_table')+ ->and($schema)->not->toContain('2026_06_16_131229_add_cluster_id_to_v5_servers_table')+ ->and($schema)->not->toContain('2026_06_16_132000_make_v5_server_private_key_nullable')+ ->and($schema)->not->toContain('v5_hosts');+});diff --git a/tests/Feature/V5/V5RouteMiddlewareTest.php b/tests/Feature/V5/V5RouteMiddlewareTest.phpnew file mode 100644index 0000000000..0246d889d5--- /dev/null+++ b/tests/Feature/V5/V5RouteMiddlewareTest.php@@ -0,0 +1,94 @@+<?php++use App\Http\Kernel;+use App\Http\Middleware\CheckForcePasswordReset;+use App\Http\Middleware\DecideWhatToDoWithUser;+use App\Http\Middleware\V5\EnsureCurrentTeam;+use App\Http\Middleware\V5\HandleInertiaRequests;+use App\Models\Team;+use App\Models\User;+use Illuminate\Support\Facades\Route;++beforeEach(function () {+ resetV5DashboardTestState();+});++it('registers the v5 dashboard route', function () {+ expect(Route::has('v5.dashboard'))->toBeTrue()+ ->and(Route::has('v5.home'))->toBeFalse()+ ->and(Route::has('v5.selection.update'))->toBeTrue()+ ->and(Route::has('v5.clusters.index'))->toBeTrue()+ ->and(Route::has('v5.clusters.show'))->toBeTrue()+ ->and(Route::has('v5.clusters.store'))->toBeTrue()+ ->and(Route::has('v5.clusters.destroy'))->toBeTrue()+ ->and(Route::has('v5.clusters.servers.store'))->toBeTrue()+ ->and(Route::has('v5.clusters.servers.update'))->toBeTrue()+ ->and(Route::has('v5.clusters.servers.check'))->toBeTrue()+ ->and(Route::has('v5.clusters.servers.coold-logs'))->toBeTrue()+ ->and(Route::has('v5.clusters.servers.corrosion-tables'))->toBeTrue()+ ->and(Route::has('v5.clusters.servers.bootstrap'))->toBeTrue()+ ->and(Route::has('v5.clusters.servers.destroy'))->toBeTrue()+ ->and(Route::has('v5.applications.nginx'))->toBeTrue()+ ->and(Route::has('v5.applications.refresh'))->toBeTrue()+ ->and(Route::has('v5.applications.position'))->toBeTrue()+ ->and(Route::has('v5.applications.ingress'))->toBeTrue()+ ->and(Route::has('v5.caddy-ingresses.position'))->toBeTrue()+ ->and(Route::has('v5.applications.destroy'))->toBeTrue()+ ->and(Route::has('v5.resource-connections.store'))->toBeTrue()+ ->and(Route::has('v5.resource-connections.update'))->toBeTrue()+ ->and(Route::has('v5.resource-connections.destroy'))->toBeTrue()+ ->and(Route::has('v5.realtime-test'))->toBeTrue()+ ->and(Route::has('v5.realtime-test.broadcast'))->toBeTrue()+ ->and(Route::has('v5.coolify.version'))->toBeFalse()+ ->and(Route::has('v5.coolify.bootstrap'))->toBeFalse();+});++it('uses separated v5 middleware groups', function () {+ $kernel = app(Kernel::class);+ $reflection = new ReflectionClass($kernel);+ $property = $reflection->getProperty('middlewareGroups');+ $property->setAccessible(true);+ $groups = $property->getValue($kernel);++ expect($groups)->toHaveKey('v5.web')+ ->and($groups)->toHaveKey('v5.authenticated')+ ->and($groups['v5.web'])->toContain(HandleInertiaRequests::class)+ ->and($groups['v5.web'])->not->toContain(CheckForcePasswordReset::class)+ ->and($groups['v5.web'])->not->toContain(DecideWhatToDoWithUser::class)+ ->and($groups['v5.authenticated'])->toContain('auth')+ ->and($groups['v5.authenticated'])->toContain('verified')+ ->and($groups['v5.authenticated'])->toContain(EnsureCurrentTeam::class);+});++it('redirects guests to the shared login', function () {+ $this->get('/v5')+ ->assertRedirect('/login');+});++it('selects a shared team when the session has no current team', function () {+ $this->withoutVite();+ fakeFluxHealth();+ createSharedUserAndTeamTables();++ $user = User::withoutEvents(fn () => User::query()->create([+ 'name' => 'Grace Hopper',+ 'email' => '[email protected]',+ 'email_verified_at' => now(),+ 'password' => 'password',+ ]));+ $team = Team::withoutEvents(fn () => Team::query()->create([+ 'name' => 'Auto Selected Team',+ 'description' => null,+ 'personal_team' => false,+ 'show_boarding' => false,+ ]));+ $user->teams()->attach($team, ['role' => 'admin']);++ $this+ ->actingAs($user)+ ->get('/v5')+ ->assertSuccessful()+ ->assertSessionHas('currentTeam')+ ->assertDontSee('Auto Selected Team')+ ->assertDontSee('admin');+});diff --git a/tests/Feature/V5/V5TeardownTeamTest.php b/tests/Feature/V5/V5TeardownTeamTest.phpnew file mode 100644index 0000000000..4c6174c8da--- /dev/null+++ b/tests/Feature/V5/V5TeardownTeamTest.php@@ -0,0 +1,329 @@+<?php++use App\Jobs\V5TeardownTeamJob;+use App\Models\Environment;+use App\Models\InstanceSettings;+use App\Models\PrivateKey;+use App\Models\Project;+use App\Models\Team;+use App\Models\User;+use App\Models\V5\Application as V5Application;+use App\Models\V5\RevokedAgentToken;+use App\Models\V5\Server as V5Server;+use App\Services\Flux\FluxClient;+use Illuminate\Foundation\Testing\RefreshDatabase;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Facades\Process;+use Illuminate\Support\Facades\Queue;+use Mockery\MockInterface;++uses(RefreshDatabase::class);++beforeEach(function () {+ InstanceSettings::updateOrCreate(['id' => 0]);++ $this->owner = User::factory()->create();+ $this->team = Team::factory()->create(['name' => 'Teardown Team']);+ $this->team->members()->attach($this->owner->id, ['role' => 'owner']);+ $this->privateKey = PrivateKey::factory()->create(['team_id' => $this->team->id]);+});++/**+ * @param array<string, mixed> $attributes+ */+function createTeardownServer(Team $team, User $owner, PrivateKey $privateKey, array $attributes = []): V5Server+{+ return V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $owner->id,+ 'private_key_id' => $privateKey->id,+ 'name' => 'prod-'.fake()->unique()->numberBetween(1, 9999),+ 'host' => fake()->unique()->ipv4(),+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ ...$attributes,+ ]);+}++function createTeardownApplication(Team $team, User $owner, V5Server $server): V5Application+{+ $project = Project::query()->create(['name' => fake()->unique()->company(), 'team_id' => $team->id]);+ // Project creation auto-provisions a default environment; reuse it rather+ // than colliding with the (name, project_id) unique index.+ $environment = $project->environments()->first()+ ?? Environment::query()->create(['name' => 'production', 'project_id' => $project->id]);++ // The checked-in testing-schema.sql dump predates the v5_applications.uuid+ // column, so skip the V5Model uuid-generating event (matching how the other+ // V5 suites hand-roll their schema) to insert against the dump.+ return V5Application::withoutEvents(fn () => V5Application::query()->forceCreate([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $owner->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-'.fake()->unique()->numerify('#######'),+ 'status' => 'running',+ ]));+}++/**+ * @param array<string, mixed> $overrides+ * @param array<int, array<string, mixed>> $applications+ * @return array<string, mixed>+ */+function teardownServerPayload(array $overrides = [], array $applications = []): array+{+ return [+ 'id' => 1,+ 'uuid' => 'teardown-server-uuid',+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'node_address' => '203.0.113.10',+ 'wireguard_management_ip' => '100.64.0.10',+ 'is_ingress' => false,+ 'ingress_type' => null,+ 'status' => 'installed',+ 'last_bootstrapped_at' => now()->toISOString(),+ 'private_key' => "-----BEGIN OPENSSH PRIVATE KEY-----\ntest-key\n-----END OPENSSH PRIVATE KEY-----\n",+ 'applications' => $applications,+ ...$overrides,+ ];+}++it('dispatches the v5 teardown job for the team servers when the team is deleted', function () {+ Queue::fake();++ $serverOne = createTeardownServer($this->team, $this->owner, $this->privateKey, [+ 'host' => '203.0.113.10',+ 'is_ingress' => true,+ 'ingress_type' => 'caddy',+ 'wireguard_management_ip' => '100.64.0.10',+ 'last_bootstrapped_at' => now(),+ ]);+ createTeardownApplication($this->team, $this->owner, $serverOne);+ $serverTwo = createTeardownServer($this->team, $this->owner, $this->privateKey, [+ 'host' => '203.0.113.11',+ 'last_bootstrapped_at' => now(),+ ]);++ $this->team->delete();++ // The team deletion completes (the teardown hook never blocks it). The+ // per-row cascade is a database-level guarantee from the v5 migrations'+ // cascadeOnDelete() foreign keys; the in-memory SQLite test dump does not+ // enforce it, so it is not asserted here.+ expect(Team::find($this->team->id))->toBeNull();++ Queue::assertPushed(V5TeardownTeamJob::class, function (V5TeardownTeamJob $job): bool {+ if ($job->teamId !== $this->team->id || count($job->servers) !== 2) {+ return false;+ }++ $ingressServer = collect($job->servers)->firstWhere('host', '203.0.113.10');++ return $ingressServer !== null+ && $ingressServer['is_ingress'] === true+ && str_contains((string) $ingressServer['private_key'], 'BEGIN OPENSSH PRIVATE KEY')+ && count($ingressServer['applications']) === 1+ && str_starts_with((string) $ingressServer['applications'][0]['container_name'], 'coolify-v5-nginx-');+ });+});++it('does not dispatch teardown when the team owns no v5 servers', function () {+ Queue::fake();++ $this->team->delete();++ Queue::assertNotPushed(V5TeardownTeamJob::class);+});++it('runs the full per-server teardown sequence over ssh and flux', function () {+ Process::fake(['*' => Process::result(output: '')]);++ $fluxClient = Mockery::mock(FluxClient::class, function (MockInterface $mock): void {+ $mock->shouldReceive('revokeFirewallRule')->andReturn('Firewall rule revoked.');+ $mock->shouldReceive('stopIngress')+ ->once()+ ->with(Mockery::type('string'), 'caddy')+ ->andReturn('Caddy ingress stopped.');+ });+ app()->instance(FluxClient::class, $fluxClient);++ $payload = teardownServerPayload([+ 'is_ingress' => true,+ 'ingress_type' => 'caddy',+ ], [+ ['id' => 5, 'container_name' => 'coolify-v5-nginx-abc', 'runtime_container_id' => 'runtime-1'],+ ]);++ (new V5TeardownTeamJob($this->team->id, [$payload]))->handle();++ // Application container removal ran over SSH.+ Process::assertRan(fn ($process) => is_array($process->command)+ && ($process->command[0] ?? null) === 'ssh'+ && str_contains((string) end($process->command), "rm -f 'coolify-v5-nginx-abc'"));++ // On-host bootstrap identity removal ran over SSH.+ Process::assertRan(fn ($process) => is_array($process->command)+ && ($process->command[0] ?? null) === 'ssh'+ && str_contains((string) end($process->command), '/etc/coolify/v5-node.json'));+});++it('keeps tearing down other servers when one host is unreachable', function () {+ Process::fake(['*' => Process::result(output: '')]);++ // The ingress server's Flux stop throws (unreachable host); teardown of the+ // rest must still proceed and the job must not fail.+ $fluxClient = Mockery::mock(FluxClient::class, function (MockInterface $mock): void {+ $mock->shouldReceive('revokeFirewallRule')->andReturn('Firewall rule revoked.');+ $mock->shouldReceive('stopIngress')+ ->with(Mockery::type('string'), 'caddy')+ ->andThrow(new RuntimeException('flux socket unreachable'));+ });+ app()->instance(FluxClient::class, $fluxClient);++ $unreachableIngress = teardownServerPayload([+ 'id' => 1,+ 'host' => '203.0.113.10',+ 'wireguard_management_ip' => '100.64.0.10',+ 'is_ingress' => true,+ 'ingress_type' => 'caddy',+ ]);+ $healthyServer = teardownServerPayload([+ 'id' => 2,+ 'host' => '203.0.113.11',+ 'wireguard_management_ip' => '100.64.0.11',+ ]);++ (new V5TeardownTeamJob($this->team->id, [$unreachableIngress, $healthyServer]))->handle();++ // The healthy server was still cleaned up despite the first host failing.+ Process::assertRan(fn ($process) => is_array($process->command)+ && in_array('[email protected]', $process->command, true)+ && str_contains((string) end($process->command), '/etc/coolify/v5-node.json'));++ // The unreachable ingress server's marker removal was still attempted.+ Process::assertRan(fn ($process) => is_array($process->command)+ && in_array('[email protected]', $process->command, true)+ && str_contains((string) end($process->command), '/etc/coolify/v5-node.json'));+});++it('captures each server agent token jti and expiry in the dispatched payload', function () {+ Queue::fake();++ $server = createTeardownServer($this->team, $this->owner, $this->privateKey, [+ 'host' => '203.0.113.42',+ 'agent_token_jti' => 'jti-captured',+ 'agent_token_expires_at' => now()->addDay(),+ 'last_bootstrapped_at' => now(),+ ]);++ $this->team->delete();++ Queue::assertPushed(V5TeardownTeamJob::class, function (V5TeardownTeamJob $job): bool {+ $payload = collect($job->servers)->firstWhere('host', '203.0.113.42');++ return $payload !== null+ && $payload['agent_token_jti'] === 'jti-captured'+ && $payload['agent_token_expires_at'] !== null;+ });+});++it('revokes each server host token during teardown', function () {+ Process::fake(['*' => Process::result(output: '')]);++ $expiresAtOne = now()->addDay();+ $expiresAtTwo = now()->addDays(2);++ $fluxClient = Mockery::mock(FluxClient::class, function (MockInterface $mock) use ($expiresAtOne, $expiresAtTwo): void {+ $mock->shouldReceive('revokeFirewallRule')->andReturn('Firewall rule revoked.');+ $mock->shouldReceive('revokeToken')->once()->with('jti-1', $expiresAtOne->timestamp);+ $mock->shouldReceive('revokeToken')->once()->with('jti-2', $expiresAtTwo->timestamp);+ });+ app()->instance(FluxClient::class, $fluxClient);++ // last_bootstrapped_at null so only the explicit token revocation runs (no+ // SSH marker removal, which would revoke a second time).+ $serverOne = teardownServerPayload([+ 'id' => 1,+ 'host' => '203.0.113.10',+ 'last_bootstrapped_at' => null,+ 'agent_token_jti' => 'jti-1',+ 'agent_token_expires_at' => $expiresAtOne->toISOString(),+ ]);+ $serverTwo = teardownServerPayload([+ 'id' => 2,+ 'host' => '203.0.113.11',+ 'last_bootstrapped_at' => null,+ 'agent_token_jti' => 'jti-2',+ 'agent_token_expires_at' => $expiresAtTwo->toISOString(),+ ]);++ (new V5TeardownTeamJob($this->team->id, [$serverOne, $serverTwo]))->handle();++ expect(RevokedAgentToken::query()->where('jti', 'jti-1')->exists())->toBeTrue()+ ->and(RevokedAgentToken::query()->where('jti', 'jti-2')->exists())->toBeTrue();+});++it('logs the incomplete-teardown error naming hosts that could not be torn down', function () {+ Process::fake(['*' => Process::result(output: '')]);+ Log::spy();++ // The ingress host's Flux stop throws (unreachable) so it is reported+ // incomplete; the healthy host tears down cleanly.+ $fluxClient = Mockery::mock(FluxClient::class, function (MockInterface $mock): void {+ $mock->shouldReceive('revokeFirewallRule')->andReturn('Firewall rule revoked.');+ $mock->shouldReceive('revokeToken')->andReturnNull();+ $mock->shouldReceive('stopIngress')+ ->with(Mockery::type('string'), 'caddy')+ ->andThrow(new RuntimeException('flux socket unreachable'));+ });+ app()->instance(FluxClient::class, $fluxClient);++ $unreachableIngress = teardownServerPayload([+ 'id' => 1,+ 'host' => '203.0.113.10',+ 'wireguard_management_ip' => '100.64.0.10',+ 'is_ingress' => true,+ 'ingress_type' => 'caddy',+ ]);+ $healthyServer = teardownServerPayload([+ 'id' => 2,+ 'host' => '203.0.113.11',+ 'wireguard_management_ip' => '100.64.0.11',+ ]);++ (new V5TeardownTeamJob($this->team->id, [$unreachableIngress, $healthyServer]))->handle();++ // The healthy host was still cleaned up despite the ingress host failing.+ Process::assertRan(fn ($process) => is_array($process->command)+ && in_array('[email protected]', $process->command, true)+ && str_contains((string) end($process->command), '/etc/coolify/v5-node.json'));++ // The operator-facing signal names only the unreachable host.+ Log::shouldHaveReceived('error')->withArgs(+ fn (string $message, array $context = []) => str_contains($message, 'v5 team teardown incomplete')+ && ($context['team_id'] ?? null) === $this->team->id+ && collect($context['hosts'] ?? [])->contains(fn ($host) => ($host['host'] ?? null) === '203.0.113.10')+ && collect($context['hosts'] ?? [])->doesntContain(fn ($host) => ($host['host'] ?? null) === '203.0.113.11')+ )->once();+});++it('does not remove the bootstrap marker for servers that were never bootstrapped', function () {+ Process::fake(['*' => Process::result(output: '')]);++ $payload = teardownServerPayload([+ 'last_bootstrapped_at' => null,+ 'is_ingress' => false,+ ]);++ (new V5TeardownTeamJob($this->team->id, [$payload]))->handle();++ Process::assertNothingRan();+});diff --git a/tests/Pest.php b/tests/Pest.phpindex 81df3649b1..c7c2f3c0a4 100644--- a/tests/Pest.php+++ b/tests/Pest.php@@ -16,6 +16,17 @@ use Tests\TestCase;*/uses(TestCase::class)->in('Feature', 'v4/Feature', 'v4/Browser');+/*+|--------------------------------------------------------------------------+| Shared Helpers+|--------------------------------------------------------------------------+|+| Helper functions shared across multiple test files.+|+*/++require_once __DIR__.'/Support/V5TestHelpers.php';+/*|--------------------------------------------------------------------------| Test Hooksdiff --git a/tests/Support/V5TestHelpers.php b/tests/Support/V5TestHelpers.phpnew file mode 100644index 0000000000..55233a3e58--- /dev/null+++ b/tests/Support/V5TestHelpers.php@@ -0,0 +1,246 @@+<?php++/*+|--------------------------------------------------------------------------+| Shared V5 Test Helpers+|--------------------------------------------------------------------------+|+| Global Pest helper functions shared by the tests/Feature/V5 and+| tests/Unit/V5 suites. Loaded from tests/Pest.php. The v5_* table+| definitions themselves live in Tests\Support\V5TestSchema so they cannot+| drift from the migrations per test file.+|+*/++use App\Models\Environment;+use App\Models\PrivateKey;+use App\Models\Project;+use App\Models\Team;+use App\Models\User;+use App\Services\Flux\AgentTokenIssuer;+use App\Services\Flux\FluxClient;+use App\Services\Flux\FluxHealth;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Schema;+use Mockery\MockInterface;+use Tests\Support\V5TestSchema;++/**+ * The shared per-test reset used by the split V5 dashboard feature tests+ * (previously the DashboardTest beforeEach).+ */+function resetV5DashboardTestState(): void+{+ Config::set('app.maintenance.store', 'array');+ Config::set('broadcasting.default', 'log');+ Config::set('cache.default', 'array');+ Config::set('flux.bootstrap_host_connection_timeout_seconds', 0);++ V5TestSchema::dropAllTables();+ Schema::dropIfExists('private_keys');+ Schema::dropIfExists('team_user');+ Schema::dropIfExists('teams');+ Schema::dropIfExists('users');+}++function fakeFluxHealth(bool $available = true, string $message = 'Flux is running.'): void+{+ app()->instance(FluxHealth::class, Mockery::mock(FluxHealth::class, function (MockInterface $mock) use ($available, $message) {+ $mock->shouldReceive('check')+ ->once()+ ->andReturn([+ 'available' => $available,+ 'label' => $available ? 'Running' : 'Unavailable',+ 'message' => $message,+ 'socket' => '/run/coolify/flux.sock',+ ]);+ }));+}++function fakeAgentTokenIssuer(string $token = 'signed-host-jwt'): void+{+ $issuer = Mockery::mock(AgentTokenIssuer::class);+ $issuer->shouldReceive('issueForServer')->andReturn($token);+ app()->instance(AgentTokenIssuer::class, $issuer);+}++function fakeSuccessfulNginxFluxDeployment(string $image = 'docker.io/library/nginx:alpine'): void+{+ $mock = Mockery::mock(FluxClient::class, function (MockInterface $mock) use ($image): void {+ $mock->shouldReceive('pullImage')+ ->once()+ ->with(Mockery::type('string'), $image)+ ->andReturn('Image pulled.');+ $mock->shouldReceive('createContainer')+ ->once()+ ->with(Mockery::type('string'), Mockery::on(fn (array $spec): bool => ($spec['image'] ?? null) === $image+ && ($spec['networks'] ?? []) === ['coolify-default-mesh']+ && ($spec['dns_search'] ?? []) === ['default.coolify.internal']+ && in_array($spec['name'] ?? '', $spec['network_aliases'] ?? [], true)))+ ->andReturn('nginx-container-id');+ $mock->shouldReceive('startContainer')+ ->once()+ ->with(Mockery::type('string'), 'nginx-container-id')+ ->andReturn('Container started.');+ $mock->shouldReceive('inspectContainer')+ ->once()+ ->with(Mockery::type('string'), 'nginx-container-id')+ ->andReturn(['State' => ['Running' => true]]);+ });++ app()->instance(FluxClient::class, $mock);+}++function expectCaddyIngressFirewallRule(mixed $fluxClient): void+{+ $fluxClient+ ->shouldReceive('applyFirewallRule')+ ->once()+ ->with(Mockery::type('string'), [+ 'id' => 'v5-caddy-ingress:80',+ 'namespace' => 'default',+ 'src' => '0.0.0.0/0',+ 'dst' => 'coolify-v5-caddy',+ 'proto' => 'tcp',+ 'port' => 80,+ ])+ ->andReturn('Firewall rule applied.');+ $fluxClient+ ->shouldNotReceive('applyFirewallRule')+ ->with(Mockery::type('string'), Mockery::on(fn (array $rule): bool => ($rule['port'] ?? null) === 443));+}++function createSharedUserAndTeamTables(): void+{+ Schema::create('users', function ($table) {+ $table->id();+ $table->string('name')->default('Anonymous');+ $table->string('email');+ $table->timestamp('email_verified_at')->nullable();+ $table->string('password')->nullable();+ $table->rememberToken();+ $table->timestamps();+ });++ Schema::create('teams', function ($table) {+ $table->id();+ $table->string('name');+ $table->string('description')->nullable();+ $table->boolean('personal_team')->default(false);+ $table->boolean('show_boarding')->default(false);+ $table->timestamps();+ });++ Schema::create('private_keys', function ($table) {+ $table->id();+ $table->string('uuid')->unique();+ $table->string('name');+ $table->string('description')->nullable();+ $table->longText('private_key');+ $table->string('fingerprint')->nullable();+ $table->boolean('is_git_related')->default(false);+ $table->foreignId('team_id');+ $table->timestamps();+ });++ Schema::create('projects', function ($table) {+ $table->id();+ $table->string('uuid');+ $table->string('name');+ $table->text('description')->nullable();+ $table->foreignId('team_id');+ $table->timestamps();+ });++ Schema::create('environments', function ($table) {+ $table->id();+ $table->string('name');+ $table->foreignId('project_id');+ $table->timestamps();+ $table->text('description')->nullable();+ $table->string('uuid');+ });++ V5TestSchema::createAllTables();++ Schema::create('team_user', function ($table) {+ $table->id();+ $table->foreignId('team_id');+ $table->foreignId('user_id');+ $table->string('role')->default('member');+ $table->timestamps();++ $table->unique(['team_id', 'user_id']);+ });+}++/**+ * @param array<int, string> $command+ */+function cliFlagValue(array $command, string $flag): ?string+{+ $index = array_search($flag, $command, true);++ if ($index === false || ! isset($command[$index + 1])) {+ return null;+ }++ return $command[$index + 1];+}++/**+ * @return array{0: Project, 1: Environment}+ */+function createV5ProjectWithEnvironment(Team $team, string $projectName, string $environmentName): array+{+ $project = Project::withoutEvents(fn () => Project::query()->forceCreate([+ 'uuid' => str($projectName)->slug().'-uuid',+ 'name' => $projectName,+ 'description' => null,+ 'team_id' => $team->id,+ ]));++ $environment = Environment::withoutEvents(fn () => Environment::query()->forceCreate([+ 'uuid' => str($environmentName)->slug().'-uuid',+ 'name' => $environmentName,+ 'description' => null,+ 'project_id' => $project->id,+ ]));++ return [$project, $environment];+}++function createV5PrivateKey(Team $team, string $name): PrivateKey+{+ return PrivateKey::withoutEvents(fn () => PrivateKey::query()->forceCreate([+ 'uuid' => str($name)->slug().'-uuid',+ 'name' => $name,+ 'description' => null,+ 'private_key' => "-----BEGIN OPENSSH PRIVATE KEY-----\ntest-key\n-----END OPENSSH PRIVATE KEY-----\n",+ 'fingerprint' => str($name)->slug()->toString(),+ 'is_git_related' => false,+ 'team_id' => $team->id,+ ]));+}++/**+ * @return array{0: User, 1: Team}+ */+function createV5UserWithTeam(string $email = '[email protected]'): array+{+ $user = User::withoutEvents(fn () => User::query()->create([+ 'name' => 'Margaret Hamilton',+ 'email' => $email,+ 'email_verified_at' => now(),+ 'password' => 'password',+ ]));+ $team = Team::withoutEvents(fn () => Team::query()->create([+ 'name' => 'V5 Tooling Team',+ 'description' => null,+ 'personal_team' => false,+ 'show_boarding' => false,+ ]));+ $user->teams()->attach($team, ['role' => 'owner']);++ return [$user, $team];+}diff --git a/tests/Support/V5TestSchema.php b/tests/Support/V5TestSchema.phpnew file mode 100644index 0000000000..8ecf46f8ab--- /dev/null+++ b/tests/Support/V5TestSchema.php@@ -0,0 +1,230 @@+<?php++namespace Tests\Support;++use Illuminate\Support\Facades\Schema;++/**+ * Single source of truth for the v5_* table definitions used by tests that+ * build their schema by hand instead of running the full migration set.+ *+ * The column definitions must exactly mirror the final state produced by the+ * database/migrations/*v5* files (including the 2026_07_05/2026_07_06+ * additions: status_observed_at, coold_version, has_coold/is_ingress booleans+ * replacing the dropped capabilities json, and NOT NULL server uuids). Update+ * this class in the same change as any v5 migration.+ *+ * Cross-table foreign key constraints and the composite unique indexes on+ * v5_servers (team_id/host/ssh_port) and v5_clusters (team_id/name) are+ * intentionally omitted: tests seed sparse rows (team_id => 1 without a teams+ * row) and rely on application-level validation, matching the previous+ * hand-rolled schemas. Unique indexes that encode behaviour are kept.+ */+class V5TestSchema+{+ public static function createAllTables(): void+ {+ self::createClustersTable();+ self::createServersTable();+ self::createContainerStatusesTable();+ self::createApplicationsTable();+ self::createApplicationDomainsTable();+ self::createResourceConnectionsTable();+ self::createResourceConnectionRulesTable();+ self::createRevokedAgentTokensTable();+ }++ public static function dropAllTables(): void+ {+ Schema::dropIfExists('v5_revoked_agent_tokens');+ Schema::dropIfExists('v5_resource_connection_rules');+ Schema::dropIfExists('v5_resource_connections');+ Schema::dropIfExists('v5_application_domains');+ Schema::dropIfExists('v5_applications');+ Schema::dropIfExists('v5_container_statuses');+ Schema::dropIfExists('v5_servers');+ Schema::dropIfExists('v5_clusters');+ }++ public static function createClustersTable(): void+ {+ Schema::create('v5_clusters', function ($table) {+ $table->id();+ $table->string('uuid')->unique();+ $table->foreignId('team_id');+ $table->foreignId('created_by_user_id');+ $table->string('name');+ $table->text('description')->nullable();+ $table->string('wireguard_interface')->default('wg0');+ $table->string('wireguard_management_pool')->default('100.64.0.0/16');+ $table->unsignedInteger('wireguard_listen_port')->default(51820);+ $table->string('container_network_pool')->default('10.210.0.0/16');+ $table->unsignedTinyInteger('container_network_prefix')->default(24);+ $table->json('namespaces')->nullable();+ $table->boolean('default_deny_containers')->default(true);+ $table->string('coold_version')->default('nightly');+ $table->string('corrosion_version')->default('v1.0.0');+ $table->unsignedInteger('corrosion_gossip_port')->default(8787);+ $table->unsignedInteger('corrosion_api_port')->default(8080);+ $table->boolean('builder_enabled')->default(true);+ $table->unsignedInteger('builder_capacity')->default(2);+ $table->string('builder_cpu_quota')->default('200%');+ $table->string('builder_memory_max')->default('2G');+ $table->unsignedInteger('builder_timeout_secs')->default(1800);+ $table->string('last_cli_action')->nullable();+ $table->string('last_cli_status')->nullable();+ $table->text('last_cli_summary')->nullable();+ $table->timestamp('last_cli_ran_at')->nullable();+ $table->timestamps();+ });+ }++ public static function createServersTable(): void+ {+ Schema::create('v5_servers', function ($table) {+ $table->id();+ $table->string('uuid')->unique();+ $table->foreignId('team_id');+ $table->foreignId('cluster_id')->nullable();+ $table->foreignId('created_by_user_id');+ $table->foreignId('private_key_id')->nullable();+ $table->string('name');+ $table->string('host');+ $table->string('ssh_user');+ $table->unsignedInteger('ssh_port')->default(22);+ $table->string('status')->default('installed');+ $table->timestamp('status_observed_at')->nullable();+ $table->string('ingress_type')->nullable();+ $table->string('ingress_status')->nullable();+ $table->boolean('has_coold')->default(false)->index();+ $table->boolean('is_ingress')->default(false)->index();+ $table->boolean('builder_enabled')->default(false);+ $table->unsignedInteger('builder_capacity')->default(0);+ $table->string('builder_cpu_quota')->default('200%');+ $table->string('node_address')->nullable();+ $table->unsignedInteger('wireguard_listen_port_override')->nullable();+ $table->string('wireguard_endpoint_override')->nullable();+ $table->string('wireguard_management_ip')->nullable();+ $table->string('wireguard_public_key')->nullable();+ $table->string('coold_version')->nullable();+ $table->string('agent_token_jti')->nullable();+ $table->timestamp('agent_token_expires_at')->nullable();+ $table->json('container_subnets')->nullable();+ $table->integer('canvas_x')->nullable();+ $table->integer('canvas_y')->nullable();+ $table->timestamp('last_bootstrapped_at')->nullable();+ $table->string('last_bootstrap_action')->nullable();+ $table->string('last_bootstrap_status')->nullable();+ $table->text('last_bootstrap_output')->nullable();+ $table->timestamp('last_bootstrap_ran_at')->nullable();+ $table->string('last_status_check')->nullable();+ $table->text('last_status_output')->nullable();+ $table->timestamp('last_status_checked_at')->nullable();+ $table->timestamps();+ });+ }++ public static function createContainerStatusesTable(): void+ {+ Schema::create('v5_container_statuses', function ($table) {+ $table->id();+ $table->foreignId('team_id');+ $table->foreignId('server_id');+ $table->string('container_id');+ $table->string('container_name')->nullable();+ $table->string('image')->nullable();+ $table->string('status')->default('unknown');+ $table->text('status_message')->nullable();+ $table->timestamp('status_observed_at')->nullable();+ $table->timestamp('last_seen_at')->nullable()->index();+ $table->timestamps();++ $table->unique(['server_id', 'container_id']);+ });+ }++ public static function createApplicationsTable(): void+ {+ Schema::create('v5_applications', function ($table) {+ $table->id();+ $table->string('uuid')->unique();+ $table->foreignId('team_id');+ $table->foreignId('project_id');+ $table->foreignId('environment_id');+ $table->foreignId('server_id')->nullable();+ $table->foreignId('created_by_user_id');+ $table->string('name');+ $table->string('image');+ $table->string('container_name')->unique();+ $table->string('status')->default('creating');+ $table->text('status_message')->nullable();+ $table->timestamp('status_observed_at')->nullable();+ $table->string('runtime_container_id')->nullable();+ $table->string('mesh_namespace')->default('default');+ $table->boolean('ingress_enabled')->default(false);+ $table->unsignedSmallInteger('internal_port')->nullable();+ $table->integer('canvas_x')->default(0);+ $table->integer('canvas_y')->default(0);+ $table->timestamps();+ });+ }++ public static function createApplicationDomainsTable(): void+ {+ Schema::create('v5_application_domains', function ($table) {+ $table->id();+ $table->foreignId('application_id');+ $table->string('domain');+ $table->timestamps();++ $table->unique(['application_id', 'domain']);+ });+ }++ public static function createResourceConnectionsTable(): void+ {+ Schema::create('v5_resource_connections', function ($table) {+ $table->id();+ $table->string('uuid')->unique();+ $table->foreignId('team_id');+ $table->foreignId('project_id');+ $table->foreignId('environment_id');+ $table->string('resource_one_type');+ $table->unsignedBigInteger('resource_one_id');+ $table->string('resource_two_type');+ $table->unsignedBigInteger('resource_two_id');+ $table->string('resource_pair_key');+ $table->foreignId('created_by_user_id');+ $table->timestamps();++ $table->unique(['team_id', 'resource_pair_key']);+ });+ }++ public static function createRevokedAgentTokensTable(): void+ {+ Schema::create('v5_revoked_agent_tokens', function ($table) {+ $table->id();+ $table->string('jti')->unique();+ $table->foreignId('server_id')->nullable();+ $table->timestamp('revoked_at')->nullable();+ $table->timestamp('expires_at')->nullable()->index();+ $table->timestamps();+ });+ }++ public static function createResourceConnectionRulesTable(): void+ {+ Schema::create('v5_resource_connection_rules', function ($table) {+ $table->id();+ $table->foreignId('connection_id');+ $table->string('source_resource_type');+ $table->unsignedBigInteger('source_resource_id');+ $table->string('target_resource_type');+ $table->unsignedBigInteger('target_resource_id');+ $table->string('protocol')->default('tcp');+ $table->unsignedSmallInteger('port');+ $table->timestamps();+ });+ }+}diff --git a/tests/Unit/V5/AgentTokenIssuerTest.php b/tests/Unit/V5/AgentTokenIssuerTest.phpnew file mode 100644index 0000000000..1009008751--- /dev/null+++ b/tests/Unit/V5/AgentTokenIssuerTest.php@@ -0,0 +1,151 @@+<?php++use App\Models\V5\Server as V5Server;+use App\Services\Flux\AgentTokenIssuer;+use Firebase\JWT\JWT;+use Firebase\JWT\Key;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Log;+use Tests\TestCase;++uses(TestCase::class);++/**+ * @return array{0: string, 1: string}+ */+function createAgentTokenIssuerKeypair(): array+{+ $directory = storage_path('framework/testing/agent-token-keys-'.bin2hex(random_bytes(4)));+ mkdir($directory, 0777, true);++ $privateKeyPath = $directory.'/jwt.priv';+ $publicKeyPath = $directory.'/jwt.pub';++ exec('openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out '.escapeshellarg($privateKeyPath), $out, $code);+ expect($code)->toBe(0);+ chmod($privateKeyPath, 0600);++ exec('openssl pkey -in '.escapeshellarg($privateKeyPath).' -pubout -out '.escapeshellarg($publicKeyPath), $out, $code);+ expect($code)->toBe(0);++ return [$privateKeyPath, $publicKeyPath];+}++function decodeAgentToken(string $token, string $publicKeyPath, ?stdClass &$headers = null): stdClass+{+ // Firebase's JWT::decode only populates $headers when it is non-null on+ // entry (it opts out of clobbering by default), so seed a placeholder.+ if (func_num_args() >= 3) {+ $headers = new stdClass;+ }++ return JWT::decode($token, new Key(file_get_contents($publicKeyPath), 'ES256'), $headers);+}++beforeEach(function () {+ [$this->privateKeyPath, $this->publicKeyPath] = createAgentTokenIssuerKeypair();+ Config::set('flux.jwt_private_key_path', $this->privateKeyPath);+});++it('mints the explicit advertised capability list by default, not the wildcard profile', function () {+ $token = app(AgentTokenIssuer::class)->issue('100.64.0.10');+ $claims = decodeAgentToken($token, $this->publicKeyPath);++ expect((array) $claims->caps)->toBe(config('flux.host_capabilities'))+ ->and((array) $claims->caps)->toContain('containers.create')+ ->and((array) $claims->caps)->toContain('ingress.apply')+ ->and((array) $claims->caps)->toContain('host.jwt.set')+ ->and((array) $claims->caps)->not->toContain('host-agent:default')+ ->and((array) $claims->caps)->not->toContain('host-agent:dev')+ ->and((array) $claims->caps)->not->toContain('*');+});++it('mints the escape-hatch capability profile when configured', function () {+ Config::set('flux.host_capability_profile', 'host-agent:default');++ $token = app(AgentTokenIssuer::class)->issue('100.64.0.10');+ $claims = decodeAgentToken($token, $this->publicKeyPath);++ expect((array) $claims->caps)->toBe(['host-agent:default']);+});++it('includes a unique jti on every minted token', function () {+ $issuer = app(AgentTokenIssuer::class);++ $first = decodeAgentToken($issuer->issue('100.64.0.10'), $this->publicKeyPath);+ $second = decodeAgentToken($issuer->issue('100.64.0.10'), $this->publicKeyPath);++ expect($first->jti)->toBeString()->not->toBe('')+ ->and($second->jti)->toBeString()->not->toBe('')+ ->and($first->jti)->not->toBe($second->jti);+});++it('derives the token lifetime from config', function () {+ Config::set('flux.host_token_ttl', 1234);++ $before = time();+ $claims = decodeAgentToken(app(AgentTokenIssuer::class)->issue('100.64.0.10'), $this->publicKeyPath);++ expect($claims->exp - $claims->iat)->toBe(1234)+ ->and($claims->exp)->toBeGreaterThanOrEqual($before + 1234);+});++it('defaults host token lifetime to the flux max token lifetime', function () {+ $claims = decodeAgentToken(app(AgentTokenIssuer::class)->issue('100.64.0.10'), $this->publicKeyPath);++ expect($claims->exp - $claims->iat)->toBe(3600)+ ->and(config('flux.host_token_refresh_threshold'))->toBeLessThan(config('flux.host_token_ttl'));+});++it('clamps a below-floor ttl to 60 seconds', function () {+ $claims = decodeAgentToken(app(AgentTokenIssuer::class)->issue('100.64.0.10', null, 5), $this->publicKeyPath);++ expect($claims->exp - $claims->iat)->toBe(60);+});++it('sets the configured kid header for future key rotation', function () {+ Config::set('flux.jwt_kid', 'flux-2026');++ $headers = null;+ decodeAgentToken(app(AgentTokenIssuer::class)->issue('100.64.0.10'), $this->publicKeyPath, $headers);++ expect($headers->kid)->toBe('flux-2026')+ ->and($headers->alg)->toBe('ES256');+});++it('refuses to mint a host token before the server has a stable Flux host id', function () {+ $server = new V5Server([+ 'node_address' => '203.0.113.10',+ 'wireguard_management_ip' => '100.64.0.10',+ ]);++ expect(fn () => app(AgentTokenIssuer::class)->issueForServer($server))+ ->toThrow(RuntimeException::class, 'Server is missing a valid Flux host id.');+});++it('mints server host tokens for the stable server uuid, not the WireGuard management IP', function () {+ $server = new V5Server([+ 'uuid' => 'server_abc123',+ 'team_id' => 12,+ 'cluster_id' => 34,+ 'node_address' => '203.0.113.10',+ 'wireguard_management_ip' => '100.64.0.10',+ ]);++ $claims = decodeAgentToken(app(AgentTokenIssuer::class)->issueForServer($server), $this->publicKeyPath);++ expect($claims->sub)->toBe('server_abc123')+ ->and($claims->server_id)->toBe('server_abc123')+ ->and($claims->wireguard_management_ip)->toBe('100.64.0.10');+});++it('warns when the private key file has insecure permissions', function () {+ chmod($this->privateKeyPath, 0644);++ Log::shouldReceive('warning')+ ->once()+ ->withArgs(fn (string $message, array $context) => str_contains($message, 'insecure permissions')+ && $context['expected'] === '0600');++ app(AgentTokenIssuer::class)->issue('100.64.0.10');+});diff --git a/tests/Unit/V5/BroadcastPayloadTest.php b/tests/Unit/V5/BroadcastPayloadTest.phpnew file mode 100644index 0000000000..0892a01aa8--- /dev/null+++ b/tests/Unit/V5/BroadcastPayloadTest.php@@ -0,0 +1,100 @@+<?php++use App\Events\V5CanvasResourceUpdated;+use App\Events\V5ClusterUpdated;+use App\Models\V5\Application as V5Application;+use App\Models\V5\Server as V5Server;+use App\Support\V5\CanvasResourceSerializer;+use Tests\TestCase;++uses(TestCase::class);++beforeEach(function () {+ resetV5DashboardTestState();+ createSharedUserAndTeamTables();+});++/**+ * @param array<string, mixed> $attributes+ */+function createBroadcastPayloadServer(array $attributes = []): V5Server+{+ [$user, $team] = createV5UserWithTeam();++ return V5Server::query()->create([+ 'team_id' => $team->id,+ 'created_by_user_id' => $user->id,+ 'name' => 'edge-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'wireguard_management_ip' => '100.64.0.10',+ ...$attributes,+ ]);+}++it('serializes a null cluster payload when the cluster is gone before the queued broadcast runs', function () {+ [, $team] = createV5UserWithTeam();++ $event = new V5ClusterUpdated($team->id, 999);++ expect($event->broadcastWith())->toBe(['cluster' => null]);+});++it('omits the caddy ingress payload for a non-ingress server', function () {+ $server = createBroadcastPayloadServer(['is_ingress' => false]);++ $event = new V5CanvasResourceUpdated($server->team_id, null, $server->id);++ expect($event->broadcastWith()['caddyIngress'])->toBeNull();+});++it('serializes the caddy ingress payload for an ingress server', function () {+ $server = createBroadcastPayloadServer([+ 'is_ingress' => true,+ 'ingress_type' => 'caddy',+ 'ingress_status' => 'running',+ ]);++ $payload = (new V5CanvasResourceUpdated($server->team_id, null, $server->id))->broadcastWith();++ expect($payload['caddyIngress'])->toBe(+ app(CanvasResourceSerializer::class)->serializeCaddyIngress($server->fresh()),+ )->and($payload['caddyIngress']['id'])->toBe($server->uuid);+});++it('broadcasts the same application shape as the initial-load canvas serializer', function () {+ $server = createBroadcastPayloadServer();+ $team = $server->team;+ [$project, $environment] = createV5ProjectWithEnvironment($team, 'Payload Parity', 'production');++ $application = V5Application::query()->create([+ 'team_id' => $team->id,+ 'project_id' => $project->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'created_by_user_id' => $server->created_by_user_id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-parity',+ 'status' => 'running',+ 'status_message' => 'Container started.',+ 'runtime_container_id' => 'container-123',+ 'ingress_enabled' => true,+ 'internal_port' => 8080,+ ]);+ $application->domains()->create(['domain' => 'parity.example.com']);++ $payload = (new V5CanvasResourceUpdated($team->id, $application->id))->broadcastWith();++ $expected = app(CanvasResourceSerializer::class)->serializeApplication(+ V5Application::query()->with(['server', 'domains'])->findOrFail($application->id),+ );++ expect($payload['application'])->toBe($expected)+ ->and($payload['application']['id'])->toBe($application->uuid)+ ->and($payload['application']['domains'])->toBe(['parity.example.com'])+ ->and($payload['application']['projectUuid'])->toBe($project->uuid)+ ->and($payload['application']['environmentUuid'])->toBe($environment->uuid);+});diff --git a/tests/Unit/V5/CaddyIngressConfigurationTest.php b/tests/Unit/V5/CaddyIngressConfigurationTest.phpindex 09ef7a7462..deacf10a94 100644--- a/tests/Unit/V5/CaddyIngressConfigurationTest.php+++ b/tests/Unit/V5/CaddyIngressConfigurationTest.php@@ -9,6 +9,7 @@ use App\Models\V5\Server;use App\Services\Flux\FluxClient;use Illuminate\Support\Collection;use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Log;use Tests\TestCase;uses(TestCase::class);@@ -48,6 +49,143 @@ it('generates a caddy ingress compose file with health endpoint and application->and($configuration['apps'][0]['caddyfile'])->toContain('reverse_proxy coolify-v5-nginx-test.default.coolify.internal:8080');});+it('generates byte-identical caddy routes for valid domains', function () {+ $application = new Application([+ 'name' => 'nginx-test',+ 'container_name' => 'coolify-v5-nginx-test',+ 'mesh_namespace' => 'default',+ 'ingress_enabled' => true,+ 'internal_port' => 8080,+ ]);+ $application->setRelation('domains', new Collection([+ new ApplicationDomain(['domain' => 'nginx.example.com']),+ new ApplicationDomain(['domain' => 'www.nginx.example.com']),+ ]));++ $configuration = GenerateCaddyIngressConfiguration::run(new Collection([$application]));++ expect($configuration['apps'][0]['caddyfile'])->toBe(implode("\n", [+ 'http://nginx.example.com {',+ ' reverse_proxy coolify-v5-nginx-test.default.coolify.internal:8080',+ '}',+ '',+ 'http://www.nginx.example.com {',+ ' reverse_proxy coolify-v5-nginx-test.default.coolify.internal:8080',+ '}',+ ]));+});++it('never emits domains with caddyfile injection payloads into the configuration', function () {+ Log::spy();++ $application = new Application([+ 'name' => 'nginx-test',+ 'container_name' => 'coolify-v5-nginx-test',+ 'mesh_namespace' => 'default',+ 'ingress_enabled' => true,+ 'internal_port' => 8080,+ ]);+ $application->setRelation('domains', new Collection([+ new ApplicationDomain(['domain' => "evil.com {\n} http://x"]),+ new ApplicationDomain(['domain' => "evil\n.com"]),+ new ApplicationDomain(['domain' => 'safe.example.com']),+ ]));++ $configuration = GenerateCaddyIngressConfiguration::run(new Collection([$application]));++ expect($configuration['apps'])->toHaveCount(1)+ ->and($configuration['apps'][0]['caddyfile'])->not->toContain('evil')+ ->and($configuration['apps'][0]['caddyfile'])->toBe(implode("\n", [+ 'http://safe.example.com {',+ ' reverse_proxy coolify-v5-nginx-test.default.coolify.internal:8080',+ '}',+ ]));++ Log::shouldHaveReceived('warning')+ ->with('Skipping a caddy ingress route with an unsafe domain.', Mockery::type('array'))+ ->twice();+});++it('skips whole applications when every domain is malicious', function () {+ Log::spy();++ $application = new Application([+ 'name' => 'nginx-test',+ 'container_name' => 'coolify-v5-nginx-test',+ 'mesh_namespace' => 'default',+ 'ingress_enabled' => true,+ 'internal_port' => 8080,+ ]);+ $application->setRelation('domains', new Collection([+ new ApplicationDomain(['domain' => 'evil.com { respond "pwned" }']),+ ]));++ $configuration = GenerateCaddyIngressConfiguration::run(new Collection([$application]));++ expect($configuration['apps'])->toBe([]);++ Log::shouldHaveReceived('warning')+ ->with('Skipping a caddy ingress route with an unsafe domain.', Mockery::type('array'))+ ->once();+});++it('never emits unsafe container names or namespaces into the configuration', function () {+ Log::spy();++ $application = new Application([+ 'name' => 'nginx-test',+ 'container_name' => "coolify {\n} injected",+ 'mesh_namespace' => 'default',+ 'ingress_enabled' => true,+ 'internal_port' => 8080,+ ]);+ $application->setRelation('domains', new Collection([+ new ApplicationDomain(['domain' => 'app.example.com']),+ ]));++ $namespaceApplication = new Application([+ 'name' => 'nginx-test-2',+ 'container_name' => 'coolify-v5-nginx-test',+ 'mesh_namespace' => "default {\n}",+ 'ingress_enabled' => true,+ 'internal_port' => 8080,+ ]);+ $namespaceApplication->setRelation('domains', new Collection([+ new ApplicationDomain(['domain' => 'other.example.com']),+ ]));++ $configuration = GenerateCaddyIngressConfiguration::run(new Collection([$application, $namespaceApplication]));++ expect($configuration['apps'])->toBe([]);++ Log::shouldHaveReceived('warning')+ ->with('Skipping a caddy ingress route with an unsafe container name or namespace.', Mockery::type('array'))+ ->twice();+});++it('never emits out-of-range internal ports into the configuration', function () {+ Log::spy();++ $application = new Application([+ 'name' => 'nginx-test',+ 'container_name' => 'coolify-v5-nginx-test',+ 'mesh_namespace' => 'default',+ 'ingress_enabled' => true,+ ]);+ $application->internal_port = 70000;+ $application->setRelation('domains', new Collection([+ new ApplicationDomain(['domain' => 'app.example.com']),+ ]));++ $configuration = GenerateCaddyIngressConfiguration::run(new Collection([$application]));++ expect($configuration['apps'])->toBe([]);++ Log::shouldHaveReceived('warning')+ ->with('Skipping a caddy ingress route with an out-of-range internal port.', Mockery::type('array'))+ ->once();+});+it('does not generate app routes for applications without domains', function () {$application = new Application(['name' => 'private-app',@@ -103,6 +241,7 @@ it('does not generate app routes when the internal port is missing', function ()it('applies caddy ingress configuration through flux instead of ssh', function () {$server = new Server([+ 'uuid' => 'test-server-uuid','wireguard_management_ip' => '100.64.0.10','node_address' => '10.0.0.10','capabilities' => ['ingress'],@@ -113,7 +252,7 @@ it('applies caddy ingress configuration through flux instead of ssh', function (->shouldReceive('applyIngress')->once()->with(- '100.64.0.10',+ Mockery::type('string'),'caddy',Mockery::on(fn (string $caddyfile): bool => str_contains($caddyfile, 'respond /coolify-health 200')),[]@@ -122,7 +261,7 @@ it('applies caddy ingress configuration through flux instead of ssh', function ($fluxClient->shouldReceive('applyFirewallRule')->once()- ->with('100.64.0.10', [+ ->with(Mockery::type('string'), ['id' => 'v5-caddy-ingress:80','namespace' => 'default','src' => '0.0.0.0/0',@@ -132,17 +271,8 @@ it('applies caddy ingress configuration through flux instead of ssh', function (])->andReturn('Firewall rule applied.');$fluxClient- ->shouldReceive('applyFirewallRule')- ->once()- ->with('100.64.0.10', [- 'id' => 'v5-caddy-ingress:443',- 'namespace' => 'default',- 'src' => '0.0.0.0/0',- 'dst' => 'coolify-v5-caddy',- 'proto' => 'tcp',- 'port' => 443,- ])- ->andReturn('Firewall rule applied.');+ ->shouldNotReceive('applyFirewallRule')+ ->with(Mockery::type('string'), Mockery::on(fn (array $rule): bool => ($rule['port'] ?? null) === 443));app()->instance(FluxClient::class, $fluxClient);$result = StartCaddyIngress::run($server);@@ -162,32 +292,103 @@ it('does not start caddy ingress for non-ingress servers', function () {it('stops caddy ingress through flux instead of ssh', function () {$server = new Server([+ 'uuid' => 'test-server-uuid','wireguard_management_ip' => '100.64.0.10','node_address' => '10.0.0.10',- 'capabilities' => [],+ 'capabilities' => ['ingress'],]);$fluxClient = Mockery::mock(FluxClient::class);$fluxClient->shouldReceive('stopIngress')->once()- ->with('100.64.0.10', 'caddy')+ ->with(Mockery::type('string'), 'caddy')->andReturn('Caddy ingress stopped.');$fluxClient->shouldReceive('revokeFirewallRule')->once()- ->with('100.64.0.10', 'v5-caddy-ingress:80')+ ->with(Mockery::type('string'), 'v5-caddy-ingress:80')->andReturn('Firewall rule removed.');+ $fluxClient+ ->shouldNotReceive('revokeFirewallRule')+ ->with(Mockery::type('string'), 'v5-caddy-ingress:443');+ app()->instance(FluxClient::class, $fluxClient);++ $result = StopCaddyIngress::run($server);++ expect($result)->toBe('Caddy ingress stopped.');+});++it('does not stop caddy ingress for servers that never had ingress', function () {+ $server = new Server([+ 'uuid' => 'test-server-uuid',+ 'wireguard_management_ip' => '100.64.0.10',+ 'capabilities' => [],+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldNotReceive('stopIngress');+ $fluxClient->shouldNotReceive('revokeFirewallRule');+ app()->instance(FluxClient::class, $fluxClient);++ expect(StopCaddyIngress::run($server))->toBe('Server is not an ingress server.');+});++it('revokes the caddy firewall rule before stopping the ingress container', function () {+ $server = new Server([+ 'uuid' => 'test-server-uuid',+ 'wireguard_management_ip' => '100.64.0.10',+ 'capabilities' => ['ingress'],+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);$fluxClient->shouldReceive('revokeFirewallRule')->once()- ->with('100.64.0.10', 'v5-caddy-ingress:443')+ ->with(Mockery::type('string'), 'v5-caddy-ingress:80')+ ->ordered()->andReturn('Firewall rule removed.');+ $fluxClient+ ->shouldReceive('stopIngress')+ ->once()+ ->with(Mockery::type('string'), 'caddy')+ ->ordered()+ ->andThrow(new RuntimeException('podman rm failed'));app()->instance(FluxClient::class, $fluxClient);- $result = StopCaddyIngress::run($server);+ expect(fn () => StopCaddyIngress::run($server))->toThrow(RuntimeException::class, 'podman rm failed');+});- expect($result)->toBe('Caddy ingress stopped.');+it('tolerates already-revoked caddy firewall rules when stopping ingress', function () {+ $server = new Server([+ 'uuid' => 'test-server-uuid',+ 'wireguard_management_ip' => '100.64.0.10',+ 'capabilities' => ['ingress'],+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient+ ->shouldReceive('revokeFirewallRule')+ ->once()+ ->andThrow(new RuntimeException('firewall rule not found'));+ $fluxClient+ ->shouldReceive('stopIngress')+ ->once()+ ->andReturn('Caddy ingress stopped.');+ app()->instance(FluxClient::class, $fluxClient);++ expect(StopCaddyIngress::run($server))->toBe('Caddy ingress stopped.');+});++it('reports an unknown ingress status until coold confirms one', function () {+ $installed = new Server(['capabilities' => ['ingress']]);+ $installed->status = 'installed';++ expect($installed->ingressStatus())->toBe('unknown');++ $running = new Server(['capabilities' => ['ingress'], 'ingress_status' => 'running']);++ expect($running->ingressStatus())->toBe('running');});it('includes flux error response details when dispatch returns a non success status', function () {@@ -315,6 +516,8 @@ it('dispatches image pull and container lifecycle primitives for v5 apps', funct['request_id' => 'test-request', 'status' => 'ok', 'data' => ['id' => 'container-123']],['request_id' => 'test-request', 'status' => 'ok', 'data' => ['output' => 'Container started.']],['request_id' => 'test-request', 'status' => 'ok', 'data' => ['State' => ['Running' => true]]],+ ['request_id' => 'test-request', 'status' => 'ok', 'data' => ['output' => 'Container stopped.']],+ ['request_id' => 'test-request', 'status' => 'ok', 'data' => ['output' => 'Container removed.']],];$requestPath = storage_path('framework/testing/flux-request-'.bin2hex(random_bytes(8)).'.txt');@@ -332,7 +535,9 @@ it('dispatches image pull and container lifecycle primitives for v5 apps', funct'restart_policy' => 'unless-stopped',]))->toBe('container-123')->and($fluxClient->startContainer('100.64.0.10', 'container-123'))->toBe('Container started.')- ->and($fluxClient->inspectContainer('100.64.0.10', 'container-123'))->toBe(['State' => ['Running' => true]]);+ ->and($fluxClient->inspectContainer('100.64.0.10', 'container-123'))->toBe(['State' => ['Running' => true]])+ ->and($fluxClient->stopContainer('100.64.0.10', 'container-123'))->toBe('Container stopped.')+ ->and($fluxClient->removeContainer('100.64.0.10', 'container-123', true))->toBe('Container removed.');});$request = file_get_contents($requestPath) ?: '';@@ -343,7 +548,10 @@ it('dispatches image pull and container lifecycle primitives for v5 apps', funct->toContain('"network_aliases":["coolify-v5-nginx-test"]')->toContain('"dns_search":["default.coolify.internal"]')->toContain('"type":"containers.start"')- ->toContain('"type":"containers.inspect"');+ ->toContain('"type":"containers.inspect"')+ ->toContain('"type":"containers.stop"')+ ->toContain('"type":"containers.delete"')+ ->toContain('"force":true');});it('dispatches firewall allow through the firewall allow primitive', function () {diff --git a/tests/Unit/V5/CooldVerbContractTest.php b/tests/Unit/V5/CooldVerbContractTest.phpnew file mode 100644index 0000000000..9f6f3098fe--- /dev/null+++ b/tests/Unit/V5/CooldVerbContractTest.php@@ -0,0 +1,314 @@+<?php++use App\Actions\V5\Proxy\StartCaddyIngress;+use App\Actions\V5\Proxy\StopCaddyIngress;+use App\Exceptions\V5\UnsupportedCooldVerb;+use App\Models\V5\Server;+use App\Services\Flux\FluxClient;+use App\Support\V5\ConnectionFirewallSync;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Event;+use Illuminate\Support\Facades\Schema;+use Tests\Support\V5TestSchema;+use Tests\TestCase;++uses(TestCase::class);++it('detects unsupported coold verbs from flux http 501 responses', function () {+ if (! function_exists('pcntl_fork')) {+ $this->markTestSkipped('pcntl is required to fake a Flux Unix socket.');+ }++ // Flux rejects verbs the node's coold did not advertise with HTTP 501 and+ // "primitive <verb> is not supported by host" (coold repo:+ // flux/src/routing.rs:50-53, flux/src/unix_bridge.rs:227-245).+ $body = json_encode([+ 'request_id' => 'test-request',+ 'status' => 'error',+ 'code' => 501,+ 'message' => 'primitive firewall.allow is not supported by host',+ ], JSON_THROW_ON_ERROR);++ $caught = null;++ withCooldVerbContractFluxSocket(+ "HTTP/1.1 501 Not Implemented\r\n".+ "Content-Type: application/json\r\n".+ 'Content-Length: '.strlen($body)."\r\n".+ "\r\n".+ $body,+ function () use (&$caught): void {+ try {+ (new FluxClient)->applyFirewallRule('100.64.0.10', [+ 'id' => 'rule-1',+ 'namespace' => 'default',+ 'src' => '0.0.0.0/0',+ 'dst' => 'coolify-v5-caddy',+ 'proto' => 'tcp',+ 'port' => 80,+ ]);+ } catch (RuntimeException $exception) {+ $caught = $exception;+ }+ }+ );++ expect($caught)->toBeInstanceOf(UnsupportedCooldVerb::class)+ ->and($caught->verb)->toBe('firewall.allow')+ ->and($caught->getMessage())->toBe('primitive firewall.allow is not supported by host');+});++it('detects unsupported coold verbs from the flux message even without a 501 status', function () {+ if (! function_exists('pcntl_fork')) {+ $this->markTestSkipped('pcntl is required to fake a Flux Unix socket.');+ }++ $body = json_encode([+ 'request_id' => 'test-request',+ 'status' => 'error',+ 'code' => 502,+ 'message' => 'primitive coold.logs is not supported by host',+ ], JSON_THROW_ON_ERROR);++ $caught = null;++ withCooldVerbContractFluxSocket(+ "HTTP/1.1 502 Bad Gateway\r\n".+ "Content-Type: application/json\r\n".+ 'Content-Length: '.strlen($body)."\r\n".+ "\r\n".+ $body,+ function () use (&$caught): void {+ try {+ (new FluxClient)->cooldLogs('100.64.0.10');+ } catch (RuntimeException $exception) {+ $caught = $exception;+ }+ }+ );++ expect($caught)->toBeInstanceOf(UnsupportedCooldVerb::class)+ ->and($caught->verb)->toBe('coold.logs');+});++it('keeps generic flux dispatch failures as plain runtime exceptions', function () {+ if (! function_exists('pcntl_fork')) {+ $this->markTestSkipped('pcntl is required to fake a Flux Unix socket.');+ }++ $body = json_encode([+ 'request_id' => 'test-request',+ 'status' => 'error',+ 'code' => 500,+ 'message' => 'apply firewall rule: nft exited with status 1',+ ], JSON_THROW_ON_ERROR);++ $caught = null;++ withCooldVerbContractFluxSocket(+ "HTTP/1.1 500 Internal Server Error\r\n".+ "Content-Type: application/json\r\n".+ 'Content-Length: '.strlen($body)."\r\n".+ "\r\n".+ $body,+ function () use (&$caught): void {+ try {+ (new FluxClient)->applyFirewallRule('100.64.0.10', [+ 'id' => 'rule-1',+ 'namespace' => 'default',+ 'src' => '0.0.0.0/0',+ 'dst' => 'coolify-v5-caddy',+ 'proto' => 'tcp',+ 'port' => 80,+ ]);+ } catch (RuntimeException $exception) {+ $caught = $exception;+ }+ }+ );++ expect($caught)->toBeInstanceOf(RuntimeException::class)+ ->not->toBeInstanceOf(UnsupportedCooldVerb::class)+ ->and($caught->getMessage())->toBe('apply firewall rule: nft exited with status 1');+});++it('marks caddy ingress running with a warning when the node coold lacks firewall support', function () {+ Event::fake();++ Schema::dropIfExists('v5_applications');+ Schema::dropIfExists('v5_servers');+ V5TestSchema::createServersTable();+ V5TestSchema::createApplicationsTable();++ $server = Server::query()->create([+ 'uuid' => 'cooldverb-ingress-server-uuid',+ 'team_id' => 1,+ 'created_by_user_id' => 1,+ 'name' => 'ingress-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'capabilities' => ['ingress'],+ 'uuid' => 'test-server-uuid',+ 'wireguard_management_ip' => '100.64.0.10',+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient+ ->shouldReceive('applyIngress')+ ->once()+ ->andReturn('Caddy ingress applied.');+ $fluxClient+ ->shouldReceive('applyFirewallRule')+ ->once()+ ->andThrow(new UnsupportedCooldVerb('firewall.allow', 'primitive firewall.allow is not supported by host'));+ app()->instance(FluxClient::class, $fluxClient);++ $result = StartCaddyIngress::run($server);++ $server->refresh();++ expect($result)->toBe('Caddy ingress applied.')+ ->and($server->ingress_type)->toBe('caddy')+ ->and($server->ingress_status)->toBe('running')+ ->and($server->last_status_check)->toBe('flux')+ ->and($server->last_status_output)->toContain('does not support firewall.allow');++ Schema::dropIfExists('v5_applications');+ Schema::dropIfExists('v5_servers');+});++it('still surfaces supported-but-failed firewall errors when starting caddy ingress', function () {+ $server = new Server([+ 'uuid' => 'test-server-uuid',+ 'wireguard_management_ip' => '100.64.0.10',+ 'capabilities' => ['ingress'],+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient+ ->shouldReceive('applyIngress')+ ->once()+ ->andReturn('Caddy ingress applied.');+ $fluxClient+ ->shouldReceive('applyFirewallRule')+ ->once()+ ->andThrow(new RuntimeException('apply firewall rule: nft exited with status 1'));+ app()->instance(FluxClient::class, $fluxClient);++ expect(fn () => StartCaddyIngress::run($server))+ ->toThrow(RuntimeException::class, 'apply firewall rule: nft exited with status 1');+});++it('stops caddy ingress even when the node coold lacks firewall support', function () {+ $server = new Server([+ 'uuid' => 'test-server-uuid',+ 'wireguard_management_ip' => '100.64.0.10',+ 'capabilities' => ['ingress'],+ ]);++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient+ ->shouldReceive('revokeFirewallRule')+ ->once()+ ->andThrow(new UnsupportedCooldVerb('firewall.revoke', 'primitive firewall.revoke is not supported by host'));+ $fluxClient+ ->shouldReceive('stopIngress')+ ->once()+ ->with(Mockery::type('string'), 'caddy')+ ->andReturn('Caddy ingress stopped.');+ app()->instance(FluxClient::class, $fluxClient);++ expect(StopCaddyIngress::run($server))->toBe('Caddy ingress stopped.');+});++it('skips resource connection firewall sync rules when the node coold lacks firewall support', function () {+ $sync = new ConnectionFirewallSync;++ $oldRule = [+ 'id' => 'v5-resource-connection:1:1:2:tcp:5432',+ 'hostId' => '100.64.0.11',+ 'rule' => [+ 'id' => 'v5-resource-connection:1:1:2:tcp:5432',+ 'namespace' => 'default',+ 'src' => 'coolify-v5-api',+ 'dst' => 'coolify-v5-postgres',+ 'proto' => 'tcp',+ 'port' => 5432,+ ],+ ];+ $newRule = [+ 'id' => 'v5-resource-connection:1:1:2:tcp:6379',+ 'hostId' => '100.64.0.10',+ 'rule' => [+ 'id' => 'v5-resource-connection:1:1:2:tcp:6379',+ 'namespace' => 'default',+ 'src' => 'coolify-v5-api',+ 'dst' => 'coolify-v5-redis',+ 'proto' => 'tcp',+ 'port' => 6379,+ ],+ ];++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient+ ->shouldReceive('revokeFirewallRule')+ ->once()+ ->with(Mockery::type('string'), $oldRule['id'])+ ->andThrow(new UnsupportedCooldVerb('firewall.revoke', 'primitive firewall.revoke is not supported by host'));+ $fluxClient+ ->shouldReceive('applyFirewallRule')+ ->once()+ ->with(Mockery::type('string'), $newRule['rule'])+ ->andThrow(new UnsupportedCooldVerb('firewall.allow', 'primitive firewall.allow is not supported by host'));++ $sync->sync($fluxClient, collect([$oldRule]), collect([$newRule]));++ expect(true)->toBeTrue();+});++function withCooldVerbContractFluxSocket(string $response, Closure $callback): void+{+ $directory = storage_path('framework/testing');++ if (! is_dir($directory)) {+ mkdir($directory, 0777, true);+ }++ $socketPath = $directory.'/flux-'.bin2hex(random_bytes(8)).'.sock';+ $socketServer = stream_socket_server("unix://{$socketPath}", $errorCode, $errorMessage);++ expect($socketServer)->not->toBeFalse("Could not create fake Flux socket: {$errorMessage} ({$errorCode})");++ $pid = pcntl_fork();++ if ($pid === 0) {+ $connection = stream_socket_accept($socketServer, 5);++ if ($connection !== false) {+ $request = '';++ while (! str_contains($request, "\r\n\r\n") && ! feof($connection)) {+ $request .= fread($connection, 8192);+ }++ fwrite($connection, $response);+ fclose($connection);+ }++ fclose($socketServer);+ exit(0);+ }++ fclose($socketServer);+ Config::set('flux.unix_socket_path', $socketPath);+ Config::set('flux.connection_timeout_seconds', 1.0);+ Config::set('flux.dispatch_timeout_seconds', 1.0);++ try {+ $callback();+ } finally {+ pcntl_waitpid($pid, $status);+ @unlink($socketPath);+ }+}diff --git a/tests/Unit/V5/NginxApplicationDeploymentTest.php b/tests/Unit/V5/NginxApplicationDeploymentTest.phpindex d0f8f27443..130eb904e3 100644--- a/tests/Unit/V5/NginxApplicationDeploymentTest.php+++ b/tests/Unit/V5/NginxApplicationDeploymentTest.php@@ -2,7 +2,12 @@use App\Actions\V5\Application\DeployNginxApplication;use App\Models\V5\Application;+use App\Models\V5\Server;use App\Services\Flux\FluxClient;+use Illuminate\Support\Facades\Event;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Facades\Schema;+use Tests\Support\V5TestSchema;use Tests\TestCase;uses(TestCase::class);@@ -33,3 +38,205 @@ it('builds an nginx container spec for the coold mesh runtime', function () {->not->toHaveKey('command')->not->toHaveKey('privileged');});++it('stops and removes the created container when starting it fails', function () {+ Event::fake();+ $application = createNginxDeploymentApplication();++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('pullImage')->once()->andReturn('Image pulled.');+ $fluxClient->shouldReceive('createContainer')->once()->andReturn('container-123');+ $fluxClient+ ->shouldReceive('startContainer')+ ->once()+ ->with(Mockery::type('string'), 'container-123')+ ->andThrow(new RuntimeException('podman start exited with status 125'));+ $fluxClient+ ->shouldReceive('stopContainer')+ ->once()+ ->with(Mockery::type('string'), 'container-123')+ ->andReturn('Container stopped.');+ $fluxClient+ ->shouldReceive('removeContainer')+ ->once()+ ->with(Mockery::type('string'), 'container-123', true)+ ->andReturn('Container removed.');++ $result = (new DeployNginxApplication($fluxClient))->handle($application);++ expect($result->status)->toBe('failed')+ ->and($result->status_message)->toBe('podman start exited with status 125')+ ->and($result->runtime_container_id)->toBeNull();+});++it('does not clean up any container when creating the container fails', function () {+ Event::fake();+ $application = createNginxDeploymentApplication();++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('pullImage')->once()->andReturn('Image pulled.');+ $fluxClient+ ->shouldReceive('createContainer')+ ->once()+ ->andThrow(new RuntimeException('Flux did not return a container id.'));+ $fluxClient->shouldNotReceive('startContainer');+ $fluxClient->shouldNotReceive('stopContainer');+ $fluxClient->shouldNotReceive('removeContainer');++ $result = (new DeployNginxApplication($fluxClient))->handle($application);++ expect($result->status)->toBe('failed')+ ->and($result->status_message)->toBe('Flux did not return a container id.')+ ->and($result->runtime_container_id)->toBeNull();+});++it('keeps the original deploy failure and logs a warning when cleanup itself fails', function () {+ Event::fake();+ Log::spy();+ $application = createNginxDeploymentApplication();++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('pullImage')->once()->andReturn('Image pulled.');+ $fluxClient->shouldReceive('createContainer')->once()->andReturn('container-123');+ $fluxClient+ ->shouldReceive('startContainer')+ ->once()+ ->andThrow(new RuntimeException('original deploy failure'));+ $fluxClient+ ->shouldReceive('stopContainer')+ ->once()+ ->andThrow(new RuntimeException('stop failed'));+ $fluxClient+ ->shouldReceive('removeContainer')+ ->once()+ ->andThrow(new RuntimeException('remove failed'));++ $result = (new DeployNginxApplication($fluxClient))->handle($application);++ expect($result->status)->toBe('failed')+ ->and($result->status_message)->toBe('original deploy failure')+ ->and($result->runtime_container_id)->toBeNull();++ Log::shouldHaveReceived('warning')+ ->with('Could not stop the container created by a failed v5 deploy.', Mockery::type('array'))+ ->once();+ Log::shouldHaveReceived('warning')+ ->with('Could not remove the container created by a failed v5 deploy.', Mockery::type('array'))+ ->once();+});++it('cleans up the container when it does not stay running after start', function () {+ Event::fake();+ $application = createNginxDeploymentApplication();++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('pullImage')->once()->andReturn('Image pulled.');+ $fluxClient->shouldReceive('createContainer')->once()->andReturn('container-123');+ $fluxClient->shouldReceive('startContainer')->once()->andReturn('Container started.');+ $fluxClient+ ->shouldReceive('inspectContainer')+ ->once()+ ->andReturn(['State' => ['Running' => false]]);+ $fluxClient+ ->shouldReceive('stopContainer')+ ->once()+ ->with(Mockery::type('string'), 'container-123')+ ->andReturn('Container stopped.');+ $fluxClient+ ->shouldReceive('removeContainer')+ ->once()+ ->with(Mockery::type('string'), 'container-123', true)+ ->andReturn('Container removed.');++ $result = (new DeployNginxApplication($fluxClient))->handle($application);++ expect($result->status)->toBe('failed')+ ->and($result->status_message)->toBe('Container did not stay running.')+ ->and($result->runtime_container_id)->toBeNull();+});++it('persists the container id only for a successful deploy', function () {+ Event::fake();+ $application = createNginxDeploymentApplication();++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('pullImage')->once()->andReturn('Image pulled.');+ $fluxClient->shouldReceive('createContainer')->once()->andReturn('container-123');+ $fluxClient->shouldReceive('startContainer')->once()->andReturn('Container started.');+ $fluxClient+ ->shouldReceive('inspectContainer')+ ->once()+ ->andReturn(['State' => ['Running' => true]]);+ $fluxClient->shouldNotReceive('stopContainer');+ $fluxClient->shouldNotReceive('removeContainer');++ $result = (new DeployNginxApplication($fluxClient))->handle($application);++ expect($result->status)->toBe('running')+ ->and($result->runtime_container_id)->toBe('container-123');+});++it('persists the runtime container id immediately after create, before start', function () {+ Event::fake();+ $application = createNginxDeploymentApplication();++ $fluxClient = Mockery::mock(FluxClient::class);+ $fluxClient->shouldReceive('pullImage')->once()->andReturn('Image pulled.');+ $fluxClient->shouldReceive('createContainer')->once()->andReturn('container-123');++ $persistedBeforeStart = null;+ $fluxClient+ ->shouldReceive('startContainer')+ ->once()+ ->andReturnUsing(function () use ($application, &$persistedBeforeStart) {+ // Read the row straight from the database to prove the id is durable+ // before start runs, not just held in the in-memory model.+ $persistedBeforeStart = Application::query()->find($application->getKey())?->runtime_container_id;++ throw new RuntimeException('podman start exited with status 125');+ });+ $fluxClient->shouldReceive('stopContainer')->once()->andReturn('Container stopped.');+ $fluxClient->shouldReceive('removeContainer')->once()->andReturn('Container removed.');++ $result = (new DeployNginxApplication($fluxClient))->handle($application);++ expect($persistedBeforeStart)->toBe('container-123')+ ->and($result->status)->toBe('failed')+ ->and($result->runtime_container_id)->toBeNull();+});++function createNginxDeploymentApplication(): Application+{+ Schema::dropIfExists('v5_applications');+ Schema::dropIfExists('v5_servers');++ V5TestSchema::createServersTable();+ V5TestSchema::createApplicationsTable();++ $server = Server::query()->forceCreate([+ 'uuid' => 'nginx-deployment-server-uuid',+ 'team_id' => 1,+ 'created_by_user_id' => 1,+ 'name' => 'node-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'status' => 'installed',+ 'wireguard_management_ip' => '100.64.0.10',+ 'last_bootstrapped_at' => now(),+ ]);++ return Application::query()->forceCreate([+ 'uuid' => 'nginx-deployment-application-uuid',+ 'team_id' => 1,+ 'project_id' => 1,+ 'environment_id' => 1,+ 'created_by_user_id' => 1,+ 'server_id' => $server->id,+ 'name' => 'nginx-test',+ 'image' => 'docker.io/library/nginx:alpine',+ 'container_name' => 'coolify-v5-nginx-test',+ 'status' => 'creating',+ 'mesh_namespace' => 'default',+ ]);+}diff --git a/tests/Unit/V5/Policies/V5PolicyTest.php b/tests/Unit/V5/Policies/V5PolicyTest.phpnew file mode 100644index 0000000000..a3cc4b6847--- /dev/null+++ b/tests/Unit/V5/Policies/V5PolicyTest.php@@ -0,0 +1,253 @@+<?php++use App\Models\Team;+use App\Models\User;+use App\Models\V5\Application as V5Application;+use App\Models\V5\Cluster;+use App\Models\V5\ResourceConnection;+use App\Models\V5\Server as V5Server;+use App\Policies\V5\ApplicationPolicy;+use App\Policies\V5\ClusterPolicy;+use App\Policies\V5\ResourceConnectionPolicy;+use App\Policies\V5\ServerPolicy;+use Illuminate\Database\Eloquent\Relations\Pivot;+use Tests\TestCase;++uses(TestCase::class);++/**+ * Build a user whose team membership carries the given role, so the policies'+ * $user->isAdminOfTeam() role gate can be exercised without touching the DB.+ */+function v5PolicyUser(string $role = 'owner', int $teamId = 10): User+{+ $user = (new User)->forceFill(['id' => 1]);+ $team = (new Team)->forceFill(['id' => $teamId]);+ $pivot = new Pivot;+ $pivot->role = $role;+ $team->setRelation('pivot', $pivot);+ $user->setRelation('teams', collect([$team]));++ return $user;+}++function v5PolicyMemberUser(int $teamId = 10): User+{+ return v5PolicyUser('member', $teamId);+}++function v5PolicyTeam(int $id = 10): Team+{+ return (new Team)->forceFill(['id' => $id]);+}++it('allows adding a server to a cluster of the current team', function () {+ $team = v5PolicyTeam();+ $cluster = (new Cluster)->forceFill(['id' => 5, 'team_id' => $team->id]);++ $response = (new ServerPolicy)->create(v5PolicyUser(), $team, $cluster);++ expect($response->allowed())->toBeTrue();+});++it('denies adding a server to another teams cluster as forbidden instead of not found', function () {+ $team = v5PolicyTeam(10);+ $foreignCluster = (new Cluster)->forceFill(['id' => 5, 'team_id' => 99]);++ $response = (new ServerPolicy)->create(v5PolicyUser(), $team, $foreignCluster);++ // A plain deny carries no status override, so the framework renders the+ // historical 403 instead of a 404.+ expect($response->denied())->toBeTrue()+ ->and($response->status())->toBeNull();+});++it('denies server update and delete outside the current team as not found', function () {+ $team = v5PolicyTeam(10);+ $foreignCluster = (new Cluster)->forceFill(['id' => 5, 'team_id' => 99]);+ $foreignServer = (new V5Server)->forceFill(['id' => 7, 'team_id' => 99, 'cluster_id' => 5]);++ $policy = new ServerPolicy;++ $update = $policy->update(v5PolicyUser(), $foreignServer, $team, $foreignCluster);+ $delete = $policy->delete(v5PolicyUser(), $foreignServer, $team, $foreignCluster);++ expect($update->denied())->toBeTrue()+ ->and($update->status())->toBe(404)+ ->and($delete->denied())->toBeTrue()+ ->and($delete->status())->toBe(404);+});++it('denies server update for a server outside the addressed cluster as not found', function () {+ $team = v5PolicyTeam(10);+ $cluster = (new Cluster)->forceFill(['id' => 5, 'team_id' => $team->id]);+ $serverInOtherCluster = (new V5Server)->forceFill(['id' => 7, 'team_id' => $team->id, 'cluster_id' => 6]);++ $response = (new ServerPolicy)->update(v5PolicyUser(), $serverInOtherCluster, $team, $cluster);++ expect($response->denied())->toBeTrue()+ ->and($response->status())->toBe(404);+});++it('allows moving the caddy ingress canvas card only for ingress servers of the current team', function () {+ $team = v5PolicyTeam(10);+ $policy = new ServerPolicy;++ $ingressServer = (new V5Server)->forceFill(['id' => 7, 'team_id' => $team->id, 'is_ingress' => true]);++ expect($policy->updateCanvasPosition(v5PolicyUser(), $ingressServer, $team)->allowed())->toBeTrue();+});++it('denies moving the canvas card of a non-ingress server as not found', function () {+ $team = v5PolicyTeam(10);+ $nonIngressServer = (new V5Server)->forceFill(['id' => 7, 'team_id' => $team->id, 'is_ingress' => false]);++ $response = (new ServerPolicy)->updateCanvasPosition(v5PolicyUser(), $nonIngressServer, $team);++ expect($response->denied())->toBeTrue()+ ->and($response->status())->toBe(404);+});++it('denies moving another teams ingress canvas card as not found', function () {+ $team = v5PolicyTeam(10);+ $foreignIngressServer = (new V5Server)->forceFill(['id' => 7, 'team_id' => 99, 'is_ingress' => true]);++ $response = (new ServerPolicy)->updateCanvasPosition(v5PolicyUser(), $foreignIngressServer, $team);++ expect($response->denied())->toBeTrue()+ ->and($response->status())->toBe(404);+});++it('scopes cluster viewing and deletion to the current team with not-found denials', function () {+ $team = v5PolicyTeam(10);+ $policy = new ClusterPolicy;++ $ownCluster = (new Cluster)->forceFill(['id' => 5, 'team_id' => $team->id]);+ $foreignCluster = (new Cluster)->forceFill(['id' => 6, 'team_id' => 99]);++ expect($policy->view(v5PolicyUser(), $ownCluster, $team)->allowed())->toBeTrue()+ ->and($policy->delete(v5PolicyUser(), $ownCluster, $team)->allowed())->toBeTrue();++ $view = $policy->view(v5PolicyUser(), $foreignCluster, $team);+ $delete = $policy->delete(v5PolicyUser(), $foreignCluster, $team);++ expect($view->denied())->toBeTrue()+ ->and($view->status())->toBe(404)+ ->and($delete->denied())->toBeTrue()+ ->and($delete->status())->toBe(404);+});++it('scopes application mutations to the current team with not-found denials', function () {+ $team = v5PolicyTeam(10);+ $policy = new ApplicationPolicy;++ $ownApplication = (new V5Application)->forceFill(['id' => 3, 'team_id' => $team->id]);+ $foreignApplication = (new V5Application)->forceFill(['id' => 4, 'team_id' => 99]);++ expect($policy->update(v5PolicyUser(), $ownApplication, $team)->allowed())->toBeTrue()+ ->and($policy->updateIngress(v5PolicyUser(), $ownApplication, $team)->allowed())->toBeTrue()+ ->and($policy->delete(v5PolicyUser(), $ownApplication, $team)->allowed())->toBeTrue();++ foreach (['update', 'updateIngress', 'delete'] as $ability) {+ $response = $policy->{$ability}(v5PolicyUser(), $foreignApplication, $team);++ expect($response->denied())->toBeTrue()+ ->and($response->status())->toBe(404);+ }+});++it('scopes resource connection mutations to the current team with not-found denials', function () {+ $team = v5PolicyTeam(10);+ $policy = new ResourceConnectionPolicy;++ $ownConnection = (new ResourceConnection)->forceFill(['id' => 3, 'team_id' => $team->id]);+ $foreignConnection = (new ResourceConnection)->forceFill(['id' => 4, 'team_id' => 99]);++ expect($policy->update(v5PolicyUser(), $ownConnection, $team)->allowed())->toBeTrue()+ ->and($policy->delete(v5PolicyUser(), $ownConnection, $team)->allowed())->toBeTrue();++ foreach (['update', 'delete'] as $ability) {+ $response = $policy->{$ability}(v5PolicyUser(), $foreignConnection, $team);++ expect($response->denied())->toBeTrue()+ ->and($response->status())->toBe(404);+ }+});++it('denies server mutations for a member of the current team as forbidden not not-found', function () {+ $team = v5PolicyTeam(10);+ $cluster = (new Cluster)->forceFill(['id' => 5, 'team_id' => $team->id]);+ $server = (new V5Server)->forceFill(['id' => 7, 'team_id' => $team->id, 'cluster_id' => 5, 'is_ingress' => true]);+ $member = v5PolicyMemberUser();+ $policy = new ServerPolicy;++ expect($policy->create($member, $team, $cluster)->denied())->toBeTrue()+ ->and($policy->create($member, $team, $cluster)->status())->toBeNull();++ foreach (['update', 'delete', 'check', 'bootstrap'] as $ability) {+ $response = $policy->{$ability}($member, $server, $team, $cluster);++ expect($response->denied())->toBeTrue()+ ->and($response->status())->toBeNull();+ }++ expect($policy->updateCanvasPosition($member, $server, $team)->denied())->toBeTrue()+ ->and($policy->updateCanvasPosition($member, $server, $team)->status())->toBeNull();+});++it('still lets a member read server diagnostics of the current team', function () {+ $team = v5PolicyTeam(10);+ $cluster = (new Cluster)->forceFill(['id' => 5, 'team_id' => $team->id]);+ $server = (new V5Server)->forceFill(['id' => 7, 'team_id' => $team->id, 'cluster_id' => 5]);++ expect((new ServerPolicy)->viewDiagnostics(v5PolicyMemberUser(), $server, $team, $cluster)->allowed())->toBeTrue();+});++it('denies cluster create and delete for a member of the current team as forbidden', function () {+ $team = v5PolicyTeam(10);+ $cluster = (new Cluster)->forceFill(['id' => 5, 'team_id' => $team->id]);+ $member = v5PolicyMemberUser();+ $policy = new ClusterPolicy;++ expect($policy->create($member, $team)->denied())->toBeTrue()+ ->and($policy->create($member, $team)->status())->toBeNull()+ ->and($policy->delete($member, $cluster, $team)->denied())->toBeTrue()+ ->and($policy->delete($member, $cluster, $team)->status())->toBeNull();++ // Members may still read.+ expect($policy->view($member, $cluster, $team)->allowed())->toBeTrue();+});++it('allows an admin to create a cluster in the current team', function () {+ $team = v5PolicyTeam(10);++ expect((new ClusterPolicy)->create(v5PolicyUser('admin'), $team)->allowed())->toBeTrue();+});++it('denies application mutations for a member of the current team as forbidden', function () {+ $team = v5PolicyTeam(10);+ $application = (new V5Application)->forceFill(['id' => 3, 'team_id' => $team->id]);+ $member = v5PolicyMemberUser();+ $policy = new ApplicationPolicy;++ foreach (['update', 'updateIngress', 'delete'] as $ability) {+ $response = $policy->{$ability}($member, $application, $team);++ expect($response->denied())->toBeTrue()+ ->and($response->status())->toBeNull();+ }+});++it('denies resource connection mutations for a member of the current team as forbidden', function () {+ $team = v5PolicyTeam(10);+ $connection = (new ResourceConnection)->forceFill(['id' => 3, 'team_id' => $team->id]);+ $member = v5PolicyMemberUser();+ $policy = new ResourceConnectionPolicy;++ foreach (['update', 'delete'] as $ability) {+ $response = $policy->{$ability}($member, $connection, $team);++ expect($response->denied())->toBeTrue()+ ->and($response->status())->toBeNull();+ }+});diff --git a/tests/Unit/V5/V5QueueIdempotencyTest.php b/tests/Unit/V5/V5QueueIdempotencyTest.phpnew file mode 100644index 0000000000..bf58b46ab7--- /dev/null+++ b/tests/Unit/V5/V5QueueIdempotencyTest.php@@ -0,0 +1,73 @@+<?php++use App\Events\V5CanvasResourceUpdated;+use App\Events\V5ClusterUpdated;+use App\Events\V5RealtimeTestEvent;+use App\Jobs\V5BootstrapServerJob;+use App\Jobs\V5DeployApplicationJob;+use Illuminate\Contracts\Broadcasting\ShouldBroadcast;+use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;+use Illuminate\Contracts\Queue\ShouldBeUnique;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Queue;+use Tests\TestCase;++uses(TestCase::class);++it('locks v5 deploy jobs per application for the job timeout plus a margin', function () {+ $job = new V5DeployApplicationJob(42);++ expect($job)->toBeInstanceOf(ShouldBeUnique::class)+ ->and($job->uniqueId())->toBe('42')+ ->and($job->uniqueFor)->toBe($job->timeout + 60);+});++it('locks v5 bootstrap jobs per server aligned with the controller bootstrap claim window', function () {+ $job = new V5BootstrapServerJob(7, 13);++ expect($job)->toBeInstanceOf(ShouldBeUnique::class)+ ->and($job->uniqueId())->toBe('13')+ ->and($job->uniqueFor)->toBe(V5BootstrapServerJob::TIMEOUT_SECONDS + 300);+});++it('does not queue a second v5 deploy job while one is pending for the same application', function () {+ Config::set('cache.default', 'array');+ Queue::fake();++ V5DeployApplicationJob::dispatch(101);+ V5DeployApplicationJob::dispatch(101);+ V5DeployApplicationJob::dispatch(202);++ Queue::assertPushed(V5DeployApplicationJob::class, 2);+ Queue::assertPushed(V5DeployApplicationJob::class, fn (V5DeployApplicationJob $job): bool => $job->applicationId === 101);+ Queue::assertPushed(V5DeployApplicationJob::class, fn (V5DeployApplicationJob $job): bool => $job->applicationId === 202);+});++it('does not queue a second v5 bootstrap job while one is pending for the same server', function () {+ Config::set('cache.default', 'array');+ Queue::fake();++ V5BootstrapServerJob::dispatch(1, 55);+ V5BootstrapServerJob::dispatch(2, 55);+ V5BootstrapServerJob::dispatch(1, 66);++ Queue::assertPushed(V5BootstrapServerJob::class, 2);+ Queue::assertPushed(V5BootstrapServerJob::class, fn (V5BootstrapServerJob $job): bool => $job->serverId === 55);+ Queue::assertPushed(V5BootstrapServerJob::class, fn (V5BootstrapServerJob $job): bool => $job->serverId === 66);+});++it('queues v5 canvas and cluster broadcasts after commit instead of pushing on the request thread', function () {+ $canvasEvent = new V5CanvasResourceUpdated(1, 2);+ $clusterEvent = new V5ClusterUpdated(1, 2);++ expect($canvasEvent)->toBeInstanceOf(ShouldBroadcast::class)+ ->not->toBeInstanceOf(ShouldBroadcastNow::class)+ ->and($canvasEvent->afterCommit)->toBeTrue()+ ->and($clusterEvent)->toBeInstanceOf(ShouldBroadcast::class)+ ->not->toBeInstanceOf(ShouldBroadcastNow::class)+ ->and($clusterEvent->afterCommit)->toBeTrue();+});++it('keeps the manual v5 realtime test ping broadcasting immediately', function () {+ expect(new V5RealtimeTestEvent(1, 'ping'))->toBeInstanceOf(ShouldBroadcastNow::class);+});diff --git a/tests/Unit/ValidHostnameTest.php b/tests/Unit/ValidHostnameTest.phpindex 6580a7c5d2..42e80638e9 100644--- a/tests/Unit/ValidHostnameTest.php+++ b/tests/Unit/ValidHostnameTest.php@@ -50,6 +50,11 @@ it('rejects invalid RFC 1123 hostnames', function (string $hostname, string $exp'special characters' => ['my@server', 'letters (a-z, A-Z), numbers (0-9), hyphens (-), and dots (.)'],'space' => ['my server', 'letters (a-z, A-Z), numbers (0-9), hyphens (-), and dots (.)'],'shell metacharacters' => ['my;server', 'letters (a-z, A-Z), numbers (0-9), hyphens (-), and dots (.)'],+ 'newline before dot' => ["evil\n.com", 'letters (a-z, A-Z), numbers (0-9), hyphens (-), and dots (.)'],+ 'newline inside label' => ["evil\ncom", 'letters (a-z, A-Z), numbers (0-9), hyphens (-), and dots (.)'],+ 'carriage return' => ["evil\r.com", 'letters (a-z, A-Z), numbers (0-9), hyphens (-), and dots (.)'],+ 'tab character' => ["evil\t.com", 'letters (a-z, A-Z), numbers (0-9), hyphens (-), and dots (.)'],+ 'caddy block injection' => ["evil.com {\n} http://x", 'letters (a-z, A-Z), numbers (0-9), hyphens (-), and dots (.)'],]);it('accepts empty hostname', function () {