* feat(sync): add Helm chart for SuperSync Kubernetes deployment Includes Deployment, StatefulSet (PostgreSQL), Service, Ingress, ConfigMap, Secret, HPA, PDB, NetworkPolicy, and test templates. Supports both bundled PostgreSQL and external database configurations. * feat(sync): add WebSocket push notifications for near-realtime sync Server: Fastify WebSocket plugin with connection manager, app-level heartbeat (30s), debounced notifications, and per-user routing. Client: WebSocket service with exponential backoff reconnection, WS-triggered download service, and reduced polling when connected. * fix(sync): improve WebSocket error handling and reactivity Make syncInterval$ reactive to WS connection state, fix Set/Map mutation during heartbeat iteration, add error handling to WS route handler, separate JSON parsing from message handling, detect auth failures in WS-triggered downloads, and add logging to all empty catch blocks. * fix(sync): address PR review findings for WebSocket and Helm Fix race condition in WS-triggered download pipeline by moving isSyncInProgress filter after debounce and adding guard in _downloadOps. Add logging to remaining empty catch blocks, fix missing $NODE_IP in Helm NOTES.txt, and correct inaccurate comments in values.yaml and ws-triggered-download.service.ts. * fix(sync): add rate limiting to WebSocket upgrade endpoint Limit WS connection attempts to 10 per minute per IP to prevent connection flooding, matching the rate-limit pattern used by other sync endpoints. * fix(sync): extract shared constants, fix debounce correctness, replace deprecated toPromise Extract CLIENT_ID_REGEX and MAX_CLIENT_ID_LENGTH into sync.const.ts to prevent drift between sync.routes.ts and websocket.routes.ts. Fix debounce in notifyNewOps to accumulate excluded client IDs across rapid calls from different clients, preventing self-notifications. Replace deprecated toPromise() with firstValueFrom in connectWebSocket and _sync methods. Add .catch() to reconnect path and logging to silent early returns in _downloadOps. * fix(build): restore correct package-lock.json and fix upstream lint errors * revert: restore upstream HTML formatting to match CI prettier config * fix(sync): use DownloadOutcome discriminated union in WsTriggeredDownloadService * fix(sync): narrow TokenVerificationResult before accessing userId * fix(sync): await async getProviderById in connectWebSocket Missing await caused the Promise object to be cast to SuperSyncProvider, making getWebSocketParams undefined. * feat(sync): add SEED_USERS env var to create verified users on startup For self-hosted single-user setups: set SEED_USERS=email1,email2 to create verified users on boot and log their access tokens. Skips existing users. Removes need for SMTP/magic link registration. Also fix Dockerfile to use npm install instead of npm ci for lockfile compatibility. * fix(sync): address PR review feedback for Helm chart and server Security: - Remove seed-users.ts (logged full JWT tokens to stdout) - Add fail assertions for missing jwtSecret and postgresql.password - Add smtp.user/smtp.password values fields - Add from: selector to NetworkPolicy ingress - Add egress rule for external database when postgresql.enabled=false Correctness: - Fix PostgreSQL StatefulSet indentation for non-persistent mode - Fix NOTES.txt panic on empty tls list (use len instead of index) - Restore npm ci in Dockerfile by using node:24-alpine (ships npm 11) - Add Recreate deployment strategy when using RWO PVC Operational: - Add fail guard preventing HPA maxReplicas > 1 (in-memory WS state) - Fix PDB to use maxUnavailable instead of minAvailable - Add WebSocket ingress timeout annotation examples - Add Prisma db push init container for schema migrations - Default serviceAccount.automount to false - Add Chart.yaml maintainers, home, sources metadata * feat(sync): add ALLOWED_EMAILS env var to restrict registration Supports fully qualified emails (user@example.com) and domain wildcards (*@example.com). When unset, all emails are allowed. Applied to all three registration endpoints (passkey options, passkey verify, magic link). * fix(sync): exempt health endpoint from rate limiting Kubernetes liveness/readiness probes hit /health every 5-15s, exhausting the global rate limit (100 req/15min) and causing 429 responses that trigger container restarts. * fix(sync): harden WebSocket, Helm chart, and sync services from multi-agent review - Pin prisma@5.22.0 in init container and use migrate deploy instead of db push - Add per-user WebSocket connection limit (max 10) to prevent resource exhaustion - Add replicaCount > 1 fail guard in deployment template (in-memory WS state) - Set maxPayload: 1024 on WebSocket plugin (only pong messages expected) - Remove premature IN_SYNC status from download-only WS-triggered sync - Fix double removeConnection on error+close events (let close handle cleanup) - DRY debounce logic in notifyNewOps and store latestSeq on pending entry - Remove dead fromClientId from NewOpsNotification and WsMessage interfaces - Add takeUntilDestroyed to _wsProviderCleanup subscription - Simplify email-allowlist.ts to eager init (eliminate mutable state) - Guard connectWebSocket at call site for non-SuperSync providers - Add distinctUntilChanged to syncInterval$ to prevent unnecessary resets - Add container-level securityContext to PostgreSQL StatefulSet - Fix HPA maxReplicas default to 1 (matches single-replica constraint) * fix(sync): restore migration in Dockerfile CMD for non-Helm Docker users Helm users get migration via init container (runs first, CMD becomes no-op). Docker-compose/plain Docker users get automatic migration back on startup. * fix(boards): add missing drag delay for touch and extract shared signal Add cdkDragStartDelay to board-panel drag items, which was missing entirely. Extract the repeated `isTouchActive() ? DRAG_DELAY_FOR_TOUCH : 0` expression into a shared `dragDelayForTouch` computed signal and refactor all 8 components to use it. * test(sync): add comprehensive WebSocket test coverage Add unit tests for the new WebSocket real-time sync notification pipeline: - WebSocketConnectionService (server): connection lifecycle, max-per-user limits, notification debouncing, heartbeat, graceful shutdown (13 tests) - WebSocket routes validation: token/clientId validation, close codes, error handling, validation ordering (18 tests) - SuperSyncWebSocketService (frontend): reconnection with exponential backoff, heartbeat, disconnect cleanup, URL conversion (6 tests) - WsTriggeredDownloadService: auth error handling, pipeline resilience, start() idempotency (3 tests) - SyncWrapperService: connectWebSocket guards for non-SuperSync, null params, and already-connected cases (3 tests) - E2E realtime push: verifies WS-triggered download between two clients Quality fixes: - Replace waitForTimeout with syncAndWait in E2E - Add explanatory comment for microtask flushing in sync-wrapper spec - Use getter for isSyncInProgress mock in ws-triggered-download spec --------- Co-authored-by: Johannes Millan <johannes.millan@gmail.com> |
||
|---|---|---|
| .. | ||
| constants | ||
| fixtures | ||
| helpers | ||
| pages | ||
| tests | ||
| utils | ||
| .gitignore | ||
| CLAUDE.md | ||
| global-setup.ts | ||
| playwright.config.ts | ||
| README.md | ||
| tsconfig.json | ||
E2E Testing Guide for Super Productivity
This guide provides comprehensive information for writing and maintaining end-to-end tests for Super Productivity using Playwright.
Table of Contents
- Overview
- Running Tests
- Test Structure
- Page Objects
- Common Patterns
- Selectors
- Wait Utilities
- Writing New Tests
- Best Practices
- Troubleshooting
Overview
Our E2E tests are built with Playwright and follow the Page Object Model (POM) pattern for maintainability and reusability. Tests are organized by feature and use shared fixtures for common setup.
Key Technologies
- Playwright: Modern E2E testing framework
- TypeScript: Type-safe test code
- Page Object Model: Encapsulates page interactions
- Fixtures: Shared setup and utilities
Running Tests
Basic Commands
# Run all tests
npm run e2e
# Run tests in UI mode (interactive)
npm run e2e:ui
# Run a single test file with detailed output
npm run e2e:file tests/task-basic/task-crud.spec.ts
# Run tests in headed mode (see browser)
npm run e2e:headed
# Run tests in debug mode
npm run e2e:debug
# Show test report
npm run e2e:show-report
WebDAV Sync Tests
# Run WebDAV tests (starts Docker container)
npm run e2e:webdav
Test Structure
Directory Layout
e2e/
├── constants/ # Shared selectors and constants
│ └── selectors.ts # Centralized CSS selectors
├── fixtures/ # Test fixtures and setup
│ └── test.fixture.ts # Custom test fixtures with page objects
├── helpers/ # Test helper functions
│ └── plugin-test.helpers.ts
├── pages/ # Page Object Models
│ ├── base.page.ts # Base page with common methods
│ ├── work-view.page.ts
│ ├── project.page.ts
│ ├── task.page.ts
│ ├── settings.page.ts
│ ├── dialog.page.ts
│ ├── planner.page.ts
│ ├── schedule.page.ts
│ ├── side-nav.page.ts
│ ├── sync.page.ts
│ ├── tag.page.ts
│ └── note.page.ts
├── tests/ # Test specifications
│ ├── task-basic/
│ ├── project/
│ ├── planner/
│ └── ...
├── utils/ # Utility functions
│ ├── waits.ts # Wait helpers
│ └── sync-helpers.ts
├── playwright.config.ts
└── global-setup.ts
Page Objects
Page Objects encapsulate interactions with specific pages or components. All page objects extend BasePage and receive a page and optional testPrefix.
Available Page Objects
1. BasePage (base.page.ts)
Base class for all page objects. Provides common functionality:
class BasePage {
async addTask(taskName: string): Promise<void>;
// Adds a task with automatic test prefix
}
Example:
await workViewPage.addTask('My Task');
// Creates task with name "W0-P0-My Task" (prefixed for isolation)
2. WorkViewPage (work-view.page.ts)
Interactions with the main work view:
class WorkViewPage extends BasePage {
async waitForTaskList(): Promise<void>;
async addSubTask(task: Locator, subTaskName: string): Promise<void>;
}
Example:
await workViewPage.waitForTaskList();
await workViewPage.addTask('Parent Task');
const task = page.locator('task').first();
await workViewPage.addSubTask(task, 'Child Task');
3. TaskPage (task.page.ts)
Task-specific operations:
class TaskPage extends BasePage {
getTask(index: number): Locator;
getTaskByText(text: string): Locator;
async markTaskAsDone(task: Locator): Promise<void>;
async editTaskTitle(task: Locator, newTitle: string): Promise<void>;
async openTaskDetail(task: Locator): Promise<void>;
async getTaskCount(): Promise<number>;
async isTaskDone(task: Locator): Promise<boolean>;
getDoneTasks(): Locator;
getUndoneTasks(): Locator;
async waitForTaskWithText(text: string): Promise<Locator>;
async taskHasTag(task: Locator, tagName: string): Promise<boolean>;
}
Example:
const task = taskPage.getTask(1); // First task
await taskPage.markTaskAsDone(task);
await expect(taskPage.getDoneTasks()).toHaveCount(1);
4. ProjectPage (project.page.ts)
Project management:
class ProjectPage extends BasePage {
async createProject(projectName: string): Promise<void>;
async navigateToProjectByName(projectName: string): Promise<void>;
async createAndGoToTestProject(): Promise<void>;
async addNote(noteContent: string): Promise<void>;
async archiveDoneTasks(): Promise<void>;
}
Example:
await projectPage.createProject('My Project');
await projectPage.navigateToProjectByName('My Project');
await projectPage.addNote('Project notes here');
5. SettingsPage (settings.page.ts)
Settings and configuration:
class SettingsPage extends BasePage {
async navigateToSettings(): Promise<void>;
async expandSection(sectionSelector: string): Promise<void>;
async expandPluginSection(): Promise<void>;
async navigateToPluginSettings(): Promise<void>;
async enablePlugin(pluginName: string): Promise<boolean>;
async disablePlugin(pluginName: string): Promise<boolean>;
async isPluginEnabled(pluginName: string): Promise<boolean>;
async uploadPlugin(pluginPath: string): Promise<void>;
}
Example:
await settingsPage.navigateToPluginSettings();
await settingsPage.enablePlugin('Test Plugin');
expect(await settingsPage.isPluginEnabled('Test Plugin')).toBeTruthy();
6. DialogPage (dialog.page.ts)
Dialog and modal interactions:
class DialogPage extends BasePage {
async waitForDialog(): Promise<Locator>;
async waitForDialogToClose(): Promise<void>;
async clickDialogButton(buttonText: string): Promise<void>;
async clickSaveButton(): Promise<void>;
async fillDialogInput(selector: string, value: string): Promise<void>;
async fillMarkdownDialog(content: string): Promise<void>;
async saveMarkdownDialog(): Promise<void>;
async editDateTime(dateValue?: string, timeValue?: string): Promise<void>;
}
Example:
await dialogPage.waitForDialog();
await dialogPage.fillDialogInput('input[name="title"]', 'New Title');
await dialogPage.clickSaveButton();
await dialogPage.waitForDialogToClose();
Common Patterns
Pattern 1: Basic Task CRUD
test('should create and edit task', async ({ page, workViewPage, taskPage }) => {
await workViewPage.waitForTaskList();
// Create
await workViewPage.addTask('Test Task');
await expect(taskPage.getAllTasks()).toHaveCount(1);
// Edit
const task = taskPage.getTask(1);
await taskPage.editTaskTitle(task, 'Updated Task');
await expect(taskPage.getTaskTitle(task)).toContainText('Updated Task');
// Mark as done
await taskPage.markTaskAsDone(task);
await expect(taskPage.getDoneTasks()).toHaveCount(1);
});
Pattern 2: Project Workflow
test('should create project and add tasks', async ({ projectPage, workViewPage }) => {
await projectPage.createAndGoToTestProject();
await workViewPage.addTask('Project Task 1');
await workViewPage.addTask('Project Task 2');
await expect(page.locator('task')).toHaveCount(2);
});
Pattern 3: Settings Configuration
test('should enable plugin', async ({ settingsPage, waitForNav }) => {
await settingsPage.navigateToPluginSettings();
await settingsPage.enablePlugin('My Plugin');
await waitForNav();
expect(await settingsPage.isPluginEnabled('My Plugin')).toBeTruthy();
});
Pattern 4: Dialog Interactions
test('should edit date in dialog', async ({ taskPage, dialogPage }) => {
const task = taskPage.getTask(1);
await taskPage.openTaskDetail(task);
const dateInfo = dialogPage.getDateInfo('Created');
await dateInfo.click();
await dialogPage.editDateTime('12/25/2025', undefined);
await dialogPage.clickSaveButton();
});
Selectors
All selectors are centralized in constants/selectors.ts. Always use these constants instead of hardcoding selectors in tests.
Using Selectors
import { cssSelectors } from '../constants/selectors';
const { TASK, TASK_TITLE, TASK_DONE_BTN } = cssSelectors;
// In test:
const task = page.locator(TASK).first();
const title = task.locator(TASK_TITLE);
Selector Categories
- Navigation:
SIDENAV,NAV_ITEM,SETTINGS_BTN - Layout:
ROUTE_WRAPPER,BACKDROP,PAGE_TITLE - Tasks:
TASK,TASK_TITLE,TASK_DONE_BTN,SUB_TASK - Add Task:
ADD_TASK_INPUT,ADD_TASK_SUBMIT - Dialogs:
MAT_DIALOG,DIALOG_FULLSCREEN_MARKDOWN - Settings:
PAGE_SETTINGS,PLUGIN_SECTION,PLUGIN_MANAGEMENT - Projects:
PAGE_PROJECT,CREATE_PROJECT_BTN,WORK_CONTEXT_MENU
Wait Utilities
Located in utils/waits.ts, these utilities help handle Angular's async nature.
Available Wait Functions
waitForAngularStability(page, timeout?)
Waits for Angular to finish all async operations.
await waitForAngularStability(page);
waitForAppReady(page, options?)
Comprehensive wait for app initialization.
await waitForAppReady(page, {
selector: 'task-list',
ensureRoute: true,
routeRegex: /#\/project\/\w+/,
});
waitForStatePersistence(page)
Waits for IndexedDB persistence to complete (important before sync operations).
await workViewPage.addTask('Task');
await waitForStatePersistence(page); // Ensure saved to IndexedDB
// Now safe to trigger sync
Writing New Tests
Step 1: Create Test File
// e2e/tests/my-feature/my-feature.spec.ts
import { test, expect } from '../../fixtures/test.fixture';
test.describe('My Feature', () => {
test('should do something', async ({ page, workViewPage, taskPage }) => {
// Test code here
});
});
Step 2: Use Page Objects
test('my test', async ({ workViewPage, taskPage, dialogPage }) => {
// Wait for page ready
await workViewPage.waitForTaskList();
// Use page objects for interactions
await workViewPage.addTask('Task 1');
const task = taskPage.getTask(1);
await taskPage.markTaskAsDone(task);
// Assertions
await expect(taskPage.getDoneTasks()).toHaveCount(1);
});
Step 3: Handle Waits Properly
// GOOD: Use Angular stability waits
await workViewPage.addTask('Task');
await waitForAngularStability(page);
await expect(page.locator('task')).toBeVisible();
// BAD: Arbitrary timeouts
await page.waitForTimeout(5000); // Avoid unless necessary
Step 4: Use Selectors from Constants
import { cssSelectors } from '../../constants/selectors';
const { TASK, TASK_TITLE } = cssSelectors;
const title = page.locator(TASK).first().locator(TASK_TITLE);
Best Practices
✅ DO
- Use page objects for all interactions
- Use centralized selectors from
constants/selectors.ts - Wait for Angular stability after state changes
- Use test prefixes (automatic via fixtures) for isolation
- Test one thing per test - keep tests focused
- Use descriptive test names - "should create task and mark as done"
- Clean up state - tests should be independent
- Use role-based selectors when possible (accessibility)
// GOOD
await page.getByRole('button', { name: 'Save' }).click();
// LESS GOOD
await page.locator('.save-btn').click();
❌ DON'T
- Don't hardcode selectors - use
cssSelectors - Don't use arbitrary waits - use
waitForAngularStability - Don't share state between tests - each test should be independent
- Don't access DOM directly - use page objects
- Don't skip error handling - tests should fail clearly
- Don't use
anytypes - maintain type safety
Test Isolation
Each test gets:
- Isolated browser context (clean storage)
- Unique test prefix (
W0-P0-,W1-P0-, etc.) - Fresh page instance
This ensures tests don't interfere with each other.
Handling Flakiness
// Use waitFor with explicit conditions
await page.waitForFunction(() => document.querySelectorAll('task').length === 3, {
timeout: 10000,
});
// Use locator assertions (auto-retry)
await expect(page.locator('task')).toHaveCount(3);
// Avoid fixed timeouts
await page.waitForTimeout(1000); // BAD
await waitForAngularStability(page); // GOOD
Troubleshooting
Test Fails with "Element not found"
- Check if selector is correct in
constants/selectors.ts - Add wait before interaction:
await waitForAngularStability(page) - Use
await element.waitFor({ state: 'visible' }) - Check if element is in a different context (iframe, shadow DOM)
Test Timeout
- Increase timeout in specific waitFor calls
- Check if Angular is stuck - look for pending HTTP requests
- Use
page.pause()to debug interactively - Check network tab for failed requests
Flaky Tests
- Add proper waits:
waitForAngularStability,waitForAppReady - Avoid
page.waitForTimeout()- use condition-based waits - Check for race conditions - ensure state is persisted
- Use
waitForStatePersistencebefore operations that depend on saved state
Debugging
// Pause execution and open Playwright Inspector
await page.pause();
// Take screenshot
await page.screenshot({ path: 'debug.png' });
// Console log page content
console.log(await page.content());
// Get element text for debugging
const text = await page.locator('task').first().textContent();
console.log('Task text:', text);
Running Single Test
# Run specific file
npm run e2e:file tests/task-basic/task-crud.spec.ts
# Run in debug mode
npm run e2e:debug
# Run in headed mode to see browser
npm run e2e:headed
Examples
Example 1: Full Task CRUD Test
import { test, expect } from '../../fixtures/test.fixture';
test.describe('Task CRUD', () => {
test('should create, edit, and delete tasks', async ({
page,
workViewPage,
taskPage,
}) => {
await workViewPage.waitForTaskList();
// Create
await workViewPage.addTask('Task 1');
await workViewPage.addTask('Task 2');
await expect(taskPage.getAllTasks()).toHaveCount(2);
// Edit
const firstTask = taskPage.getTask(1);
await taskPage.editTaskTitle(firstTask, 'Updated Task');
await expect(taskPage.getTaskTitle(firstTask)).toContainText('Updated Task');
// Mark as done
await taskPage.markTaskAsDone(firstTask);
await expect(taskPage.getDoneTasks()).toHaveCount(1);
await expect(taskPage.getUndoneTasks()).toHaveCount(1);
});
});
Example 2: Project Workflow
test('should create project with tasks', async ({
projectPage,
workViewPage,
taskPage,
}) => {
await projectPage.createAndGoToTestProject();
await workViewPage.addTask('Project Task');
await projectPage.addNote('Important notes');
const task = taskPage.getTask(1);
await taskPage.markTaskAsDone(task);
await projectPage.archiveDoneTasks();
await expect(taskPage.getUndoneTasks()).toHaveCount(0);
});
Example 3: Settings Test
test('should configure plugin', async ({ settingsPage, page }) => {
await settingsPage.navigateToPluginSettings();
const pluginExists = await settingsPage.pluginExists('Test Plugin');
expect(pluginExists).toBeTruthy();
await settingsPage.enablePlugin('Test Plugin');
expect(await settingsPage.isPluginEnabled('Test Plugin')).toBeTruthy();
await settingsPage.navigateBackToWorkView();
await expect(page).toHaveURL(/tag\/TODAY/);
});
Getting Help
- Check existing tests in
e2e/tests/for examples - Review page objects in
e2e/pages/for available methods - Look at
constants/selectors.tsfor available selectors - Use Playwright Inspector (
npm run e2e:debug) for debugging - Check Playwright docs: https://playwright.dev/
Summary Checklist
When writing a new test:
- Create test file in appropriate
tests/subdirectory - Import
testandexpectfromfixtures/test.fixture.ts - Use page objects for all interactions
- Use selectors from
constants/selectors.ts - Add proper waits (
waitForAngularStability, etc.) - Use descriptive test names
- Ensure test is isolated (no shared state)
- Run test locally before committing
- Test passes consistently (run 3+ times)