Skip to content

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.

fix(terminal): show an error instead of an endless connecting spinner

Andras Bacsai0d20a14c5c71
diff --git a/app/Livewire/Project/Shared/ExecuteContainerCommand.php b/app/Livewire/Project/Shared/ExecuteContainerCommand.php
index e8202b8547..91064e6895 100644
--- a/app/Livewire/Project/Shared/ExecuteContainerCommand.php
+++ b/app/Livewire/Project/Shared/ExecuteContainerCommand.php
@@ -153,6 +153,9 @@ class ExecuteContainerCommand extends Component
if ($this->containers->count() === 1) {
$this->selected_container = $this->containerTarget($this->containers->first());
$this->connectToContainer();
+ } elseif ($this->containers->count() > 1) {
+ // The terminal was rendered with auto-start before the containers were known.
+ $this->dispatch(Terminal::AUTO_START_CANCELLED_EVENT)->to(Terminal::class);
}
$this->containersLoaded = true;
@@ -190,7 +193,7 @@ class ExecuteContainerCommand extends Component
// Dispatch a frontend event to ensure terminal gets focus after connection
$this->dispatch('terminal-should-focus');
} catch (\Throwable $e) {
- return handleError($e, $this);
+ $this->failTerminalSession(Terminal::sessionFailureMessage($e));
} finally {
$this->isConnecting = false;
}
@@ -200,7 +203,7 @@ class ExecuteContainerCommand extends Component
public function connectToContainer()
{
if ($this->selected_container === 'default') {
- $this->dispatch('error', 'Please select a container.');
+ $this->failTerminalSession('Please select a container.');
return;
}
@@ -251,12 +254,20 @@ class ExecuteContainerCommand extends Component
// Dispatch a frontend event to ensure terminal gets focus after connection
$this->dispatch('terminal-should-focus');
} catch (\Throwable $e) {
- return handleError($e, $this);
+ $this->failTerminalSession(Terminal::sessionFailureMessage($e));
} finally {
$this->isConnecting = false;
}
}
+ /**
+ * Stop the terminal "connecting…" state and show why. The terminal also shows the toast.
+ */
+ private function failTerminalSession(string $message): void
+ {
+ $this->dispatch(Terminal::SESSION_FAILED_EVENT, message: $message)->to(Terminal::class);
+ }
+
public function render()
{
return view('livewire.project.shared.execute-container-command');
diff --git a/app/Livewire/Project/Shared/Terminal.php b/app/Livewire/Project/Shared/Terminal.php
index de4e00cf20..01a89b721a 100644
--- a/app/Livewire/Project/Shared/Terminal.php
+++ b/app/Livewire/Project/Shared/Terminal.php
@@ -5,14 +5,27 @@ namespace App\Livewire\Project\Shared;
use App\Models\Server;
use App\Services\TerminalSessionService;
use App\Support\ValidationPatterns;
+use Illuminate\Auth\Access\AuthorizationException;
+use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\On;
use Livewire\Component;
+use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
+use Throwable;
class Terminal extends Component
{
use AuthorizesRequests;
+ /** Browser event: no terminal token was issued. Payload: `message`. */
+ public const SESSION_FAILED_EVENT = 'terminal-session-failed';
+
+ /** Browser event: the page did not auto-select a target, so stop the auto-start wait. */
+ public const AUTO_START_CANCELLED_EVENT = 'terminal-auto-start-cancelled';
+
+ /** Same text for denied and unknown targets, so other teams' resources stay hidden. */
+ public const NOT_ALLOWED_MESSAGE = 'You are not allowed to open a terminal for this resource.';
+
public bool $hasShell = true;
public bool $isTerminalConnected = false;
@@ -31,38 +44,52 @@ class Terminal extends Component
], $server);
return true;
- } catch (\Throwable) {
+ } catch (Throwable) {
return false;
}
}
#[On('send-terminal-command')]
- public function sendTerminalCommand($isContainer, $identifier, $serverUuid, TerminalSessionService $terminalSessionService)
+ public function sendTerminalCommand($isContainer, $identifier, $serverUuid, TerminalSessionService $terminalSessionService): void
{
- $this->authorize('canAccessTerminal');
+ try {
+ $this->authorize('canAccessTerminal');
+
+ $server = Server::ownedByCurrentTeam()->whereUuid($serverUuid)->firstOrFail();
+ $this->authorize('view', $server);
+ } catch (AuthorizationException|ModelNotFoundException) {
+ $this->failTerminalSession(self::NOT_ALLOWED_MESSAGE);
- $server = Server::ownedByCurrentTeam()->whereUuid($serverUuid)->firstOrFail();
- $this->authorize('view', $server);
+ return;
+ }
if (! $server->isTerminalEnabled() || $server->isForceDisabled()) {
- abort(403, 'Terminal access is disabled on this server.');
+ $this->failTerminalSession('Terminal access is disabled on this server.');
+
+ return;
}
if ($isContainer) {
// Validate container identifier format (alphanumeric, dashes, and underscores only)
- if (! ValidationPatterns::isValidContainerName($identifier)) {
- throw new \InvalidArgumentException('Invalid container identifier format');
+ if (! is_string($identifier) || ! ValidationPatterns::isValidContainerName($identifier)) {
+ $this->failTerminalSession('The container name is not valid.');
+
+ return;
}
// Verify container exists and belongs to the user's team
$status = getContainerStatus($server, $identifier);
if ($status !== 'running') {
+ $this->failTerminalSession('The container is not running.');
+
return;
}
// Check shell availability
$this->hasShell = $this->checkShellAvailability($server, $identifier);
if (! $this->hasShell) {
+ $this->failTerminalSession('No shell is available in this container.');
+
return;
}
}
@@ -71,6 +98,28 @@ class Terminal extends Component
$this->dispatch('send-terminal-token', $token);
}
+ /**
+ * Message for an exception on the terminal start path. Denied and missing
+ * resources get the same text, so the message does not reveal other teams' data.
+ */
+ public static function sessionFailureMessage(Throwable $exception): string
+ {
+ $isDenied = $exception instanceof AuthorizationException
+ || $exception instanceof ModelNotFoundException
+ || ($exception instanceof HttpExceptionInterface && in_array($exception->getStatusCode(), [403, 404], true));
+
+ if ($isDenied) {
+ return self::NOT_ALLOWED_MESSAGE;
+ }
+
+ return $exception->getMessage() ?: 'Could not start the terminal session.';
+ }
+
+ private function failTerminalSession(string $message): void
+ {
+ $this->dispatch(self::SESSION_FAILED_EVENT, message: $message)->self();
+ }
+
#[On('terminalConnected')]
public function markTerminalConnected(): void
{
diff --git a/resources/js/terminal-connection.js b/resources/js/terminal-connection.js
index 27fab80e61..f2f463f94a 100644
--- a/resources/js/terminal-connection.js
+++ b/resources/js/terminal-connection.js
@@ -79,3 +79,85 @@ export function resolveTerminalCloseOutcome({ code, sessionPending, reconnectAtt
error: sessionPending || !reconnect ? TERMINAL_CONNECTION_ERRORS.connectionFailed : null,
};
}
+
+/**
+ * Session-start state for the terminal Alpine component (`terminalData()` spreads it in).
+ *
+ * The host provides `starting`, `terminalActive`, `connectionError`, `authRejected`,
+ * `pendingCommand`, `sessionStartTimeoutId`, `$wire`, and `ensureWebSocketConnection()`.
+ * Only one session-start timer exists at a time: every start clears the previous timer.
+ */
+export const terminalSessionStartMethods = {
+ /** A session was requested and the UI shows "connecting…" until `pty-ready`. */
+ isTerminalSessionPending() {
+ return this.starting && !this.terminalActive;
+ },
+
+ /**
+ * Leave the "connecting" state and show why. The first reason wins unless
+ * `override` is set (auth rejections replace generic connection errors).
+ */
+ failTerminalConnection(message, { override = false } = {}) {
+ this.starting = false;
+ this.clearSessionStartTimeout();
+
+ if (this.connectionError === message || (this.connectionError && !override)) {
+ return;
+ }
+
+ this.connectionError = message;
+ this.$wire.dispatch('error', message);
+ },
+
+ /** Called whenever a new terminal session is requested (target chosen or token issued). */
+ beginTerminalSessionStart() {
+ this.starting = true;
+ this.connectionError = null;
+ this.authRejected = false;
+ this.armTerminalSessionStartTimeout();
+ this.ensureWebSocketConnection();
+ },
+
+ /** Show the timeout error if no session is ready in time. Replaces an earlier timer. */
+ armTerminalSessionStartTimeout() {
+ this.clearSessionStartTimeout();
+ this.sessionStartTimeoutId = setTimeout(() => {
+ this.sessionStartTimeoutId = null;
+ if (this.isTerminalSessionPending()) {
+ // Single-use tokens must not be sent after the user was told to retry.
+ this.pendingCommand = null;
+ this.failTerminalConnection(TERMINAL_CONNECTION_ERRORS.timeout);
+ }
+ }, TERMINAL_SESSION_START_TIMEOUT_MS);
+ },
+
+ clearSessionStartTimeout() {
+ if (this.sessionStartTimeoutId) {
+ clearTimeout(this.sessionStartTimeoutId);
+ this.sessionStartTimeoutId = null;
+ }
+ },
+
+ /** The server reported `pty-ready`. */
+ completeTerminalSessionStart() {
+ this.starting = false;
+ this.connectionError = null;
+ this.clearSessionStartTimeout();
+ },
+
+ /** Coolify refused to issue a terminal token (`terminal-session-failed`). */
+ failTerminalSessionStart(message) {
+ this.pendingCommand = null;
+ this.failTerminalConnection(message || TERMINAL_CONNECTION_ERRORS.connectionFailed, { override: true });
+ },
+
+ /** No container was auto-selected (`terminal-auto-start-cancelled`); wait for the user. */
+ cancelTerminalAutoStart() {
+ if (this.terminalActive || this.pendingCommand) {
+ return;
+ }
+
+ this.starting = false;
+ this.clearSessionStartTimeout();
+ },
+};
diff --git a/resources/js/terminal-session-start.test.js b/resources/js/terminal-session-start.test.js
new file mode 100644
index 0000000000..1f1181803b
--- /dev/null
+++ b/resources/js/terminal-session-start.test.js
@@ -0,0 +1,179 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ TERMINAL_CONNECTION_ERRORS,
+ TERMINAL_SESSION_START_TIMEOUT_MS,
+ terminalSessionStartMethods,
+} from './terminal-connection.js';
+
+/**
+ * Builds the smallest host that the terminal Alpine component gives to the mixin.
+ */
+function createTerminalHost(overrides = {}) {
+ const host = {
+ starting: false,
+ terminalActive: false,
+ connectionError: null,
+ authRejected: false,
+ pendingCommand: null,
+ sessionStartTimeoutId: null,
+ toasts: [],
+ websocketStarts: 0,
+ $wire: {
+ dispatch(name, message) {
+ host.toasts.push([name, message]);
+ },
+ },
+ ensureWebSocketConnection() {
+ host.websocketStarts++;
+ },
+ ...terminalSessionStartMethods,
+ ...overrides,
+ };
+
+ return host;
+}
+
+/** Same steps as `init()` in terminal.js for `data-auto-start="true"`. */
+function autoStart(host) {
+ host.starting = true;
+ host.armTerminalSessionStartTimeout();
+}
+
+test('auto-start without a token leaves connecting and shows the timeout error', (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const host = createTerminalHost();
+
+ autoStart(host);
+ t.mock.timers.tick(TERMINAL_SESSION_START_TIMEOUT_MS - 1);
+
+ assert.equal(host.starting, true);
+ assert.equal(host.connectionError, null);
+
+ t.mock.timers.tick(1);
+
+ assert.equal(host.starting, false);
+ assert.equal(host.connectionError, TERMINAL_CONNECTION_ERRORS.timeout);
+ assert.equal(host.sessionStartTimeoutId, null);
+ assert.deepEqual(host.toasts, [['error', TERMINAL_CONNECTION_ERRORS.timeout]]);
+});
+
+test('a token after auto-start replaces the timer and pty-ready clears it', (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const host = createTerminalHost();
+
+ autoStart(host);
+ t.mock.timers.tick(TERMINAL_SESSION_START_TIMEOUT_MS - 1000);
+
+ // send-terminal-token
+ host.beginTerminalSessionStart();
+ assert.equal(host.websocketStarts, 1);
+
+ // The auto-start timer was replaced, so its deadline passes without an error.
+ t.mock.timers.tick(2000);
+ assert.equal(host.starting, true);
+ assert.equal(host.connectionError, null);
+
+ // pty-ready
+ host.terminalActive = true;
+ host.completeTerminalSessionStart();
+ t.mock.timers.tick(TERMINAL_SESSION_START_TIMEOUT_MS * 2);
+
+ assert.equal(host.starting, false);
+ assert.equal(host.connectionError, null);
+ assert.equal(host.sessionStartTimeoutId, null);
+ assert.deepEqual(host.toasts, []);
+});
+
+test('a token that arrives after the timeout error still starts the session', (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const host = createTerminalHost();
+
+ autoStart(host);
+ t.mock.timers.tick(TERMINAL_SESSION_START_TIMEOUT_MS);
+ assert.equal(host.connectionError, TERMINAL_CONNECTION_ERRORS.timeout);
+
+ host.beginTerminalSessionStart();
+
+ assert.equal(host.starting, true);
+ assert.equal(host.connectionError, null);
+
+ host.terminalActive = true;
+ host.completeTerminalSessionStart();
+
+ assert.equal(host.starting, false);
+ assert.equal(host.sessionStartTimeoutId, null);
+});
+
+test('arming the timer twice keeps one timer only', (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const host = createTerminalHost();
+
+ autoStart(host);
+ host.armTerminalSessionStartTimeout();
+ // Teardown must clear the only timer; an orphaned first timer would still fire.
+ host.clearSessionStartTimeout();
+ t.mock.timers.tick(TERMINAL_SESSION_START_TIMEOUT_MS * 2);
+
+ assert.equal(host.starting, true);
+ assert.equal(host.connectionError, null);
+ assert.deepEqual(host.toasts, []);
+});
+
+test('a server-side start failure stops the spinner at once with its message', (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const host = createTerminalHost({ pendingCommand: { terminalToken: 'stale' } });
+
+ autoStart(host);
+ host.failTerminalSessionStart('The container is not running.');
+
+ assert.equal(host.starting, false);
+ assert.equal(host.connectionError, 'The container is not running.');
+ assert.equal(host.pendingCommand, null);
+ assert.equal(host.sessionStartTimeoutId, null);
+
+ t.mock.timers.tick(TERMINAL_SESSION_START_TIMEOUT_MS);
+
+ assert.deepEqual(host.toasts, [['error', 'The container is not running.']]);
+});
+
+test('a server-side start failure replaces an earlier timeout error', () => {
+ const host = createTerminalHost({ connectionError: TERMINAL_CONNECTION_ERRORS.timeout });
+
+ host.failTerminalSessionStart('No shell is available in this container.');
+
+ assert.equal(host.connectionError, 'No shell is available in this container.');
+});
+
+test('a server-side start failure without a message falls back to the generic error', () => {
+ const host = createTerminalHost();
+
+ host.failTerminalSessionStart(undefined);
+
+ assert.equal(host.connectionError, TERMINAL_CONNECTION_ERRORS.connectionFailed);
+});
+
+test('a cancelled auto-start waits for a container choice without an error', (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const host = createTerminalHost();
+
+ autoStart(host);
+ host.cancelTerminalAutoStart();
+ t.mock.timers.tick(TERMINAL_SESSION_START_TIMEOUT_MS * 2);
+
+ assert.equal(host.starting, false);
+ assert.equal(host.connectionError, null);
+ assert.equal(host.sessionStartTimeoutId, null);
+ assert.deepEqual(host.toasts, []);
+});
+
+test('a cancelled auto-start does not stop a session that is already starting', (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const host = createTerminalHost({ pendingCommand: { terminalToken: 'token' } });
+
+ autoStart(host);
+ host.cancelTerminalAutoStart();
+
+ assert.equal(host.starting, true);
+ assert.notEqual(host.sessionStartTimeoutId, null);
+});
diff --git a/resources/js/terminal.js b/resources/js/terminal.js
index b58b3e59c3..420e20fb11 100644
--- a/resources/js/terminal.js
+++ b/resources/js/terminal.js
@@ -9,9 +9,9 @@ import {
import {
TERMINAL_CONNECT_TIMEOUT_MS,
TERMINAL_CONNECTION_ERRORS,
- TERMINAL_SESSION_START_TIMEOUT_MS,
classifyTerminalServerMessage,
resolveTerminalCloseOutcome,
+ terminalSessionStartMethods,
} from './terminal-connection.js';
import { FitAddon } from '@xterm/addon-fit';
@@ -226,8 +226,15 @@ export function initializeTerminalComponent() {
? localStorage.getItem('coolify-console-theme')
: 'system',
+ ...terminalSessionStartMethods,
+
init() {
this.starting = this.$el.dataset.autoStart === 'true';
+ // Auto-start requests a token without a user action. If no token or error
+ // arrives, the session-start timeout ends "connecting…" with an error.
+ if (this.starting) {
+ this.armTerminalSessionStartTimeout();
+ }
this.updateKeyboardInset = () => {
const viewport = window.visualViewport;
const viewportWidth = viewport?.width ?? window.innerWidth;
@@ -309,6 +316,16 @@ export function initializeTerminalComponent() {
this.sendCommandWhenReady({ terminalToken: token });
});
+ // Coolify did not issue a token (container stopped, no shell, access denied).
+ this.$wire.on('terminal-session-failed', ({ message }) => {
+ this.failTerminalSessionStart(message);
+ });
+
+ // The page shows a container picker; nothing starts until the user chooses.
+ this.$wire.on('terminal-auto-start-cancelled', () => {
+ this.cancelTerminalAutoStart();
+ });
+
this.$wire.on('terminal-should-focus', () => {
// Wait for terminal to be ready, then focus
const focusWhenReady = () => {
@@ -767,52 +784,6 @@ export function initializeTerminalComponent() {
this.scheduleReconnect();
},
- /** A session was requested and the UI shows "connecting…" until `pty-ready`. */
- isTerminalSessionPending() {
- return this.starting && !this.terminalActive;
- },
-
- /**
- * Leave the "connecting" state and show why. The first reason wins unless
- * `override` is set (auth rejections replace generic connection errors).
- */
- failTerminalConnection(message, { override = false } = {}) {
- this.starting = false;
- this.clearSessionStartTimeout();
-
- if (this.connectionError === message || (this.connectionError && !override)) {
- return;
- }
-
- this.connectionError = message;
- this.$wire.dispatch('error', message);
- },
-
- /** Called whenever a new terminal session is requested (target chosen or token issued). */
- beginTerminalSessionStart() {
- this.starting = true;
- this.connectionError = null;
- this.authRejected = false;
- this.clearSessionStartTimeout();
- this.sessionStartTimeoutId = setTimeout(() => {
- this.sessionStartTimeoutId = null;
- if (this.isTerminalSessionPending()) {
- logTerminal('error', `[Terminal] Session did not start within ${TERMINAL_SESSION_START_TIMEOUT_MS}ms`);
- // Single-use tokens must not be sent after the user was told to retry.
- this.pendingCommand = null;
- this.failTerminalConnection(TERMINAL_CONNECTION_ERRORS.timeout);
- }
- }, TERMINAL_SESSION_START_TIMEOUT_MS);
- this.ensureWebSocketConnection();
- },
-
- clearSessionStartTimeout() {
- if (this.sessionStartTimeoutId) {
- clearTimeout(this.sessionStartTimeoutId);
- this.sessionStartTimeoutId = null;
- }
- },
-
/** Reconnect immediately for a user-requested session if the socket is closed. */
ensureWebSocketConnection() {
if (this.socket && this.socket.readyState !== WebSocket.CLOSED) {
@@ -894,9 +865,7 @@ export function initializeTerminalComponent() {
}
if (event.data === 'pty-ready') {
- this.starting = false;
- this.connectionError = null;
- this.clearSessionStartTimeout();
+ this.completeTerminalSessionStart();
if (!this.term._initialized) {
this.term.open(document.getElementById('terminal'));
this.term._initialized = true;
@@ -1029,6 +998,7 @@ export function initializeTerminalComponent() {
},
destroy() {
+ this.clearSessionStartTimeout();
this.themeObserver?.disconnect();
window.visualViewport?.removeEventListener('resize', this.syncKeyboardInset);
window.visualViewport?.removeEventListener('scroll', this.syncKeyboardInset);
diff --git a/tests/Feature/RealtimeTerminalPackagingTest.php b/tests/Feature/RealtimeTerminalPackagingTest.php
index e44135e0c2..3b678a7a8b 100644
--- a/tests/Feature/RealtimeTerminalPackagingTest.php
+++ b/tests/Feature/RealtimeTerminalPackagingTest.php
@@ -610,11 +610,26 @@ it('leaves the terminal connecting state when the connection is rejected, lost,
->toContain('Ignoring terminal token after authentication was rejected.')
->toContain('failTerminalConnection(TERMINAL_CONNECTION_ERRORS.timeout)')
->toContain('failTerminalConnection(TERMINAL_CONNECTION_ERRORS.connectionFailed)')
- ->toContain('TERMINAL_SESSION_START_TIMEOUT_MS')
+ ->toContain('...terminalSessionStartMethods,')
->toContain('this.beginTerminalSessionStart();')
+ ->and(file_get_contents(resource_path('js/terminal-connection.js')))
+ ->toContain('export const terminalSessionStartMethods = {')
+ ->toContain('}, TERMINAL_SESSION_START_TIMEOUT_MS);')
->and($terminalView)
->toContain('data-terminal-connection-error')
->toContain('x-text="connectionError"')
->toContain('x-on:click="reloadTerminalPage()"')
->toContain('x-show="!connectionError" class="terminal-loading-label');
});
+
+it('ends the auto-start connecting state when no terminal token arrives', function () {
+ $terminalClient = file_get_contents(resource_path('js/terminal.js'));
+
+ expect($terminalClient)
+ ->toMatch("/this\.starting = this\.\\\$el\.dataset\.autoStart === 'true';.*?if \(this\.starting\) \{\s*this\.armTerminalSessionStartTimeout\(\);\s*\}/s")
+ ->toContain("this.\$wire.on('terminal-session-failed', ({ message }) => {")
+ ->toContain('this.failTerminalSessionStart(message);')
+ ->toContain("this.\$wire.on('terminal-auto-start-cancelled', () => {")
+ ->toMatch('/destroy\(\) \{\s*this\.clearSessionStartTimeout\(\);/')
+ ->toMatch("/event\.data === 'pty-ready'\) \{\s*this\.completeTerminalSessionStart\(\);/");
+});
diff --git a/tests/Feature/TerminalSessionStartFailureTest.php b/tests/Feature/TerminalSessionStartFailureTest.php
new file mode 100644
index 0000000000..0da9a68efb
--- /dev/null
+++ b/tests/Feature/TerminalSessionStartFailureTest.php
@@ -0,0 +1,272 @@
+<?php
+
+use App\Livewire\Project\Shared\ExecuteContainerCommand;
+use App\Livewire\Project\Shared\Terminal;
+use App\Models\Application;
+use App\Models\Environment;
+use App\Models\InstanceSettings;
+use App\Models\PrivateKey;
+use App\Models\Project;
+use App\Models\Server;
+use App\Models\StandaloneDocker;
+use App\Models\Team;
+use App\Models\User;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Routing\Events\RouteMatched;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\Event;
+use Illuminate\Support\Facades\Process;
+use Livewire\Livewire;
+
+uses(RefreshDatabase::class);
+
+beforeEach(function () {
+ InstanceSettings::forceCreate(['id' => 0]);
+ config([
+ 'app.maintenance.store' => 'array',
+ 'constants.ssh.mux_enabled' => false,
+ ]);
+ Cache::flush();
+
+ $this->team = Team::factory()->create();
+ $this->owner = User::factory()->create();
+ $this->owner->teams()->attach($this->team, ['role' => 'owner']);
+ $this->privateKey = PrivateKey::factory()->create(['team_id' => $this->team->id]);
+ $this->server = Server::factory()->create([
+ 'team_id' => $this->team->id,
+ 'private_key_id' => $this->privateKey->id,
+ ]);
+ $this->server->settings->update([
+ 'is_reachable' => true,
+ 'is_usable' => true,
+ 'is_terminal_enabled' => true,
+ ]);
+
+ $this->actingAs($this->owner);
+ session(['currentTeam' => $this->team]);
+});
+
+/**
+ * Fake the SSH commands used before a container terminal token is issued.
+ */
+function fakeTerminalContainer(string $state, bool $hasShell = true, array $runningContainers = []): void
+{
+ Process::fake(function ($process) use ($state, $hasShell, $runningContainers) {
+ $command = (string) $process->command;
+
+ if (str_contains($command, 'docker ps -a')) {
+ return Process::result(output: collect($runningContainers)
+ ->map(fn (string $name) => json_encode(['Names' => $name, 'State' => 'running', 'Labels' => '']))
+ ->implode("\n"));
+ }
+
+ if (str_contains($command, 'docker inspect')) {
+ return Process::result(output: json_encode(['State' => ['Status' => $state]]));
+ }
+
+ if (str_contains($command, "-c 'exit 0'")) {
+ return $hasShell ? Process::result() : Process::result(exitCode: 1);
+ }
+
+ return Process::result();
+ });
+}
+
+function actAsTerminalMember(Team $team): void
+{
+ $member = User::factory()->create();
+ $member->teams()->attach($team, ['role' => 'member']);
+ test()->actingAs($member);
+ session(['currentTeam' => $team]);
+}
+
+/**
+ * Make `get_route_parameters()` return the page parameters. Livewire::test() mounts the
+ * component through its own testing route, so add the parameters to every matched route.
+ */
+function bindTerminalRouteParameters(array $parameters): void
+{
+ Event::listen(RouteMatched::class, function (RouteMatched $event) use ($parameters): void {
+ foreach ($parameters as $name => $value) {
+ $event->route->setParameter($name, $value);
+ }
+ });
+}
+
+function createTerminalApplication(Server $server, Team $team): Application
+{
+ $destination = StandaloneDocker::query()->where('server_id', $server->id)->firstOrFail();
+ $project = Project::factory()->create(['team_id' => $team->id]);
+ $environment = Environment::factory()->create(['project_id' => $project->id]);
+
+ return Application::factory()->create([
+ 'environment_id' => $environment->id,
+ 'destination_id' => $destination->id,
+ 'destination_type' => $destination->getMorphClass(),
+ ]);
+}
+
+describe('Terminal::sendTerminalCommand', function () {
+ it('issues a token for a running container with a shell', function () {
+ fakeTerminalContainer('running');
+
+ Livewire::test(Terminal::class)
+ ->call('sendTerminalCommand', true, 'app-container', $this->server->uuid)
+ ->assertDispatched('send-terminal-token')
+ ->assertNotDispatched(Terminal::SESSION_FAILED_EVENT);
+ });
+
+ it('reports a stopped container instead of leaving the terminal connecting', function () {
+ fakeTerminalContainer('exited');
+
+ Livewire::test(Terminal::class)
+ ->call('sendTerminalCommand', true, 'app-container', $this->server->uuid)
+ ->assertDispatched(Terminal::SESSION_FAILED_EVENT, message: 'The container is not running.')
+ ->assertNotDispatched('send-terminal-token');
+ });
+
+ it('reports a container without a shell', function () {
+ fakeTerminalContainer('running', hasShell: false);
+
+ Livewire::test(Terminal::class)
+ ->call('sendTerminalCommand', true, 'app-container', $this->server->uuid)
+ ->assertDispatched(Terminal::SESSION_FAILED_EVENT, message: 'No shell is available in this container.')
+ ->assertSet('hasShell', false)
+ ->assertNotDispatched('send-terminal-token');
+ });
+
+ it('reports an invalid container name without running remote commands', function () {
+ Process::fake();
+
+ Livewire::test(Terminal::class)
+ ->call('sendTerminalCommand', true, '-oProxyCommand=id', $this->server->uuid)
+ ->assertDispatched(Terminal::SESSION_FAILED_EVENT, message: 'The container name is not valid.')
+ ->assertNotDispatched('send-terminal-token');
+
+ Process::assertNothingRan();
+ });
+
+ it('reports a server with terminal access disabled', function () {
+ Process::fake();
+ $this->server->settings->update(['is_terminal_enabled' => false]);
+
+ Livewire::test(Terminal::class)
+ ->call('sendTerminalCommand', false, $this->server->name, $this->server->uuid)
+ ->assertDispatched(Terminal::SESSION_FAILED_EVENT, message: 'Terminal access is disabled on this server.')
+ ->assertNotDispatched('send-terminal-token');
+
+ Process::assertNothingRan();
+ });
+
+ it('denies members with a generic message and no token', function () {
+ Process::fake();
+ actAsTerminalMember($this->team);
+
+ Livewire::test(Terminal::class)
+ ->call('sendTerminalCommand', true, 'app-container', $this->server->uuid)
+ ->assertDispatched(Terminal::SESSION_FAILED_EVENT, message: Terminal::NOT_ALLOWED_MESSAGE)
+ ->assertNotDispatched('send-terminal-token');
+
+ Process::assertNothingRan();
+ });
+
+ it('denies a server of another team with the same generic message', function () {
+ Process::fake();
+ $otherTeam = Team::factory()->create();
+ $otherServer = Server::factory()->create([
+ 'team_id' => $otherTeam->id,
+ 'private_key_id' => $this->privateKey->id,
+ ]);
+
+ Livewire::test(Terminal::class)
+ ->call('sendTerminalCommand', false, $otherServer->name, $otherServer->uuid)
+ ->assertDispatched(Terminal::SESSION_FAILED_EVENT, message: Terminal::NOT_ALLOWED_MESSAGE)
+ ->assertNotDispatched('send-terminal-token');
+
+ Process::assertNothingRan();
+ });
+});
+
+describe('ExecuteContainerCommand', function () {
+ it('reports a denied server terminal to the terminal component', function () {
+ Process::fake();
+ bindTerminalRouteParameters(['server_uuid' => $this->server->uuid]);
+ $component = Livewire::test(ExecuteContainerCommand::class);
+
+ actAsTerminalMember($this->team);
+
+ $component->call('connectToServer')
+ ->assertDispatchedTo(Terminal::class, Terminal::SESSION_FAILED_EVENT, message: Terminal::NOT_ALLOWED_MESSAGE)
+ ->assertNotDispatched('send-terminal-command');
+ });
+
+ it('reports a disabled server to the terminal component', function () {
+ Process::fake();
+ bindTerminalRouteParameters(['server_uuid' => $this->server->uuid]);
+ $component = Livewire::test(ExecuteContainerCommand::class);
+
+ $this->server->settings->update(['force_disabled' => true]);
+
+ $component->call('connectToServer')
+ ->assertDispatchedTo(Terminal::class, Terminal::SESSION_FAILED_EVENT, message: 'Server is disabled.')
+ ->assertNotDispatched('send-terminal-command');
+ });
+
+ it('reports a missing container selection to the terminal component', function () {
+ fakeTerminalContainer('running');
+ $application = createTerminalApplication($this->server, $this->team);
+ bindTerminalRouteParameters(['application_uuid' => $application->uuid]);
+
+ Livewire::test(ExecuteContainerCommand::class)
+ ->call('connectToContainer')
+ ->assertDispatchedTo(Terminal::class, Terminal::SESSION_FAILED_EVENT, message: 'Please select a container.')
+ ->assertNotDispatched('send-terminal-command');
+ });
+
+ it('reports a container that is no longer in the running list', function () {
+ fakeTerminalContainer('running');
+ $application = createTerminalApplication($this->server, $this->team);
+ bindTerminalRouteParameters(['application_uuid' => $application->uuid]);
+
+ Livewire::test(ExecuteContainerCommand::class)
+ ->set('selected_container', "{$this->server->uuid}:gone-container")
+ ->assertDispatchedTo(Terminal::class, Terminal::SESSION_FAILED_EVENT, message: 'Container not found.')
+ ->assertNotDispatched('send-terminal-command');
+ });
+
+ it('denies members before it looks up the container', function () {
+ fakeTerminalContainer('running');
+ $application = createTerminalApplication($this->server, $this->team);
+ bindTerminalRouteParameters(['application_uuid' => $application->uuid]);
+ $component = Livewire::test(ExecuteContainerCommand::class);
+
+ actAsTerminalMember($this->team);
+
+ $component->set('selected_container', "{$this->server->uuid}:app-container")
+ ->assertDispatchedTo(Terminal::class, Terminal::SESSION_FAILED_EVENT, message: Terminal::NOT_ALLOWED_MESSAGE)
+ ->assertNotDispatched('send-terminal-command');
+ });
+
+ it('auto-connects when exactly one container is running', function () {
+ fakeTerminalContainer('running', runningContainers: ['app-container']);
+ $application = createTerminalApplication($this->server, $this->team);
+ bindTerminalRouteParameters(['application_uuid' => $application->uuid]);
+
+ Livewire::test(ExecuteContainerCommand::class)
+ ->call('loadContainers')
+ ->assertDispatched('send-terminal-command')
+ ->assertNotDispatched(Terminal::AUTO_START_CANCELLED_EVENT)
+ ->assertNotDispatched(Terminal::SESSION_FAILED_EVENT);
+ });
+
+ it('cancels the terminal auto-start when the user must choose a container', function () {
+ fakeTerminalContainer('running', runningContainers: ['app-container-a', 'app-container-b']);
+ $application = createTerminalApplication($this->server, $this->team);
+ bindTerminalRouteParameters(['application_uuid' => $application->uuid]);
+
+ Livewire::test(ExecuteContainerCommand::class)
+ ->call('loadContainers')
+ ->assertDispatchedTo(Terminal::class, Terminal::AUTO_START_CANCELLED_EVENT)
+ ->assertNotDispatched('send-terminal-command');
+ });
+});
diff --git a/tests/v4/Browser/TerminalAutoStartFailureTest.php b/tests/v4/Browser/TerminalAutoStartFailureTest.php
new file mode 100644
index 0000000000..013b7d5ed6
--- /dev/null
+++ b/tests/v4/Browser/TerminalAutoStartFailureTest.php
@@ -0,0 +1,60 @@
+<?php
+
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\Process;
+use Symfony\Component\Process\Process as SymfonyProcess;
+
+uses(RefreshDatabase::class);
+
+beforeEach(function () {
+ config()->set('app.maintenance.store', 'array');
+ config()->set('constants.ssh.mux_enabled', false);
+
+ $stack = seedBrowserResourceStack();
+ $stack['server']->settings->update(['is_terminal_enabled' => true]);
+ $this->application = createBrowserApplication($stack, ['uuid' => 'app-terminal-autostart']);
+ $this->terminalPath = "/project/{$stack['project']->uuid}/environment/{$stack['environment']->uuid}/application/{$this->application->uuid}/terminal";
+ Cache::flush();
+
+ // An open WebSocket that accepts the connection and waits (it only reacts to a client frame).
+ $this->terminalServer = new SymfonyProcess(['node', base_path('tests/Fixtures/terminal-websocket-rejection-server.mjs'), 'reject-token']);
+ $this->terminalServer->start();
+ $this->terminalServer->waitUntil(fn (string $type, string $output) => str_contains($output, "\n"));
+ config()->set('constants.terminal.protocol', 'ws');
+ config()->set('constants.terminal.host', '127.0.0.1');
+ config()->set('constants.terminal.port', trim($this->terminalServer->getOutput()));
+});
+
+afterEach(function () {
+ $this->terminalServer?->stop(0);
+});
+
+it('shows why an auto-started container terminal cannot start instead of connecting forever', function () {
+ // One running container makes the page auto-connect; it stops before the token is issued.
+ Process::fake(function ($process) {
+ $command = (string) $process->command;
+
+ if (str_contains($command, 'docker ps -a')) {
+ return Process::result(output: json_encode(['Names' => 'app-terminal-autostart-1', 'State' => 'running', 'Labels' => '']));
+ }
+
+ if (str_contains($command, 'docker inspect')) {
+ return Process::result(output: json_encode(['State' => ['Status' => 'exited']]));
+ }
+
+ return Process::result();
+ });
+
+ $page = visit('/login')
+ ->fill('email', '[email protected]')
+ ->fill('password', 'password')
+ ->click('Login')
+ ->assertSee('Dashboard')
+ ->navigate($this->terminalPath)
+ ->assertSee('The container is not running.')
+ ->assertSee('Reload page')
+ ->assertDontSee('connecting…');
+
+ $page->screenshot(filename: 'terminal-auto-start-container-not-running');
+});