Skip to content

Modern Docker Management, Designed for Everyone

56.1 KB
Raw Blame
import { test, expect, type Page, type Response } from '../fixtures/test.fixture';
import {
	readApiData,
	removeApiResource,
	fetchProjectCountsWithRetry,
	fetchProjectsWithRetry
} from '../utils/fetch.util';
import type { Activity } from '../types/activity.type';
import { Project, ProjectStatusCounts } from 'types/project.type';
import { TEST_COMPOSE_YAML, TEST_ENV_FILE } from '../setup/project.data';
import { openRowActionsMenu } from '../utils/table-actions.util';
import { getCodeMirrorValue, setCodeMirrorValue } from '../utils/playwright.util';

const ROUTES = {
	page: '/projects',
	apiProjects: '/api/environments/0/projects',
	apiImageUpdatesCheckAll: '/api/environments/0/image-updates/check-all',
	apiUpdaterRun: '/api/environments/0/updater/run',
	newProject: '/projects/new'
};

const DEPLOY_STREAM_SUCCESS =
	'{"log":"Container test-1  Creating"}\n' +
	'{"log":"Container test-1  Started"}\n' +
	'{"done":true}\n';

async function navigateToProjects(page: Page) {
	await page.goto(ROUTES.page);
	await page.waitForLoadState('load');
}

async function clickProjectsPageUpdateAction(page: Page) {
	const updateProjectsButton = page
		.getByRole('button', { name: 'Update Projects', exact: true })
		.filter({ visible: true })
		.first();
	await expect(updateProjectsButton).toBeVisible();
	await updateProjectsButton.click();
}

async function clickProjectDetailUpdateAction(page: Page) {
	const recheckButton = page.getByRole('button', { name: 'Re-check Updates', exact: true }).first();
	const updateTrigger = page.getByTestId('project-update-trigger').first();
	await expect(recheckButton.or(updateTrigger).filter({ visible: true }).first()).toBeVisible();
	if (await recheckButton.isVisible()) {
		await recheckButton.click();
		return true;
	}
	if (await updateTrigger.evaluate((element) => element.tagName === 'BUTTON')) {
		await updateTrigger.click();
		return true;
	}

	const usesTouchPopover = await page.evaluate(() => window.matchMedia('(hover: none)').matches);
	if (usesTouchPopover) await updateTrigger.click();
	else await updateTrigger.hover();
	await recheckButton.click();
	return true;
}

async function fetchProjectDetail(page: Page, projectId: string): Promise<Project> {
	const project = await readApiData<Project>(
		await page.request.get(`/api/environments/0/projects/${projectId}`),
		`Get project ${projectId}`
	);
	expect(project.id).toBeTruthy();
	return project;
}

async function fetchLatestProjectDeployActivity(
	page: Page,
	projectId: string,
	projectName: string
): Promise<Activity | null> {
	const params = new URLSearchParams({
		type: 'project_deploy',
		resourceType: 'project',
		search: projectName,
		limit: '10'
	});
	const activities = await readApiData<Activity[]>(
		await page.request.get(`/api/environments/0/activities?${params.toString()}`),
		'List project deploy activities'
	);
	expect(Array.isArray(activities)).toBe(true);
	return (
		activities.find(
			(activity) =>
				activity.type === 'project_deploy' &&
				activity.resourceType === 'project' &&
				activity.resourceId === projectId
		) ?? null
	);
}

async function expectProjectDeployActivitySucceeded(
	page: Page,
	projectId: string,
	projectName: string
) {
	await expect
		.poll(
			async () =>
				(await fetchLatestProjectDeployActivity(page, projectId, projectName))?.status ?? 'missing',
			{
				message: 'Expected project deploy activity to complete before reload',
				timeout: 60000
			}
		)
		.toBe('success');
}

