Bug fixes and stability improvements (#815)

* fix(copilot): correct tool.execution_complete event handling

The CopilotProvider was using incorrect event type and data structure
for tool execution completion events from the @github/copilot-sdk,
causing tool call outputs to be empty.

Changes:
- Update event type from 'tool.execution_end' to 'tool.execution_complete'
- Fix data structure to use nested result.content instead of flat result
- Fix error structure to use error.message instead of flat error
- Add success field to match SDK event structure
- Add tests for empty and missing result handling

This aligns with the official @github/copilot-sdk v0.1.16 types
defined in session-events.d.ts.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* test(copilot): add edge case test for error with code field

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* refactor(copilot): improve error handling and code quality

Code review improvements:
- Extract magic string '[ERROR]' to TOOL_ERROR_PREFIX constant
- Add null-safe error handling with direct error variable assignment
- Include error codes in error messages for better debugging
- Add JSDoc documentation for tool.execution_complete handler
- Update tests to verify error codes are displayed
- Add missing tool_use_id assertion in error test

These changes improve:
- Code maintainability (no magic strings)
- Debugging experience (error codes now visible)
- Type safety (explicit null checks)
- Test coverage (verify error code formatting)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Changes from fix/bug-fixes-1-0

* test(copilot): add edge case test for error with code field

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Changes from fix/bug-fixes-1-0

* fix: Handle detached HEAD state in worktree discovery and recovery

* fix: Remove unused isDevServerStarting prop and md: breakpoint classes

* fix: Add missing dependency and sanitize persisted cache data

* feat: Ensure NODE_ENV is set to test in vitest configs

* feat: Configure Playwright to run only E2E tests

* fix: Improve PR tracking and dev server lifecycle management

* feat: Add settings-based defaults for planning mode, model config, and custom providers. Fixes #816

* feat: Add worktree and branch selector to graph view

* fix: Add timeout and error handling for worktree HEAD ref resolution

* fix: use absolute icon path and place icon outside asar on Linux

The hicolor icon theme index only lists sizes up to 512x512, so an icon
installed only at 1024x1024 is invisible to GNOME/KDE's theme resolver,
causing both the app launcher and taskbar to show a generic icon.
Additionally, BrowserWindow.icon cannot be read by the window manager
when the file is inside app.asar.

- extraResources: copy logo_larger.png to resources/ (outside asar) so
  it lands at /opt/Automaker/resources/logo_larger.png on install
- linux.desktop.Icon: set to the absolute resources path, bypassing the
  hicolor theme lookup and its size constraints entirely
- icon-manager.ts: on Linux production use process.resourcesPath so
  BrowserWindow receives a real filesystem path the WM can read directly

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: use linux.desktop.entry for custom desktop Icon field

electron-builder v26 rejects arbitrary keys in linux.desktop — the
correct schema wraps custom .desktop overrides inside desktop.entry.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: set desktop name on Linux so taskbar uses the correct app icon

Without app.setDesktopName(), the window manager cannot associate the
running Electron process with automaker.desktop. GNOME/KDE fall back to
_NET_WM_ICON which defaults to Electron's own bundled icon.

Calling app.setDesktopName('automaker.desktop') before any window is
created sets the _GTK_APPLICATION_ID hint and XDG app_id so the WM
picks up the desktop entry's Icon for the taskbar.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix: memory and context views mobile friendly (#818)

* Changes from fix/memory-and-context-mobile-friendly

* fix: Improve file extension detection and add path traversal protection

* refactor: Extract file extension utilities and add path traversal guards

Code review improvements:
- Extract isMarkdownFilename and isImageFilename to shared image-utils.ts
- Remove duplicated code from context-view.tsx and memory-view.tsx
- Add path traversal guard for context fixture utilities (matching memory)
- Add 7 new tests for context fixture path traversal protection
- Total 61 tests pass

Addresses code review feedback from PR #813

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* test: Add e2e tests for profiles crud and board background persistence

* Update apps/ui/playwright.config.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* fix: Add robust test navigation handling and file filtering

* fix: Format NODE_OPTIONS configuration on single line

* test: Update profiles and board background persistence tests

* test: Replace iPhone 13 Pro with Pixel 5 for mobile test consistency

* Update apps/ui/src/components/views/context-view.tsx

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* chore: Remove test project directory

* feat: Filter context files by type and improve mobile menu visibility

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* fix: Improve test reliability and localhost handling

* chore: Use explicit TEST_USE_EXTERNAL_BACKEND env var for server cleanup

* feat: Add E2E/CI mock mode for provider factory and auth verification

* feat: Add remoteBranch parameter to pull and rebase operations

* chore: Enhance E2E testing setup with worker isolation and auth state management

- Updated .gitignore to include worker-specific test fixtures.
- Modified e2e-tests.yml to implement test sharding for improved CI performance.
- Refactored global setup to authenticate once and save session state for reuse across tests.
- Introduced worker-isolated fixture paths to prevent conflicts during parallel test execution.
- Improved test navigation and loading handling for better reliability.
- Updated various test files to utilize new auth state management and fixture paths.

* fix: Update Playwright configuration and improve test reliability

- Increased the number of workers in Playwright configuration for better parallelism in CI environments.
- Enhanced the board background persistence test to ensure dropdown stability by waiting for the list to populate before interaction, improving test reliability.

* chore: Simplify E2E test configuration and enhance mock implementations

- Updated e2e-tests.yml to run tests in a single shard for streamlined CI execution.
- Enhanced unit tests for worktree list handling by introducing a mock for execGitCommand, improving test reliability and coverage.
- Refactored setup functions to better manage command mocks for git operations in tests.
- Improved error handling in mkdirSafe function to account for undefined stats in certain environments.

* refactor: Improve test configurations and enhance error handling

- Updated Playwright configuration to clear VITE_SERVER_URL, ensuring the frontend uses the Vite proxy and preventing cookie domain mismatches.
- Enhanced MergeRebaseDialog logic to normalize selectedBranch for better handling of various ref formats.
- Improved global setup with a more robust backend health check, throwing an error if the backend is not healthy after retries.
- Refactored project creation tests to handle file existence checks more reliably.
- Added error handling for missing E2E source fixtures to guide setup process.
- Enhanced memory navigation to handle sandbox dialog visibility more effectively.

* refactor: Enhance Git command execution and improve test configurations

- Updated Git command execution to merge environment paths correctly, ensuring proper command execution context.
- Refactored the Git initialization process to handle errors more gracefully and ensure user configuration is set before creating the initial commit.
- Improved test configurations by updating Playwright test identifiers for better clarity and consistency across different project states.
- Enhanced cleanup functions in tests to handle directory removal more robustly, preventing errors during test execution.

* fix: Resolve React hooks errors from duplicate instances in dependency tree

* style: Format alias configuration for improved readability

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: DhanushSantosh <dhanushsantoshs05@gmail.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
This commit is contained in:
gsxdsm
2026-02-27 17:03:29 -08:00
committed by GitHub
parent 70d400793b
commit 0196911d59
234 changed files with 15881 additions and 2916 deletions

View File

@@ -282,9 +282,25 @@ export async function apiListBranches(
*/
export async function authenticateWithApiKey(page: Page, apiKey: string): Promise<boolean> {
try {
// Fast path: check if we already have a valid session (from global setup storageState)
try {
const statusRes = await page.request.get(`${API_BASE_URL}/api/auth/status`, {
timeout: 3000,
});
const statusJson = (await statusRes.json().catch(() => null)) as {
authenticated?: boolean;
} | null;
if (statusJson?.authenticated === true) {
return true;
}
} catch {
// Status check failed, proceed with full auth
}
// Ensure the backend is up before attempting login (especially in local runs where
// the backend may be started separately from Playwright).
const start = Date.now();
let authBackoff = 250;
while (Date.now() - start < 15000) {
try {
const health = await page.request.get(`${API_BASE_URL}/api/health`, {
@@ -294,7 +310,8 @@ export async function authenticateWithApiKey(page: Page, apiKey: string): Promis
} catch {
// Retry
}
await page.waitForTimeout(250);
await page.waitForTimeout(authBackoff);
authBackoff = Math.min(authBackoff * 2, 2000);
}
// Ensure we're on a page (needed for cookies to work)
@@ -322,34 +339,22 @@ export async function authenticateWithApiKey(page: Page, apiKey: string): Promis
{
name: 'automaker_session',
value: response.token,
domain: 'localhost',
domain: '127.0.0.1',
path: '/',
httpOnly: true,
sameSite: 'Lax',
},
]);
// Verify the session is working by polling auth status
// This replaces arbitrary timeout with actual condition check
let attempts = 0;
const maxAttempts = 10;
while (attempts < maxAttempts) {
const statusRes = await page.request.get(`${API_BASE_URL}/api/auth/status`, {
timeout: 5000,
});
const statusResponse = (await statusRes.json().catch(() => null)) as {
authenticated?: boolean;
} | null;
// Single verification check (no polling loop needed)
const verifyRes = await page.request.get(`${API_BASE_URL}/api/auth/status`, {
timeout: 5000,
});
const verifyJson = (await verifyRes.json().catch(() => null)) as {
authenticated?: boolean;
} | null;
if (statusResponse?.authenticated === true) {
return true;
}
attempts++;
// Use a very short wait between polling attempts (this is acceptable for polling)
await page.waitForTimeout(50);
}
return false;
return verifyJson?.authenticated === true;
}
return false;
@@ -394,12 +399,14 @@ export async function waitForBackendHealth(
checkIntervalMs = 500
): Promise<void> {
const startTime = Date.now();
let backoff = checkIntervalMs;
while (Date.now() - startTime < maxWaitMs) {
if (await checkBackendHealth(page, checkIntervalMs)) {
if (await checkBackendHealth(page, Math.min(backoff, 3000))) {
return;
}
await page.waitForTimeout(checkIntervalMs);
await page.waitForTimeout(backoff);
backoff = Math.min(backoff * 2, 2000);
}
throw new Error(

View File

@@ -0,0 +1,50 @@
/**
* Cleanup leftover E2E test artifact directories.
* Used by globalSetup (start of run) and globalTeardown (end of run) to ensure
* test/board-bg-test-*, test/edit-feature-test-*, etc. are removed.
*
* Per-spec afterAll hooks clean up their own dirs, but when workers crash,
* runs are aborted, or afterAll fails, dirs can be left behind.
*/
import * as fs from 'fs';
import * as path from 'path';
import { getWorkspaceRoot } from './core/safe-paths';
/** Prefixes used by createTempDirPath() across all spec files */
const TEST_DIR_PREFIXES = [
'board-bg-test',
'edit-feature-test',
'open-project-test',
'opus-thinking-level-none',
'project-creation-test',
'agent-session-test',
'running-task-display-test',
'planning-mode-verification-test',
'list-view-priority-test',
'skip-tests-toggle-test',
'manual-review-test',
'feature-backlog-test',
'agent-output-modal-responsive',
] as const;
export function cleanupLeftoverTestDirs(): void {
const testBase = path.join(getWorkspaceRoot(), 'test');
if (!fs.existsSync(testBase)) return;
const entries = fs.readdirSync(testBase, { withFileTypes: true });
for (const prefix of TEST_DIR_PREFIXES) {
const pattern = prefix + '-';
for (const entry of entries) {
if (entry.isDirectory() && entry.name.startsWith(pattern)) {
const dirPath = path.join(testBase, entry.name);
try {
fs.rmSync(dirPath, { recursive: true, force: true });
console.log('[Cleanup] Removed', entry.name);
} catch (err) {
console.warn('[Cleanup] Failed to remove', dirPath, err);
}
}
}
}
}

View File

@@ -0,0 +1,282 @@
/**
* Responsive testing utilities for modal components
* These utilities help test responsive behavior across different screen sizes
*/
import { Page, expect } from '@playwright/test';
import { waitForElement } from '../core/waiting';
/**
* Wait for viewport resize to stabilize by polling element dimensions
* until they stop changing. Much more reliable than a fixed timeout.
*/
async function waitForLayoutStable(page: Page, testId: string, timeout = 2000): Promise<void> {
await page.waitForFunction(
({ testId: tid, timeout: t }) => {
return new Promise<boolean>((resolve) => {
const el = document.querySelector(`[data-testid="${tid}"]`);
if (!el) {
resolve(true);
return;
}
let lastWidth = el.clientWidth;
let lastHeight = el.clientHeight;
let stableCount = 0;
const interval = setInterval(() => {
const w = el.clientWidth;
const h = el.clientHeight;
if (w === lastWidth && h === lastHeight) {
stableCount++;
if (stableCount >= 3) {
clearInterval(interval);
resolve(true);
}
} else {
stableCount = 0;
lastWidth = w;
lastHeight = h;
}
}, 50);
setTimeout(() => {
clearInterval(interval);
resolve(true);
}, t);
});
},
{ testId, timeout },
{ timeout: timeout + 500 }
);
}
/**
* Viewport sizes for different device types
*/
export const VIEWPORTS = {
mobile: { width: 375, height: 667 },
mobileLarge: { width: 414, height: 896 },
tablet: { width: 768, height: 1024 },
tabletLarge: { width: 1024, height: 1366 },
desktop: { width: 1280, height: 720 },
desktopLarge: { width: 1920, height: 1080 },
} as const;
/**
* Expected responsive classes for AgentOutputModal
*/
export const EXPECTED_CLASSES = {
mobile: {
width: ['w-full', 'max-w-[calc(100%-2rem)]'],
height: ['max-h-[85dvh]'],
},
small: {
width: ['sm:w-[60vw]', 'sm:max-w-[60vw]'],
height: ['sm:max-h-[80vh]'],
},
tablet: {
width: ['md:w-[90vw]', 'md:max-w-[1200px]'],
height: ['md:max-h-[85vh]'],
},
} as const;
/**
* Get the computed width of the modal in pixels
*/
export async function getModalWidth(page: Page): Promise<number> {
const modal = page.locator('[data-testid="agent-output-modal"]');
return await modal.evaluate((el) => el.offsetWidth);
}
/**
* Get the computed height of the modal in pixels
*/
export async function getModalHeight(page: Page): Promise<number> {
const modal = page.locator('[data-testid="agent-output-modal"]');
return await modal.evaluate((el) => el.offsetHeight);
}
/**
* Get the computed style properties of the modal
*/
export async function getModalComputedStyle(page: Page): Promise<{
width: string;
height: string;
maxWidth: string;
maxHeight: string;
}> {
const modal = page.locator('[data-testid="agent-output-modal"]');
return await modal.evaluate((el) => {
const style = window.getComputedStyle(el);
return {
width: style.width,
height: style.height,
maxWidth: style.maxWidth,
maxHeight: style.maxHeight,
};
});
}
/**
* Check if modal has expected classes for a specific viewport
*/
export async function expectModalResponsiveClasses(
page: Page,
viewport: keyof typeof VIEWPORTS,
expectedClasses: string[]
): Promise<void> {
const modal = page.locator('[data-testid="agent-output-modal"]');
for (const className of expectedClasses) {
await expect(modal).toContainClass(className);
}
}
/**
* Test modal width across different viewports
*/
export async function testModalWidthAcrossViewports(
page: Page,
viewports: Array<keyof typeof VIEWPORTS>
): Promise<void> {
for (const viewport of viewports) {
const size = VIEWPORTS[viewport];
// Set viewport
await page.setViewportSize(size);
// Wait for any responsive transitions
await waitForLayoutStable(page, 'agent-output-modal');
// Get modal width
const modalWidth = await getModalWidth(page);
const viewportWidth = size.width;
// Check constraints based on viewport
if (viewport === 'mobile' || viewport === 'mobileLarge') {
// Mobile: should be close to full width with 2rem margins
expect(modalWidth).toBeGreaterThan(viewportWidth - 40);
expect(modalWidth).toBeLessThan(viewportWidth - 20);
} else if (viewport === 'tablet' || viewport === 'tabletLarge') {
// Tablet: should be around 90vw but not exceed max-w-[1200px]
const expected90vw = Math.floor(viewportWidth * 0.9);
expect(modalWidth).toBeLessThanOrEqual(expected90vw);
expect(modalWidth).toBeLessThanOrEqual(1200);
} else if (viewport === 'desktop' || viewport === 'desktopLarge') {
// Desktop: should be bounded by viewport and max-width constraints
const expectedMaxWidth = Math.floor(viewportWidth * 0.9);
const modalHeight = await getModalHeight(page);
const viewportHeight = size.height;
const expectedMaxHeight = Math.floor(viewportHeight * 0.9);
expect(modalWidth).toBeLessThanOrEqual(expectedMaxWidth);
expect(modalWidth).toBeLessThanOrEqual(1200);
expect(modalWidth).toBeGreaterThan(0);
expect(modalHeight).toBeLessThanOrEqual(expectedMaxHeight);
expect(modalHeight).toBeGreaterThan(0);
}
}
}
/**
* Test modal height across different viewports
*/
export async function testModalHeightAcrossViewports(
page: Page,
viewports: Array<keyof typeof VIEWPORTS>
): Promise<void> {
for (const viewport of viewports) {
const size = VIEWPORTS[viewport];
// Set viewport
await page.setViewportSize(size);
// Wait for any responsive transitions
await waitForLayoutStable(page, 'agent-output-modal');
// Get modal height
const modalHeight = await getModalHeight(page);
const viewportHeight = size.height;
// Check constraints based on viewport
if (viewport === 'mobile' || viewport === 'mobileLarge') {
// Mobile: should be max-h-[85dvh]
const expected85dvh = Math.floor(viewportHeight * 0.85);
expect(modalHeight).toBeLessThanOrEqual(expected85dvh);
} else if (viewport === 'tablet' || viewport === 'tabletLarge') {
// Tablet: should be max-h-[85vh]
const expected85vh = Math.floor(viewportHeight * 0.85);
expect(modalHeight).toBeLessThanOrEqual(expected85vh);
}
}
}
/**
* Test modal responsiveness during resize
*/
export async function testModalResponsiveResize(
page: Page,
fromViewport: keyof typeof VIEWPORTS,
toViewport: keyof typeof VIEWPORTS
): Promise<void> {
// Set initial viewport
await page.setViewportSize(VIEWPORTS[fromViewport]);
await waitForLayoutStable(page, 'agent-output-modal');
// Get initial modal dimensions (used for comparison context)
await getModalComputedStyle(page);
// Resize to new viewport
await page.setViewportSize(VIEWPORTS[toViewport]);
await waitForLayoutStable(page, 'agent-output-modal');
// Get new modal dimensions
const newDimensions = await getModalComputedStyle(page);
// Verify dimensions changed appropriately using resolved pixel values
const toSize = VIEWPORTS[toViewport];
if (fromViewport === 'mobile' && toViewport === 'tablet') {
const widthPx = parseFloat(newDimensions.width);
const maxWidthPx = parseFloat(newDimensions.maxWidth);
const expected90vw = toSize.width * 0.9;
expect(widthPx).toBeLessThanOrEqual(expected90vw + 2);
expect(maxWidthPx).toBeGreaterThanOrEqual(1200);
} else if (fromViewport === 'tablet' && toViewport === 'mobile') {
const widthPx = parseFloat(newDimensions.width);
const maxWidthPx = parseFloat(newDimensions.maxWidth);
expect(widthPx).toBeGreaterThan(toSize.width - 60);
expect(maxWidthPx).toBeLessThan(1200);
}
}
/**
* Verify modal maintains functionality across viewports
*/
export async function verifyModalFunctionalityAcrossViewports(
page: Page,
viewports: Array<keyof typeof VIEWPORTS>
): Promise<void> {
for (const viewport of viewports) {
const size = VIEWPORTS[viewport];
// Set viewport
await page.setViewportSize(size);
await waitForLayoutStable(page, 'agent-output-modal');
// Verify modal is visible
const modal = await waitForElement(page, 'agent-output-modal');
await expect(modal).toBeVisible();
// Verify modal content is visible
const description = page.locator('[data-testid="agent-output-description"]');
await expect(description).toBeVisible();
// Verify view mode buttons are visible
if (
viewport === 'tablet' ||
viewport === 'tabletLarge' ||
viewport === 'desktop' ||
viewport === 'desktopLarge'
) {
const logsButton = page.getByTestId('view-mode-parsed');
await expect(logsButton).toBeVisible();
}
}
}

View File

@@ -12,16 +12,16 @@
* Uses TEST_SERVER_PORT env var (default 3108) for test runs
*/
export const API_BASE_URL = process.env.TEST_SERVER_PORT
? `http://localhost:${process.env.TEST_SERVER_PORT}`
: 'http://localhost:3108';
? `http://127.0.0.1:${process.env.TEST_SERVER_PORT}`
: 'http://127.0.0.1:3108';
/**
* Base URL for the frontend web server
* Uses TEST_PORT env var (default 3107) for test runs
*/
export const WEB_BASE_URL = process.env.TEST_PORT
? `http://localhost:${process.env.TEST_PORT}`
: 'http://localhost:3107';
? `http://127.0.0.1:${process.env.TEST_PORT}`
: 'http://127.0.0.1:3107';
/**
* API endpoints for worktree operations

View File

@@ -70,21 +70,29 @@ const APP_CONTENT_SELECTOR =
/**
* Handle login screen if it appears after navigation
* Returns true if login was handled, false if no login screen was found
*
* Optimized: uses a short timeout (3s) since we're pre-authenticated via storageState.
* Login screens should only appear in exceptional cases (session expired, etc.)
*/
export async function handleLoginScreenIfPresent(page: Page): Promise<boolean> {
// Check for login screen by waiting for either login input or app-container to be visible
// Use data-testid selector (preferred) with fallback to the old selector
// Short timeout: with storageState auth, login should rarely appear
const maxWaitMs = 3000;
const appContent = page.locator(APP_CONTENT_SELECTOR);
const loginInput = page
.locator('[data-testid="login-api-key-input"], input[type="password"][placeholder*="API key"]')
.first();
const appContent = page.locator(APP_CONTENT_SELECTOR);
const loggedOutPage = page.getByRole('heading', { name: /logged out/i });
const goToLoginButton = page.locator('button:has-text("Go to login")');
const maxWaitMs = 15000;
// Race between login screen, logged-out page, a delayed redirect to /login, and actual content
// App content check is first in the array to win ties (most common case)
const result = await Promise.race([
appContent
.first()
.waitFor({ state: 'visible', timeout: maxWaitMs })
.then(() => 'app-content' as const)
.catch(() => null),
page
.waitForURL((url) => url.pathname.includes('/login'), { timeout: maxWaitMs })
.then(() => 'login-redirect' as const)
@@ -97,17 +105,17 @@ export async function handleLoginScreenIfPresent(page: Page): Promise<boolean> {
.waitFor({ state: 'visible', timeout: maxWaitMs })
.then(() => 'logged-out' as const)
.catch(() => null),
appContent
.first()
.waitFor({ state: 'visible', timeout: maxWaitMs })
.then(() => 'app-content' as const)
.catch(() => null),
]);
// Happy path: app content loaded, no login needed
if (result === 'app-content' || result === null) {
return false;
}
// Handle logged-out page - click "Go to login" button and then login
if (result === 'logged-out') {
await goToLoginButton.click();
await page.waitForLoadState('load');
await page.waitForLoadState('domcontentloaded');
// Now handle the login screen
return handleLoginScreenIfPresent(page);
}
@@ -115,12 +123,12 @@ export async function handleLoginScreenIfPresent(page: Page): Promise<boolean> {
const loginVisible = result === 'login-redirect' || result === 'login-input';
if (loginVisible) {
// Wait for login input to be visible if we were redirected
await loginInput.waitFor({ state: 'visible', timeout: 5000 }).catch(() => {});
const apiKey = process.env.AUTOMAKER_API_KEY || 'test-api-key-for-e2e-tests';
await loginInput.fill(apiKey);
// Wait a moment for the button to become enabled
await page.waitForTimeout(100);
// Wait for button to be enabled (it's disabled when input is empty)
const loginButton = page
.locator('[data-testid="login-submit-button"], button:has-text("Login")')
@@ -134,8 +142,7 @@ export async function handleLoginScreenIfPresent(page: Page): Promise<boolean> {
appContent.first().waitFor({ state: 'visible', timeout: 15000 }),
]).catch(() => {});
// Wait for page to load
await page.waitForLoadState('load');
await page.waitForLoadState('domcontentloaded');
return true;
}
@@ -160,15 +167,17 @@ export async function focusOnInput(page: Page, testId: string): Promise<void> {
/**
* Close any open dialog by pressing Escape
* Waits for dialog to be removed from DOM rather than using arbitrary timeout
* Waits for dialog overlay to disappear. Use shorter timeout when no dialog expected (e.g. navigation).
* @param options.timeout - Max wait for dialog to close (default 5000). Use ~1500 when dialog may not exist.
*/
export async function closeDialogWithEscape(page: Page): Promise<void> {
export async function closeDialogWithEscape(
page: Page,
options?: { timeout?: number }
): Promise<void> {
await page.keyboard.press('Escape');
// Wait for any dialog overlay to disappear
await page
.locator('[data-radix-dialog-overlay], [role="dialog"]')
.waitFor({ state: 'hidden', timeout: 5000 })
.catch(() => {
// Dialog may have already closed or not exist
});
const timeout = options?.timeout ?? 5000;
const openDialog = page.locator('[role="dialog"][data-state="open"]').first();
if ((await openDialog.count()) > 0) {
await openDialog.waitFor({ state: 'hidden', timeout }).catch(() => {});
}
}

View File

@@ -0,0 +1,54 @@
/**
* Safe path helpers for E2E tests
* Ensures test project paths never point at the main repo, avoiding git branch/merge side effects.
*/
import * as os from 'os';
import * as path from 'path';
/**
* Resolve the workspace root - handle both running from apps/ui and from monorepo root
*/
export function getWorkspaceRoot(): string {
const cwd = process.cwd();
if (cwd.includes('apps/ui')) {
return path.resolve(cwd, '../..');
}
return cwd;
}
/** Base directory for all test-only project paths (under workspace root) */
export const TEST_BASE_DIR = path.join(getWorkspaceRoot(), 'test');
/**
* Assert that a project path is safe for E2E tests (never the main repo root).
* Safe paths must be either:
* - Under workspace root's test/ directory (e.g. test/fixtures/projectA, test/open-project-test-xxx)
* - Under the OS temp directory (e.g. /tmp/automaker-e2e-workspace)
*
* This prevents tests from checking out or modifying branches in the main project's git repo.
*
* @throws Error if path is the workspace root or outside allowed test directories
*/
export function assertSafeProjectPath(projectPath: string): void {
const normalized = path.resolve(projectPath);
const workspaceRoot = path.resolve(getWorkspaceRoot());
const testBase = path.resolve(TEST_BASE_DIR);
const tmpDir = path.resolve(os.tmpdir());
if (normalized === workspaceRoot) {
throw new Error(
`E2E project path must not be the workspace root (${workspaceRoot}). ` +
'Use a path under test/ or os.tmpdir() to avoid affecting the main project git state.'
);
}
const underTest = normalized.startsWith(testBase + path.sep) || normalized === testBase;
const underTmp = normalized.startsWith(tmpDir + path.sep) || normalized === tmpDir;
if (!underTest && !underTmp) {
throw new Error(
`E2E project path must be under test/ or temp directory to avoid affecting main project git. ` +
`Got: ${normalized} (workspace root: ${workspaceRoot})`
);
}
}

View File

@@ -9,6 +9,7 @@ import { exec } from 'child_process';
import { promisify } from 'util';
import { Page } from '@playwright/test';
import { sanitizeBranchName, TIMEOUTS } from '../core/constants';
import { getWorkspaceRoot } from '../core/safe-paths';
const execAsync = promisify(exec);
@@ -35,19 +36,8 @@ export interface FeatureData {
// ============================================================================
/**
* Get the workspace root directory (internal use only)
* Note: Also exported from project/fixtures.ts for broader use
*/
function getWorkspaceRoot(): string {
const cwd = process.cwd();
if (cwd.includes('apps/ui')) {
return path.resolve(cwd, '../..');
}
return cwd;
}
/**
* Create a unique temp directory path for tests
* Create a unique temp directory path for tests (always under workspace test/ dir).
* Git operations in these dirs never affect the main project.
*/
export function createTempDirPath(prefix: string = 'temp-worktree-tests'): string {
const uniqueId = `${process.pid}-${Math.random().toString(36).substring(2, 9)}`;
@@ -158,11 +148,45 @@ export async function cleanupTestRepo(repoPath: string): Promise<void> {
}
/**
* Cleanup a temp directory and all its contents
* Recursively remove directory contents then the directory (avoids ENOTEMPTY on some systems)
*/
function rmDirRecursive(dir: string): void {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
rmDirRecursive(fullPath);
fs.rmdirSync(fullPath);
} else {
fs.unlinkSync(fullPath);
}
}
}
/**
* Cleanup a temp directory and all its contents.
* Tries rmSync first; on ENOTEMPTY (e.g. macOS with git worktrees) falls back to recursive delete.
*/
export function cleanupTempDir(tempDir: string): void {
if (fs.existsSync(tempDir)) {
if (!fs.existsSync(tempDir)) return;
try {
fs.rmSync(tempDir, { recursive: true, force: true });
} catch (err) {
const code = (err as NodeJS.ErrnoException)?.code;
if (code === 'ENOENT') {
// Directory already removed, nothing to do
} else if (code === 'ENOTEMPTY' || code === 'EPERM' || code === 'EBUSY') {
rmDirRecursive(tempDir);
try {
fs.rmdirSync(tempDir);
} catch (e2) {
if ((e2 as NodeJS.ErrnoException)?.code !== 'ENOENT') {
throw e2;
}
}
} else {
throw err;
}
}
}

View File

@@ -0,0 +1,23 @@
import * as os from 'os';
import * as path from 'path';
import * as fs from 'fs';
/**
* Create a deterministic temp directory path for a test suite.
* The directory is NOT created on disk — call fs.mkdirSync in beforeAll.
*/
export function createTempDirPath(prefix: string): string {
return path.join(os.tmpdir(), `automaker-test-${prefix}-${process.pid}`);
}
/**
* Remove a temp directory and all its contents.
* Silently ignores errors (e.g. directory already removed).
*/
export function cleanupTempDir(dirPath: string): void {
try {
fs.rmSync(dirPath, { recursive: true, force: true });
} catch {
// Ignore cleanup errors
}
}

View File

@@ -5,6 +5,7 @@ export * from './core/elements';
export * from './core/interactions';
export * from './core/waiting';
export * from './core/constants';
export * from './core/safe-paths';
// API utilities
export * from './api/client';

View File

@@ -1,7 +1,7 @@
import { Page } from '@playwright/test';
import { clickElement } from '../core/interactions';
import { clickElement, closeDialogWithEscape } from '../core/interactions';
import { handleLoginScreenIfPresent } from '../core/interactions';
import { waitForElement, waitForSplashScreenToDisappear } from '../core/waiting';
import { waitForElement } from '../core/waiting';
import { authenticateForTests } from '../api/client';
/**
@@ -9,19 +9,12 @@ import { authenticateForTests } from '../api/client';
* Note: Navigates directly to /board since index route shows WelcomeView
*/
export async function navigateToBoard(page: Page): Promise<void> {
// Authenticate before navigating
// Authenticate before navigating (fast-path: skips if already authed via storageState)
await authenticateForTests(page);
// Wait for any pending navigation to complete before starting a new one
await page.waitForLoadState('domcontentloaded').catch(() => {});
await page.waitForTimeout(100);
// Navigate directly to /board route
await page.goto('/board', { waitUntil: 'domcontentloaded' });
// Wait for splash screen to disappear (safety net)
await waitForSplashScreenToDisappear(page, 3000);
// Handle login redirect if needed
await handleLoginScreenIfPresent(page);
@@ -34,37 +27,43 @@ export async function navigateToBoard(page: Page): Promise<void> {
* Note: Navigates directly to /context since index route shows WelcomeView
*/
export async function navigateToContext(page: Page): Promise<void> {
// Authenticate before navigating
// Authenticate before navigating (fast-path: skips if already authed via storageState)
await authenticateForTests(page);
// Wait for any pending navigation to complete before starting a new one
// This prevents race conditions, especially on mobile viewports
await page.waitForLoadState('domcontentloaded').catch(() => {});
await page.waitForTimeout(100);
// Navigate directly to /context route
await page.goto('/context', { waitUntil: 'domcontentloaded' });
// Wait for splash screen to disappear (safety net)
await waitForSplashScreenToDisappear(page, 3000);
// Handle login redirect if needed
await handleLoginScreenIfPresent(page);
// Wait for one of: context-view, context-view-no-project, or context-view-loading.
// Store hydration and loadContextFiles can be async, so we accept any of these first.
const viewSelector =
'[data-testid="context-view"], [data-testid="context-view-no-project"], [data-testid="context-view-loading"]';
await page.locator(viewSelector).first().waitFor({ state: 'visible', timeout: 15000 });
// If we see "no project", give hydration a moment then re-check (avoids flake when store hydrates after first paint).
const noProject = page.locator('[data-testid="context-view-no-project"]');
if (await noProject.isVisible().catch(() => false)) {
// Poll for the view to appear rather than a fixed timeout
await page
.locator('[data-testid="context-view"], [data-testid="context-view-loading"]')
.first()
.waitFor({ state: 'visible', timeout: 5000 })
.catch(() => {
throw new Error(
'Context view showed "No project selected". Ensure setupProjectWithFixture runs before navigateToContext and store has time to hydrate.'
);
});
}
// Wait for loading to complete (if present)
const loadingElement = page.locator('[data-testid="context-view-loading"]');
try {
const loadingVisible = await loadingElement.isVisible({ timeout: 2000 });
if (loadingVisible) {
// Wait for loading to disappear (context view will appear)
await loadingElement.waitFor({ state: 'hidden', timeout: 10000 });
}
} catch {
// Loading element not found or already hidden, continue
if (await loadingElement.isVisible().catch(() => false)) {
await loadingElement.waitFor({ state: 'hidden', timeout: 15000 });
}
// Wait for the context view to be visible
// Increase timeout to handle slower server startup
await waitForElement(page, 'context-view', { timeout: 15000 });
// On mobile, close the sidebar if open so the header actions trigger is clickable (not covered by backdrop)
@@ -72,8 +71,10 @@ export async function navigateToContext(page: Page): Promise<void> {
const backdrop = page.locator('[data-testid="sidebar-backdrop"]');
if (await backdrop.isVisible().catch(() => false)) {
await backdrop.evaluate((el) => (el as HTMLElement).click());
await page.waitForTimeout(200);
}
// Dismiss any open dialog that may block interactions (e.g. sandbox warning, onboarding)
await closeDialogWithEscape(page, { timeout: 2000 });
}
/**
@@ -81,38 +82,23 @@ export async function navigateToContext(page: Page): Promise<void> {
* Note: Navigates directly to /spec since index route shows WelcomeView
*/
export async function navigateToSpec(page: Page): Promise<void> {
// Authenticate before navigating
// Authenticate before navigating (fast-path: skips if already authed via storageState)
await authenticateForTests(page);
// Wait for any pending navigation to complete before starting a new one
await page.waitForLoadState('domcontentloaded').catch(() => {});
await page.waitForTimeout(100);
// Navigate directly to /spec route
await page.goto('/spec', { waitUntil: 'domcontentloaded' });
// Wait for splash screen to disappear (safety net)
await waitForSplashScreenToDisappear(page, 3000);
// Wait for loading state to complete first (if present)
const loadingElement = page.locator('[data-testid="spec-view-loading"]');
try {
const loadingVisible = await loadingElement.isVisible({ timeout: 2000 });
if (loadingVisible) {
// Wait for loading to disappear (spec view or empty state will appear)
await loadingElement.waitFor({ state: 'hidden', timeout: 10000 });
}
} catch {
// Loading element not found or already hidden, continue
if (await loadingElement.isVisible().catch(() => false)) {
await loadingElement.waitFor({ state: 'hidden', timeout: 10000 });
}
// Wait for either the main spec view or empty state to be visible
// The spec-view element appears when loading is complete and spec exists
// The spec-view-empty element appears when loading is complete and spec doesn't exist
await Promise.race([
waitForElement(page, 'spec-view', { timeout: 10000 }).catch(() => null),
waitForElement(page, 'spec-view-empty', { timeout: 10000 }).catch(() => null),
]);
await page
.locator('[data-testid="spec-view"], [data-testid="spec-view-empty"]')
.first()
.waitFor({ state: 'visible', timeout: 10000 });
}
/**
@@ -120,19 +106,12 @@ export async function navigateToSpec(page: Page): Promise<void> {
* Note: Navigates directly to /agent since index route shows WelcomeView
*/
export async function navigateToAgent(page: Page): Promise<void> {
// Authenticate before navigating
// Authenticate before navigating (fast-path: skips if already authed via storageState)
await authenticateForTests(page);
// Wait for any pending navigation to complete before starting a new one
await page.waitForLoadState('domcontentloaded').catch(() => {});
await page.waitForTimeout(100);
// Navigate directly to /agent route
await page.goto('/agent', { waitUntil: 'domcontentloaded' });
// Wait for splash screen to disappear (safety net)
await waitForSplashScreenToDisappear(page, 3000);
// Handle login redirect if needed
await handleLoginScreenIfPresent(page);
@@ -145,15 +124,11 @@ export async function navigateToAgent(page: Page): Promise<void> {
* Note: Navigates directly to /settings since index route shows WelcomeView
*/
export async function navigateToSettings(page: Page): Promise<void> {
// Authenticate before navigating
// Authenticate before navigating (fast-path: skips if already authed via storageState)
await authenticateForTests(page);
// Navigate directly to /settings route
await page.goto('/settings');
await page.waitForLoadState('load');
// Wait for splash screen to disappear (safety net)
await waitForSplashScreenToDisappear(page, 3000);
await page.goto('/settings', { waitUntil: 'domcontentloaded' });
// Wait for the settings view to be visible
await waitForElement(page, 'settings-view', { timeout: 10000 });
@@ -177,14 +152,10 @@ export async function navigateToSetup(page: Page): Promise<void> {
* Note: The app redirects from / to /dashboard when no project is selected
*/
export async function navigateToWelcome(page: Page): Promise<void> {
// Authenticate before navigating
// Authenticate before navigating (fast-path: skips if already authed via storageState)
await authenticateForTests(page);
await page.goto('/');
await page.waitForLoadState('load');
// Wait for splash screen to disappear (safety net)
await waitForSplashScreenToDisappear(page, 3000);
await page.goto('/', { waitUntil: 'domcontentloaded' });
// Handle login redirect if needed
await handleLoginScreenIfPresent(page);
@@ -204,7 +175,6 @@ export async function navigateToWelcome(page: Page): Promise<void> {
export async function navigateToView(page: Page, viewId: string): Promise<void> {
const navSelector = viewId === 'settings' ? 'settings-button' : `nav-${viewId}`;
await clickElement(page, navSelector);
await page.waitForTimeout(100);
}
/**

View File

@@ -1,23 +1,12 @@
import { Page } from '@playwright/test';
import * as fs from 'fs';
import * as path from 'path';
import { getWorkspaceRoot, assertSafeProjectPath } from '../core/safe-paths';
/**
* Resolve the workspace root - handle both running from apps/ui and from root
*/
export function getWorkspaceRoot(): string {
const cwd = process.cwd();
if (cwd.includes('apps/ui')) {
return path.resolve(cwd, '../..');
}
return cwd;
}
export { getWorkspaceRoot };
const WORKSPACE_ROOT = getWorkspaceRoot();
const FIXTURE_PATH = path.join(WORKSPACE_ROOT, 'test/fixtures/projectA');
const SPEC_FILE_PATH = path.join(FIXTURE_PATH, '.automaker/app_spec.txt');
const CONTEXT_PATH = path.join(FIXTURE_PATH, '.automaker/context');
const MEMORY_PATH = path.join(FIXTURE_PATH, '.automaker/memory');
// Original spec content for resetting between tests
const ORIGINAL_SPEC_CONTENT = `<app_spec>
@@ -30,43 +19,121 @@ const ORIGINAL_SPEC_CONTENT = `<app_spec>
</app_spec>
`;
// Worker-isolated fixture path to avoid conflicts when running tests in parallel.
// Each Playwright worker gets its own copy of the fixture directory.
let _workerFixturePath: string | null = null;
/**
* Bootstrap the shared fixture directory if it doesn't exist.
* The fixture contains a nested .git/ dir so it can't be tracked by the
* parent repo — in CI this directory won't exist after checkout.
*/
function ensureFixtureExists(): void {
if (fs.existsSync(FIXTURE_PATH)) return;
fs.mkdirSync(path.join(FIXTURE_PATH, '.automaker/context'), { recursive: true });
fs.writeFileSync(path.join(FIXTURE_PATH, '.automaker/app_spec.txt'), ORIGINAL_SPEC_CONTENT);
fs.writeFileSync(path.join(FIXTURE_PATH, '.automaker/categories.json'), '[]');
fs.writeFileSync(
path.join(FIXTURE_PATH, '.automaker/context/context-metadata.json'),
'{"files": {}}'
);
}
/**
* Get a worker-isolated fixture path. Creates a copy of the fixture directory
* for this worker process so parallel tests don't conflict.
* Falls back to the shared fixture path for backwards compatibility.
*/
function getWorkerFixturePath(): string {
if (_workerFixturePath) return _workerFixturePath;
// Ensure the source fixture exists (may not in CI)
ensureFixtureExists();
if (!fs.existsSync(FIXTURE_PATH)) {
throw new Error(
`E2E source fixture is missing at ${FIXTURE_PATH}. ` +
'Run the setup script to create it: from apps/ui, run `node scripts/setup-e2e-fixtures.mjs` (or use `pnpm test`, which runs it via pretest).'
);
}
// Use process.pid + a unique suffix to isolate per-worker
const workerId = process.env.TEST_WORKER_INDEX || process.pid.toString();
const workerDir = path.join(WORKSPACE_ROOT, `test/fixtures/.worker-${workerId}`);
// Copy projectA fixture to worker directory if it doesn't exist
if (!fs.existsSync(workerDir)) {
fs.cpSync(FIXTURE_PATH, workerDir, { recursive: true });
}
_workerFixturePath = workerDir;
return workerDir;
}
/**
* Get the worker-isolated context path
*/
function getWorkerContextPath(): string {
return path.join(getWorkerFixturePath(), '.automaker/context');
}
/**
* Get the worker-isolated memory path
*/
function getWorkerMemoryPath(): string {
return path.join(getWorkerFixturePath(), '.automaker/memory');
}
/**
* Get the worker-isolated spec file path
*/
function getWorkerSpecPath(): string {
return path.join(getWorkerFixturePath(), '.automaker/app_spec.txt');
}
/**
* Reset the fixture's app_spec.txt to original content
*/
export function resetFixtureSpec(): void {
const dir = path.dirname(SPEC_FILE_PATH);
const specPath = getWorkerSpecPath();
const dir = path.dirname(specPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(SPEC_FILE_PATH, ORIGINAL_SPEC_CONTENT);
fs.writeFileSync(specPath, ORIGINAL_SPEC_CONTENT);
}
/**
* Reset the context directory to empty state
*/
export function resetContextDirectory(): void {
if (fs.existsSync(CONTEXT_PATH)) {
fs.rmSync(CONTEXT_PATH, { recursive: true });
const contextPath = getWorkerContextPath();
if (fs.existsSync(contextPath)) {
fs.rmSync(contextPath, { recursive: true });
}
fs.mkdirSync(CONTEXT_PATH, { recursive: true });
fs.mkdirSync(contextPath, { recursive: true });
}
/**
* Reset the memory directory to empty state
*/
export function resetMemoryDirectory(): void {
if (fs.existsSync(MEMORY_PATH)) {
fs.rmSync(MEMORY_PATH, { recursive: true });
const memoryPath = getWorkerMemoryPath();
if (fs.existsSync(memoryPath)) {
fs.rmSync(memoryPath, { recursive: true });
}
fs.mkdirSync(MEMORY_PATH, { recursive: true });
fs.mkdirSync(memoryPath, { recursive: true });
}
/**
* Resolve and validate a context fixture path to prevent path traversal
*/
function resolveContextFixturePath(filename: string): string {
const resolved = path.resolve(CONTEXT_PATH, filename);
const base = path.resolve(CONTEXT_PATH) + path.sep;
const contextPath = getWorkerContextPath();
const resolved = path.resolve(contextPath, filename);
const base = path.resolve(contextPath) + path.sep;
if (!resolved.startsWith(base)) {
throw new Error(`Invalid context filename: ${filename}`);
}
@@ -85,8 +152,9 @@ export function createContextFileOnDisk(filename: string, content: string): void
* Resolve and validate a memory fixture path to prevent path traversal
*/
function resolveMemoryFixturePath(filename: string): string {
const resolved = path.resolve(MEMORY_PATH, filename);
const base = path.resolve(MEMORY_PATH) + path.sep;
const memoryPath = getWorkerMemoryPath();
const resolved = path.resolve(memoryPath, filename);
const base = path.resolve(memoryPath) + path.sep;
if (!resolved.startsWith(base)) {
throw new Error(`Invalid memory filename: ${filename}`);
}
@@ -120,11 +188,14 @@ export function memoryFileExistsOnDisk(filename: string): boolean {
/**
* Set up localStorage with a project pointing to our test fixture
* Note: In CI, setup wizard is also skipped via NEXT_PUBLIC_SKIP_SETUP env var
* Project path must be under test/ or temp to avoid affecting the main project's git.
* Defaults to a worker-isolated copy of the fixture to support parallel test execution.
*/
export async function setupProjectWithFixture(
page: Page,
projectPath: string = FIXTURE_PATH
projectPath: string = getWorkerFixturePath()
): Promise<void> {
assertSafeProjectPath(projectPath);
await page.addInitScript((pathArg: string) => {
const mockProject = {
id: 'test-project-fixture',
@@ -181,6 +252,7 @@ export async function setupProjectWithFixture(
theme: 'dark',
sidebarOpen: true,
maxConcurrency: 3,
skipSandboxWarning: true,
};
localStorage.setItem('automaker-settings-cache', JSON.stringify(settingsCache));
@@ -190,10 +262,10 @@ export async function setupProjectWithFixture(
}
/**
* Get the fixture path
* Get the fixture path (worker-isolated for parallel test execution)
*/
export function getFixturePath(): string {
return FIXTURE_PATH;
return getWorkerFixturePath();
}
/**
@@ -204,5 +276,5 @@ export async function setupMockProjectWithProfiles(
page: Page,
_options?: { customProfilesCount?: number }
): Promise<void> {
await setupProjectWithFixture(page, FIXTURE_PATH);
await setupProjectWithFixture(page);
}

View File

@@ -1,4 +1,5 @@
import { Page } from '@playwright/test';
import { assertSafeProjectPath } from '../core/safe-paths';
/**
* Store version constants - centralized to avoid hardcoding across tests
@@ -108,18 +109,22 @@ export async function setupWelcomeView(
// Disable splash screen in tests
localStorage.setItem('automaker-disable-splash', 'true');
// Set up a mechanism to keep currentProject null even after settings hydration
// Settings API might restore a project, so we override it after hydration
// Use a flag to indicate we want welcome view
// Set up a mechanism to keep currentProject null even after settings hydration.
// Settings API might restore a project, so we watch for changes and override.
sessionStorage.setItem('automaker-test-welcome-view', 'true');
// Override currentProject after a short delay to ensure it happens after settings hydration
setTimeout(() => {
// Use a MutationObserver + storage event to detect when hydration sets a project,
// then immediately override it back to null. This is more reliable than a fixed timeout.
const enforceWelcomeView = () => {
const storage = localStorage.getItem('automaker-storage');
if (storage) {
try {
const state = JSON.parse(storage);
if (state.state && sessionStorage.getItem('automaker-test-welcome-view') === 'true') {
if (
state.state &&
sessionStorage.getItem('automaker-test-welcome-view') === 'true' &&
state.state.currentProject !== null
) {
state.state.currentProject = null;
state.state.currentView = 'welcome';
localStorage.setItem('automaker-storage', JSON.stringify(state));
@@ -128,7 +133,17 @@ export async function setupWelcomeView(
// Ignore parse errors
}
}
}, 2000); // Wait 2 seconds for settings hydration to complete
};
// Listen for storage changes (catches hydration from settings API)
window.addEventListener('storage', enforceWelcomeView);
// Also poll briefly to catch synchronous hydration that doesn't fire storage events
const pollInterval = setInterval(enforceWelcomeView, 200);
setTimeout(() => {
clearInterval(pollInterval);
window.removeEventListener('storage', enforceWelcomeView);
}, 5000); // Stop after 5s - hydration should be done by then
},
{ opts: options, versions: STORE_VERSIONS }
);
@@ -136,7 +151,8 @@ export async function setupWelcomeView(
/**
* Set up localStorage with a project at a real filesystem path
* Use this when testing with actual files on disk
* Use this when testing with actual files on disk.
* Project path must be under test/ or temp to avoid affecting the main project's git.
*
* @param page - Playwright page
* @param projectPath - Absolute path to the project directory
@@ -156,6 +172,7 @@ export async function setupRealProject(
projectId?: string;
}
): Promise<void> {
assertSafeProjectPath(projectPath);
await page.addInitScript(
({
path,

View File

@@ -21,6 +21,9 @@ export async function getNewSessionButton(page: Page): Promise<Locator> {
export async function clickNewSessionButton(page: Page): Promise<void> {
// Wait for splash screen to disappear first (safety net)
await waitForSplashScreenToDisappear(page, 3000);
// Ensure session list (and thus SessionManager) is visible before clicking
const sessionList = page.locator('[data-testid="session-list"]');
await sessionList.waitFor({ state: 'visible', timeout: 10000 });
const button = await getNewSessionButton(page);
await button.click();
}
@@ -76,12 +79,16 @@ export async function countSessionItems(page: Page): Promise<number> {
/**
* Wait for a new session to be created (by checking if a session item appears)
* Scopes to session-list to match countSessionItems and avoid matching stale elements
*/
export async function waitForNewSession(page: Page, options?: { timeout?: number }): Promise<void> {
// Wait for any session item to appear
const sessionItem = page.locator('[data-testid^="session-item-"]').first();
await sessionItem.waitFor({
timeout: options?.timeout ?? 5000,
state: 'visible',
});
const timeout = options?.timeout ?? 10000;
// Ensure session list container is visible first (handles sidebar render delay)
const sessionList = page.locator('[data-testid="session-list"]');
await sessionList.waitFor({ state: 'visible', timeout });
// Wait for a session item to appear within the session list
const sessionItem = sessionList.locator('[data-testid^="session-item-"]').first();
await sessionItem.waitFor({ state: 'visible', timeout });
}

View File

@@ -130,33 +130,32 @@ export async function fillAddFeatureDialog(
.locator('[id="feature-other"]');
await otherBranchRadio.waitFor({ state: 'visible', timeout: 5000 });
await otherBranchRadio.click();
// Wait for the branch input to appear
await page.waitForTimeout(300);
// Now click on the branch input (autocomplete)
// Wait for the branch input to appear after radio click
const branchInput = page.locator('[data-testid="feature-input"]');
await branchInput.waitFor({ state: 'visible', timeout: 5000 });
await branchInput.click();
// Wait for the popover to open
await page.waitForTimeout(300);
// Type in the command input
// Wait for the command list popover to open
const commandInput = page.locator('[cmdk-input]');
await commandInput.waitFor({ state: 'visible', timeout: 5000 });
await commandInput.fill(options.branch);
// Press Enter to select/create the branch
await commandInput.press('Enter');
// Wait for popover to close
await page.waitForTimeout(200);
await commandInput.waitFor({ state: 'hidden', timeout: 5000 }).catch(() => {});
}
// Fill category if provided (it's also a combobox autocomplete)
if (options?.category) {
const categoryButton = page.locator('[data-testid="feature-category-input"]');
await categoryButton.click();
await page.waitForTimeout(300);
// Wait for the command list popover to open
const commandInput = page.locator('[cmdk-input]');
await commandInput.waitFor({ state: 'visible', timeout: 5000 });
await commandInput.fill(options.category);
await commandInput.press('Enter');
await page.waitForTimeout(200);
// Wait for popover to close
await commandInput.waitFor({ state: 'hidden', timeout: 5000 }).catch(() => {});
}
}
@@ -203,7 +202,8 @@ export async function selectWorktreeBranch(page: Page, branchName: string): Prom
name: new RegExp(branchName, 'i'),
});
await branchButton.click();
await page.waitForTimeout(500); // Wait for UI to update
// Wait for the button to become selected (aria-pressed="true")
await branchButton.waitFor({ state: 'visible', timeout: 5000 }).catch(() => {});
}
/**

View File

@@ -88,8 +88,11 @@ export async function createContextImage(
export async function deleteSelectedContextFile(page: Page): Promise<void> {
await clickElement(page, 'delete-context-file');
await waitForElement(page, 'delete-context-dialog');
await clickElement(page, 'confirm-delete-file');
await waitForElementHidden(page, 'delete-context-dialog');
// Click the confirm button scoped to the dialog to avoid multiple matches
const dialog = page.locator('[data-testid="delete-context-dialog"]');
await dialog.locator('[data-testid="confirm-delete-file"]').click();
// Wait for dialog to close (server delete can take a moment)
await waitForElementHidden(page, 'delete-context-dialog', { timeout: 15000 });
}
/**
@@ -126,17 +129,21 @@ export async function toggleContextPreviewMode(page: Page): Promise<void> {
/**
* Wait for a specific file to appear in the context file list
* Uses retry mechanism to handle race conditions with API/UI updates
* Uses retry mechanism to handle race conditions with API/UI updates.
* On mobile, scrolls the file list into view first so new items are visible.
*/
export async function waitForContextFile(
page: Page,
filename: string,
timeout: number = 15000
timeout: number = 20000
): Promise<void> {
await expect(async () => {
const locator = page.locator(`[data-testid="context-file-${filename}"]`);
await expect(locator).toBeVisible();
}).toPass({ timeout, intervals: [500, 1000, 2000] });
// Ensure file list is in view (helps on mobile when list is scrollable)
const fileList = page.locator('[data-testid="context-file-list"]');
await fileList.scrollIntoViewIfNeeded().catch(() => {});
const locator = page.locator(`[data-testid="context-file-${filename}"]`);
// Use a longer per-attempt timeout so slow API/state updates can complete
await expect(locator).toBeVisible({ timeout });
}
/**
@@ -160,7 +167,7 @@ export async function selectContextFile(
'[data-testid="context-editor"], [data-testid="markdown-preview"], [data-testid="image-preview"]'
);
await expect(contentLocator).toBeVisible();
}).toPass({ timeout, intervals: [500, 1000, 2000] });
}).toPass({ timeout, intervals: [200, 500, 1000] });
}
/**
@@ -173,7 +180,7 @@ export async function waitForFileContentToLoad(page: Page, timeout: number = 150
'[data-testid="context-editor"], [data-testid="markdown-preview"], [data-testid="image-preview"]'
);
await expect(contentLocator).toBeVisible();
}).toPass({ timeout, intervals: [500, 1000, 2000] });
}).toPass({ timeout, intervals: [200, 500, 1000] });
}
/**

View File

@@ -1,10 +1,11 @@
import { Page, Locator } from '@playwright/test';
import { clickElement, fillInput, handleLoginScreenIfPresent } from '../core/interactions';
import {
waitForElement,
waitForElementHidden,
waitForSplashScreenToDisappear,
} from '../core/waiting';
clickElement,
fillInput,
handleLoginScreenIfPresent,
closeDialogWithEscape,
} from '../core/interactions';
import { waitForElement, waitForElementHidden } from '../core/waiting';
import { getByTestId } from '../core/elements';
import { expect } from '@playwright/test';
import { authenticateForTests } from '../api/client';
@@ -124,7 +125,7 @@ export async function waitForMemoryFile(
await expect(async () => {
const locator = page.locator(`[data-testid="memory-file-${filename}"]`);
await expect(locator).toBeVisible();
}).toPass({ timeout, intervals: [500, 1000, 2000] });
}).toPass({ timeout, intervals: [200, 500, 1000] });
}
/**
@@ -140,6 +141,8 @@ export async function selectMemoryFile(
// Retry click + wait for content panel to handle timing issues
// Note: On mobile, delete button is hidden, so we wait for content panel instead
// Use shorter inner timeout so retries can run; loadFileContent is async (API read)
const innerTimeout = Math.min(2000, Math.floor(timeout / 3));
await expect(async () => {
// Use JavaScript click to ensure React onClick handler fires
await fileButton.evaluate((el) => (el as HTMLButtonElement).click());
@@ -147,8 +150,8 @@ export async function selectMemoryFile(
const contentLocator = page.locator(
'[data-testid="memory-editor"], [data-testid="markdown-preview"]'
);
await expect(contentLocator).toBeVisible();
}).toPass({ timeout, intervals: [500, 1000, 2000] });
await expect(contentLocator).toBeVisible({ timeout: innerTimeout });
}).toPass({ timeout, intervals: [200, 500, 1000] });
}
/**
@@ -159,12 +162,13 @@ export async function waitForMemoryContentToLoad(
page: Page,
timeout: number = 15000
): Promise<void> {
const innerTimeout = Math.min(2000, Math.floor(timeout / 3));
await expect(async () => {
const contentLocator = page.locator(
'[data-testid="memory-editor"], [data-testid="markdown-preview"]'
);
await expect(contentLocator).toBeVisible();
}).toPass({ timeout, intervals: [500, 1000, 2000] });
await expect(contentLocator).toBeVisible({ timeout: innerTimeout });
}).toPass({ timeout, intervals: [200, 500, 1000] });
}
/**
@@ -186,37 +190,64 @@ export async function switchMemoryToEditMode(page: Page): Promise<void> {
}
}
/**
* Refresh the memory file list (clicks the Refresh button).
* Use instead of page.reload() to avoid ERR_CONNECTION_REFUSED when the dev server
* is under load, and to match real user behavior.
*/
export async function refreshMemoryList(page: Page): Promise<void> {
// Desktop: refresh button is visible; mobile: open panel then click mobile refresh
const desktopRefresh = page.locator('[data-testid="refresh-memory-button"]');
const mobileRefresh = page.locator('[data-testid="refresh-memory-button-mobile"]');
if (await desktopRefresh.isVisible().catch(() => false)) {
await desktopRefresh.click();
} else {
await clickElement(page, 'header-actions-panel-trigger');
await mobileRefresh.click();
}
// Allow list to re-fetch
await page.waitForTimeout(150);
}
/**
* Navigate to the memory view
* Note: Navigates directly to /memory since index route shows WelcomeView
*/
export async function navigateToMemory(page: Page): Promise<void> {
// Authenticate before navigating (same pattern as navigateToContext / navigateToBoard)
// Authenticate before navigating (fast-path: skips if already authed via storageState)
await authenticateForTests(page);
// Wait for any pending navigation to complete before starting a new one
await page.waitForLoadState('domcontentloaded').catch(() => {});
await page.waitForTimeout(100);
// Navigate directly to /memory route
await page.goto('/memory', { waitUntil: 'domcontentloaded' });
// Wait for splash screen to disappear (safety net)
await waitForSplashScreenToDisappear(page, 3000);
// Handle login redirect if needed (e.g. when redirected to /logged-out)
await handleLoginScreenIfPresent(page);
// Wait for one of: memory-view, memory-view-no-project, or memory-view-loading.
// Store hydration and loadMemoryFiles can be async, so we accept any of these first.
const viewSelector =
'[data-testid="memory-view"], [data-testid="memory-view-no-project"], [data-testid="memory-view-loading"]';
await page.locator(viewSelector).first().waitFor({ state: 'visible', timeout: 15000 });
// If we see "no project", give hydration a moment then re-check (avoids flake when store hydrates after first paint).
const noProject = page.locator('[data-testid="memory-view-no-project"]');
if (await noProject.isVisible().catch(() => false)) {
// Poll for the view to appear rather than a fixed timeout
await page
.locator('[data-testid="memory-view"], [data-testid="memory-view-loading"]')
.first()
.waitFor({ state: 'visible', timeout: 5000 })
.catch(() => {
throw new Error(
'Memory view showed "No project selected". Ensure setupProjectWithFixture runs before navigateToMemory and store has time to hydrate.'
);
});
}
// Wait for loading to complete (if present)
const loadingElement = page.locator('[data-testid="memory-view-loading"]');
try {
const loadingVisible = await loadingElement.isVisible({ timeout: 2000 });
if (loadingVisible) {
// Wait for loading to disappear (memory view will appear)
await loadingElement.waitFor({ state: 'hidden', timeout: 10000 });
}
} catch {
// Loading element not found or already hidden, continue
if (await loadingElement.isVisible().catch(() => false)) {
await loadingElement.waitFor({ state: 'hidden', timeout: 10000 });
}
// Wait for the memory view to be visible
@@ -227,7 +258,24 @@ export async function navigateToMemory(page: Page): Promise<void> {
const backdrop = page.locator('[data-testid="sidebar-backdrop"]');
if (await backdrop.isVisible().catch(() => false)) {
await backdrop.evaluate((el) => (el as HTMLElement).click());
await page.waitForTimeout(200);
}
// Dismiss any open dialog that may block interactions (e.g. sandbox warning, onboarding).
// The sandbox dialog blocks Escape, so click "I Accept the Risks" if it becomes visible within 1s.
const sandboxAcceptBtn = page.locator('button:has-text("I Accept the Risks")');
const sandboxVisible = await sandboxAcceptBtn
.waitFor({ state: 'visible', timeout: 1000 })
.then(() => true)
.catch(() => false);
if (sandboxVisible) {
await sandboxAcceptBtn.click();
await page
.locator('[role="dialog"][data-state="open"]')
.first()
.waitFor({ state: 'hidden', timeout: 3000 })
.catch(() => {});
} else {
await closeDialogWithEscape(page, { timeout: 2000 });
}
// Ensure the header (and actions panel trigger on mobile) is interactive