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 bootstrap job with realtime cluster broadcasting
Andras Bacsai24bbfe07c6fb
diff --git a/app/Events/V5ClusterUpdated.php b/app/Events/V5ClusterUpdated.phpnew file mode 100644index 0000000000..a820ba6d40--- /dev/null+++ b/app/Events/V5ClusterUpdated.php@@ -0,0 +1,104 @@+<?php++namespace App\Events;++use App\Models\V5\Cluster as V5Cluster;+use App\Models\V5\Server as V5Server;+use Illuminate\Broadcasting\InteractsWithSockets;+use Illuminate\Broadcasting\PrivateChannel;+use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;+use Illuminate\Foundation\Events\Dispatchable;+use Illuminate\Queue\SerializesModels;++class V5ClusterUpdated implements ShouldBroadcastNow+{+ use Dispatchable, InteractsWithSockets, SerializesModels;++ public function __construct(public int $teamId, public int $clusterId) {}++ public function broadcastOn(): array+ {+ return [+ new PrivateChannel("team.{$this->teamId}"),+ ];+ }++ public function broadcastAs(): string+ {+ return 'v5.cluster.updated';+ }++ /**+ * @return array{cluster: array<string, mixed>|null}+ */+ public function broadcastWith(): array+ {+ $cluster = V5Cluster::query()+ ->where('team_id', $this->teamId)+ ->with(['servers' => fn ($query) => $query+ ->with('privateKey')+ ->orderBy('name')])+ ->withCount('servers')+ ->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(),+ ];+ }+}diff --git a/app/Events/V5RealtimeTestEvent.php b/app/Events/V5RealtimeTestEvent.phpnew file mode 100644index 0000000000..1a446b3016--- /dev/null+++ b/app/Events/V5RealtimeTestEvent.php@@ -0,0 +1,45 @@+<?php++namespace App\Events;++use Illuminate\Broadcasting\InteractsWithSockets;+use Illuminate\Broadcasting\PrivateChannel;+use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;+use Illuminate\Foundation\Events\Dispatchable;+use Illuminate\Queue\SerializesModels;++class V5RealtimeTestEvent implements ShouldBroadcastNow+{+ use Dispatchable, InteractsWithSockets, SerializesModels;++ public string $sentAt;++ public function __construct(public int $teamId, public string $message)+ {+ $this->sentAt = now()->toJSON();+ }++ public function broadcastOn(): array+ {+ return [+ new PrivateChannel("team.{$this->teamId}"),+ ];+ }++ public function broadcastAs(): string+ {+ return 'v5.realtime.test';+ }++ /**+ * @return array{message: string, teamId: int, sentAt: string}+ */+ public function broadcastWith(): array+ {+ return [+ 'message' => $this->message,+ 'teamId' => $this->teamId,+ 'sentAt' => $this->sentAt,+ ];+ }+}diff --git a/app/Http/Controllers/V5/DashboardController.php b/app/Http/Controllers/V5/DashboardController.phpindex ef4a9a3769..904e1e9d01 100644--- a/app/Http/Controllers/V5/DashboardController.php+++ b/app/Http/Controllers/V5/DashboardController.php@@ -2,7 +2,10 @@namespace App\Http\Controllers\V5;+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\Models\Project;@@ -55,6 +58,56 @@ class DashboardController extends Controller]);}+ 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);+ }++ return Inertia::render('RealtimeTest', [+ 'currentTeam' => [+ 'id' => $currentTeam->id,+ ],+ ]);+ }++ public function broadcastRealtimeTest(Request $request): JsonResponse+ {+ $currentTeam = $request->attributes->get('v5.currentTeam');++ if (! $currentTeam instanceof Team) {+ abort(403);+ }++ $validated = $request->validate([+ 'message' => ['nullable', 'string', 'max:255'],+ ]);++ V5RealtimeTestEvent::dispatch(+ $currentTeam->id,+ $validated['message'] ?? 'Manual v5 realtime test'+ );++ return response()->json([+ 'message' => 'Realtime test event broadcasted.',+ ], 202);+ }+public function updateSelection(Request $request): \Illuminate\Http\Response{$currentTeam = $request->attributes->get('v5.currentTeam');@@ -115,7 +168,9 @@ class DashboardController extends Controller'corrosion_gossip_port' => ['sometimes', 'integer', 'min:1', 'max:65535'],'corrosion_api_port' => ['sometimes', 'integer', 'min:1', 'max:65535'],'builder_enabled' => ['sometimes', 'boolean'],- 'builder_capacity' => ['sometimes', 'integer', 'min:0', 'max:1000'],+ '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'],@@ -159,12 +214,18 @@ class DashboardController extends Controller], 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();- $action = $installedServers->isEmpty() ? 'bootstrap' : 'extend';$server->load('privateKey');$servers = $installedServers->toBase()->push($server)@@ -177,75 +238,20 @@ class DashboardController extends Controller], 422);}- $cluster->update([- 'last_cli_action' => $action,- 'last_cli_status' => 'running',- 'last_cli_summary' => "Starting Coolify CLI {$action} for {$server->name}...",- 'last_cli_ran_at' => now(),- ]);-- $keyDirectory = storage_path('app/ssh/keys');- if (! is_dir($keyDirectory)) {- mkdir($keyDirectory, 0700, true);- }-- $tempDirectory = $keyDirectory.'/v5_bootstrap_'.str()->random(16);- if (! mkdir($tempDirectory, 0700, true) && ! is_dir($tempDirectory)) {- $cluster->update([- 'last_cli_status' => 'failed',- 'last_cli_summary' => 'Could not create a temporary SSH configuration directory.',- 'last_cli_ran_at' => now(),- ]);-- return response()->json([- 'cluster' => $this->freshSerializedCluster($cluster),- ], 500);- }-- try {- $sshConfigLocation = $this->writeBootstrapSshConfig($servers, $tempDirectory);- $result = Process::timeout(max(60, (int) $cluster->builder_timeout_secs + 120))- ->run($this->bootstrapCommand($cluster, $servers, $server, $sshConfigLocation, $action));- $output = trim($result->output()."\n".$result->errorOutput());- $successful = $result->successful();- } catch (\Throwable $e) {- $output = $e->getMessage();- $successful = false;- } finally {- $this->deleteDirectory($tempDirectory);- }-- $cluster->update([- 'last_cli_action' => $action,- 'last_cli_status' => $successful ? 'succeeded' : 'failed',- 'last_cli_summary' => str($output !== '' ? $output : 'No output returned.')->limit(20000)->toString(),- 'last_cli_ran_at' => now(),+ $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(),]);- if ($successful) {- $capabilities = collect($server->capabilities ?? [])- ->push('coold')- ->when($server->builder_enabled, fn ($capabilities) => $capabilities->push('builder'))- ->unique()- ->values()- ->all();-- $server->update([- 'status' => 'installed',- 'capabilities' => $capabilities,- 'last_bootstrapped_at' => now(),- ]);- }+ V5ClusterUpdated::dispatch($currentTeam->id, $cluster->id);+ V5BootstrapServerJob::dispatch($cluster->id, $server->id);- $payload = [+ return response()->json(['cluster' => $this->freshSerializedCluster($cluster),- ];-- if (! $successful) {- $payload['message'] = $cluster->last_cli_summary;- }-- return response()->json($payload, $successful ? 200 : 500);+ 'message' => 'Bootstrap queued.',+ ], 202);}public function storeServer(Request $request, V5Cluster $cluster): JsonResponse@@ -275,7 +281,9 @@ class DashboardController extends Controller],'node_address' => ['nullable', 'string', 'max:255'],'builder_enabled' => ['sometimes', 'boolean'],- 'builder_capacity' => ['sometimes', 'integer', 'min:0', 'max:1000'],+ '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'],@@ -295,10 +303,10 @@ class DashboardController extends Controller'ssh_user' => $validated['ssh_user'],'ssh_port' => $validated['ssh_port'],'private_key_id' => $validated['private_key_id'] ?? null,- 'status' => 'pending',+ 'status' => 'added','capabilities' => $builderEnabled ? ['coold', 'builder'] : ['coold'],'builder_enabled' => $builderEnabled,- 'builder_capacity' => $builderEnabled ? $builderCapacity : 0,+ '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'],@@ -330,7 +338,10 @@ class DashboardController extends Controller$validated = $request->validate(['builder_enabled' => ['required', 'boolean'],- 'builder_capacity' => ['required', 'integer', 'min:0', 'max:1000'],+ 'builder_capacity' => $this->builderCapacityRules(+ $request->boolean('builder_enabled'),+ required: true+ ),'builder_cpu_quota' => ['required', 'string', 'max:32'],]);@@ -346,7 +357,7 @@ class DashboardController extends Controller$server->update(['capabilities' => $capabilities,'builder_enabled' => $builderEnabled,- 'builder_capacity' => $builderEnabled ? (int) $validated['builder_capacity'] : 0,+ 'builder_capacity' => (int) $validated['builder_capacity'],'builder_cpu_quota' => $validated['builder_cpu_quota'],]);@@ -374,14 +385,10 @@ class DashboardController extends Controller}if (! $server->privateKey instanceof PrivateKey) {- $server->update([- 'last_status_check' => 'failed',- 'last_status_output' => 'No private key is attached to this server.',- 'last_status_checked_at' => now(),- ]);-return response()->json([- 'cluster' => $this->freshSerializedCluster($cluster),+ 'status' => 'failed',+ 'output' => 'No private key is attached to this server.',+ 'checkedAt' => now()->toJSON(),]);}@@ -392,14 +399,10 @@ class DashboardController extends Controller$keyLocation = tempnam($keyDirectory, 'v5_ssh_key_');if ($keyLocation === false) {- $server->update([- 'last_status_check' => 'failed',- 'last_status_output' => 'Could not create a temporary SSH key file.',- 'last_status_checked_at' => now(),- ]);-return response()->json([- 'cluster' => $this->freshSerializedCluster($cluster),+ 'status' => 'failed',+ 'output' => 'Could not create a temporary SSH key file.',+ 'checkedAt' => now()->toJSON(),]);}@@ -440,14 +443,10 @@ class DashboardController extends Controller@unlink($keyLocation);}- $server->update([- 'last_status_check' => $status,- 'last_status_output' => str($output !== '' ? $output : 'No output returned.')->limit(10000)->toString(),- 'last_status_checked_at' => now(),- ]);-return response()->json([- 'cluster' => $this->freshSerializedCluster($cluster),+ 'status' => $status,+ 'output' => str($output !== '' ? $output : 'No output returned.')->limit(10000)->toString(),+ 'checkedAt' => now()->toJSON(),]);}@@ -464,12 +463,6 @@ class DashboardController extends Controllerabort(404);}- if ($server->last_bootstrapped_at !== null) {- return response()->json([- 'message' => 'Only unbootstrapped servers can be deleted.',- ], 409);- }-$server->delete();return response()->json([@@ -800,6 +793,7 @@ class DashboardController extends Controller'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,@@ -808,9 +802,10 @@ class DashboardController extends Controller'containerSubnets' => $server->container_subnets ?? [],'privateKeyName' => $server->privateKey?->name,'lastBootstrappedAt' => $server->last_bootstrapped_at?->toJSON(),- 'lastStatusCheck' => $server->last_status_check,- 'lastStatusOutput' => $server->last_status_output,- 'lastStatusCheckedAt' => $server->last_status_checked_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(),];}@@ -875,6 +870,28 @@ class DashboardController extends Controller};}+ /**+ * @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}diff --git a/app/Http/Middleware/V5/HandleInertiaRequests.php b/app/Http/Middleware/V5/HandleInertiaRequests.phpindex 2772c9c2eb..8951e161fa 100644--- a/app/Http/Middleware/V5/HandleInertiaRequests.php+++ b/app/Http/Middleware/V5/HandleInertiaRequests.php@@ -20,6 +20,9 @@ class HandleInertiaRequests extends Middleware'email' => $request->user()->email,] : null,],+ 'currentTeam' => $request->attributes->get('v5.currentTeam') ? [+ 'id' => $request->attributes->get('v5.currentTeam')->id,+ ] : null,];}}diff --git a/app/Jobs/V5BootstrapServerJob.php b/app/Jobs/V5BootstrapServerJob.phpnew file mode 100644index 0000000000..3773a34fdf--- /dev/null+++ b/app/Jobs/V5BootstrapServerJob.php@@ -0,0 +1,447 @@+<?php++namespace App\Jobs;++use App\Events\V5ClusterUpdated;+use App\Models\PrivateKey;+use App\Models\V5\Cluster as V5Cluster;+use App\Models\V5\Server as V5Server;+use Illuminate\Bus\Queueable;+use Illuminate\Contracts\Queue\ShouldBeEncrypted;+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+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ private const BOOTSTRAP_MARKER_PATH = '/etc/coolify/v5-node.json';++ public int $tries = 1;++ public int $timeout = 7200;++ public function __construct(public int $clusterId, public int $serverId) {}++ /**+ * @return array<int, object>+ */+ public function middleware(): array+ {+ return [(new WithoutOverlapping("v5-bootstrap-server-{$this->serverId}"))->expireAfter(7200)->dontRelease()];+ }++ public function handle(): void+ {+ $cluster = V5Cluster::query()->findOrFail($this->clusterId);+ $server = V5Server::query()->with('privateKey')->findOrFail($this->serverId);++ if ($server->cluster_id !== $cluster->id || $server->last_bootstrapped_at !== null) {+ return;+ }++ $installedServers = $cluster->servers()+ ->with('privateKey')+ ->whereNotNull('last_bootstrapped_at')+ ->orderBy('name')+ ->get();+ $action = $installedServers->isEmpty() ? 'bootstrap' : 'extend';+ $servers = $installedServers->toBase()+ ->push($server)+ ->unique('id')+ ->values();++ 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');+ if (! is_dir($keyDirectory)) {+ mkdir($keyDirectory, 0700, true);+ }++ $tempDirectory = $keyDirectory.'/v5_bootstrap_'.str()->random(16);+ if (! mkdir($tempDirectory, 0700, true) && ! is_dir($tempDirectory)) {+ $this->markFailed($server, $action, 'Could not create a temporary SSH configuration directory.');++ return;+ }++ try {+ $sshConfigLocation = $this->writeBootstrapSshConfig($servers, $tempDirectory);+ $existingBootstrap = $this->detectExistingBootstrap($server, $sshConfigLocation);++ if (($existingBootstrap['cluster_id'] ?? null) !== null) {+ if ((string) $existingBootstrap['cluster_id'] !== (string) $cluster->id) {+ $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);++ return;+ }++ $result = Process::timeout(max(60, (int) $cluster->builder_timeout_secs + 120))+ ->run($this->bootstrapCommand($cluster, $servers, $server, $sshConfigLocation, $action));+ $output = trim($result->output()."\n".$result->errorOutput());+ $successful = $result->successful();++ $server->update([+ 'last_bootstrap_action' => $action,+ 'last_bootstrap_status' => $successful ? 'succeeded' : 'failed',+ 'last_bootstrap_output' => str($output !== '' ? $output : 'No output returned.')->limit(20000)->toString(),+ 'last_bootstrap_ran_at' => now(),+ ]);+ $this->broadcastClusterUpdated($server);++ if (! $successful) {+ return;+ }++ $capabilities = collect($server->capabilities ?? [])+ ->push('coold')+ ->when($server->builder_enabled, fn ($capabilities) => $capabilities->push('builder'))+ ->unique()+ ->values()+ ->all();++ $server->update([+ 'status' => 'installed',+ 'capabilities' => $capabilities,+ 'last_bootstrapped_at' => now(),+ ]);+ $this->broadcastClusterUpdated($server);++ $this->writeBootstrapMarker($cluster, $server, $sshConfigLocation);+ } catch (\Throwable $e) {+ $this->markFailed($server, $action, $e->getMessage());+ } finally {+ $this->deleteDirectory($tempDirectory);+ }+ }++ public function failed(?\Throwable $exception): void+ {+ $server = V5Server::query()->find($this->serverId);++ if (! $server instanceof V5Server) {+ return;+ }++ $this->markFailed($server, $server->last_bootstrap_action ?? 'bootstrap', $exception?->getMessage() ?? 'Bootstrap job failed.');++ Log::warning('V5 server bootstrap job failed', [+ 'server_id' => $this->serverId,+ 'cluster_id' => $this->clusterId,+ 'exception' => $exception?->getMessage(),+ ]);+ }++ private function markFailed(V5Server $server, string $action, string $output): void+ {+ $server->update([+ 'last_bootstrap_action' => $action,+ 'last_bootstrap_status' => 'failed',+ 'last_bootstrap_output' => str($output)->limit(20000)->toString(),+ 'last_bootstrap_ran_at' => now(),+ ]);+ $this->broadcastClusterUpdated($server);+ }++ private function broadcastClusterUpdated(V5Server $server): void+ {+ V5ClusterUpdated::dispatch($server->team_id, $server->cluster_id);+ }++ 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';+ }++ $builderServers = $servers->filter(fn (V5Server $server) => $server->builder_enabled);+ if ($cluster->builder_enabled && $builderServers->isNotEmpty()) {+ array_push(+ $command,+ '--enable-builder',+ '--builder-hosts',+ $builderServers+ ->map(fn (V5Server $server) => $this->bootstrapNode($server))+ ->implode(','),+ '--builder-capacity',+ (string) $cluster->builder_capacity,+ '--builder-cpu-quota',+ $cluster->builder_cpu_quota,+ '--builder-memory-max',+ $cluster->builder_memory_max,+ '--builder-timeout-secs',+ (string) $cluster->builder_timeout_secs,+ );+ }++ $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->uuid ?: $server->id);+ }++ /**+ * @return array<string, mixed>+ */+ private function detectExistingBootstrap(V5Server $server, string $sshConfigLocation): array+ {+ $result = Process::timeout(15)->run([+ 'ssh',+ '-F',+ $sshConfigLocation,+ $this->bootstrapNode($server),+ 'if [ -f '.escapeshellarg(self::BOOTSTRAP_MARKER_PATH).' ]; then cat '.escapeshellarg(self::BOOTSTRAP_MARKER_PATH).'; fi',+ ]);++ if (! $result->successful()) {+ return [];+ }++ $output = trim($result->output());++ if ($output === '') {+ return [];+ }++ try {+ $decoded = json_decode($output, true, flags: JSON_THROW_ON_ERROR);+ } catch (\JsonException) {+ return [];+ }++ return is_array($decoded) ? $decoded : [];+ }++ /**+ * @param array<string, mixed> $marker+ */+ private function adoptExistingBootstrap(V5Server $server, array $marker): void+ {+ $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,+ 'container_subnets' => is_array($marker['container_subnets'] ?? null) ? $marker['container_subnets'] : $server->container_subnets,+ 'status' => 'installed',+ 'last_bootstrap_status' => 'succeeded',+ 'last_bootstrap_output' => 'Adopted existing Coolify bootstrap state for this cluster.',+ 'last_bootstrap_ran_at' => now(),+ 'last_bootstrapped_at' => now(),+ ];++ if ($serverUuid !== null && ! V5Server::query()->where('uuid', $serverUuid)->whereKeyNot($server->id)->exists()) {+ $updates['uuid'] = $serverUuid;+ }++ $server->update($updates);+ $this->broadcastClusterUpdated($server);+ }++ private function writeBootstrapMarker(V5Cluster $cluster, V5Server $server, string $sshConfigLocation): void+ {+ $payload = base64_encode(json_encode([+ 'cluster_id' => $cluster->id,+ 'server_uuid' => $server->uuid,+ 'wireguard_management_ip' => $server->wireguard_management_ip,+ 'wireguard_public_key' => $server->wireguard_public_key,+ 'container_subnets' => $server->container_subnets ?? [],+ ], JSON_THROW_ON_ERROR));++ 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',+ ]);+ }++ /**+ * @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(',');+ }+}diff --git a/app/Models/V5/Server.php b/app/Models/V5/Server.phpindex 6b19103d64..7aa13b9de7 100644--- a/app/Models/V5/Server.php+++ b/app/Models/V5/Server.php@@ -12,6 +12,7 @@ class Server extends V5Modelprotected $table = 'v5_servers';protected $fillable = [+ 'uuid','team_id','cluster_id','created_by_user_id',@@ -32,6 +33,10 @@ class Server extends V5Model'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',@@ -44,6 +49,7 @@ class Server extends V5Model'builder_enabled' => 'boolean','container_subnets' => 'array','last_bootstrapped_at' => 'datetime',+ 'last_bootstrap_ran_at' => 'datetime','last_status_checked_at' => 'datetime',];}diff --git a/app/Models/V5/V5Model.php b/app/Models/V5/V5Model.phpindex 9907e827d7..4180ad3e36 100644--- a/app/Models/V5/V5Model.php+++ b/app/Models/V5/V5Model.php@@ -3,8 +3,21 @@namespace App\Models\V5;use Illuminate\Database\Eloquent\Model;+use Illuminate\Support\Facades\Schema;abstract class V5Model extends Model{- //+ 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());+ }+ });+ }}diff --git a/database/migrations/2026_06_16_130649_v5_create_clusters_table.php b/database/migrations/2026_06_16_130649_v5_create_clusters_table.phpindex afc8209069..fcbabc8138 100644--- a/database/migrations/2026_06_16_130649_v5_create_clusters_table.php+++ b/database/migrations/2026_06_16_130649_v5_create_clusters_table.php@@ -17,6 +17,26 @@ return new class extends Migration$table->foreignId('created_by_user_id')->constrained('users')->cascadeOnDelete();$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();$table->unique(['team_id', 'name']);diff --git a/database/migrations/2026_06_16_130650_v5_create_servers_table.php b/database/migrations/2026_06_16_130650_v5_create_servers_table.phpindex 29fbaf91d6..6e3579b3be 100644--- a/database/migrations/2026_06_16_130650_v5_create_servers_table.php+++ b/database/migrations/2026_06_16_130650_v5_create_servers_table.php@@ -13,6 +13,7 @@ return new class extends Migration{Schema::create('v5_servers', function (Blueprint $table) {$table->id();+ $table->string('uuid')->nullable()->unique();$table->foreignId('team_id')->constrained('teams')->cascadeOnDelete();$table->foreignId('cluster_id')->nullable()->constrained('v5_clusters')->nullOnDelete();$table->foreignId('created_by_user_id')->constrained('users')->cascadeOnDelete();@@ -25,7 +26,21 @@ return new class extends Migration$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->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();$table->unique(['team_id', 'host', 'ssh_port']);diff --git a/database/migrations/2026_06_16_204644_v5_add_wireguard_cli_configuration_to_clusters_and_servers.php b/database/migrations/2026_06_16_204644_v5_add_wireguard_cli_configuration_to_clusters_and_servers.phpdeleted file mode 100644index 8ac987e002..0000000000--- a/database/migrations/2026_06_16_204644_v5_add_wireguard_cli_configuration_to_clusters_and_servers.php+++ /dev/null@@ -1,90 +0,0 @@-<?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_clusters', function (Blueprint $table) {- $table->string('wireguard_interface')->default('wg0')->after('description');- $table->string('wireguard_management_pool')->default('100.64.0.0/16')->after('wireguard_interface');- $table->unsignedInteger('wireguard_listen_port')->default(51820)->after('wireguard_management_pool');- $table->string('container_network_pool')->default('10.210.0.0/16')->after('wireguard_listen_port');- $table->unsignedTinyInteger('container_network_prefix')->default(24)->after('container_network_pool');- $table->json('namespaces')->nullable()->after('container_network_prefix');- $table->boolean('default_deny_containers')->default(true)->after('namespaces');- $table->string('coold_version')->default('nightly')->after('default_deny_containers');- $table->string('corrosion_version')->default('v1.0.0')->after('coold_version');- $table->unsignedInteger('corrosion_gossip_port')->default(8787)->after('corrosion_version');- $table->unsignedInteger('corrosion_api_port')->default(8080)->after('corrosion_gossip_port');- $table->boolean('builder_enabled')->default(true)->after('corrosion_api_port');- $table->unsignedInteger('builder_capacity')->default(2)->after('builder_enabled');- $table->string('builder_cpu_quota')->default('200%')->after('builder_capacity');- $table->string('builder_memory_max')->default('2G')->after('builder_cpu_quota');- $table->unsignedInteger('builder_timeout_secs')->default(1800)->after('builder_memory_max');- $table->string('last_cli_action')->nullable()->after('builder_timeout_secs');- $table->string('last_cli_status')->nullable()->after('last_cli_action');- $table->text('last_cli_summary')->nullable()->after('last_cli_status');- $table->timestamp('last_cli_ran_at')->nullable()->after('last_cli_summary');- });-- Schema::table('v5_servers', function (Blueprint $table) {- $table->string('builder_cpu_quota')->default('200%')->after('builder_capacity');- $table->string('node_address')->nullable()->after('builder_cpu_quota');- $table->unsignedInteger('wireguard_listen_port_override')->nullable()->after('node_address');- $table->string('wireguard_endpoint_override')->nullable()->after('wireguard_listen_port_override');- $table->string('wireguard_management_ip')->nullable()->after('wireguard_endpoint_override');- $table->string('wireguard_public_key')->nullable()->after('wireguard_management_ip');- $table->json('container_subnets')->nullable()->after('wireguard_public_key');- });- }-- /**- * Reverse the migrations.- */- public function down(): void- {- Schema::table('v5_servers', function (Blueprint $table) {- $table->dropColumn([- 'builder_cpu_quota',- 'node_address',- 'wireguard_listen_port_override',- 'wireguard_endpoint_override',- 'wireguard_management_ip',- 'wireguard_public_key',- 'container_subnets',- ]);- });-- Schema::table('v5_clusters', function (Blueprint $table) {- $table->dropColumn([- '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',- ]);- });- }-};diff --git a/database/migrations/2026_06_17_165112_v5_add_builder_cpu_quota_to_servers_table.php b/database/migrations/2026_06_17_165112_v5_add_builder_cpu_quota_to_servers_table.phpdeleted file mode 100644index a07d18d8af..0000000000--- a/database/migrations/2026_06_17_165112_v5_add_builder_cpu_quota_to_servers_table.php+++ /dev/null@@ -1,36 +0,0 @@-<?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- {- if (Schema::hasColumn('v5_servers', 'builder_cpu_quota')) {- return;- }-- Schema::table('v5_servers', function (Blueprint $table) {- $table->string('builder_cpu_quota')->default('200%')->after('builder_capacity');- });- }-- /**- * Reverse the migrations.- */- public function down(): void- {- if (! Schema::hasColumn('v5_servers', 'builder_cpu_quota')) {- return;- }-- Schema::table('v5_servers', function (Blueprint $table) {- $table->dropColumn('builder_cpu_quota');- });- }-};diff --git a/database/migrations/2026_06_17_172845_add_status_check_fields_to_v5_servers_table.php b/database/migrations/2026_06_17_172845_add_status_check_fields_to_v5_servers_table.phpdeleted file mode 100644index 76dd8f2c2d..0000000000--- a/database/migrations/2026_06_17_172845_add_status_check_fields_to_v5_servers_table.php+++ /dev/null@@ -1,34 +0,0 @@-<?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('last_status_check')->nullable()->after('last_bootstrapped_at');- $table->text('last_status_output')->nullable()->after('last_status_check');- $table->timestamp('last_status_checked_at')->nullable()->after('last_status_output');- });- }-- /**- * Reverse the migrations.- */- public function down(): void- {- Schema::table('v5_servers', function (Blueprint $table) {- $table->dropColumn([- 'last_status_check',- 'last_status_output',- 'last_status_checked_at',- ]);- });- }-};diff --git a/database/schema/testing-schema.sql b/database/schema/testing-schema.sqlindex c2fde927e8..dcc64d2f7d 100644--- a/database/schema/testing-schema.sql+++ b/database/schema/testing-schema.sql@@ -1353,6 +1353,7 @@ CREATE TABLE IF NOT EXISTS "v5_clusters" (CREATE TABLE IF NOT EXISTS "v5_servers" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ "uuid" TEXT,"team_id" INTEGER NOT NULL,"cluster_id" INTEGER,"created_by_user_id" INTEGER NOT NULL,@@ -1373,6 +1374,10 @@ CREATE TABLE IF NOT EXISTS "v5_servers" ("wireguard_public_key" TEXT,"container_subnets" JSON,"last_bootstrapped_at" TEXT,+ "last_bootstrap_action" TEXT,+ "last_bootstrap_status" TEXT,+ "last_bootstrap_output" TEXT,+ "last_bootstrap_ran_at" TEXT,"last_status_check" TEXT,"last_status_output" TEXT,"last_status_checked_at" TEXT,@@ -1494,6 +1499,7 @@ CREATE INDEX IF NOT EXISTS "user_changelog_reads_release_tag_index" ON "user_chaCREATE INDEX IF NOT EXISTS "user_changelog_reads_user_id_index" ON "user_changelog_reads" (user_id);CREATE UNIQUE INDEX IF NOT EXISTS "user_changelog_reads_user_id_release_tag_unique" ON "user_changelog_reads" (user_id, release_tag);CREATE UNIQUE INDEX IF NOT EXISTS "users_email_unique" ON "users" (email);+CREATE UNIQUE INDEX IF NOT EXISTS "v5_servers_uuid_unique" ON "v5_servers" (uuid);CREATE UNIQUE INDEX IF NOT EXISTS "webhook_notification_settings_team_id_unique" ON "webhook_notification_settings" (team_id);-- Migration records@@ -1811,8 +1817,5 @@ INSERT INTO "migrations" ("id", "migration", "batch") VALUES (311, '2025_12_10_1INSERT INTO "migrations" ("id", "migration", "batch") VALUES (312, '2025_12_15_143052_trim_s3_storage_credentials', 312);INSERT INTO "migrations" ("id", "migration", "batch") VALUES (313, '2025_12_17_000001_add_is_wire_navigate_enabled_to_instance_settings_table', 313);INSERT INTO "migrations" ("id", "migration", "batch") VALUES (314, '2025_12_17_000002_add_restart_tracking_to_standalone_databases', 314);-INSERT INTO "migrations" ("id", "migration", "batch") VALUES (316, '2026_06_16_130650_v5_create_servers_table', 316);-INSERT INTO "migrations" ("id", "migration", "batch") VALUES (317, '2026_06_16_130649_v5_create_clusters_table', 317);-INSERT INTO "migrations" ("id", "migration", "batch") VALUES (318, '2026_06_16_204644_v5_add_wireguard_cli_configuration_to_clusters_and_servers', 318);-INSERT INTO "migrations" ("id", "migration", "batch") VALUES (319, '2026_06_17_165112_v5_add_builder_cpu_quota_to_servers_table', 319);-INSERT INTO "migrations" ("id", "migration", "batch") VALUES (320, '2026_06_17_172845_add_status_check_fields_to_v5_servers_table', 320);+INSERT INTO "migrations" ("id", "migration", "batch") VALUES (316, '2026_06_16_130649_v5_create_clusters_table', 316);+INSERT INTO "migrations" ("id", "migration", "batch") VALUES (317, '2026_06_16_130650_v5_create_servers_table', 317);diff --git a/dev/coold-dev.md b/dev/coold-dev.mdindex a1f2d50366..8052059e21 100644--- a/dev/coold-dev.md+++ b/dev/coold-dev.md@@ -4,7 +4,15 @@ This file documents the current local v5/coold dev setup in Coolify.## Roles-- `scripts/dev.sh` owns local developer convenience.+- `scripts/dev.sh` is the main developer-facing entrypoint. Use it for normal+ local workflows such as starting/stopping the stack, creating fresh dev state,+ inspecting Corrosion, managing firewall allow rules, and running example+ containers.+- `scripts/coold-vm.sh` is a lower-level Lima VM helper used by `scripts/dev.sh`.+ It exists separately to keep VM lifecycle and guest setup details out of the+ main dev orchestration script. Call it directly only when debugging or+ operating an individual VM, for example `shell`, `status`, `logs-agent`, or+ `delete`.- Lima VMs act like real deployment servers.- `coolify init bootstrap` owns host wiring:- WireGuarddiff --git a/resources/css/v5/app.css b/resources/css/v5/app.cssindex e1637b694d..519c1ecd43 100644--- a/resources/css/v5/app.css+++ b/resources/css/v5/app.css@@ -58,6 +58,7 @@--radius-2xl: calc(var(--radius) * 1.8);--radius-3xl: calc(var(--radius) * 2.2);--radius-4xl: calc(var(--radius) * 2.6);+ --default-ring-color: var(--ring);}:root {@@ -140,6 +141,11 @@::backdrop,::file-selector-button {@apply border-border outline-ring/50;+ --tw-ring-offset-color: var(--background);+ }++ :where(a, button, input, select, textarea, [role="button"], [tabindex]:not([tabindex="-1"])):focus-visible {+ @apply outline-none ring-2 ring-ring ring-offset-2;}html,diff --git a/resources/js/v5/Pages/Clusters.tsx b/resources/js/v5/Pages/Clusters.tsxindex a564b710eb..0f784bdc66 100644--- a/resources/js/v5/Pages/Clusters.tsx+++ b/resources/js/v5/Pages/Clusters.tsx@@ -1,9 +1,18 @@import { Head } from '@inertiajs/react';-import { useMemo, useState } from 'react';+import { DotsThreeIcon } from '@phosphor-icons/react';+import { useEffect, useMemo, useState } from 'react';import type { FormEvent } from 'react';import { AppNavbar } from '@/components/app-navbar';import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';import { Field, FieldError, FieldLabel } from '@/components/ui/field';import { Input } from '@/components/ui/input';import { Textarea } from '@/components/ui/textarea';@@ -15,6 +24,7 @@ import {DialogHeader,DialogTitle,} from '@/components/ui/dialog';+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';import { csrfToken } from '@/lib/csrf';import { usePendingIds } from '@/lib/use-pending-ids';import type { V5Cluster, V5DashboardProps, V5Server } from '@/types';@@ -67,18 +77,49 @@ type UpdateServerResponse = {};type CheckServerResponse = {- cluster: V5Cluster;+ status: string;+ output: string;+ checkedAt: string;};type DeleteServerResponse = {cluster: V5Cluster;};+type BootstrapServerResponse = {cluster?: V5Cluster;message?: string;};+type ServerSshCheck = {+ status: string;+ output: string;+ checkedAt: string;+};++type V5ClusterUpdatedEvent = {+ cluster: V5Cluster | 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;+ }+}+const clusterDefaults = {wireguardInterface: 'wg0',wireguardManagementPool: '100.64.0.0/16',@@ -109,16 +150,9 @@ function formatDate(value: string | null): string {}).format(new Date(value));}-function normalizeCapabilities(capabilities: string[]): string {- if (capabilities.length === 0) {- return 'No capabilities';- }-- return capabilities.join(', ');-}-export default function Clusters({flux,+ currentTeam = null,clusters = [],privateKeys = [],projects = [],@@ -167,6 +201,8 @@ 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 bootstrappingServers = usePendingIds<string>();const [bootstrapServerError, setBootstrapServerError] = useState<string | null>(null);const deletingServers = usePendingIds<string>();@@ -186,6 +222,106 @@ export default function Clusters({[clusterList, selectedClusterId],);+ const notInitializedServers = selectedCluster?.servers.filter((server) => server.lastBootstrappedAt === null) ?? [];+ const initializedServers = selectedCluster?.servers.filter((server) => server.lastBootstrappedAt !== null) ?? [];+ const hasBootstrapInProgress =+ selectedCluster?.servers.some((server) => ['queued', 'running'].includes(server.lastBootstrapStatus ?? '')) ?? false;++ 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 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]);++ useEffect(() => {+ if (!selectedCluster || !hasBootstrapInProgress) {+ return;+ }++ let isCancelled = false;++ async function refreshCluster(): Promise<void> {+ if (!selectedCluster) {+ return;+ }++ const response = await fetch(`/v5/clusters/${selectedCluster.id}`, {+ method: 'GET',+ credentials: 'same-origin',+ headers: {+ Accept: 'application/json',+ },+ });++ if (!response.ok || isCancelled) {+ return;+ }++ const payload = (await response.json()) as { cluster?: V5Cluster };++ if (payload.cluster) {+ setClusterList((currentClusters) =>+ currentClusters.map((cluster) => (cluster.id === payload.cluster?.id ? payload.cluster : cluster)),+ );+ }+ }++ const interval = window.setInterval(() => void refreshCluster(), 3000);++ return () => {+ isCancelled = true;+ window.clearInterval(interval);+ };+ }, [hasBootstrapInProgress, selectedCluster]);+async function createCluster(event: FormEvent<HTMLFormElement>): Promise<void> {event.preventDefault();setIsSubmitting(true);@@ -393,10 +529,10 @@ export default function Clusters({if (response.ok) {const payload = (await response.json()) as CheckServerResponse;-- setClusterList((currentClusters) =>- currentClusters.map((cluster) => (cluster.id === payload.cluster.id ? payload.cluster : cluster)),- );+ setSshChecks((currentChecks) => ({+ ...currentChecks,+ [server.id]: payload,+ }));}checkingServers.finish(server.id);@@ -428,7 +564,7 @@ export default function Clusters({}if (!response.ok) {- setBootstrapServerError(payload.message ?? 'Unable to bootstrap this server. Check the CLI state output.');+ setBootstrapServerError(payload.message ?? 'Unable to queue bootstrap for this server.');}bootstrappingServers.finish(server.id);@@ -448,7 +584,7 @@ export default function Clusters({}function openDeleteServerDialog(server: V5Server): void {- if (!selectedCluster || server.lastBootstrappedAt !== null) {+ if (!selectedCluster) {return;}@@ -458,11 +594,7 @@ export default function Clusters({setIsDeleteDialogOpen(true);}- async function deleteUnbootstrappedServer(cluster: V5Cluster, server: V5Server): Promise<void> {- if (server.lastBootstrappedAt !== null) {- return;- }-+ async function deleteServer(cluster: V5Cluster, server: V5Server): Promise<void> {deletingServers.start(server.id);const response = await fetch(`/v5/clusters/${cluster.id}/servers/${server.id}`, {@@ -548,7 +680,7 @@ export default function Clusters({}if (serverPendingDelete) {- await deleteUnbootstrappedServer(clusterPendingDelete, serverPendingDelete);+ await deleteServer(clusterPendingDelete, serverPendingDelete);return;}@@ -600,6 +732,168 @@ export default function Clusters({setEditServerErrors({});}++ function renderServerCard(server: V5Server) {+ const isCheckingServer = checkingServers.has(server.id);+ const isBootstrapInProgress = ['queued', 'running'].includes(server.lastBootstrapStatus ?? '');+ 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">+ <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">+ <div className="min-w-0">+ <h4 className="break-words text-sm font-semibold text-foreground">{server.name}</h4>+ <p className="mt-1 break-all text-xs text-muted-foreground">{server.host}</p>+ </div>+ <div className="flex w-full flex-col items-stretch gap-2 sm:w-auto sm:flex-row sm:flex-wrap sm:items-center sm:justify-end">+ {!isServerInitialized ? (+ <div role="group" aria-label="Server initialization" className="inline-flex">+ <span className="inline-flex h-7 items-center rounded-l-md border border-r-0 border-destructive/30 bg-destructive/10 px-2 text-xs font-medium text-destructive">+ Not initialized+ </span>+ <Button+ type="button"+ variant="coolify"+ size="sm"+ className="rounded-r-md"+ disabled={isBootstrappingServer}+ onClick={() => void bootstrapServer(server)}+ >+ {isBootstrapInProgress+ ? 'Bootstrapping...'+ : isBootstrappingServer+ ? 'Queueing...'+ : 'Bootstrap'}+ </Button>+ </div>+ ) : null}+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Server actions"+ />+ }+ >+ <DotsThreeIcon data-icon="inline-start" weight="bold" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-48">+ <DropdownMenuGroup>+ <DropdownMenuItem+ disabled={isCheckingServer}+ onClick={() => void checkServer(server)}+ >+ {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>+ ) : null}+ <DropdownMenuItem onClick={() => openEditServerDialog(server)}>+ Edit server+ </DropdownMenuItem>+ </DropdownMenuGroup>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ disabled={isDeletingServer}+ onClick={() => openDeleteServerDialog(server)}+ >+ {isDeletingServer ? 'Deleting...' : 'Delete server'}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>++ <dl className="mt-4 grid grid-cols-1 gap-3 text-xs sm:grid-cols-2">+ <div>+ <dt className="text-muted-foreground">Builder capacity</dt>+ <dd className="mt-1 break-words font-medium text-foreground">+ {server.builderEnabled ? server.builderCapacity : 'Disabled'}+ </dd>+ </div>+ {server.builderEnabled ? (+ <div>+ <dt className="text-muted-foreground">Builder CPU quota</dt>+ <dd className="mt-1 break-words font-medium text-foreground">{server.builderCpuQuota}</dd>+ </div>+ ) : null}+ <div>+ <dt className="text-muted-foreground">WireGuard IP</dt>+ <dd className="mt-1 break-words font-medium text-foreground">+ {server.wireguardManagementIp ?? 'Not assigned'}+ </dd>+ </div>+ <div>+ <dt className="text-muted-foreground">Server IP</dt>+ <dd className="mt-1 break-words font-medium text-foreground">{server.host}</dd>+ </div>+ <div>+ <dt className="text-muted-foreground">Private key</dt>+ <dd className="mt-1 break-words font-medium text-foreground">+ {server.privateKeyName ?? 'No key'}+ </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>+ );+ }+return (<><Head title="Clusters" />@@ -614,56 +908,69 @@ export default function Clusters({/><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="grid w-full grid-cols-1 gap-4 py-4 lg:min-h-0 lg:py-6 lg:grid-cols-[20rem_minmax(0,1fr)]">- <aside className="flex max-h-80 flex-col rounded-lg border border-border bg-card lg:max-h-none lg:min-h-0">- <div className="flex items-start justify-between gap-3 border-b border-border p-4">- <div>+ <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">+ <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">+ <div className="min-w-0"><p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Clusters</p><h1 className="mt-1 text-lg font-semibold text-foreground">Cluster inventory</h1></div>- <Button- type="button"- variant="coolify"- size="sm"- aria-label="Create cluster"- onClick={() => setIsCreateDialogOpen(true)}- >- <span className="text-base leading-none">+</span>- Add cluster- </Button>- </div>- <div className="min-h-0 flex-1 overflow-y-auto p-2">- {clusterList.length === 0 ? (- <div className="rounded-md border border-dashed border-border p-4 text-sm text-muted-foreground">- No clusters yet. Create your first cluster to group servers.- </div>- ) : (- <div className="flex flex-col gap-2">- {clusterList.map((cluster) => (- <button- key={cluster.id}- type="button"- onClick={() => setSelectedClusterId(cluster.id)}- className={`rounded-md border p-3 text-left transition-colors ${- selectedCluster?.id === cluster.id- ? 'border-warning bg-warning/10 text-foreground'- : 'border-border bg-background hover:bg-muted/50'- }`}+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center">+ {clusterList.length === 0 ? (+ <div className="rounded-md border border-dashed border-border px-3 py-2 text-sm text-muted-foreground">+ No clusters yet.+ </div>+ ) : (+ <Select+ items={clusterList.map((cluster) => ({+ label: cluster.name,+ value: cluster.id,+ }))}+ value={selectedClusterId}+ onValueChange={(value) => {+ if (value !== null) {+ setSelectedClusterId(value);+ }+ }}+ >+ <SelectTrigger+ aria-label="Select a cluster"+ className="w-full sm:w-72">- <span className="block text-sm font-medium">{cluster.name}</span>- <span className="mt-1 block text-xs text-muted-foreground">- {cluster.serversCount}{' '}- {cluster.serversCount === 1 ? 'server' : 'servers'}- </span>- </button>- ))}- </div>- )}+ <SelectValue placeholder="Select a cluster" />+ </SelectTrigger>+ <SelectContent position="popper" align="end" sideOffset={4}>+ <SelectGroup>+ {clusterList.map((cluster) => (+ <SelectItem+ key={cluster.id}+ value={cluster.id}+ >+ {cluster.name}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ )}++ <Button+ type="button"+ variant="coolify"+ size="default"+ aria-label="Create cluster"+ onClick={() => setIsCreateDialogOpen(true)}+ className="sm:shrink-0"+ >+ <span className="text-base leading-none">+</span>+ Add cluster+ </Button>+ </div></div>- </aside>+ </div><section className="overflow-visible rounded-lg border border-border bg-card lg:min-h-0 lg:overflow-y-auto">{selectedCluster ? (@@ -686,7 +993,7 @@ export default function Clusters({<Buttontype="button"variant="delete"- size="sm"+ size="default"onClick={openDeleteClusterDialog}disabled={isDeletingCluster}>@@ -803,7 +1110,6 @@ export default function Clusters({<Buttontype="button"variant="coolify"- size="sm"aria-label="Add server to cluster"onClick={() => {setServerBuilderEnabled(selectedCluster.builderEnabled);@@ -822,11 +1128,6 @@ export default function Clusters({<p className="text-sm font-medium text-destructive">{bootstrapServerError}</p>- {selectedCluster.lastCliSummary ? (- <pre className="mt-2 max-h-48 overflow-auto whitespace-pre-wrap rounded bg-background p-2 text-xs text-muted-foreground">- {selectedCluster.lastCliSummary}- </pre>- ) : null}</div>) : null}@@ -840,157 +1141,44 @@ export default function Clusters({</p></div>) : (- <div className="grid grid-cols-1 gap-3 xl:grid-cols-2">- {selectedCluster.servers.map((server) => {- const isCheckingServer = checkingServers.has(server.id);- const isBootstrappingServer = bootstrappingServers.has(server.id);- const isDeletingServer = deletingServers.has(server.id);-- return (- <article- key={server.id}- className="rounded-lg border border-border bg-background p-4"- >- <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">- <div className="min-w-0">- <h4 className="break-words text-sm font-semibold text-foreground">- {server.name}- </h4>- <p className="mt-1 break-all text-xs text-muted-foreground">- {server.host}- </p>- </div>- <div className="flex w-full flex-col items-stretch gap-2 sm:w-auto sm:flex-row sm:flex-wrap sm:items-center sm:justify-end">- <span className="rounded-full border border-border bg-muted/40 px-2 py-1 text-xs text-muted-foreground">- Bootstrap: {server.status}- </span>- <Button- type="button"- variant="outline"- size="sm"- disabled={isCheckingServer}- onClick={() => void checkServer(server)}- >- {isCheckingServer- ? 'Checking...'- : 'Check SSH'}- </Button>- {server.lastBootstrappedAt === null ? (- <Button- type="button"- variant="outline"- size="sm"- disabled={isBootstrappingServer}- onClick={() => void bootstrapServer(server)}- >- {isBootstrappingServer- ? 'Bootstrapping...'- : 'Bootstrap'}- </Button>- ) : null}- <Button- type="button"- variant="outline"- size="sm"- onClick={() => openEditServerDialog(server)}- >- Edit server- </Button>- {server.lastBootstrappedAt === null ? (- <Button- type="button"- variant="delete"- size="sm"- disabled={isDeletingServer}- onClick={() => openDeleteServerDialog(server)}- >- {isDeletingServer- ? 'Deleting...'- : 'Delete'}- </Button>- ) : null}- </div>+ <div className="flex flex-col gap-6">+ {notInitializedServers.length > 0 ? (+ <section aria-labelledby="not-initialized-servers-heading">+ <div className="mb-3">+ <h4+ id="not-initialized-servers-heading"+ className="text-sm font-semibold text-foreground"+ >+ Not initialized servers+ </h4>+ <p className="mt-1 text-xs text-muted-foreground">+ Bootstrap these servers before using them for workloads.+ </p>+ </div>+ <div className="grid grid-cols-1 gap-3 xl:grid-cols-2">+ {notInitializedServers.map(renderServerCard)}</div>+ </section>+ ) : null}- <dl className="mt-4 grid grid-cols-1 gap-3 text-xs sm:grid-cols-2">- <div>- <dt className="text-muted-foreground">- Builder capacity- </dt>- <dd className="mt-1 break-words font-medium text-foreground">- {server.builderEnabled- ? server.builderCapacity- : 'Disabled'}- </dd>- </div>- <div>- <dt className="text-muted-foreground">- Builder CPU quota- </dt>- <dd className="mt-1 break-words font-medium text-foreground">- {server.builderCpuQuota}- </dd>- </div>- <div>- <dt className="text-muted-foreground">WireGuard IP</dt>- <dd className="mt-1 break-words font-medium text-foreground">- {server.wireguardManagementIp ?? 'Not assigned'}- </dd>- </div>- <div>- <dt className="text-muted-foreground">CLI node</dt>- <dd className="mt-1 break-words font-medium text-foreground">- {server.nodeAddress ?? server.host}- </dd>- </div>- <div>- <dt className="text-muted-foreground">Private key</dt>- <dd className="mt-1 break-words font-medium text-foreground">- {server.privateKeyName ?? 'No key'}- </dd>- </div>- <div>- <dt className="text-muted-foreground">- Last bootstrap- </dt>- <dd className="mt-1 break-words font-medium text-foreground">- {formatDate(server.lastBootstrappedAt)}- </dd>- </div>- </dl>-- <p className="mt-4 text-xs text-muted-foreground">- Capabilities: {normalizeCapabilities(server.capabilities)}- </p>-- <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- {server.lastStatusCheck- ? `: ${server.lastStatusCheck}`- : ''}- </span>- <span className="text-muted-foreground">- {server.lastStatusCheckedAt- ? formatDate(server.lastStatusCheckedAt)- : 'Never run'}- </span>- </div>- {server.lastStatusOutput ? (- <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap rounded bg-background p-2 text-muted-foreground">- {server.lastStatusOutput}- </pre>- ) : (- <p className="mt-2 text-muted-foreground">- Run Check SSH to verify connectivity and capture- diagnostic output.- </p>- )}+ {initializedServers.length > 0 ? (+ <section aria-labelledby="initialized-servers-heading">+ <div className="mb-3">+ <h4+ id="initialized-servers-heading"+ className="text-sm font-semibold text-foreground"+ >+ Servers+ </h4>+ <p className="mt-1 text-xs text-muted-foreground">+ Initialized servers currently assigned to this cluster.+ </p>+ </div>+ <div className="grid grid-cols-1 gap-3 xl:grid-cols-2">+ {initializedServers.map(renderServerCard)}</div>- </article>- );- })}+ </section>+ ) : null}</div>)}</div>@@ -1023,7 +1211,7 @@ export default function Clusters({<DialogTitle>Confirm deletion</DialogTitle><DialogDescription>{serverPendingDelete- ? `Delete unbootstrapped server ${serverPendingDelete.name}? This only removes it from this cluster.`+ ? `Delete server ${serverPendingDelete.name}? This removes it from this cluster inventory so you can add it again later.`: `Delete cluster ${clusterPendingDelete?.name ?? ''}? This cannot be undone.`}</DialogDescription></DialogHeader>@@ -1088,10 +1276,10 @@ export default function Clusters({<FieldError message={errors.description?.[0]} /></Field>- <div className="rounded-lg border border-border bg-muted/20">+ <div className="rounded-lg border border-border bg-muted/20 transition-colors focus-within:border-ring"><buttontype="button"- className="flex w-full items-center justify-between gap-3 px-4 py-3 text-left text-sm font-medium text-foreground"+ className="flex w-full items-center justify-between gap-3 px-4 py-3 text-left text-sm font-medium text-foreground outline-none"onClick={() => setShowAdvancedConfiguration((value) => !value)}><span>Advanced configuration</span>@@ -1361,7 +1549,7 @@ export default function Clusters({<selectvalue={selectedPrivateKeyId}onChange={(event) => setSelectedPrivateKeyId(event.target.value)}- className="appearance-none rounded-md border border-border bg-background bg-[length:1rem_1rem] bg-[position:right_0.75rem_center] bg-no-repeat px-3 py-2 pr-10 text-sm outline-none transition focus:border-ring focus:ring-1 focus:ring-ring aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40"+ className="appearance-none rounded-md border border-border bg-background bg-[length:1rem_1rem] bg-[position:right_0.75rem_center] bg-no-repeat px-3 py-2 pr-10 text-sm outline-none transition focus:border-ring focus:ring-0 aria-invalid:border-destructive aria-invalid:ring-0 dark:aria-invalid:border-destructive/50"aria-invalid={serverErrors.private_key_id ? true : undefined}style={{backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 256 256' fill='none' stroke='%23ffffff' stroke-width='28' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m64 96 64 64 64-64'/%3E%3C/svg%3E")`,@@ -1377,10 +1565,10 @@ export default function Clusters({<FieldError message={serverErrors.private_key_id?.[0]} /></Field>- <div className="rounded-lg border border-border bg-muted/20">+ <div className="rounded-lg border border-border bg-muted/20 transition-colors focus-within:border-ring"><buttontype="button"- className="flex w-full items-center justify-between gap-3 px-4 py-3 text-left text-sm font-medium text-foreground"+ className="flex w-full items-center justify-between gap-3 px-4 py-3 text-left text-sm font-medium text-foreground outline-none"onClick={() => setShowAdvancedServerConfiguration((value) => !value)}><span>Advanced server configuration</span>@@ -1392,11 +1580,11 @@ export default function Clusters({{showAdvancedServerConfiguration ? (<div className="grid grid-cols-1 gap-4 border-t border-border p-4 sm:grid-cols-2"><Field>- <FieldLabel>CLI node address</FieldLabel>+ <FieldLabel>Node address override</FieldLabel><Inputvalue={serverNodeAddress}onChange={(event) => setServerNodeAddress(event.target.value)}- placeholder="Defaults to host"+ placeholder="Defaults to server IP"aria-invalid={serverErrors.node_address ? true : undefined}/><FieldError message={serverErrors.node_address?.[0]} />diff --git a/resources/js/v5/Pages/RealtimeTest.tsx b/resources/js/v5/Pages/RealtimeTest.tsxnew file mode 100644index 0000000000..f286fce41f--- /dev/null+++ b/resources/js/v5/Pages/RealtimeTest.tsx@@ -0,0 +1,199 @@+import { Head } from '@inertiajs/react';+import { 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 type { V5DashboardProps } from '@/types';++type RealtimeTestProps = V5DashboardProps & {+ currentTeam: {+ id: number;+ } | null;+};++type RealtimeTestEvent = {+ message: string;+ teamId: number;+ 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;+ }++ return JSON.stringify(payload, null, 2);+}++export default function RealtimeTest({ currentTeam, flux, projects = [], selectedProjectUuid = null, selectedEnvironmentUuid = null }: RealtimeTestProps) {+ const [message, setMessage] = useState('Hello from v5 realtime test');+ const [isBroadcasting, setIsBroadcasting] = useState(false);+ const [logs, setLogs] = useState<string[]>([]);++ function addLog(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;+ }++ let isCancelled = false;+ let attempts = 0;+ const channelName = `team.${currentTeam.id}`;++ const interval = window.setInterval(() => {+ attempts += 1;++ 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]);++ async function broadcastTestEvent(): Promise<void> {+ setIsBroadcasting(true);+ addLog('Sending POST /v5/realtime-test');++ const response = await fetch('/v5/realtime-test', {+ method: 'POST',+ credentials: 'same-origin',+ headers: {+ Accept: 'application/json',+ 'Content-Type': 'application/json',+ 'X-CSRF-TOKEN': csrfToken(),+ },+ body: JSON.stringify({ message }),+ });++ const payload = await response.json().catch(() => null);+ addLog(`POST /v5/realtime-test responded ${response.status}`, payload);+ setIsBroadcasting(false);+ }++ return (+ <>+ <Head title="Realtime test" />+ <div className="min-h-dvh bg-background text-foreground">+ <AppNavbar+ flux={flux}+ clusters={[]}+ projects={projects}+ selectedProjectUuid={selectedProjectUuid}+ selectedEnvironmentUuid={selectedEnvironmentUuid}+ />+ <main className="mx-auto flex max-w-5xl flex-col gap-6 px-4 pt-20 pb-8 lg:px-6">+ <section className="rounded-lg border border-border bg-card p-5">+ <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">RealtimeTest</p>+ <h1 className="mt-1 text-2xl font-semibold text-foreground">v5 realtime websocket test</h1>+ <p className="mt-2 text-sm text-muted-foreground">+ Opens a private team channel subscription and broadcasts a manual backend event named{' '}+ <code className="rounded bg-muted px-1 py-0.5">v5.realtime.test</code>.+ </p>+ </section>++ <section className="grid grid-cols-1 gap-4 lg:grid-cols-3">+ <div className="rounded-lg border border-border bg-card p-4">+ <h2 className="text-sm font-semibold text-foreground">Runtime state</h2>+ <dl className="mt-3 space-y-2 text-sm">+ <div className="flex justify-between gap-3">+ <dt className="text-muted-foreground">Team ID</dt>+ <dd className="font-medium text-foreground">{currentTeam?.id ?? 'Missing'}</dd>+ </div>+ <div className="flex justify-between gap-3">+ <dt className="text-muted-foreground">Echo</dt>+ <dd className="font-medium text-foreground">{typeof window !== 'undefined' && window.Echo ? 'Available' : 'Missing'}</dd>+ </div>+ <div className="flex justify-between gap-3">+ <dt className="text-muted-foreground">Channel</dt>+ <dd className="font-medium text-foreground">{currentTeam ? `private-team.${currentTeam.id}` : 'Missing'}</dd>+ </div>+ </dl>+ </div>++ <div className="rounded-lg border border-border bg-card p-4 lg:col-span-2">+ <h2 className="text-sm font-semibold text-foreground">Send test event</h2>+ <div className="mt-3 flex flex-col gap-3 sm:flex-row">+ <Input value={message} onChange={(event) => setMessage(event.target.value)} />+ <Button type="button" variant="coolify" disabled={isBroadcasting} onClick={() => void broadcastTestEvent()}>+ {isBroadcasting ? 'Broadcasting...' : 'Broadcast event'}+ </Button>+ </div>+ </div>+ </section>++ <section className="rounded-lg border border-border bg-card p-4">+ <div className="flex items-center justify-between gap-3">+ <h2 className="text-sm font-semibold text-foreground">Event log</h2>+ <Button type="button" variant="outline" size="sm" onClick={() => setLogs([])}>+ Clear+ </Button>+ </div>+ <pre className="mt-3 min-h-64 overflow-auto whitespace-pre-wrap rounded-md bg-background p-4 text-xs text-muted-foreground">+ {logs.length === 0 ? 'No logs yet.' : logs.join('\n\n')}+ </pre>+ </section>+ </main>+ </div>+ </>+ );+}diff --git a/resources/js/v5/components/app-navbar.tsx b/resources/js/v5/components/app-navbar.tsxindex 1b205f9ed6..be15340731 100644--- a/resources/js/v5/components/app-navbar.tsx+++ b/resources/js/v5/components/app-navbar.tsx@@ -26,8 +26,6 @@ function persistSelection(projectUuid: string, environmentUuid: string): void {type AppNavbarProps = V5DashboardProps;export function AppNavbar({- flux,- clusters = [],projects = [],selectedProjectUuid = null,selectedEnvironmentUuid = null,@@ -86,7 +84,7 @@ export function AppNavbar({className="flex shrink-0 items-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"aria-label="Coolify dashboard">- <img src="/coolify-logo.svg" alt="Coolify" className="size-8" />+ <img src="/coolify-logo.svg" alt="Coolify" className="size-6" /></Link><div 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">@@ -141,13 +139,6 @@ export function AppNavbar({Clusters</Link>- <div- className="hidden rounded-md border border-border bg-muted/40 px-3 py-1 text-xs text-muted-foreground lg:block"- title={flux?.socket ?? flux?.message ?? undefined}- >- Flux: {flux?.label ?? 'Unknown'} · {clusters.length} clusters- </div>-<Sheet><SheetTriggerclassName="inline-flex rounded-md p-2 text-warning transition-colors hover:bg-muted hover:text-warning md:hidden"diff --git a/resources/js/v5/components/ui/button.tsx b/resources/js/v5/components/ui/button.tsxindex 3c7faecd9f..7bf486a562 100644--- a/resources/js/v5/components/ui/button.tsx+++ b/resources/js/v5/components/ui/button.tsx@@ -5,21 +5,21 @@ import type * as React from 'react';import { cn } from '@/lib/utils';const buttonVariants = cva(- "group/button inline-flex shrink-0 items-center justify-center rounded-none border border-transparent bg-clip-padding text-xs font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "group/button inline-flex shrink-0 items-center justify-center rounded-none border border-transparent bg-clip-padding text-xs font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive dark:aria-invalid:border-destructive/50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants: {variant: {default: 'bg-primary text-primary-foreground hover:bg-primary/80',coolify:- 'border-coollabs bg-coollabs-50 text-coollabs-200 hover:bg-coollabs hover:text-white dark:border-coollabs-100 dark:bg-coollabs/20 dark:text-white dark:hover:bg-coollabs-100 dark:hover:text-white',+ 'border-coollabs bg-coollabs-50 text-coollabs-200 hover:bg-coollabs hover:text-white focus-visible:border-coollabs-100 focus-visible:bg-coollabs focus-visible:text-white dark:border-coollabs-100 dark:bg-coollabs/20 dark:text-white dark:hover:bg-coollabs-100 dark:hover:text-white dark:focus-visible:border-coollabs-100 dark:focus-visible:bg-coollabs-100',outline:'border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50',secondary:'bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground',ghost: 'hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50',destructive:- 'bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40',- delete: 'bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40',+ 'bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-ring dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:border-ring',+ delete: 'bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-ring dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:border-ring',link: 'text-primary underline-offset-4 hover:underline',},size: {diff --git a/resources/js/v5/components/ui/dialog.tsx b/resources/js/v5/components/ui/dialog.tsxindex 4a72fbe500..d479855066 100644--- a/resources/js/v5/components/ui/dialog.tsx+++ b/resources/js/v5/components/ui/dialog.tsx@@ -63,7 +63,7 @@ function DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {}function DialogFooter({ className, ...props }: React.ComponentProps<'div'>) {- return <div data-slot="dialog-footer" className={cn('flex justify-end gap-2', className)} {...props} />;+ return <div data-slot="dialog-footer" className={cn('mt-6 flex justify-end gap-2', className)} {...props} />;}function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {diff --git a/resources/js/v5/components/ui/dropdown-menu.tsx b/resources/js/v5/components/ui/dropdown-menu.tsxnew file mode 100644index 0000000000..28077c0aa9--- /dev/null+++ b/resources/js/v5/components/ui/dropdown-menu.tsx@@ -0,0 +1,266 @@+import * as React from "react"+import { Menu as MenuPrimitive } from "@base-ui/react/menu"++import { cn } from "@/lib/utils"+import { CaretRightIcon, CheckIcon } from "@phosphor-icons/react"++function DropdownMenu({ ...props }: MenuPrimitive.Root.Props) {+ return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />+}++function DropdownMenuPortal({ ...props }: MenuPrimitive.Portal.Props) {+ return <MenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />+}++function DropdownMenuTrigger({ ...props }: MenuPrimitive.Trigger.Props) {+ return <MenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />+}++function DropdownMenuContent({+ align = "start",+ alignOffset = 0,+ side = "bottom",+ sideOffset = 4,+ className,+ ...props+}: MenuPrimitive.Popup.Props &+ Pick<+ MenuPrimitive.Positioner.Props,+ "align" | "alignOffset" | "side" | "sideOffset"+ >) {+ return (+ <MenuPrimitive.Portal>+ <MenuPrimitive.Positioner+ className="isolate z-50 outline-none"+ align={align}+ alignOffset={alignOffset}+ side={side}+ sideOffset={sideOffset}+ >+ <MenuPrimitive.Popup+ data-slot="dropdown-menu-content"+ className={cn("z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-none bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95", className )}+ {...props}+ />+ </MenuPrimitive.Positioner>+ </MenuPrimitive.Portal>+ )+}++function DropdownMenuGroup({ ...props }: MenuPrimitive.Group.Props) {+ return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />+}++function DropdownMenuLabel({+ className,+ inset,+ ...props+}: MenuPrimitive.GroupLabel.Props & {+ inset?: boolean+}) {+ return (+ <MenuPrimitive.GroupLabel+ data-slot="dropdown-menu-label"+ data-inset={inset}+ className={cn(+ "px-2 py-2 text-xs text-muted-foreground data-inset:pl-7",+ className+ )}+ {...props}+ />+ )+}++function DropdownMenuItem({+ className,+ inset,+ variant = "default",+ ...props+}: MenuPrimitive.Item.Props & {+ inset?: boolean+ variant?: "default" | "destructive"+}) {+ return (+ <MenuPrimitive.Item+ data-slot="dropdown-menu-item"+ data-inset={inset}+ data-variant={variant}+ className={cn(+ "group/dropdown-menu-item relative flex cursor-default items-center gap-2 rounded-none px-2 py-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",+ className+ )}+ {...props}+ />+ )+}++function DropdownMenuSub({ ...props }: MenuPrimitive.SubmenuRoot.Props) {+ return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />+}++function DropdownMenuSubTrigger({+ className,+ inset,+ children,+ ...props+}: MenuPrimitive.SubmenuTrigger.Props & {+ inset?: boolean+}) {+ return (+ <MenuPrimitive.SubmenuTrigger+ data-slot="dropdown-menu-sub-trigger"+ data-inset={inset}+ className={cn(+ "flex cursor-default items-center gap-2 rounded-none px-2 py-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-popup-open:bg-accent data-popup-open:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ className+ )}+ {...props}+ >+ {children}+ <CaretRightIcon className="ml-auto" />+ </MenuPrimitive.SubmenuTrigger>+ )+}++function DropdownMenuSubContent({+ align = "start",+ alignOffset = -3,+ side = "right",+ sideOffset = 0,+ className,+ ...props+}: React.ComponentProps<typeof DropdownMenuContent>) {+ return (+ <DropdownMenuContent+ data-slot="dropdown-menu-sub-content"+ className={cn("w-auto min-w-[96px] rounded-none bg-popover text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}+ align={align}+ alignOffset={alignOffset}+ side={side}+ sideOffset={sideOffset}+ {...props}+ />+ )+}++function DropdownMenuCheckboxItem({+ className,+ children,+ checked,+ inset,+ ...props+}: MenuPrimitive.CheckboxItem.Props & {+ inset?: boolean+}) {+ return (+ <MenuPrimitive.CheckboxItem+ data-slot="dropdown-menu-checkbox-item"+ data-inset={inset}+ className={cn(+ "relative flex cursor-default items-center gap-2 rounded-none py-2 pr-8 pl-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ className+ )}+ checked={checked}+ {...props}+ >+ <span+ className="pointer-events-none absolute right-2 flex items-center justify-center"+ data-slot="dropdown-menu-checkbox-item-indicator"+ >+ <MenuPrimitive.CheckboxItemIndicator>+ <CheckIcon+ />+ </MenuPrimitive.CheckboxItemIndicator>+ </span>+ {children}+ </MenuPrimitive.CheckboxItem>+ )+}++function DropdownMenuRadioGroup({ ...props }: MenuPrimitive.RadioGroup.Props) {+ return (+ <MenuPrimitive.RadioGroup+ data-slot="dropdown-menu-radio-group"+ {...props}+ />+ )+}++function DropdownMenuRadioItem({+ className,+ children,+ inset,+ ...props+}: MenuPrimitive.RadioItem.Props & {+ inset?: boolean+}) {+ return (+ <MenuPrimitive.RadioItem+ data-slot="dropdown-menu-radio-item"+ data-inset={inset}+ className={cn(+ "relative flex cursor-default items-center gap-2 rounded-none py-2 pr-8 pl-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ className+ )}+ {...props}+ >+ <span+ className="pointer-events-none absolute right-2 flex items-center justify-center"+ data-slot="dropdown-menu-radio-item-indicator"+ >+ <MenuPrimitive.RadioItemIndicator>+ <CheckIcon+ />+ </MenuPrimitive.RadioItemIndicator>+ </span>+ {children}+ </MenuPrimitive.RadioItem>+ )+}++function DropdownMenuSeparator({+ className,+ ...props+}: MenuPrimitive.Separator.Props) {+ return (+ <MenuPrimitive.Separator+ data-slot="dropdown-menu-separator"+ className={cn("-mx-1 h-px bg-border", className)}+ {...props}+ />+ )+}++function DropdownMenuShortcut({+ className,+ ...props+}: React.ComponentProps<"span">) {+ return (+ <span+ data-slot="dropdown-menu-shortcut"+ className={cn(+ "ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground",+ className+ )}+ {...props}+ />+ )+}++export {+ DropdownMenu,+ DropdownMenuPortal,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuLabel,+ DropdownMenuItem,+ DropdownMenuCheckboxItem,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuShortcut,+ DropdownMenuSub,+ DropdownMenuSubTrigger,+ DropdownMenuSubContent,+}diff --git a/resources/js/v5/components/ui/input.tsx b/resources/js/v5/components/ui/input.tsxindex 1bda40f0c6..c16cd13f59 100644--- a/resources/js/v5/components/ui/input.tsx+++ b/resources/js/v5/components/ui/input.tsx@@ -7,7 +7,7 @@ function Input({ className, ...props }: React.ComponentProps<'input'>) {<inputdata-slot="input"className={cn(- 'rounded-md border border-border bg-background px-3 py-2 text-sm outline-none transition focus:border-ring focus:ring-1 focus:ring-ring aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40',+ 'rounded-md border border-border bg-background px-3 py-2 text-sm outline-none transition focus:border-ring focus:ring-0 aria-invalid:border-destructive aria-invalid:ring-0 dark:aria-invalid:border-destructive/50',className,)}{...props}diff --git a/resources/js/v5/components/ui/select.tsx b/resources/js/v5/components/ui/select.tsxindex 36f011c2d9..a8fcc41fc8 100644--- a/resources/js/v5/components/ui/select.tsx+++ b/resources/js/v5/components/ui/select.tsx@@ -30,11 +30,11 @@ function SelectTrigger({ className, size = 'default', variant = 'default', childdata-size={size}data-variant={variant}className={cn(- "flex w-fit items-center justify-between gap-1.5 rounded-none whitespace-nowrap transition-colors outline-none select-none focus-visible:ring-1 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-none *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "flex w-fit items-center justify-between gap-1.5 rounded-none whitespace-nowrap transition-colors outline-none select-none disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-none *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:aria-invalid:border-destructive/50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",variant === 'default' &&'border border-input bg-transparent py-2 pr-2 pl-2.5 text-xs focus-visible:border-ring dark:bg-input/30 dark:hover:bg-input/50',variant === 'ghost' &&- 'h-auto border border-transparent bg-transparent px-0 py-0 text-sm font-medium text-foreground hover:bg-transparent focus-visible:border-transparent dark:bg-transparent dark:hover:bg-transparent',+ 'h-auto border border-transparent bg-transparent px-0 py-0 text-sm font-medium text-foreground hover:bg-transparent focus-visible:border-ring dark:bg-transparent dark:hover:bg-transparent',className,)}{...props}diff --git a/resources/js/v5/components/ui/textarea.tsx b/resources/js/v5/components/ui/textarea.tsxindex 4a353f60d1..9a5bdb1c65 100644--- a/resources/js/v5/components/ui/textarea.tsx+++ b/resources/js/v5/components/ui/textarea.tsx@@ -7,7 +7,7 @@ function Textarea({ className, ...props }: React.ComponentProps<'textarea'>) {<textareadata-slot="textarea"className={cn(- 'min-h-24 rounded-md border border-border bg-background px-3 py-2 text-sm outline-none transition focus:border-ring focus:ring-1 focus:ring-ring aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40',+ 'min-h-24 rounded-md border border-border bg-background px-3 py-2 text-sm outline-none transition focus:border-ring focus:ring-0 aria-invalid:border-destructive aria-invalid:ring-0 dark:aria-invalid:border-destructive/50',className,)}{...props}diff --git a/resources/js/v5/types.ts b/resources/js/v5/types.tsindex 97f924fff5..0f3b6a8b86 100644--- a/resources/js/v5/types.ts+++ b/resources/js/v5/types.ts@@ -14,6 +14,7 @@ export type V5Server = {builderEnabled: boolean;builderCapacity: number;builderCpuQuota: string;+ uuid: string | null;nodeAddress: string | null;wireguardListenPortOverride: number | null;wireguardEndpointOverride: string | null;@@ -22,9 +23,10 @@ export type V5Server = {containerSubnets: Record<string, string> | string[];privateKeyName: string | null;lastBootstrappedAt: string | null;- lastStatusCheck: string | null;- lastStatusOutput: string | null;- lastStatusCheckedAt: string | null;+ lastBootstrapAction: string | null;+ lastBootstrapStatus: string | null;+ lastBootstrapOutput: string | null;+ lastBootstrapRanAt: string | null;};export type V5Cluster = {@@ -73,6 +75,9 @@ export type V5PrivateKey = {export type V5DashboardProps = {flux: FluxStatus | null;+ currentTeam?: {+ id: number;+ } | null;clusters?: V5Cluster[];privateKeys?: V5PrivateKey[];projects?: V5Project[];diff --git a/resources/views/v5/app.blade.php b/resources/views/v5/app.blade.phpindex 575d0a9a01..18dd296423 100644--- a/resources/views/v5/app.blade.php+++ b/resources/views/v5/app.blade.php@@ -11,6 +11,28 @@@else<link rel="icon" href="{{ asset('coolify-logo.svg') }}" type="image/svg+xml" />@endenv+ @auth+ <script type="text/javascript" src="{{ URL::asset('js/echo.js') }}"></script>+ <script type="text/javascript" src="{{ URL::asset('js/pusher.js') }}"></script>+ <script>+ window.Pusher = Pusher;+ const EchoConstructor = typeof Echo === 'function' ? Echo : Echo.default;+ window.Echo = new EchoConstructor({+ broadcaster: 'pusher',+ cluster: "{{ config('constants.pusher.host') }}" || window.location.hostname,+ key: "{{ config('constants.pusher.app_key') }}" || 'coolify',+ wsHost: "{{ config('constants.pusher.host') }}" || window.location.hostname,+ wsPort: "{{ getRealtime() }}",+ wssPort: "{{ getRealtime() }}",+ forceTLS: false,+ encrypted: true,+ enableStats: false,+ enableLogging: true,+ enabledTransports: ['ws', 'wss'],+ disabledTransports: ['sockjs', 'xhr_streaming', 'xhr_polling'],+ });+ </script>+ @endauth@php$viteHotFile = public_path('hot');$viteDevServerUrl = null;diff --git a/routes/v5.php b/routes/v5.phpindex 7441576756..cd5daf23ef 100644--- a/routes/v5.php+++ b/routes/v5.php@@ -5,8 +5,11 @@ use Illuminate\Support\Facades\Route;Route::middleware('v5.authenticated')->group(function () {Route::get('/', DashboardController::class)->name('dashboard');+ 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::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');diff --git a/scripts/coold-vm.sh b/scripts/coold-vm.shindex cbbd35dde5..ea7b9c9942 100755--- a/scripts/coold-vm.sh+++ b/scripts/coold-vm.sh@@ -29,6 +29,7 @@ VERSION="$(read_coolify_env COOLIFY_COOLD_VERSION nightly)"CORROSION_VERSION="$(read_coolify_env COOLIFY_CORROSION_VERSION v1.0.0)"FLUX_URL="$(read_coolify_env COOLIFY_COOLD_VM_FLUX_URL http://host.lima.internal:6443)"BUILDER_CAPACITY="$(read_coolify_env COOLIFY_COOLD_VM_BUILDER_CAPACITY 2)"+START_TIMEOUT="$(read_coolify_env COOLIFY_COOLD_VM_START_TIMEOUT 300)"SSH_PORT="$(read_coolify_env COOLIFY_COOLD_VM_SSH_PORT 60002)"WG_IP="$(read_coolify_env COOLIFY_COOLD_VM_WG_IP "")"WG_PEER_IP="$(read_coolify_env COOLIFY_COOLD_VM_WG_PEER_IP "")"@@ -70,6 +71,7 @@ Environment:COOLIFY_CORROSION_VERSION corrosion release tag to install (default: v1.0.0)COOLIFY_COOLD_VM_FLUX_URL Flux gRPC URL visible from the VM (default: http://host.lima.internal:6443)COOLIFY_COOLD_VM_BUILDER_CAPACITY VM builder capacity to advertise (default: 2; set 0 to disable)+ COOLIFY_COOLD_VM_START_TIMEOUT Seconds to wait for Lima SSH/provisioning (default: 300)COOLIFY_COOLD_VM_SSH_PORT Host SSH port forwarded to this VM (default: 60002)COOLIFY_COOLD_VM_WG_IP Optional WireGuard mgmt IP for this hostCOOLIFY_COOLD_VM_CONTAINER_SUBNET Podman mesh subnet for this host@@ -103,6 +105,60 @@ lima_shell() {(cd /tmp && limactl shell "$INSTANCE" -- "$@")}+kill_matching_processes() {+ local pattern="$1"+ local pids++ pids="$(pgrep -f "$pattern" 2>/dev/null || true)"+ if [ -z "$pids" ]; then+ return+ fi++ kill $pids >/dev/null 2>&1 || true+ sleep 1+ kill -9 $pids >/dev/null 2>&1 || true+}++cleanup_lima_probe_processes() {+ kill_matching_processes "limactl shell ${INSTANCE} -- true"+ kill_matching_processes "ssh .*ControlPath=.*${INSTANCE}/ssh.sock"+ kill_matching_processes "ssh: .*/.lima/${INSTANCE}/ssh.sock"+ rm -f "$HOME/.lima/${INSTANCE}/ssh.sock"+}++cleanup_lima_hostagent_processes() {+ kill_matching_processes "limactl hostagent .*${INSTANCE}"+ rm -f "$HOME/.lima/${INSTANCE}/ha.sock"+}++lima_shell_timeout() {+ local timeout_seconds="$1"+ shift+ local pid+ local elapsed=0++ lima_shell "$@" &+ pid="$!"++ while kill -0 "$pid" >/dev/null 2>&1; do+ if [ "$elapsed" -ge "$timeout_seconds" ]; then+ pkill -P "$pid" >/dev/null 2>&1 || true+ kill "$pid" >/dev/null 2>&1 || true+ sleep 1+ pkill -P "$pid" >/dev/null 2>&1 || true+ kill -9 "$pid" >/dev/null 2>&1 || true+ wait "$pid" >/dev/null 2>&1 || true+ cleanup_lima_probe_processes+ return 124+ fi++ sleep 1+ elapsed=$((elapsed + 1))+ done++ wait "$pid"+}+vm_primary_ip() {lima_shell sh -lc "ip -4 route get 1.1.1.1 | awk '{print \$7; exit}'"}@@ -408,6 +464,9 @@ start_vm() {returnfi+ cleanup_lima_probe_processes+ cleanup_lima_hostagent_processes+if instance_exists; thenlimactl start --tty=false "$INSTANCE"else@@ -432,7 +491,16 @@ wait_for_lima_start() {elapsed=0while kill -0 "$start_pid" 2>/dev/null; do- if instance_exists && lima_shell true >/dev/null 2>&1; then+ if [ "$elapsed" -ge "$START_TIMEOUT" ]; then+ echo "ERROR: Lima start timed out after ${START_TIMEOUT}s for ${INSTANCE}." >&2+ kill "$start_pid" >/dev/null 2>&1 || true+ sleep 2+ kill -9 "$start_pid" >/dev/null 2>&1 || true+ wait "$start_pid" >/dev/null 2>&1 || true+ return 124+ fi++ if instance_exists && lima_shell_timeout 5 true >/dev/null 2>&1; thenstatus="$(lima_shell cloud-init status 2>/dev/null || true)"printf '==> [%3ss] Lima start: guest SSH ready, cloud-init %s' "$elapsed" "${status:-unknown}"@@ -460,11 +528,18 @@ wait_for_lima_start() {wait_for_guest_provisioning() {echo "==> Waiting for guest SSH..."- until instance_exists && lima_shell true >/dev/null 2>&1; do+ elapsed=0+ until instance_exists && lima_shell_timeout 5 true >/dev/null 2>&1; do+ if [ "$elapsed" -ge "$START_TIMEOUT" ]; then+ echo "ERROR: Guest SSH timed out after ${START_TIMEOUT}s for ${INSTANCE}." >&2+ return 124+ fi+message="$(latest_lima_message)"printf '==> Waiting for guest SSH: %s' "${message:-booting}"sleep 5+ elapsed=$((elapsed + 5))donestatus="$(lima_shell cloud-init status 2>/dev/null || true)"@@ -477,6 +552,13 @@ wait_for_guest_provisioning() {tail_pid=$!while true; do+ if [ "$elapsed" -ge "$START_TIMEOUT" ]; then+ echo "ERROR: Guest provisioning timed out after ${START_TIMEOUT}s for ${INSTANCE}." >&2+ kill "$tail_pid" >/dev/null 2>&1 || true+ wait "$tail_pid" 2>/dev/null || true+ return 124+ fi+status="$(lima_shell cloud-init status 2>/dev/null || true)"printf '==> Guest cloud-init: %s' "${status:-unknown}"@@ -486,6 +568,7 @@ wait_for_guest_provisioning() {fisleep 5+ elapsed=$((elapsed + 5))donekill "$tail_pid" >/dev/null 2>&1 || truediff --git a/scripts/dev.sh b/scripts/dev.shindex 05a0ca7443..9a1102ef6a 100755--- a/scripts/dev.sh+++ b/scripts/dev.sh@@ -258,6 +258,14 @@ coolify_ssh_user() {read_coolify_env COOLIFY_CLI_SSH_USER "$USER"}+coolify_bootstrap_concurrency() {+ read_coolify_env COOLIFY_COOLD_BOOTSTRAP_CONCURRENCY 1+}++coolify_bootstrap_ssh_timeout() {+ read_coolify_env COOLIFY_COOLD_BOOTSTRAP_SSH_TIMEOUT 90s+}+coolify_bootstrap_command() {local nodeslocal ssh_config@@ -275,6 +283,9 @@ $(coolify_cli_bin) init bootstrap \\--nodes "${nodes}" \\--ssh-config "${ssh_config}" \\--ssh-user "$(coolify_ssh_user)" \\+ --concurrency "$(coolify_bootstrap_concurrency)" \\+ --ssh-timeout "$(coolify_bootstrap_ssh_timeout)" \\+ --debug \\--wg-listen-port-overrides "${listen_overrides}" \\--wg-endpoint-overrides "${endpoint_overrides}" \\--coold-version "$(read_coolify_env COOLIFY_COOLD_VERSION nightly)" \\@@ -299,6 +310,9 @@ coolify_bootstrap() {--nodes "$nodes" \--ssh-config "$ssh_config" \--ssh-user "$(coolify_ssh_user)" \+ --concurrency "$(coolify_bootstrap_concurrency)" \+ --ssh-timeout "$(coolify_bootstrap_ssh_timeout)" \+ --debug \--wg-listen-port-overrides "$listen_overrides" \--wg-endpoint-overrides "$endpoint_overrides" \--coold-version "$(read_coolify_env COOLIFY_COOLD_VERSION nightly)" \@@ -306,6 +320,35 @@ coolify_bootstrap() {--yes}+diagnose_coold_bootstrap_failure() {+ local count+ local instance+ count="$(coold_vm_count)"++ echo "==> Bootstrap failed; collecting quick VM diagnostics..." >&2+ for index in $(seq 1 "$count"); do+ instance="$(coold_vm_instance "$index")"+ echo "--- ${instance}: diagnostics ---" >&2+ run_with_timeout 45 env COOLIFY_COOLD_LIMA_INSTANCE="$instance" scripts/coold-vm.sh shell <<'SH' >&2 || true+set +e+echo '[cloud-init]'+cloud-init status 2>/dev/null || true+echo '[systemd]'+systemctl is-system-running 2>/dev/null || true+echo '[apt/dpkg locks]'+for lock in /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock; do+ fuser "$lock" 2>/dev/null && echo "busy: $lock" || true+done+echo '[failed units]'+systemctl --failed --no-pager 2>/dev/null || true+echo '[coolify services]'+systemctl --no-pager --full status wg-quick@wg0 podman.socket corrosion coold 2>/dev/null | tail -n 120 || true+echo '[disk]'+df -h / /var 2>/dev/null || true+SH+ done+}+coolify_bootstrap_with_retry() {local attemptlocal attempts=5@@ -315,6 +358,8 @@ coolify_bootstrap_with_retry() {returnfi+ diagnose_coold_bootstrap_failure+if [ "$attempt" = "$attempts" ]; thenreturn 1fi@@ -379,6 +424,32 @@ coold_vm() {scripts/coold-vm.sh "$@"}+coold_vm_up_with_retry() {+ local index="$1"+ local attempt+ local attempts=2+ local instance++ instance="$(coold_vm_instance "$index")"++ for attempt in $(seq 1 "$attempts"); do+ if coold_vm "$index" up; then+ return+ fi++ if [ "$attempt" = "$attempts" ]; then+ echo "ERROR: ${instance} did not become ready after ${attempts} attempts." >&2+ return 1+ fi++ echo "WARN: ${instance} did not become ready; deleting and retrying with a fresh Lima instance..." >&2+ limactl stop --force --tty=false "$instance" >/dev/null 2>&1 || true+ cleanup_lima_instance_processes "$instance"+ limactl delete --force --tty=false "$instance" >/dev/null 2>&1 || true+ cleanup_lima_instance_processes "$instance"+ done+}+mint_host_jwt_for_host() {local host_id="$1"local attempts=60@@ -525,7 +596,7 @@ up() {if [ "$coold_vm_enabled" != "false" ]; thenecho "==> Starting ${count} Coolify coold VM(s) before Spin..."for index in $(seq 1 "$count"); do- coold_vm "$index" up+ coold_vm_up_with_retry "$index"doneelseecho "==> COOLIFY_COOLD_VM_ENABLED=false; skipping coold VM."@@ -610,6 +681,29 @@ down() {fi}+kill_matching_processes() {+ local pattern="$1"+ local pids++ pids="$(pgrep -f "$pattern" 2>/dev/null || true)"+ if [ -z "$pids" ]; then+ return+ fi++ kill $pids >/dev/null 2>&1 || true+ sleep 1+ kill -9 $pids >/dev/null 2>&1 || true+}++cleanup_lima_instance_processes() {+ local instance="$1"++ kill_matching_processes "limactl hostagent .*${instance}"+ kill_matching_processes "ssh: .*/.lima/${instance}/ssh.sock"+ kill_matching_processes "ssh .*ControlPath=.*${instance}/ssh.sock"+ rm -f "$HOME/.lima/${instance}/ssh.sock" "$HOME/.lima/${instance}/ha.sock"+}+clean_vms() {local countcount="$(coold_vm_count)"@@ -619,11 +713,13 @@ clean_vms() {instance="$(coold_vm_instance "$index")"echo "==> Deleting ${instance}..."limactl stop --force --tty=false "$instance" >/dev/null 2>&1 || true+ cleanup_lima_instance_processes "$instance"if ! run_with_timeout 60 limactl delete --force --tty=false "$instance"; thenecho "WARN: limactl delete timed out for ${instance}; killing matching limactl clients." >&2pkill -f "limactl.*${instance}" >/dev/null 2>&1 || truerm -rf "$HOME/.lima/${instance}"fi+ cleanup_lima_instance_processes "$instance"done}@@ -1088,12 +1184,74 @@ firewall() {esac}++refresh_test_host_key() {+ echo "==> Refreshing /tmp/testhostkey inside coolify..."+ spin exec -T coolify php artisan tinker --execute='file_put_contents("/tmp/testhostkey", \App\Models\PrivateKey::query()->where("name", "Testing Host Key")->sole()->private_key); chmod("/tmp/testhostkey", 0600);'+}++recreate_naked_lima_vm() {+ local instance="${1:-coolify-naked-test}"+ local config="${2:-.dev/lima/coolify-naked-test.yaml}"+ local attempt+ local attempts=2+ local start_timeout++ start_timeout="$(read_coolify_env COOLIFY_NAKED_VM_START_TIMEOUT "$(read_coolify_env COOLIFY_COOLD_VM_START_TIMEOUT 300)")"++ if [ ! -f "$config" ]; then+ echo "ERROR: naked Lima config not found: ${config}" >&2+ exit 1+ fi++ echo "==> Recreating naked Lima VM: ${instance}..."+ for attempt in $(seq 1 "$attempts"); do+ limactl stop --force --tty=false "$instance" >/dev/null 2>&1 || true+ cleanup_lima_instance_processes "$instance"+ limactl delete --force --tty=false "$instance" >/dev/null 2>&1 || true+ cleanup_lima_instance_processes "$instance"++ if run_with_timeout "$start_timeout" limactl start --tty=false --name="$instance" "$config"; then+ return+ fi++ echo "WARN: ${instance} did not become ready on attempt ${attempt}/${attempts}; deleting and retrying..." >&2+ done++ echo "ERROR: ${instance} did not become ready after ${attempts} attempts." >&2+ return 1+}++fresh() {+ echo "==> Recreating coold Lima VMs and Coolify dev stack..."+ down --cleanup+ COOLIFY_DEV_FOLLOW_LOGS=false up++ echo "==> Refreshing Coolify database with seed data..."+ spin exec -T coolify php artisan migrate:fresh --seed --force++ if [ "$(read_coolify_env COOLIFY_COOLD_VM_ENABLED true)" != "false" ]; then+ echo "==> Re-syncing seeded v5 Lima servers after DB refresh..."+ sync_v5_dev_lima_servers+ fi++ recreate_naked_lima_vm+ refresh_test_host_key++ echo "==> Restarting Horizon so workers use the latest code..."+ spin exec -T coolify php artisan horizon:terminate || true++ echo "==> Fresh dev environment is ready."+ limactl list | grep -E 'NAME|coold-dev|coolify-naked-test' || true+}+usage() {cat <<'USAGE'Usage: scripts/dev.sh <command> [spin args]Commands:up Start the coold VM, Spin stack, and dev coold agent+ fresh Recreate coold/naked Lima VMs, refresh DB, seed, sync v5 dev serversup --nakedStart the coold VM(s) and Spin stack only; skip host bootstrap so /v5 can bootstrapdown Stop the dev coold agent and Spin stack@@ -1102,6 +1260,7 @@ Commands:shell [n] Open a shell inside coold VM n (default: 1)list Show Lima instancesclean-vms Delete the coold Lima VMs and all VM-local runtime state (alias for down --cleanup)+ naked-vm Recreate the naked Lima VM used for bootstrap testingcorrosion <command> Inspect Corrosion state, config, logs, and registered containersfirewall <command> Manage dev coold firewall allow rulesexample-nginx <command> Start/check example nginx containers with coold DNS@@ -1121,6 +1280,9 @@ case "$cmd" indown)down "$@";;+ fresh)+ fresh+ ;;shell)coold_vm "${1:-1}" shell;;@@ -1130,6 +1292,9 @@ case "$cmd" inclean-vms|clean-vm|reset-vms)down --cleanup;;+ naked-vm)+ recreate_naked_lima_vm+ ;;corrosion)corrosion "$@";;diff --git a/tests/Feature/DevScriptFirewallDelegationTest.php b/tests/Feature/DevScriptFirewallDelegationTest.phpindex a4759c7b66..1cd46efc1f 100644--- a/tests/Feature/DevScriptFirewallDelegationTest.php+++ b/tests/Feature/DevScriptFirewallDelegationTest.php@@ -46,6 +46,9 @@ it('supports a naked up mode that starts VMs and Spin but skips server bootstrap->and($script)->toContain('if [ "$naked" = "true" ]; then')->and($script)->toContain('Skipping coolify bootstrap and Flux VM wiring')->and($script)->toContain('coolify_bootstrap_with_retry')+ ->and($script)->toContain('--concurrency "$(coolify_bootstrap_concurrency)"')+ ->and($script)->toContain('--ssh-timeout "$(coolify_bootstrap_ssh_timeout)"')+ ->and($script)->toContain('--debug')->and($script)->toContain('configure_flux_dev_for_vm "$index"')->and($script)->toContain('sync_v5_dev_lima_servers');});@@ -56,6 +59,9 @@ it('retries dev coolify bootstrap because fresh Lima setup can complete across pexpect($script)->toContain('coolify_bootstrap_with_retry()')->and($script)->toContain('local attempts=5')->and($script)->toContain('if coolify_bootstrap; then')+ ->and($script)->toContain('diagnose_coold_bootstrap_failure')+ ->and($script)->toContain('systemctl --failed --no-pager')+ ->and($script)->toContain('systemctl --no-pager --full status wg-quick@wg0 podman.socket corrosion coold')->and($script)->toContain('fresh Lima hosts can finish setup after partial bootstrap phases');});@@ -122,3 +128,40 @@ it('supports down cleanup as the preferred VM cleanup command', function () {->and($script)->toContain('down --cleanup')->and($script)->toContain('clean-vms Delete the coold Lima VMs and all VM-local runtime state (alias for down --cleanup)');});++it('scripts a full fresh dev reset with bounded Lima startup retries', function () {+ $script = file_get_contents(base_path('scripts/dev.sh'));+ $vmScript = file_get_contents(base_path('scripts/coold-vm.sh'));++ expect($script)->toContain('fresh()')+ ->and($script)->toContain('down --cleanup')+ ->and($script)->toContain('COOLIFY_DEV_FOLLOW_LOGS=false up')+ ->and($script)->toContain('php artisan migrate:fresh --seed --force')+ ->and($script)->toContain('sync_v5_dev_lima_servers')+ ->and($script)->toContain('recreate_naked_lima_vm')+ ->and($script)->toContain('COOLIFY_NAKED_VM_START_TIMEOUT')+ ->and($script)->toContain('limactl start --tty=false --name="$instance" "$config"')+ ->and($script)->toContain('cleanup_lima_instance_processes "$instance"')+ ->and($script)->toContain('did not become ready after ${attempts} attempts')+ ->and($script)->toContain('refresh_test_host_key')+ ->and($script)->toContain('coold_vm_up_with_retry()')+ ->and($script)->toContain('COOLIFY_COOLD_BOOTSTRAP_CONCURRENCY 1')+ ->and($script)->toContain('COOLIFY_COOLD_BOOTSTRAP_SSH_TIMEOUT 90s')+ ->and($script)->toContain('local attempts=2')+ ->and($script)->toContain('deleting and retrying with a fresh Lima instance')+ ->and($script)->toContain('cleanup_lima_instance_processes()')+ ->and($script)->toContain('kill_matching_processes()')+ ->and($script)->toContain('kill -9 $pids')+ ->and($script)->toContain('limactl hostagent .*${instance}')+ ->and($script)->toContain('ssh: .*/.lima/${instance}/ssh.sock')+ ->and($vmScript)->toContain('COOLIFY_COOLD_VM_START_TIMEOUT')+ ->and($vmScript)->toContain('lima_shell_timeout()')+ ->and($vmScript)->toContain('cleanup_lima_probe_processes()')+ ->and($vmScript)->toContain('cleanup_lima_hostagent_processes()')+ ->and($vmScript)->toContain('kill_matching_processes()')+ ->and($vmScript)->toContain('pkill -P "$pid"')+ ->and($vmScript)->toContain('lima_shell_timeout 5 true')+ ->and($vmScript)->toContain('Lima start timed out after ${START_TIMEOUT}s')+ ->and($vmScript)->toContain('Guest SSH timed out after ${START_TIMEOUT}s')+ ->and($vmScript)->toContain('Guest provisioning timed out after ${START_TIMEOUT}s');+});diff --git a/tests/Feature/V5/AppNavbarTest.php b/tests/Feature/V5/AppNavbarTest.phpnew file mode 100644index 0000000000..4e1f004367--- /dev/null+++ b/tests/Feature/V5/AppNavbarTest.php@@ -0,0 +1,17 @@+<?php++it('renders the Coolify dashboard icon smaller than the nav height', function () {+ $navbar = file_get_contents(resource_path('js/v5/components/app-navbar.tsx'));++ expect($navbar)->toContain('<img src="/coolify-logo.svg" alt="Coolify" className="size-6" />')+ ->and($navbar)->not->toContain('<img src="/coolify-logo.svg" alt="Coolify" className="size-8" />');+});++it('shows keyboard focus on ghost select dropdown triggers', function () {+ $selectComponent = file_get_contents(resource_path('js/v5/components/ui/select.tsx'));++ expect($selectComponent)+ ->toContain("variant === 'ghost'")+ ->toContain('focus-visible:border-ring')+ ->not->toContain('focus-visible:border-transparent');+});diff --git a/tests/Feature/V5/ButtonVariantTest.php b/tests/Feature/V5/ButtonVariantTest.phpnew file mode 100644index 0000000000..2cbcf8b763--- /dev/null+++ b/tests/Feature/V5/ButtonVariantTest.php@@ -0,0 +1,32 @@+<?php++it('uses yellow focus borders for normal v5 controls and purple focus borders for coolify buttons', function () {+ $v5Css = file_get_contents(resource_path('css/v5/app.css'));+ $buttonComponent = file_get_contents(resource_path('js/v5/components/ui/button.tsx'));+ $inputComponent = file_get_contents(resource_path('js/v5/components/ui/input.tsx'));+ $selectComponent = file_get_contents(resource_path('js/v5/components/ui/select.tsx'));+ $textareaComponent = file_get_contents(resource_path('js/v5/components/ui/textarea.tsx'));++ expect($v5Css)+ ->toContain(':focus-visible')+ ->toContain('ring-2 ring-ring ring-offset-2')+ ->toContain('--tw-ring-offset-color: var(--background)')+ ->and($buttonComponent)+ ->toContain('focus-visible:border-ring')+ ->toContain('focus-visible:border-coollabs-100')+ ->toContain('dark:focus-visible:border-coollabs-100')+ ->not->toContain('dark:focus-visible:border-coollabs-50')+ ->not->toContain('focus-visible:ring-')+ ->not->toContain('focus-visible:border-destructive')+ ->and($inputComponent)+ ->toContain('focus:border-ring')+ ->toContain('focus:ring-0')+ ->not->toContain('focus:ring-1')+ ->and($selectComponent)+ ->toContain('focus-visible:border-ring')+ ->not->toContain('focus-visible:ring-')+ ->and($textareaComponent)+ ->toContain('focus:border-ring')+ ->toContain('focus:ring-0')+ ->not->toContain('focus:ring-1');+});diff --git a/tests/Feature/V5/ClusterCapabilitiesSummaryTest.php b/tests/Feature/V5/ClusterCapabilitiesSummaryTest.phpnew file mode 100644index 0000000000..9433681014--- /dev/null+++ b/tests/Feature/V5/ClusterCapabilitiesSummaryTest.php@@ -0,0 +1,9 @@+<?php++it('does not render server capability summaries on the cluster page', function () {+ $clustersPage = file_get_contents(resource_path('js/v5/Pages/Clusters.tsx'));++ expect($clustersPage)+ ->not->toContain('Capabilities:')+ ->not->toContain('normalizeCapabilities');+});diff --git a/tests/Feature/V5/ClustersControlHeightTest.php b/tests/Feature/V5/ClustersControlHeightTest.phpnew file mode 100644index 0000000000..8b120573d2--- /dev/null+++ b/tests/Feature/V5/ClustersControlHeightTest.php@@ -0,0 +1,11 @@+<?php++it('keeps the cluster selector and add button the same height', function () {+ $clustersPage = file_get_contents(resource_path('js/v5/Pages/Clusters.tsx'));++ expect($clustersPage)->toContain('<SelectTrigger')+ ->and($clustersPage)->toContain('className="w-full sm:w-72"')+ ->and($clustersPage)->toContain('variant="coolify"')+ ->and($clustersPage)->toContain('size="default"')+ ->and($clustersPage)->not->toContain('variant="coolify"\n size="sm"');+});diff --git a/tests/Feature/V5/DashboardTest.php b/tests/Feature/V5/DashboardTest.phpindex 368039497a..73e31d1cff 100644--- a/tests/Feature/V5/DashboardTest.php+++ b/tests/Feature/V5/DashboardTest.php@@ -1,11 +1,14 @@<?php+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;@@ -15,15 +18,19 @@ use App\Models\V5\Cluster;use App\Models\V5\Server as V5Server;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\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_servers');@@ -39,6 +46,7 @@ it('registers the v5 dashboard route', function () {->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()@@ -46,6 +54,8 @@ it('registers the v5 dashboard route', function () {->and(Route::has('v5.clusters.servers.check'))->toBeTrue()->and(Route::has('v5.clusters.servers.bootstrap'))->toBeTrue()->and(Route::has('v5.clusters.servers.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();});@@ -83,12 +93,6 @@ it('creates v5 cluster tables and lets each server belong to one cluster', funct$serverMigration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');$serverMigration->up();- $configurationMigration = include database_path('migrations/2026_06_16_204644_v5_add_wireguard_cli_configuration_to_clusters_and_servers.php');- $configurationMigration->up();-- $statusCheckMigration = include database_path('migrations/2026_06_17_172845_add_status_check_fields_to_v5_servers_table.php');- $statusCheckMigration->up();-expect(Schema::hasTable('v5_clusters'))->toBeTrue()->and(Schema::hasColumns('v5_clusters', ['id',@@ -134,12 +138,6 @@ it('creates v5 server tables in the shared database', function () {$migration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');$migration->up();- $configurationMigration = include database_path('migrations/2026_06_16_204644_v5_add_wireguard_cli_configuration_to_clusters_and_servers.php');- $configurationMigration->up();-- $statusCheckMigration = include database_path('migrations/2026_06_17_172845_add_status_check_fields_to_v5_servers_table.php');- $statusCheckMigration->up();-expect(Schema::hasTable('v5_servers'))->toBeTrue()->and(Schema::hasColumns('v5_servers', ['id',@@ -159,10 +157,15 @@ it('creates v5 server tables in the shared database', function () {'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',@@ -171,24 +174,27 @@ it('creates v5 server tables in the shared database', function () {]))->toBeTrue();});-it('adds builder cpu quota to existing v5 server tables safely', function () {- Schema::dropIfExists('v5_servers');-- Schema::create('v5_servers', function ($table) {- $table->id();- $table->unsignedInteger('builder_capacity')->default(0);- });+it('keeps v5 server fields in the initial migration', function () {+ createSharedUserAndTeamTables();- $migration = include database_path('migrations/2026_06_17_165112_v5_add_builder_cpu_quota_to_servers_table.php');- $migration->up();- $migration->up();+ Schema::dropIfExists('v5_servers');+ Schema::dropIfExists('v5_clusters');- expect(Schema::hasColumn('v5_servers', 'builder_cpu_quota'))->toBeTrue();+ $clusterMigration = include database_path('migrations/2026_06_16_130649_v5_create_clusters_table.php');+ $clusterMigration->up();- $migration->down();- $migration->down();+ $serverMigration = include database_path('migrations/2026_06_16_130650_v5_create_servers_table.php');+ $serverMigration->up();- expect(Schema::hasColumn('v5_servers', 'builder_cpu_quota'))->toBeFalse();+ expect(Schema::hasColumns('v5_servers', [+ 'uuid',+ 'builder_cpu_quota',+ 'node_address',+ 'wireguard_management_ip',+ 'container_subnets',+ 'last_bootstrap_output',+ 'last_status_output',+ ]))->toBeTrue();});it('includes v5 tables in the dev testing schema', function () {@@ -207,14 +213,18 @@ it('includes v5 tables in the dev testing schema', function () {->and($schema)->toContain('"builder_timeout_secs" INTEGER NOT NULL DEFAULT \'1800\'')->and($schema)->toContain('"private_key_id" INTEGER')->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('"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_16_130649_v5_create_clusters_table')- ->and($schema)->toContain('2026_06_16_204644_v5_add_wireguard_cli_configuration_to_clusters_and_servers')- ->and($schema)->toContain('2026_06_17_165112_v5_add_builder_cpu_quota_to_servers_table')- ->and($schema)->toContain('2026_06_17_172845_add_status_check_fields_to_v5_servers_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');@@ -254,6 +264,9 @@ it('serves the v5 inertia shell', function () {->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)@@ -271,12 +284,151 @@ it('serves the v5 inertia shell', function () {->assertDontSee('100.64.0.1')->assertDontSee('Current team')->assertDontSee('Your teams')- ->assertDontSee('currentTeam', false)+ ->assertSee('currentTeam', false)->assertDontSee('teams', false)->assertDontSee('V5 Shared Team')->assertDontSee('Shared team details');});+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->id}/servers/{$server->id}/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('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->id}")+ ->assertSuccessful()+ ->assertJsonPath('cluster.id', (string) $cluster->id)+ ->assertJsonPath('cluster.servers.0.id', (string) $server->id)+ ->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');@@ -476,6 +628,23 @@ it('validates advanced v5 cluster cli configuration', function () {]);});+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();@@ -504,6 +673,8 @@ it('adds a v5 server to a cluster for the current team', function () {'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)@@ -511,7 +682,10 @@ it('adds a v5 server to a cluster for the current team', function () {->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)@@ -538,6 +712,72 @@ it('adds a v5 server to a cluster for the current team', function () {->toBe(['coold', 'builder']);});+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->id}/servers", [+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'private_key_id' => $privateKey->id,+ 'builder_enabled' => false,+ 'builder_capacity' => 3,+ ])+ ->assertCreated()+ ->assertJsonPath('cluster.servers.0.builderEnabled', false)+ ->assertJsonPath('cluster.servers.0.builderCapacity', 3)+ ->assertJsonPath('cluster.servers.0.capabilities', ['coold']);++ $server = V5Server::query()->where('name', 'prod-01')->first();++ expect($server->builder_enabled)->toBeFalse()+ ->and($server->builder_capacity)->toBe(3)+ ->and($server->capabilities)->toBe(['coold']);+});++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->id}/servers", [+ 'name' => 'prod-01',+ 'host' => '203.0.113.10',+ 'ssh_user' => 'root',+ 'ssh_port' => 22,+ 'private_key_id' => $privateKey->id,+ 'builder_enabled' => true,+ 'builder_capacity' => 0,+ ])+ ->assertUnprocessable()+ ->assertJsonValidationErrors(['builder_capacity']);+});+it('defaults dev Lima wireguard overrides for host docker internal servers', function () {createSharedUserAndTeamTables();@@ -659,7 +899,7 @@ it('rejects private keys from another team when adding a v5 server', function ()->assertJsonValidationErrors(['private_key_id']);});-it('checks v5 server ssh status and stores diagnostic output', function () {+it('checks v5 server ssh status without storing diagnostic output', function () {createSharedUserAndTeamTables();[$user, $team] = createV5UserWithTeam();@@ -679,7 +919,7 @@ it('checks v5 server ssh status and stores diagnostic output', function () {'host' => '203.0.113.10','ssh_user' => 'root','ssh_port' => 22,- 'status' => 'pending',+ 'status' => 'added','builder_enabled' => false,'builder_capacity' => 0,]);@@ -693,19 +933,19 @@ it('checks v5 server ssh status and stores diagnostic output', function () {->withSession(['currentTeam' => $team])->postJson("/v5/clusters/{$cluster->id}/servers/{$server->id}/check")->assertSuccessful()- ->assertJsonPath('cluster.servers.0.status', 'pending')- ->assertJsonPath('cluster.servers.0.lastStatusCheck', 'reachable')- ->assertJsonPath('cluster.servers.0.lastStatusOutput', "SSH connection OK\nprod-01\nLinux aarch64\n/usr/bin/docker");+ ->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('pending')- ->and($server->last_status_check)->toBe('reachable')- ->and($server->last_status_output)->toContain('SSH connection OK')- ->and($server->last_status_checked_at)->not->toBeNull();+ 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 () {@@ -790,7 +1030,7 @@ it('bootstraps a single v5 server with the Coolify CLI', function () {'host' => '203.0.113.10','ssh_user' => 'root','ssh_port' => 2222,- 'status' => 'pending',+ 'status' => 'added','capabilities' => ['builder'],'builder_enabled' => true,'builder_capacity' => 4,@@ -798,50 +1038,59 @@ it('bootstraps a single v5 server with the Coolify CLI', function () {'wireguard_endpoint_override' => 'prod-01.example.com:51831',]);- Process::fake([- '*' => Process::result(output: "Bootstrap completed\n"),- ]);+ Queue::fake();$this->actingAs($user)->withSession(['currentTeam' => $team])->postJson("/v5/clusters/{$cluster->id}/servers/{$server->id}/bootstrap")- ->assertSuccessful()- ->assertJsonPath('cluster.lastCliAction', 'bootstrap')- ->assertJsonPath('cluster.lastCliStatus', 'succeeded')- ->assertJsonPath('cluster.lastCliSummary', 'Bootstrap completed')- ->assertJsonPath('cluster.servers.0.status', 'installed')- ->assertJsonPath('cluster.servers.0.capabilities', ['builder', 'coold'])- ->assertJsonPath('cluster.servers.0.lastBootstrappedAt', fn (?string $value) => $value !== null);-- Process::assertRan(function ($process) use ($server): bool {+ ->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 = "v5-server-{$server->id}";+ $node = cliFlagValue($command, '--nodes');return $command[0] === '/tmp/coolify'&& in_array('init', $command, true)&& in_array('bootstrap', $command, true)- && in_array($node, $command, true)&& in_array('--ssh-config', $command, true)- && in_array('default,preview', $command, true)- && in_array('10.211.0.0/16', $command, true)- && in_array('100.65.0.0/16', $command, true)- && in_array('wg-prod', $command, true)- && in_array('v0.2.0', $command, true)- && in_array('v1.1.0', $command, true)- && in_array("{$node}=51831", $command, true)- && in_array("{$node}=prod-01.example.com:51831", $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();- $server->refresh();- expect($cluster->last_cli_status)->toBe('succeeded')- ->and($cluster->last_cli_summary)->toBe('Bootstrap completed')- ->and($server->status)->toBe('installed')+ 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();});@@ -866,25 +1115,31 @@ it('does not run a macOS development Coolify CLI binary from Docker during v5 se'host' => '203.0.113.10','ssh_user' => 'root','ssh_port' => 22,- 'status' => 'pending',+ 'status' => 'added','builder_enabled' => false,'builder_capacity' => 0,]);- Process::fake([- '*' => Process::result(output: "Bootstrap completed\n"),- ]);+ Queue::fake();$this->actingAs($user)->withSession(['currentTeam' => $team])->postJson("/v5/clusters/{$cluster->id}/servers/{$server->id}/bootstrap")- ->assertSuccessful();+ ->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 pending when Coolify CLI bootstrap fails', function () {+it('keeps a v5 server added when Coolify CLI bootstrap fails', function () {createSharedUserAndTeamTables();Config::set('coold.coolify_cli_bin', '/tmp/coolify');@@ -905,30 +1160,35 @@ it('keeps a v5 server pending when Coolify CLI bootstrap fails', function () {'host' => '203.0.113.10','ssh_user' => 'root','ssh_port' => 22,- 'status' => 'pending',+ 'status' => 'added','builder_enabled' => false,'builder_capacity' => 0,]);- Process::fake([- '*' => Process::result(errorOutput: "bootstrap failed\n", exitCode: 1),- ]);+ Queue::fake();$this->actingAs($user)->withSession(['currentTeam' => $team])->postJson("/v5/clusters/{$cluster->id}/servers/{$server->id}/bootstrap")- ->assertServerError()- ->assertJsonPath('message', 'bootstrap failed')- ->assertJsonPath('cluster.lastCliAction', 'bootstrap')- ->assertJsonPath('cluster.lastCliStatus', 'failed')- ->assertJsonPath('cluster.lastCliSummary', 'bootstrap failed')- ->assertJsonPath('cluster.servers.0.status', 'pending')- ->assertJsonPath('cluster.servers.0.lastBootstrappedAt', null);+ ->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('pending')+ 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();});@@ -944,6 +1204,8 @@ it('extends a v5 cluster when bootstrapping a new server', function () {'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,@@ -968,36 +1230,41 @@ it('extends a v5 cluster when bootstrapping a new server', function () {'host' => '203.0.113.11','ssh_user' => 'root','ssh_port' => 22,- 'status' => 'pending',+ 'status' => 'added','builder_enabled' => false,'builder_capacity' => 0,]);- Process::fake([- '*' => Process::result(output: "Extend completed\n"),- ]);+ Queue::fake();$this->actingAs($user)->withSession(['currentTeam' => $team])->postJson("/v5/clusters/{$cluster->id}/servers/{$newServer->id}/bootstrap")- ->assertSuccessful()- ->assertJsonPath('cluster.lastCliAction', 'extend')- ->assertJsonPath('cluster.lastCliStatus', 'succeeded')- ->assertJsonPath('cluster.lastCliSummary', 'Extend completed')- ->assertJsonPath('cluster.servers.0.status', 'installed')- ->assertJsonPath('cluster.servers.1.status', 'installed');+ ->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->id}";- $newNode = "v5-server-{$newServer->id}";+ $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);+ && in_array('--ssh-config', $command, true)+ && cliFlagValue($command, '--coold-version') === 'v0.3.0'+ && cliFlagValue($command, '--corrosion-version') === 'v1.2.0';});$oldServer->refresh();@@ -1005,9 +1272,112 @@ it('extends a v5 cluster when bootstrapping a new server', function () {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();@@ -1026,7 +1396,7 @@ it('deletes an unbootstrapped v5 server from a cluster', function () {'host' => '203.0.113.10','ssh_user' => 'root','ssh_port' => 22,- 'status' => 'pending',+ 'status' => 'added','builder_enabled' => false,'builder_capacity' => 0,]);@@ -1042,7 +1412,7 @@ it('deletes an unbootstrapped v5 server from a cluster', function () {expect(V5Server::query()->whereKey($server->id)->exists())->toBeFalse();});-it('does not delete a bootstrapped v5 server', function () {+it('deletes a bootstrapped v5 server from a cluster', function () {createSharedUserAndTeamTables();[$user, $team] = createV5UserWithTeam();@@ -1070,10 +1440,11 @@ it('does not delete a bootstrapped v5 server', function () {->actingAs($user)->withSession(['currentTeam' => $team])->deleteJson("/v5/clusters/{$cluster->id}/servers/{$server->id}")- ->assertConflict()- ->assertJsonPath('message', 'Only unbootstrapped servers can be deleted.');+ ->assertSuccessful()+ ->assertJsonPath('cluster.serversCount', 0)+ ->assertJsonPath('cluster.servers', []);- expect(V5Server::query()->whereKey($server->id)->exists())->toBeTrue();+ expect(V5Server::query()->whereKey($server->id)->exists())->toBeFalse();});it('updates editable v5 server builder details without changing networking', function () {@@ -1140,6 +1511,51 @@ it('updates editable v5 server builder details without changing networking', fun->and($server->wireguard_endpoint_override)->toBe('prod-01.example.com:51821');});+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' => ['coold', 'builder'],+ 'builder_enabled' => true,+ 'builder_capacity' => 5,+ 'builder_cpu_quota' => '350%',+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/clusters/{$cluster->id}/servers/{$server->id}", [+ '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(['coold']);+});+it('validates editable v5 server builder details', function () {createSharedUserAndTeamTables();@@ -1177,6 +1593,43 @@ it('validates editable v5 server builder details', function () {->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' => ['coold'],+ 'builder_enabled' => false,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '200%',+ ]);++ $this+ ->actingAs($user)+ ->withSession(['currentTeam' => $team])+ ->patchJson("/v5/clusters/{$cluster->id}/servers/{$server->id}", [+ 'builder_enabled' => true,+ 'builder_capacity' => 0,+ 'builder_cpu_quota' => '200%',+ ])+ ->assertUnprocessable()+ ->assertJsonValidationErrors(['builder_capacity']);+});+it('validates v5 cluster creation input', function () {createSharedUserAndTeamTables();@@ -1578,16 +2031,25 @@ it('defines the v5 cluster management page and create cluster form', function ()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('Select a cluster')+ ->toContain('setSelectedClusterId(value)')->toContain('aria-label="Create cluster"')->toContain('setIsCreateDialogOpen(true)')->toContain('Add cluster')->toContain('variant="coolify"')- ->toContain('border-warning bg-warning/10 text-foreground')+ ->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>')@@ -1608,9 +2070,11 @@ it('defines the v5 cluster management page and create cluster form', function ()->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('lastCliSummary')- ->toContain('Unable to bootstrap this server. Check the CLI state output.')+ ->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}`')@@ -1618,10 +2082,43 @@ it('defines the v5 cluster management page and create cluster form', function ()->toContain('fetch(`/v5/clusters/${cluster.id}/servers/${server.id}`')->toContain("method: 'PATCH'")->toContain("method: 'DELETE'")- ->toContain('Check SSH')- ->toContain('Bootstrap: {server.status}')- ->toContain('Latest SSH check')- ->toContain('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')@@ -1632,6 +2129,9 @@ it('defines the v5 cluster management page and create cluster form', function ()->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')@@ -1645,9 +2145,19 @@ it('defines the v5 cluster management page and create cluster form', function ()->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'")@@ -1656,17 +2166,21 @@ it('defines the v5 cluster management page and create cluster form', function ()->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 max-h-80 flex-col rounded-lg border border-border bg-card lg:max-h-none lg:min-h-0')+ ->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('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')->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')- ->toContain('lg:grid-cols-[20rem_minmax(0,1fr)]')+ ->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(5)+ expect(substr_count($clustersPage, 'variant="coolify"'))->toBe(6)->and($buttonComponent)->toContain('coolify:')->toContain('bg-coollabs-50')@@ -1686,7 +2200,8 @@ it('defines the v5 cluster management page and create cluster form', function ()->toContain('aria-label="Close dialog"')->toContain('<XIcon />')->toContain('DialogTitle')- ->toContain('DialogDescription');+ ->toContain('DialogDescription')+ ->toContain("'mt-6 flex justify-end gap-2'");$v5Css = file_get_contents(resource_path('css/v5/app.css'));@@ -1705,7 +2220,17 @@ it('defines the v5 cluster management page and create cluster form', function ()->toContain('builderCapacity: number;')->toContain('builderCpuQuota: string;')->toContain('privateKeyName: string | null;')- ->toContain('lastBootstrappedAt: string | null;');+ ->toContain('lastBootstrappedAt: string | null;')+ ->toContain('lastBootstrapStatus: string | null;')+ ->not->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 () {@@ -1893,13 +2418,13 @@ it('does not include coolify version controls on the v5 dashboard page', functio->not->toContain('Installed version:');});-it('renders flux status as a compact summary', function () {+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)- ->toContain('Flux: {flux?.label ??')- ->toContain('title={flux?.socket ?? flux?.message ?? undefined}')- ->toContain('{clusters.length} clusters')+ ->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}');@@ -2087,6 +2612,7 @@ function createSharedUserAndTeamTables(): voidSchema::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');@@ -2107,6 +2633,10 @@ function createSharedUserAndTeamTables(): void$table->string('wireguard_public_key')->nullable();$table->json('container_subnets')->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();@@ -2127,6 +2657,20 @@ function createSharedUserAndTeamTables(): void/*** @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([