function getPathname(url: string): string {
	return url.replace(/^[a-z]+:\/\/[^/]+/i, '').split(/[?#]/)[0] || '/';
}

function getProjectIdFromPageUrl(url: string): string {
	return url.split('/projects/')[1]?.split(/[?#]/)[0] ?? '';
}

async function expectProjectCreateResponse(responsePromise: Promise<Response>) {
	const response = await responsePromise;
	if (response.ok()) {
		return response;
	}

	const body = await response.text().catch(() => '<unreadable response body>');
	throw new Error(
		`Create project request failed with ${response.status()} ${response.statusText()}: ${body}`
	);
}

async function createProjectViaUI(
	page: Page,
	projectName: string,
	composeContent = TEST_COMPOSE_YAML
) {
	createdProjectNames.add(projectName);
	const containerName = `test-nginx-container-${Date.now()}`;
	const envFile = TEST_ENV_FILE.replace(/CONTAINER_NAME=.*/m, `CONTAINER_NAME=${containerName}`);

	await page.goto(ROUTES.newProject);
	await page.waitForLoadState('load');

	await page.getByRole('button', { name: 'My New Project' }).click();
	await page.getByRole('textbox', { name: 'My New Project' }).fill(projectName);
	await page.getByRole('textbox', { name: 'My New Project' }).press('Enter');

	const visibleEditors = page.locator('.cm-editor').filter({ visible: true });
	const composeEditor = visibleEditors.first();
	const envEditor = visibleEditors.nth(1);
	await expect(composeEditor).toBeVisible();
	await expect(envEditor).toBeVisible();

	await setCodeMirrorValue(composeEditor, composeContent);
	await setCodeMirrorValue(envEditor, envFile);
	await expect
		.poll(async () => (await getCodeMirrorValue(composeEditor)).trimEnd(), {
			message: 'Expected compose editor to contain the exact test compose fixture before creation'
		})
		.toBe(composeContent.trimEnd());

	const createButton = page.locator('button[data-action="create"]');
	await expect(createButton).toBeEnabled();
	const createResponsePromise = page.waitForResponse(
		(response) =>
			response.request().method() === 'POST' &&
			/\/api\/environments\/[^/]+\/projects$/.test(getPathname(response.url()))
	);
	await createButton.click();
	await expectProjectCreateResponse(createResponsePromise);

	await page.waitForURL(/\/projects\/(?!new$).+/, { timeout: 10000 });
	await expect(page.getByRole('button', { name: projectName })).toBeVisible();

	return getProjectIdFromPageUrl(page.url());
}

async function destroyCurrentProjectViaUI(page: Page) {
	if (page.isClosed()) {
		return;
	}

	await page.getByRole('button', { name: 'More actions', exact: true }).click();
	const destroyItem = page.getByRole('menuitem', { name: 'Destroy', exact: true });
	await expect(destroyItem).toBeVisible();
	await destroyItem.click();

	const dialog = page.getByRole('dialog');
	await expect(dialog).toBeVisible();
	await dialog
		.getByRole('checkbox', { name: 'Remove volumes (Warning: Data will be lost)', exact: true })
		.check();
	await dialog.getByRole('button', { name: 'Destroy', exact: true }).click();

	await page.waitForURL(ROUTES.page, { timeout: 10000 });
}

async function destroyProjectByNameViaAPI(page: Page, projectName: string) {
	try {
		const projects = await readApiData<Project[]>(
			await page.request.get(ROUTES.apiProjects, {
				params: { search: projectName, archived: 'all' }
			}),
			`Find project ${projectName} for cleanup`
		);
		expect(Array.isArray(projects)).toBe(true);
		for (const project of projects.filter((candidate) => candidate.name === projectName)) {
			expect(project.id).toBeTruthy();
			await destroyProjectByIdViaAPI(page, project.id!);
		}
	} catch (error) {
		expect.soft(false, `Clean up project ${projectName}: ${String(error)}`).toBe(true);
	}
}

async function destroyProjectByIdViaAPI(page: Page, projectId: string) {
	if (!projectId || page.isClosed()) {
		return;
	}

	await removeApiResource(
		page,
		`/api/environments/0/projects/${encodeURIComponent(projectId)}/destroy`,
		{
			data: {
				removeVolumes: true
			}
		}
	);
}

async function expectProjectStopped(page: Page, projectId: string) {
	await expect
		.poll(
			async () => {
				const detail = await fetchProjectDetail(page, projectId);
				return detail?.status ?? 'missing';
			},
			{
				message: 'Expected project to be stopped',
				timeout: 60000
			}
		)
		.toBe('stopped');
}

function buildExitServiceCompose(marker: string) {
	return [
		'services:',
		'  exiter:',
		'    image: public.ecr.aws/docker/library/alpine:3.20',
		'    restart: "no"',
		`    command: sh -c "echo ${marker}; exit 0"`,
		''
	].join('\n');
}

async function createExitedMarkerProject(page: Page, projectName: string) {
	const marker = `ARCANE_LOGS_MARKER_${Date.now()}`;
	const projectId = await createProjectViaUI(page, projectName, buildExitServiceCompose(marker));

	const deployResponsePromise = page.waitForResponse(
		(response) =>
			response.request().method() === 'POST' &&
			/\/api\/environments\/[^/]+\/projects\/[^/]+\/up$/.test(getPathname(response.url()))
	);
	await page
		.getByRole('button', { name: 'Up', exact: true })
		.filter({ visible: true })
		.first()
		.click();
	const deployResponse = await deployResponsePromise;
	expect(deployResponse.ok()).toBe(true);

	await expectProjectStopped(page, projectId);

	return { projectId, marker };
}

const createdProjectNames = new Set<string>();
let realProjects: Project[] = [];
let projectCounts: ProjectStatusCounts = {
	runningProjects: 0,
	stoppedProjects: 0,
	totalProjects: 0,
	archivedProjects: 0
};

function getRequiredGitOpsProject(): Project & { id: string } {
	const project = realProjects.find((candidate) => candidate.gitOpsManagedBy);
	expect(project, 'GitOps setup must provide a managed project').toBeDefined();
	expect(project!.id, 'GitOps setup project must have an ID').toBeTruthy();
	return project as Project & { id: string };
}

test.beforeEach(async ({ page, registerCleanup }) => {
	createdProjectNames.clear();
	registerCleanup(async () => {
		for (const name of createdProjectNames) await destroyProjectByNameViaAPI(page, name);
	});
	await navigateToProjects(page);

	realProjects = await fetchProjectsWithRetry(page);
	projectCounts = await fetchProjectCountsWithRetry(page);
	expect(realProjects.length, 'Project setup must provide at least one project').toBeGreaterThan(0);
});

test.describe('Projects Page', () => {
	test('should display summary cards with correct counts', async ({ page }) => {
		await expect(
			page.getByText(`${projectCounts.totalProjects} Total Projects`, {
				exact: true
			})
		).toBeVisible();
		await expect(
			page.getByText(`${projectCounts.runningProjects} Running`, {
				exact: true
			})
		).toBeVisible();
		await expect(
			page.getByText(`${projectCounts.stoppedProjects} Stopped`, {
				exact: true
			})
		).toBeVisible();
		await expect(
			page.getByText(`${projectCounts.archivedProjects} Archived Projects`, {
				exact: true
			})
		).toBeVisible();
	});

	test('should archive and unarchive a stopped project from the projects page', async ({
		page
	}) => {
		const projectName = `test-project-archive-${Date.now()}`;
		let projectId = '';

		try {
			projectId = await createProjectViaUI(page, projectName);

			await page.getByRole('button', { name: 'More actions', exact: true }).click();
			await page.getByRole('menuitem', { name: 'Archive', exact: true }).click();
			await expect(page.getByText('Project archived successfully.')).toBeVisible({
				timeout: 10000
			});

			await page.goto(ROUTES.page);
			await page.waitForLoadState('load');
			const projectLink = page.getByRole('link', { name: projectName, exact: true });
			await expect(page.getByRole('row').filter({ has: projectLink })).toHaveCount(0);

			await page.getByLabel('Show archived').check();
			await expect(page).toHaveURL(/archived=true/);
			const row = page.getByRole('row').filter({ has: projectLink }).first();
			await expect(row).toBeVisible();
			await expect(row.getByText('Archived', { exact: true })).toBeVisible();

			const menu = await openRowActionsMenu(page, row);
			await menu.getByRole('menuitem', { name: 'Unarchive', exact: true }).click();
			await expect(page.getByText('Project unarchived successfully.')).toBeVisible({
				timeout: 10000
			});
			await expect(row).toHaveCount(0, { timeout: 10000 });
		} finally {
			if (projectId) {
				await destroyProjectByIdViaAPI(page, projectId);
			} else {
				await destroyProjectByNameViaAPI(page, projectName);
			}
		}
	});

	test('should navigate to project details when project name is clicked', async ({ page }) => {
		expect(realProjects.length, 'No projects available for navigation test').toBeGreaterThan(0);

		await page.waitForLoadState('load');
		const projectName = realProjects[0].name;
		const firstProjectLink = page.getByRole('link', { name: projectName, exact: true }).first();

		await firstProjectLink.click();
		await expect(page).toHaveURL(/\/projects\/.+/);
		await expect(page.getByRole('button', { name: projectName, exact: true })).toBeVisible();
	});

	test('should allow searching/filtering projects', async ({ page }) => {
		expect(realProjects.length, 'No projects available for search test').toBeGreaterThan(0);

		const searchInput = page.getByPlaceholder('Search…');
		await expect(searchInput).toBeVisible();

		const firstProject = realProjects[0];
		if (firstProject?.name) {
			await searchInput.fill(firstProject.name);
			await expect(page.getByRole('link', { name: firstProject.name })).toBeVisible();
			await searchInput.clear();
		}
	});

	test('should check project updates without triggering updater run', async ({ page }) => {
		let checkAllRequests = 0;
		let updaterRunRequests = 0;

		await page.route('**/api/environments/*/image-updates/check-all', async (route) => {
			checkAllRequests += 1;
			await route.fulfill({
				status: 200,
				contentType: 'application/json',
				body: JSON.stringify({ success: true, data: {} })
			});
		});

		await page.route('**/api/environments/*/updater/run', async (route) => {
			updaterRunRequests += 1;
			await route.fulfill({
				status: 200,
				contentType: 'application/json',
				body: JSON.stringify({ success: true, data: { items: [] } })
			});
		});

		await clickProjectsPageUpdateAction(page);

		// The check only starts once the confirmation dialog is accepted
		const dialog = page.getByRole('dialog');
		await expect(dialog).toBeVisible();
		expect(checkAllRequests).toBe(0);
		await dialog.getByRole('button', { name: 'Update Projects', exact: true }).click();

		await expect.poll(() => checkAllRequests).toBe(1);
		expect(updaterRunRequests).toBe(0);
	});

	test('should display project status badges', async ({ page }) => {
		expect(realProjects.length, 'No projects available for status badge test').toBeGreaterThan(0);

		await page.waitForLoadState('load');

		const runningProjects = realProjects.filter((p) => p.status === 'running');
		const stoppedProjects = realProjects.filter((p) => p.status === 'stopped');

		if (runningProjects.length > 0) {
			await expect(page.getByText('Running', { exact: true }).first()).toBeVisible();
		}

		if (stoppedProjects.length > 0) {
			await expect(page.getByText('Stopped', { exact: true }).first()).toBeVisible();
		}
	});
});

test.describe('New Compose Project Page', () => {
	test.beforeEach(async ({ page }) => {
		await page.goto(ROUTES.newProject);
		await page.waitForLoadState('load');
	});

	test('should preserve YAML indentation when pressing Enter in compose editor', async ({
		page
	}) => {
		const composeEditor = page.locator('.cm-editor').filter({ visible: true }).first();
		const composeContent = composeEditor.locator('.cm-content').first();

		await setCodeMirrorValue(composeEditor, '');
		await composeContent.click({ position: { x: 10, y: 10 } });
		await expect(composeContent).toBeFocused();
		await page.keyboard.type('services:', { delay: 0 });
		await page.keyboard.press('Enter');
		await page.keyboard.type('web:', { delay: 0 });

		await expect
			.poll(async () => (await getCodeMirrorValue(composeEditor)).replace(/\r/g, ''))
			.toContain('services:\n  web:');
	});

	test('should validate required fields', async ({ page }) => {
		const createButton = page.locator('button[data-action="create"]');
		await expect(createButton).toBeDisabled();

		await page.getByRole('button', { name: 'My New Project' }).click();
		await page.getByRole('textbox', { name: 'My New Project' }).fill('test-project');
		await page.getByRole('textbox', { name: 'My New Project' }).press('Enter');
	});

	test('should enable Create Project after entering a valid name', async ({ page }) => {
		const observedErrors: string[] = [];
		page.on('pageerror', (err) => observedErrors.push(String(err?.message ?? err)));
		page.on('console', (msg) => {
			if (msg.type() === 'error') observedErrors.push(msg.text());
		});

		const createButton = page.locator('button[data-action="create"]');

		await expect(createButton).toBeVisible();

		// Open the inline name editor and set a valid name.
		await page.getByRole('button', { name: 'My New Project' }).click();
		await page.getByRole('textbox', { name: 'My New Project' }).fill('test-project');
		await page.getByRole('textbox', { name: 'My New Project' }).press('Enter');

		// The button should become enabled once name + compose content are present.
		await expect(createButton).toBeEnabled();

		const stateUnsafe = observedErrors.filter((e) => e.includes('state_unsafe_mutation'));
		expect(
			stateUnsafe,
			`Unexpected state_unsafe_mutation errors: ${stateUnsafe.join('\n')}`
		).toHaveLength(0);
	});

	test('should disable Create Project when compose syntax is invalid and enable it when fixed', async ({
		page
	}) => {
		await page.getByRole('button', { name: 'My New Project' }).click();
		await page.getByRole('textbox', { name: 'My New Project' }).fill('syntax-check-project');
		await page.getByRole('textbox', { name: 'My New Project' }).press('Enter');

		const composeEditor = page.locator('.cm-editor').filter({ visible: true }).first();
		await expect(composeEditor).toBeVisible();

		const createButton = page.locator('button[data-action="create"]');
		await setCodeMirrorValue(composeEditor, 'services:\n\tredis:\n\t\timage: redis:latest\n');
		await expect(createButton).toBeVisible();
		await expect(createButton).toBeDisabled();

		await setCodeMirrorValue(composeEditor, TEST_COMPOSE_YAML);
		await expect(createButton).toBeEnabled();
	});

	test('should disable Create Project when env syntax is invalid and enable it when fixed', async ({
		page
	}) => {
		await page.getByRole('button', { name: 'My New Project' }).click();
		await page.getByRole('textbox', { name: 'My New Project' }).fill('env-check-project');
		await page.getByRole('textbox', { name: 'My New Project' }).press('Enter');

		const visibleEditors = page.locator('.cm-editor').filter({ visible: true });
		const composeEditor = visibleEditors.first();
		const envEditor = visibleEditors.nth(1);
		await expect(composeEditor).toBeVisible();
		await expect(envEditor).toBeVisible();

		await setCodeMirrorValue(composeEditor, TEST_COMPOSE_YAML);
		const createButton = page.locator('button[data-action="create"]');
		await setCodeMirrorValue(envEditor, 'NOT VALID LINE');
		await expect(createButton).toBeVisible();
		await expect(createButton).toBeDisabled();

		await setCodeMirrorValue(envEditor, TEST_ENV_FILE);
		await expect(createButton).toBeEnabled();
	});

	test('should create a new project successfully', async ({ page }) => {
		test.slow();

		const projectName = `test-project-${Date.now()}`;
		const containerName = `test-nginx-container-${Date.now()}`;
		const envFile = TEST_ENV_FILE.replace(/CONTAINER_NAME=.*/m, `CONTAINER_NAME=${containerName}`);
		let createdProjectId: string | null = null;
		let projectPullRequestCount = 0;

		try {
			await page.getByRole('button', { name: 'My New Project' }).click();
			await page.getByRole('textbox', { name: 'My New Project' }).fill(projectName);
			await page.getByRole('textbox', { name: 'My New Project' }).press('Enter');

			const composeEditor = page.locator('.cm-editor').filter({ visible: true }).first();
			await expect(composeEditor).toBeVisible();
			await setCodeMirrorValue(composeEditor, TEST_COMPOSE_YAML);
			await expect(composeEditor).toContainText('nginx');
			await expect
				.poll(async () => (await getCodeMirrorValue(composeEditor)).trimEnd(), {
					message:
						'Expected compose editor to contain the exact test compose fixture before creation'
				})
				.toBe(TEST_COMPOSE_YAML.trimEnd());

			const envEditor = page.locator('.cm-editor').filter({ visible: true }).nth(1);
			await expect(envEditor).toBeVisible();
			await setCodeMirrorValue(envEditor, envFile);
			await expect(envEditor).toContainText('nginx');

			await page.route('/api/environments/*/projects', async (route) => {
				if (route.request().method() === 'POST') {
					const response = await route.fetch();
					const responseBody = await response.text();

					try {
						const parsed = JSON.parse(responseBody);
						createdProjectId = parsed.data?.id ?? parsed.id;
					} catch {
						// Keep existing createdProjectId value if parsing fails
					}

					await route.fulfill({
						status: response.status(),
						headers: response.headers(),
						body: responseBody
					});
				} else {
					await route.continue();
				}
			});

			const createButton = page.locator('button[data-action="create"]');
			const createResponsePromise = page.waitForResponse(
				(response) =>
					response.request().method() === 'POST' &&
					/\/api\/environments\/[^/]+\/projects$/.test(getPathname(response.url()))
			);
			await createButton.click();
			await expectProjectCreateResponse(createResponsePromise);

			await page.waitForURL(/\/projects\/.+/, { timeout: 10000 });

			if (createdProjectId) {
				await expect(page).toHaveURL(new RegExp(`/projects/${String(createdProjectId)}`));
			} else {
				await expect(page).toHaveURL(new RegExp(`/projects/[a-f0-9\\-]{36}`));
			}

			await expect(page.getByRole('button', { name: projectName, exact: true })).toBeVisible();

			await page.getByRole('tab', { name: 'Services 1', exact: true }).click();
			await expect.poll(() => new URL(page.url()).searchParams.get('tab')).toBe('services');

			const servicesPanel = page.getByRole('tabpanel').filter({ visible: true });
			const serviceNameWhenStopped = servicesPanel
				.getByText('nginx', {
					exact: true
				})
				.filter({ visible: true });
			const emptyServicesState = page
				.getByText('No services found for this project', {
					exact: true
				})
				.filter({ visible: true });
			await expect(serviceNameWhenStopped.or(emptyServicesState).first()).toBeVisible();

			await page.route('**/api/environments/*/projects/*/pull', async (route) => {
				projectPullRequestCount += 1;
				await route.continue();
			});

			const deployButton = page
				.getByRole('button', { name: 'Up', exact: true })
				.filter({ visible: true })
				.first();
			const deployResponsePromise = page.waitForResponse(
				(response) =>
					response.request().method() === 'POST' &&
					/\/api\/environments\/[^/]+\/projects\/[^/]+\/up$/.test(getPathname(response.url()))
			);
			await deployButton.click();

			const deployResponse = await deployResponsePromise;
			expect(deployResponse.ok()).toBe(true);
			// Don't await deployResponse.finished() here: for a chunked NDJSON stream
			// consumed via fetch().body, Playwright's network-layer finished() doesn't
			// reliably resolve even after the server closes the response and the UI
			// updates to "running" — it hangs until the test timeout. Deploy completion
			// is verified below via the running-status poll and the activity-success check.

			const projectId = createdProjectId ?? getProjectIdFromPageUrl(page.url());
			await expect
				.poll(async () => (await fetchProjectDetail(page, projectId))?.status, {
					message: 'Expected project to be running after deploy',
					timeout: 60000
				})
				.toBe('running');
			await expectProjectDeployActivitySucceeded(page, projectId, projectName);

			expect(projectPullRequestCount).toBe(0);
			await expect(page.getByRole('button', { name: 'Down', exact: true })).toBeVisible({
				timeout: 30000
			});
		} finally {
			await destroyProjectByNameViaAPI(page, projectName);
		}
	});

	test('should send selected deploy split-button options in the up request', async ({ page }) => {
		// Use a wider viewport to prevent the header's project-name area from
		// overlapping the deploy split-button trigger at the 1280px boundary.
		await page.setViewportSize({ width: 1440, height: 900 });

		const projectName = `test-deploy-options-${Date.now()}`;

		try {
			await createProjectViaUI(page, projectName);

			// Reset scroll so the floating header doesn't appear from stale scroll state
			await page.mouse.wheel(0, -100000);

			await page.route('**/api/environments/*/projects/*/up', async (route) => {
				await route.fulfill({
					status: 200,
					contentType: 'application/x-json-stream',
					body: DEPLOY_STREAM_SUCCESS
				});
			});

			const deployButtonGroup = page
				.getByRole('group')
				.filter({ has: page.getByRole('button', { name: 'Up', exact: true }) })
				.first();
			const deployMenuTrigger = deployButtonGroup.getByRole('button', {
				name: 'Open menu',
				exact: true
			});

			await expect(deployMenuTrigger).toBeVisible();

			// Open dropdown and select "Always" pull policy
			await deployMenuTrigger.click();
			const alwaysItem = page.getByRole('menuitemradio', {
				name: 'Always Always pull latest',
				exact: true
			});
			await expect(alwaysItem).toBeVisible();
			await alwaysItem.click();
			// Wait for the dropdown to fully close before reopening
			await expect(alwaysItem).not.toBeVisible();

			// Reopen dropdown and toggle "Force recreate containers"
			await deployMenuTrigger.click();
			const forceRecreateItem = page.getByRole('menuitemcheckbox', {
				name: 'Force recreate containers',
				exact: true
			});
			await expect(forceRecreateItem).toBeVisible();
			await forceRecreateItem.click();
			// Wait for the dropdown to fully close
			await expect(forceRecreateItem).not.toBeVisible();

			// Set up request listener right before clicking to minimize timeout window
			const deployRequestPromise = page.waitForRequest((request) => {
				if (request.method() !== 'POST') return false;
				return /\/api\/environments\/[^/]+\/projects\/[^/]+\/up$/.test(getPathname(request.url()));
			});

			await page.getByRole('button', { name: 'Up', exact: true }).click();

			const deployRequest = await deployRequestPromise;
			const deployRequestBody = deployRequest.postDataJSON() as Record<string, unknown> | null;

			await expect
				.poll(() => deployRequestBody, {
					message: 'Expected the deploy request body to be captured'
				})
				.not.toBeNull();

			expect(deployRequestBody).toEqual({
				pullPolicy: 'always',
				forceRecreate: true,
				removeOrphans: false,
				// Destructive, so it stays off unless explicitly toggled for this deploy.
				recreateVolumes: false
			});
		} finally {
			await destroyProjectByNameViaAPI(page, projectName);
		}
	});

	test('should send selected redeploy split-button options in the redeploy request', async ({
		page
	}) => {
		// Same wide viewport as the deploy options test so the header doesn't
		// overlap the split-button trigger at the 1280px boundary.
		await page.setViewportSize({ width: 1440, height: 900 });

		const projectName = `test-redeploy-options-${Date.now()}`;

		try {
			await createProjectViaUI(page, projectName);

			// Reset scroll so the floating header doesn't appear from stale scroll state
			await page.mouse.wheel(0, -100000);

			await page.route('**/api/environments/*/projects/*/redeploy', async (route) => {
				await route.fulfill({
					status: 200,
					contentType: 'application/x-json-stream',
					body: DEPLOY_STREAM_SUCCESS
				});
			});

			const redeployButtonGroup = page
				.getByRole('group')
				.filter({ has: page.getByRole('button', { name: 'Redeploy', exact: true }) })
				.first();
			const redeployMenuTrigger = redeployButtonGroup.getByRole('button', {
				name: 'Open menu',
				exact: true
			});

			await expect(redeployMenuTrigger).toBeVisible();

			// Open dropdown and select "Always" pull policy
			await redeployMenuTrigger.click();
			const alwaysItem = page.getByRole('menuitemradio', {
				name: 'Always Always pull latest',
				exact: true
			});
			await expect(alwaysItem).toBeVisible();
			await alwaysItem.click();
			// Wait for the dropdown to fully close before reopening
			await expect(alwaysItem).not.toBeVisible();

			// Reopen dropdown and toggle "Force recreate containers"
			await redeployMenuTrigger.click();
			const forceRecreateItem = page.getByRole('menuitemcheckbox', {
				name: 'Force recreate containers',
				exact: true
			});
			await expect(forceRecreateItem).toBeVisible();
			await forceRecreateItem.click();
			// Wait for the dropdown to fully close
			await expect(forceRecreateItem).not.toBeVisible();

			// Set up request listener right before confirming to minimize timeout window
			const redeployRequestPromise = page.waitForRequest((request) => {
				if (request.method() !== 'POST') return false;
				return /\/api\/environments\/[^/]+\/projects\/[^/]+\/redeploy$/.test(
					getPathname(request.url())
				);
			});

			await page.getByRole('button', { name: 'Redeploy', exact: true }).click();

			// Redeploy goes through a confirmation dialog before the request fires
			const dialog = page.getByRole('dialog');
			await expect(dialog).toBeVisible();
			await dialog.getByRole('button', { name: 'Redeploy', exact: true }).click();

			const redeployRequest = await redeployRequestPromise;
			const redeployRequestBody = redeployRequest.postDataJSON() as Record<string, unknown> | null;

			await expect
				.poll(() => redeployRequestBody, {
					message: 'Expected the redeploy request body to be captured'
				})
				.not.toBeNull();

			expect(redeployRequestBody).toEqual({
				pullPolicy: 'always',
				forceRecreate: true,
				removeOrphans: false,
				// Destructive, so it stays off unless explicitly toggled for this redeploy.
				recreateVolumes: false
			});
		} finally {
			await destroyProjectByNameViaAPI(page, projectName);
		}
	});

	test('should allow redeploy requests to complete after 10 seconds without client timeout', async ({
		page
	}) => {
		await page.clock.install();

		const projectName = `test-redeploy-timeout-${Date.now()}`;
		let redeployRequestStarted = false;
		let releaseRedeploy!: () => void;
		const redeployReleased = new Promise<void>((resolve) => {
			releaseRedeploy = resolve;
		});
		const redeployPathPattern = /\/api\/environments\/[^/]+\/projects\/[^/]+\/redeploy$/;

		try {
			await createProjectViaUI(page, projectName);
			await page.goto(ROUTES.page);
			await page.waitForLoadState('load');

			await page.route(
				(url) => redeployPathPattern.test(url.pathname),
				async (route) => {
					if (route.request().method() !== 'POST') {
						await route.continue();
						return;
					}

					redeployRequestStarted = true;
					await redeployReleased;
					await route.fulfill({
						status: 200,
						contentType: 'application/json',
						body: JSON.stringify({
							success: true,
							data: {
								message: 'Project redeployed successfully'
							}
						})
					});
				}
			);

			const searchInput = page.getByPlaceholder('Search…');
			await expect(searchInput).toBeVisible();
			await searchInput.fill(projectName);
			await searchInput.press('Enter');

			const row = page
				.getByRole('row')
				.filter({ has: page.getByRole('link', { name: projectName, exact: true }) })
				.first();
			await expect(row).toBeVisible();
			const menu = await openRowActionsMenu(page, row);
			const redeployMenuItem = menu.getByRole('menuitem', {
				name: 'Pull & Redeploy',
				exact: true
			});
			await expect(redeployMenuItem).toBeVisible();
			const redeployRequestPromise = page.waitForRequest(
				(request) =>
					request.method() === 'POST' && redeployPathPattern.test(getPathname(request.url()))
			);
			await redeployMenuItem.click();
			await redeployRequestPromise;

			await expect
				.poll(() => redeployRequestStarted, {
					message: 'Expected the redeploy request to be issued'
				})
				.toBe(true);

			const startedAt = await page.evaluate(() => Date.now());
			await page.clock.runFor(11_000);
			expect((await page.evaluate(() => Date.now())) - startedAt).toBeGreaterThanOrEqual(11_000);
			releaseRedeploy();

			await expect(page.getByText('Project pulled successfully.', { exact: true })).toBeVisible({
				timeout: 20_000
			});
		} finally {
			releaseRedeploy();
			await destroyProjectByNameViaAPI(page, projectName);
		}
	});

	test('should destroy the project and remove files from disk', async ({ page }) => {
		const projectName = `test-destroy-${Date.now()}`;
		let projectId = '';

		try {
			projectId = await createProjectViaUI(page, projectName);
			await destroyCurrentProjectViaUI(page);
			projectId = '';

			await expect(page.getByRole('link', { name: projectName })).not.toBeVisible();
		} finally {
			if (projectId) {
				await destroyProjectByIdViaAPI(page, projectId);
			}
		}
	});
});

test.describe('GitOps Managed Project', () => {
	test('should navigate back to gitops when opened from the git syncs page', async ({ page }) => {
		const gitOpsProject = getRequiredGitOpsProject();

		await page.goto('/environments/0/gitops');
		await page.waitForLoadState('load');

		const projectLink = page.locator(`a[href^='/projects/${gitOpsProject.id}?from=gitops']`);

		await expect(projectLink).toBeVisible();
		await projectLink.click();
		await page.waitForURL(/\/projects\/.+/, { timeout: 10000 });

		const backLink = page.getByRole('link', { name: 'Back', exact: true }).first();
		await expect(backLink).toBeVisible();
		await backLink.click();

		await page.waitForURL('/environments/0/gitops', { timeout: 10000 });
		await expect(page).toHaveURL('/environments/0/gitops');
	});

	test('should show read-only alert when project is GitOps managed', async ({ page }) => {
		const gitOpsProject = getRequiredGitOpsProject();

		await page.goto(`/projects/${gitOpsProject.id}`);
		await page.waitForLoadState('load');

		// Navigate to Configuration tab
		const configTab = page.getByRole('tab', { name: 'Configuration', exact: true });
		await configTab.click();
		await page.waitForLoadState('load');

		// Verify the GitOps read-only alert is visible (title contains "Git" and "Read-only")
		await expect(page.getByText('Git Read-only')).toBeVisible();
		await expect(
			page.getByRole('alert').filter({
				hasText:
					'This project is managed by Git. The compose file and project name cannot be edited here. Changes must be made in the connected Git repository.'
			})
		).toBeVisible();
	});

	test('should display Sync from Git button when GitOps managed', async ({ page }) => {
		const gitOpsProject = getRequiredGitOpsProject();

		await page.goto(`/projects/${gitOpsProject.id}`);
		await page.waitForLoadState('load');

		const configTab = page.getByRole('tab', { name: 'Configuration', exact: true });
		await configTab.click();
		await page.waitForLoadState('load');

		// Verify the Sync from Git button is present
		await expect(page.getByRole('button', { name: 'Sync from Git' })).toBeVisible();
	});

	test('should show last sync commit when GitOps managed', async ({ page }) => {
		const gitOpsProject = getRequiredGitOpsProject();
		const projectDetail = await fetchProjectDetail(page, gitOpsProject.id);
		expect(projectDetail?.lastSyncCommit, 'GitOps setup must record a sync commit').toBeTruthy();

		await page.goto(`/projects/${gitOpsProject.id}`);
		await page.waitForLoadState('load');

		// The commit hash should be visible somewhere on the page
		const commitHash = projectDetail!.lastSyncCommit!.substring(0, 7);
		await expect(page.getByText(commitHash)).toBeVisible();
	});

	test('should disable name editing when GitOps managed', async ({ page }) => {
		const gitOpsProject = getRequiredGitOpsProject();

		await page.goto(`/projects/${gitOpsProject.id}`);
		await page.waitForLoadState('load');

		// The name button should be disabled for GitOps-managed projects
		const nameButton = page.getByRole('button', { name: gitOpsProject.name });
		await expect(nameButton).toBeDisabled();
	});

	test('should have compose editor in read-only mode when GitOps managed', async ({ page }) => {
		const gitOpsProject = getRequiredGitOpsProject();

		await page.goto(`/projects/${gitOpsProject.id}`);
		await page.waitForLoadState('load');

		const configTab = page.getByRole('tab', { name: 'Configuration', exact: true });
		await configTab.click();
		await page.waitForLoadState('load');

		const composeContent = page
			.locator('.cm-editor')
			.filter({ visible: true })
			.first()
			.locator('.cm-content');
		await expect(composeContent).toHaveAttribute('aria-readonly', 'true');
	});

	test('should allow editing env editor when GitOps managed in classic and tree view', async ({
		page
	}) => {
		const gitOpsProject = getRequiredGitOpsProject();

		await page.goto(`/projects/${gitOpsProject.id}`);
		await page.waitForLoadState('load');

		const configTab = page.getByRole('tab', { name: 'Configuration', exact: true });
		await configTab.click();
		await page.waitForLoadState('load');

		const layoutSwitch = page.getByRole('switch', {
			name: 'Toggle workspace mode',
			exact: true
		});
		const workspaceFilesLabel = page.getByText('Workspace Files', { exact: true });
		// Projects with extra files default to tree view; start from classic.
		await expect(page.locator('.cm-editor').filter({ visible: true }).first()).toBeVisible();
		if (await workspaceFilesLabel.isVisible()) {
			await layoutSwitch.click();
			await expect(workspaceFilesLabel).not.toBeVisible();
		}

		const envEditor = page.locator('.cm-editor').filter({ visible: true }).nth(1);
		const marker = `ARCANE_E2E_${Date.now()}`;
		const envContent = envEditor.locator('.cm-content');
		await expect(envContent).toBeVisible();
		const originalEnv = await getCodeMirrorValue(envEditor);
		const updatedEnv = `${originalEnv.trimEnd()}\n${marker}=1\n`;

		await expect(envContent).not.toHaveAttribute('aria-readonly', 'true');
		await setCodeMirrorValue(envEditor, updatedEnv);
		await expect(envEditor).toContainText(marker);
		await expect(page.getByRole('button', { name: 'Save', exact: true }).first()).toBeEnabled();

		await expect(layoutSwitch).toBeVisible();

		await layoutSwitch.click();
		await page.waitForLoadState('load');
		await expect(workspaceFilesLabel).toBeVisible();

		const envFileButton = page.getByRole('button', { name: '.env' }).first();
		await expect(envFileButton).toBeVisible();
		await envFileButton.click();

		const treeEnvEditor = page.locator('.cm-editor').filter({ visible: true }).first();
		const treeEnvContent = treeEnvEditor.locator('.cm-content');
		await expect(treeEnvContent).not.toHaveAttribute('aria-readonly', 'true');
		await expect(treeEnvEditor).toContainText(marker);
	});

	test('should not show GitOps alert on Configuration tab for regular projects', async ({
		page
	}) => {
		const regularProject = realProjects.find((p) => !p.gitOpsManagedBy);
		expect(regularProject, 'No regular (non-GitOps) projects found').toBeTruthy();

		await page.goto(`/projects/${regularProject!.id}`);
		await page.waitForLoadState('load');

		const configTab = page.getByRole('tab', { name: 'Configuration', exact: true });
		await configTab.click();
		await page.waitForLoadState('load');

		// Verify no GitOps-related UI elements
		await expect(
			page.getByText(
				'This project is managed by Git. The compose file and project name cannot be edited here. Changes must be made in the connected Git repository.',
				{ exact: true }
			)
		).not.toBeVisible();
		await expect(page.getByRole('button', { name: 'Sync from Git' })).not.toBeVisible();
	});
});

test.describe('Project Detail Page', () => {
	test('should navigate back to projects by default', async ({ page }) => {
		expect(realProjects.length, 'No projects available for back navigation test').toBeGreaterThan(
			0
		);

		const firstProject = realProjects[0];
		await page.goto(`/projects/${firstProject.id || firstProject.name}`);
		await page.waitForLoadState('load');

		const backLink = page.getByRole('link', { name: 'Back', exact: true }).first();
		await expect(backLink).toBeVisible();
		await backLink.click();

		await page.waitForURL(ROUTES.page, { timeout: 10000 });
		await expect(page).toHaveURL(ROUTES.page);
	});

	test('should display project details for existing project', async ({ page }) => {
		expect(realProjects.length, 'No projects available for detail page test').toBeGreaterThan(0);

		const firstProject = realProjects[0];
		await page.goto(`/projects/${firstProject.id || firstProject.name}`);
		await page.waitForLoadState('load');

		await expect(page.getByRole('button', { name: firstProject.name, exact: true })).toBeVisible();

		await expect(
			page.getByRole('tab', {
				name: `Services ${firstProject.serviceCount ?? 0}`,
				exact: true
			})
		).toBeVisible();
		await expect(page.getByRole('tab', { name: 'Configuration', exact: true })).toBeVisible();
		await expect(page.getByRole('tab', { name: 'Logs', exact: true })).toHaveCount(0);
	});

	test('should check updates for the current project without deploying it', async ({ page }) => {
		const projectName = `test-project-update-check-${Date.now()}`;
		const projectID = await createProjectViaUI(page, projectName);
		const project = await readApiData<Project>(
			await page.request.get(`/api/environments/0/projects/${projectID}/updates`),
			`Get project ${projectID} update metadata`
		);
		expect(
			project.updateInfo?.imageRefs?.length,
			'Created project must expose its configured image'
		).toBeGreaterThan(0);

		let checkRequests = 0;
		let updaterRunRequests = 0;

		await page.route(`**/api/environments/*/updater/projects/${projectID}/check`, async (route) => {
			checkRequests += 1;
			expect(route.request().method()).toBe('POST');
			expect(route.request().postDataJSON()).toEqual({});
			await route.fulfill({
				status: 200,
				contentType: 'application/json',
				body: JSON.stringify({ success: true, data: project.updateInfo })
			});
		});

		await page.route('**/api/environments/*/updater/run', async (route) => {
			updaterRunRequests += 1;
			await route.fulfill({
				status: 200,
				contentType: 'application/json',
				body: JSON.stringify({ success: true, data: { items: [] } })
			});
		});

		await page.goto(`/projects/${projectID}`);
		await page.waitForLoadState('load');

		const clicked = await clickProjectDetailUpdateAction(page);
		expect(clicked, 'Current project detail view has no clickable update action').toBeTruthy();

		await expect.poll(() => checkRequests).toBe(1);
		expect(updaterRunRequests).toBe(0);
	});

	test('should display the configured service port host IP', async ({ page }) => {
		test.slow();

		const projectName = `test-project-port-host-${Date.now()}`;
		const composeContent = [
			'services:',
			'  web:',
			'    image: public.ecr.aws/nginx/nginx:stable-alpine',
			'    ports:',
			'      - "127.0.0.1:8081:80"',
			''
		].join('\n');
		let projectId = '';

		try {
			projectId = await createProjectViaUI(page, projectName, composeContent);
			const servicesTab = page.getByRole('tab', { name: 'Services 1', exact: true });
			await servicesTab.click();
			await expect.poll(() => new URL(page.url()).searchParams.get('tab')).toBe('services');
			await expect(servicesTab).toHaveAttribute('data-state', 'active');

			const port = page.getByText('8081:80', { exact: true }).filter({ visible: true }).first();
			await expect(port).toBeVisible();
			await port.hover();
			await expect(
				page
					.getByText('Published: 127.0.0.1:8081 → 80/tcp', { exact: true })
					.filter({ visible: true })
					.first()
			).toBeVisible();
		} finally {
			if (projectId) {
				await destroyProjectByIdViaAPI(page, projectId);
			} else {
				await destroyProjectByNameViaAPI(page, projectName);
			}
		}
	});

	test('should display configuration editors', async ({ page }) => {
		expect(realProjects.length, 'No projects available for configuration test').toBeGreaterThan(0);

		const firstProject = realProjects[0];
		await page.goto(`/projects/${firstProject.id || firstProject.name}`);
		await page.waitForLoadState('load');

		const configTab = page.getByRole('tab', { name: 'Configuration', exact: true });
		await configTab.click();

		// The project config editor supports two layouts:
		// - classic: side-by-side compose.yaml + .env panels
		// - tree view (default when the project has extra files): file list on the
		//   left and a tabbed code panel on the right
		const workspaceFilesLabel = page.getByText('Workspace Files', { exact: true });
		await expect(page.locator('.cm-editor').filter({ visible: true }).first()).toBeVisible();
		const isTreeView = await workspaceFilesLabel.isVisible();

		if (isTreeView) {
			const composeFileButton = page.getByRole('button', { name: 'compose.yaml' }).first();
			const envFileButton = page.getByRole('button', { name: '.env' }).first();

			await expect(composeFileButton).toBeVisible();
			await expect(envFileButton).toBeVisible();
			await expect(page.locator('[data-tab-key="compose"]')).toBeVisible();

			// Selecting files should open and activate their editor tabs
			await envFileButton.click();
			await expect(page.locator('[data-tab-key="env"][data-active="true"]')).toBeVisible();

			await composeFileButton.click();
			await expect(page.locator('[data-tab-key="compose"][data-active="true"]')).toBeVisible();
		} else {
			// Classic layout renders both editors at the same time.
			await expect(page.getByRole('heading', { name: 'compose.yaml' })).toBeVisible();
			await expect(page.getByRole('heading', { name: '.env' })).toBeVisible();

			// Also validate that we can switch to tree view and see the file list.
			const layoutSwitch = page.getByRole('switch', {
				name: 'Toggle workspace mode',
				exact: true
			});
			await expect(layoutSwitch).toBeVisible();
			{
				await layoutSwitch.click();
				await expect(workspaceFilesLabel).toBeVisible();

				const composeFileButton = page.getByRole('button', { name: 'compose.yaml' }).first();
				const envFileButton = page.getByRole('button', { name: '.env' }).first();

				await expect(composeFileButton).toBeVisible();
				await expect(envFileButton).toBeVisible();

				await envFileButton.click();
				await expect(page.locator('[data-tab-key="env"][data-active="true"]')).toBeVisible();
			}
		}
	});

	test('should apply the account default project editor layout', async ({ page }) => {
		const regularProject = realProjects.find((p) => !p.gitOpsManagedBy);
		expect(regularProject, 'No regular (non-GitOps) projects found').toBeTruthy();

		const originalUser = await readApiData<{
			preferences?: { defaultProjectEditorLayout?: 'auto' | 'classic' | 'tree' };
		}>(await page.request.get('/api/auth/me'), 'Get original editor preference');
		const setDefaultLayout = async (layout: 'auto' | 'classic' | 'tree') => {
			const response = await page.request.put('/api/auth/me/profile', {
				data: { preferences: { defaultProjectEditorLayout: layout } }
			});
			expect(response.ok(), `set default project editor layout to ${layout}`).toBeTruthy();
		};
		const openConfiguration = async () => {
			await page.goto(`/projects/${regularProject!.id || regularProject!.name}`);
			await page.waitForLoadState('load');
			await page.getByRole('tab', { name: 'Configuration', exact: true }).click();
		};
		const workspaceFilesLabel = page.getByText('Workspace Files', { exact: true });

		try {
			await setDefaultLayout('tree');
			await openConfiguration();
			await expect(workspaceFilesLabel).toBeVisible();
			await expect(page.locator('[data-tab-key="compose"][data-active="true"]')).toBeVisible();

			await page.goto(ROUTES.newProject);
			await page.waitForLoadState('load');
			await expect(workspaceFilesLabel).toBeVisible();

			await setDefaultLayout('classic');
			await openConfiguration();
			await expect(page.getByRole('heading', { name: 'compose.yaml' })).toBeVisible();
			await expect(workspaceFilesLabel).not.toBeVisible();

			await page.goto(ROUTES.newProject);
			await page.waitForLoadState('load');
			await expect(page.getByRole('heading', { name: 'Docker Compose File' })).toBeVisible();
			await expect(workspaceFilesLabel).not.toBeVisible();
		} finally {
			await setDefaultLayout(originalUser.preferences?.defaultProjectEditorLayout ?? 'auto');
		}
	});

	test('should enable Save when editing the initial file in restored tree view', async ({
		page
	}) => {
		const regularProject = realProjects.find((p) => !p.gitOpsManagedBy);
		expect(regularProject, 'No regular (non-GitOps) projects found').toBeTruthy();

		await page.goto(`/projects/${regularProject!.id || regularProject!.name}`);
		await page.waitForLoadState('load');

		const configTab = page.getByRole('tab', { name: 'Configuration', exact: true });
		await configTab.click();
		await page.waitForLoadState('load');

		let layoutSwitch = page.getByRole('switch', {
			name: 'Toggle workspace mode',
			exact: true
		});
		await expect(layoutSwitch).toBeVisible();

		const workspaceFilesLabel = page.getByText('Workspace Files', { exact: true });

		await expect(page.locator('.cm-editor').filter({ visible: true }).first()).toBeVisible();
		if (!(await workspaceFilesLabel.isVisible())) {
			await layoutSwitch.click();
			await expect(workspaceFilesLabel).toBeVisible();
		}

		await page.reload();
		await page.waitForLoadState('load');

		const restoredConfigTab = page.getByRole('tab', {
			name: 'Configuration',
			exact: true
		});
		if ((await restoredConfigTab.getAttribute('aria-selected')) !== 'true') {
			await restoredConfigTab.click();
			await page.waitForLoadState('load');
		}

		await expect(workspaceFilesLabel).toBeVisible();
		await expect(page.locator('[data-tab-key="compose"][data-active="true"]')).toBeVisible();

		const treeComposeEditor = page.locator('.cm-editor').filter({ visible: true }).first();
		await expect(treeComposeEditor).toBeVisible();

		const marker = `ARCANE_TREE_SAVE_${Date.now()}`;
		const originalCompose = await getCodeMirrorValue(treeComposeEditor);
		const updatedCompose = `${originalCompose.trimEnd()}\n# ${marker}\n`;
		await setCodeMirrorValue(treeComposeEditor, updatedCompose);

		const saveButton = page.getByRole('button', { name: 'Save', exact: true }).first();
		await expect(saveButton).toBeVisible();
		await expect(saveButton).toBeEnabled();

		const envFileButton = page.getByRole('button', { name: '.env' }).first();
		await expect(envFileButton).toBeVisible();

		layoutSwitch = page.getByRole('switch', {
			name: 'Toggle workspace mode',
			exact: true
		});
		await layoutSwitch.click();
		await expect(page.getByRole('heading', { name: 'compose.yaml' })).toBeVisible();
		await expect(page.getByRole('button', { name: 'Save', exact: true }).first()).toBeVisible();
		await expect(page.getByRole('button', { name: 'Save', exact: true }).first()).toBeEnabled();
	});

	test('should keep saved compose edits visible without a page refresh', async ({ page }) => {
		const projectName = `save-persist-${Date.now()}`;
		await createProjectViaUI(page, projectName);

		try {
			const configTab = page.getByRole('tab', { name: 'Configuration', exact: true });
			await configTab.click();
			await page.waitForLoadState('load');

			let composeEditor = page.locator('.cm-editor').filter({ visible: true }).first();
			await expect(composeEditor).toBeVisible();

			const marker = `ARCANE_SAVE_PERSIST_${Date.now()}`;
			const composeContent = composeEditor.locator('.cm-content').first();
			await expect(composeContent).toBeVisible();
			await composeContent.click({ position: { x: 10, y: 10 } });
			await page.keyboard.type(`# ${marker}\n`, { delay: 0 });

			const saveButtons = page.getByRole('button', { name: 'Save', exact: true });
			await expect(saveButtons.first()).toBeVisible();
			await expect(saveButtons.first()).toBeEnabled();
			await saveButtons.first().click();

			await expect(saveButtons.first()).toBeDisabled();

			composeEditor = page.locator('.cm-editor').filter({ visible: true }).first();
			await expect
				.poll(async () => getCodeMirrorValue(composeEditor), {
					message: 'expected saved compose editor content to remain visible'
				})
				.toContain(marker);

			const layoutSwitch = page.getByRole('switch', {
				name: 'Toggle workspace mode',
				exact: true
			});
			await expect(layoutSwitch).toBeVisible();
			{
				await layoutSwitch.click();
				await expect(page.locator('.cm-editor').filter({ visible: true }).first()).toBeVisible();

				composeEditor = page.locator('.cm-editor').filter({ visible: true }).first();
				await expect
					.poll(async () => getCodeMirrorValue(composeEditor), {
						message: 'expected saved compose editor content to persist across layout changes'
					})
					.toContain(marker);
			}

			await page.reload();
			await page.waitForLoadState('load');

			const restoredConfigTab = page.getByRole('tab', {
				name: 'Configuration',
				exact: true
			});
			if ((await restoredConfigTab.getAttribute('aria-selected')) !== 'true') {
				await restoredConfigTab.click();
				await page.waitForLoadState('load');
			}

			composeEditor = page.locator('.cm-editor').filter({ visible: true }).first();
			await expect(composeEditor).toBeVisible();
			await expect
				.poll(async () => getCodeMirrorValue(composeEditor), {
					message: 'expected saved compose editor content to persist after reload'
				})
				.toContain(marker);
		} finally {
			await destroyProjectByNameViaAPI(page, projectName);
		}
	});

	test('should show retained logs for a stopped project and reload them on refresh', async ({
		page
	}) => {
		test.slow();

		const projectName = `test-logs-stopped-${Date.now()}`;
		const logViewer = page.getByRole('log');
		let projectId = '';
		let marker = '';

		try {
			const created = await createExitedMarkerProject(page, projectName);
			projectId = created.projectId;
			marker = created.marker;

			let logSocketCount = 0;
			page.on('websocket', (ws) => {
				if (/ws\/projects\/.+\/logs/.test(ws.url())) {
					logSocketCount += 1;
				}
			});

			await page.goto(`/projects/${projectId}?tab=services`);
			await page.waitForLoadState('load');
			await expect(page.getByText('Real-time project logs', { exact: true })).toBeVisible();
			await expect(logViewer).toHaveAttribute('data-is-streaming', 'false');

			const startButton = page
				.getByRole('button', { name: 'Start', exact: true })
				.filter({ visible: true })
				.first();
			const stopButton = page
				.getByRole('button', { name: 'Stop', exact: true })
				.filter({ visible: true })
				.first();

			await startButton.click();
			await expect(logViewer).toHaveAttribute('data-is-streaming', 'true');
			await expect(logViewer).toContainText(marker, { timeout: 20000 });
			await expect(logViewer.getByText(marker).filter({ visible: true })).toHaveCount(1);

			await page.getByTitle('Refresh').click();
			await expect(logViewer).toContainText(marker, { timeout: 20000 });
			await expect(logViewer.getByText(marker).filter({ visible: true })).toHaveCount(1);

			await stopButton.click();
			await expect(logViewer).toHaveAttribute('data-is-streaming', 'false');
			await expect(logViewer).toContainText(marker);

			const socketsAfterStop = logSocketCount;
			await page.waitForTimeout(2000);
			expect(logSocketCount, 'Manual stop must not resubscribe to the log stream').toBe(
				socketsAfterStop
			);
		} finally {
			await destroyProjectByNameViaAPI(page, projectName);
		}
	});

	test('should apply the auto-start preference to stopped projects', async ({ page }) => {
		test.slow();

		const projectName = `test-log-autostart-${Date.now()}`;
		let projectId = '';

		try {
			const created = await createExitedMarkerProject(page, projectName);
			projectId = created.projectId;

			await page.goto(`/projects/${projectId}?tab=services`);
			await page.waitForLoadState('load');

			const logViewer = page.getByRole('log');
			await page.waitForTimeout(2000);
			await expect(
				logViewer,
				'With auto-start disabled the viewer must wait for Start'
			).toHaveAttribute('data-is-streaming', 'false');

			// PersistedState JSON-serializes values, so the stored form is the quoted string "true".
			await page.evaluate(() =>
				localStorage.setItem('arcane_log_auto_start', JSON.stringify('true'))
			);
			await page.reload();
			await page.waitForLoadState('load');

			const reloadedViewer = page.getByRole('log');
			await expect(reloadedViewer).toHaveAttribute('data-is-streaming', 'true', {
				timeout: 15000
			});
			await expect(reloadedViewer).toContainText(created.marker, { timeout: 20000 });
		} finally {
			await destroyProjectByIdViaAPI(page, projectId);
		}
	});

	test('should surface a project log stream connection failure inline', async ({ page }) => {
		expect(
			realProjects.length,
			'No projects available for log stream failure test'
		).toBeGreaterThan(0);

		const targetProject = realProjects[0];
		await page.routeWebSocket('**/api/environments/*/ws/projects/*/logs**', (ws) => {
			void ws.close({ code: 1013, reason: 'forced failure' });
		});

		await page.goto(`/projects/${targetProject.id || targetProject.name}?tab=services`);
		await page.waitForLoadState('load');

		await page
			.getByRole('button', { name: 'Start', exact: true })
			.filter({ visible: true })
			.first()
			.click();

		await expect(
			page
				.getByText('Failed to connect to Project log stream')
				.or(page.getByText('Connection to Project log stream lost'))
				.or(page.getByText('Project log stream was closed by server'))
				.first()
		).toBeVisible({ timeout: 20000 });
	});
});