Compare commits

..
Author SHA1 Message Date
Antigravity AI 2b4c2dc33e fix(ci): resolve playwright environment setup and database initialization
Changes:
- Patch: Added pnpm run setup step to .github/workflows/playwright.yml to generate .env in CI
- Patch: Added explicit loadEnv() helper to 	ests/global.setup.ts and 	ests/global.teardown.ts to ensure database credentials are fresh
- Patch: Hardened scripts/safe-db-push.mjs to detect missing DATABASE_URL and explicitly prompt for pnpm run setup rather than assuming production
- Patch: Updated scripts/dev.mjs to execute pnpm exec next dev instead of raw
ext dev to resolve pathing issues
- Patch: Bumped version in package.json to 2.14.4
2026-05-15 14:50:18 +12:00
Antigravity AI d08c77d8cc fix(e2e): explicitly load .env in teardown and fix dev command pathing 2026-05-15 13:35:25 +12:00
Antigravity AI 9083381f6f docs(e2e): document Playwright infrastructure and mock plugin lifecycle 2026-05-15 13:23:52 +12:00
Antigravity AI 41a30cb66a Merge main into feature/playwright-ci-setup 2026-05-15 13:20:13 +12:00
Antigravity AI 7acd879523 fix(ci): restrict GITHUB_TOKEN permissions to read contents 2026-05-15 13:12:09 +12:00
SilvertakanaandCopilot Autofix powered by AI 1594617d0c Potential fix for pull request finding 'CodeQL / Workflow does not contain permissions'
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-05-15 13:09:40 +12:00
Antigravity AI d661b3f297 feat(testing): add Playwright E2E infrastructure and stabilize test suite
- Add Playwright E2E configuration and ui-navigation / plugin-system tests
- Add GitHub Actions workflow for Playwright CI tests
- Add test helpers and fixtures (e2e-mock-plugin)
- fix(testing): resolve UnverifiedPluginBatchDialog UI blocking issue in E2E tests
- fix(testing): limit Playwright to 2 workers locally to avoid Next.js/Prisma exhaustion
- fix(api): replace deprecated processAuthCodeResponse with authorizationCodeGrant
- test(ui): add data-testid to PanelToggleArrows and AppShell
2026-05-15 13:06:26 +12:00
Silvertakana 28e4e67043 feat: Multi-Worktree Database Lifecycle Automation and Deterministic Ports (#133)
* feat: implement Extensible Bottom Panels and Worktree DB automation

- feat: Implemented BottomPanelManager and circular navigation dock for plugins
- feat: Added dynamic DATABASE_URL injection with deterministic port assignments
- fix: Added 3-retry mechanism to handle file lock (EBUSY / os error 32) issues
- feat: Added telemetry for boot sequence visibility

* fix(ui): resolve TS2339 by accessing plugin.name directly instead of plugin.metadata
2026-05-15 11:54:55 +12:00
Silvertakana 594f85afb2 feat(dx): implement worktree DB orchestration and graceful dev teardown (#132)
* feat(dx): implement worktree DB orchestration and graceful dev teardown

- feat(dx): [Minor] Implement deterministic port binding per git worktree
  to mitigate Docker port conflicts during parallel development.
- feat(dx): [Minor] Implement graceful development environment teardown
  using a custom node orchestrator (scripts/dev.mjs) replacing CLI concurrently,
  enabling cross-platform tree-kill and optional DB stopping on exit.
- build(deps): Add tree-kill for process termination.
- fix(dx): Prevent rm -rf from orphaning Docker volumes by adding
  a db:prune script and tying volume cleanup to git-wt remove.

* fix: update openid-client api usage to v6 and resolve db import

- Migrated processAuthCodeResponse to authorizationCodeGrant
- Updated db import to export prisma client correctly
- Updated unit tests with v6 openid-client mocks
- Bumped version to 2.13.1

* fix(ci): setup .env from example in local dev CI test
2026-05-15 11:20:29 +12:00
Antigravity AI b29133fca0 feat: add watcher script for automatic local plugin synchronization 2026-05-14 22:23:52 +12:00
Antigravity AI ac0092c8a8 ci: add workflow to test local development environment startup and predev tasks 2026-05-14 22:19:44 +12:00
Antigravity AI f0daefd53d chore: map postgres port to host for external access in docker-compose 2026-05-14 22:09:35 +12:00
35 changed files with 1329 additions and 1032 deletions

No files matched your search

+14
View File
@@ -39,6 +39,17 @@ Frontend runs at `http://localhost:3000`.
- **Type-Level Contract Testing**: When defining shared TypeScript interfaces/contracts (e.g., in `wwv-plugin-sdk`), you MUST use `expectTypeOf` from `vitest` to assert the actual contract shapes at compile-time instead of writing literal-value identity runtime assertions. You must also enforce `@ts-expect-error` negative type tests to ensure missing or invalid fields trigger compilation errors.
- **Key test files**: `rateLimit.test.ts`, `edition.test.ts`, `demoAdmin.test.ts`, `DeclarativePlugin.test.ts`, `cors.test.ts`, `repository.test.ts`, `marketplaceToken.test.ts`
### E2E Testing (Playwright)
WorldWideView uses Playwright for End-to-End browser testing to verify the complete UI integration including NextAuth.
- **Run**: `pnpm run test:e2e` (Ensure your database is running before executing)
- **Auth Bypass**: Playwright uses a `global.setup.ts` to directly insert a test user into the database and simulate a UI login to capture a `storageState.json` cookie file. This allows all tests to run pre-authenticated without bypassing production security logic.
- **Database Access in Setup**: Because Playwright setup scripts run in a vanilla Node context, importing Next.js backend utilities like `src/lib/db.ts` will crash with `next/headers` resolution errors. You MUST instantiate `PrismaClient` directly using `@prisma/adapter-pg` in any Playwright `setup` or `teardown` scripts.
- **Component Synchronization**: Do not use arbitrary timeouts. Tests MUST wait for the application boot sequence to finish by waiting for the `[data-testid="app-ready"]` marker on the `AppShell` to be attached.
- **Stable Selectors**: Always use `data-testid` properties (e.g. `data-testid="panel-toggle-left"`) for interacting with UI components in E2E tests rather than fragile CSS classes or dynamic text.
- **Worktree Port Conflicts**: If you are testing in a git worktree, configure `playwright.config.ts` to spawn the `webServer` on an alternative port (e.g. `3001`) to avoid colliding with other running worktrees.
## Security Headers
Configured in `next.config.ts` `headers()`:
@@ -248,6 +259,9 @@ The production Coolify instance runs on a local server at `192.168.68.64`. Direc
1. Push to `silvertakana/worldwideview`
2. Coolify webhook triggers → automated BuildKit deployment on the host server.
**GitHub Actions Workflows:**
- **Minimal Permissions:** CodeQL and GitHub security best practices dictate that `GITHUB_TOKEN` permissions should always be explicitly constrained. When creating or modifying `.github/workflows/*.yml` files, you MUST always include an explicit `permissions` block (e.g., `permissions: { contents: read }` or similar required scopes) at the top level or job level to adhere to the principle of least privilege.
**Coolify Deployment Rules & Gotchas (The "Redis 500k" Rule):**
- **Coolify Pulls from GitHub:** Coolify does *not* deploy your local workspace files. It strictly clones the repository from GitHub.
- **Push Before You Deploy:** If you make a critical infrastructure or optimization fix locally (e.g., swapping a massive `HSET` pipeline for a compressed 5-min throttled `setLiveSnapshot`), you **must** `git commit` and `git push` those changes to the `main` branch before triggering a Coolify deployment.
+34
View File
@@ -0,0 +1,34 @@
---
trigger: testing
description: Guidelines and architecture for the Playwright End-to-End (E2E) testing infrastructure.
---
# E2E Testing Infrastructure
The WorldWideView project uses **Playwright** for end-to-end (E2E) testing. This document outlines the boundaries, architectural decisions, and conventions required when authoring or modifying E2E tests.
## 1. Resource Constraints & Parallelism
- **Worker Limits:** The Playwright configuration (`playwright.config.ts`) is strictly limited to a maximum of **2 workers**.
- **Reasoning:** Running Next.js compilation alongside a heavy Prisma connection pool inside multiple parallel test workers will lead to database connection exhaustion and resource contention on CI and local environments. Do not increase the worker count beyond 2 without careful consideration of the database pool limits.
## 2. Test User Lifecycle
E2E tests require an authenticated user to access core application features. We manage this test user securely to ensure the environment stays pristine:
- **Setup (`tests/global.setup.ts`):** Before tests run, the global setup script defensively deletes any existing test user (`[email protected]`) and creates a fresh instance with the `ADMIN` role. It then performs a UI login to capture the authentication state, which is shared across all test files.
- **Teardown (`tests/global.teardown.ts`):** After the entire test suite completes (regardless of success or failure), the global teardown script runs and completely purges the test user from the database.
- **Safety:** Do not use `[email protected]` for manual testing. It is volatile and intended exclusively for the CI test runner.
## 3. UI Interaction Conventions
- **Strict Selector Usage:** Always use `data-testid` selectors (e.g., `getByTestId('panel-toggle-left')`) for DOM interactions. Do not rely on brittle CSS classes or deep DOM structures. If a `data-testid` is missing from an element you need to test, add it to the React component first.
- **Dialog Interception:** WorldWideView relies on heavy frontend plugin discovery and dynamic rendering. For example, the `UnverifiedPluginBatchDialog` may unexpectedly appear and block UI interactions in a fresh browser context.
- *Mitigation:* Ensure your test suites either explicitly handle these dialogs (e.g., in a `beforeEach` block) or inject mock plugins that bypass the verification flow entirely.
## 4. Mock Plugins
- **Injection:** We inject safe, deterministic mock plugins into the database during the `global.setup.ts` phase to test the core rendering pipeline without relying on external APIs.
- **Location:** Mock plugin configurations and manifests are stored in `public/e2e-fixtures/`. When modifying the rendering engine, ensure you also update the mock plugin (`public/e2e-fixtures/mock-plugin.js`) to reflect any changes in the Plugin SDK capabilities.
## 5. Security Permissions
- When integrating Playwright tests into GitHub Actions (e.g., `.github/workflows/playwright.yml`), you MUST include an explicit permissions block (e.g., `permissions: { contents: read }`) to adhere to CodeQL and least-privilege scoping rules.
> [!WARNING]
> If you encounter flaky tests or `ECONNREFUSED` errors during Playwright runs, check if the local Next.js dev server or the Docker engine stack is competing for ports (e.g., port 5432 or 3000). Ensure `pnpm run dev:backends` is running and stable before launching the test suite.
+13 -4
View File
@@ -24,20 +24,29 @@ If you create a worktree inside a subdirectory of the current repo (e.g., `.agen
Do not use raw `git worktree add`. Always use the `git-wt` alias provided by Worktrunk. It is pre-configured via `.config/wt.toml` to:
- Automatically place the worktree in the correct sibling path.
- Automatically run `pnpm install`.
- Automatically copy `.env` and `.env.local` files so the environment works immediately.
- Automatically copy `.env` files so the environment works immediately.
> [!IMPORTANT]
> **For AI Agents:** You MUST append the `--yes` flag when creating worktrees to bypass the interactive approval prompt for these hooks, otherwise the command will fail in your non-interactive shell.
### 3. Database Lifecycle & Port Assignment
Each worktree gets a deterministic PostgreSQL port assigned automatically based on its directory hash (to avoid collisions between multiple running worktrees).
> [!CAUTION]
> **Orphaned Volumes:** You MUST use `git-wt remove` to delete worktrees. This triggers a `pre-remove` hook that cleanly tears down the Docker database. If you manually delete the folder (`rm -rf`), the Docker volume is orphaned. If this happens, run `pnpm run db:prune` in the main repository to garbage collect orphaned database volumes.
## Quick Reference
| Action | Command | Details |
| :--- | :--- | :--- |
| **Create Worktree** | `git-wt switch --create <branch>` | Provisions the sibling directory, branch, env files, and dependencies. |
| **Create Worktree** | `git-wt switch --create <branch> --yes` | Provisions the sibling directory, branch, env files, and dependencies. |
| **Delete Worktree** | `git-wt remove` | Deletes the worktree and the associated branch cleanly. Run from within the worktree. |
## Implementation Steps
1. Run the create command from the main repository:
1. Run the create command from the main repository (always include `--yes`):
```bash
git-wt switch --create feature/my-new-idea
git-wt switch --create feature/my-new-idea --yes
```
2. **CRITICAL:** Change your working directory to the newly created worktree before editing files. Worktrunk creates it as a sibling.
```bash
+4 -1
View File
@@ -2,4 +2,7 @@
install_deps = "pnpm install"
[[pre-start]]
copy_env = """powershell -Command "if (Test-Path '../worldwideview/.env') { Copy-Item '../worldwideview/.env' '.env' -Force }; if (Test-Path '../worldwideview/.env.local') { Copy-Item '../worldwideview/.env.local' '.env.local' -Force }""""
copy_env = """powershell -Command "if (Test-Path '../worldwideview/.env') { Copy-Item '../worldwideview/.env' '.env' -Force }""""
[[pre-remove]]
docker_clean = "docker compose down -v"
+5
View File
@@ -55,6 +55,11 @@ NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS=
# Edition: "local" | "cloud" | "demo"
NEXT_PUBLIC_WWV_EDITION=local
# Optional Database Teardown
# If set to true, terminating 'pnpm run dev' (Ctrl+C) will automatically
# stop the local database container (freeing up port 5432).
WWV_TEARDOWN_DB_ON_EXIT=false
# Demo Admin Secret (demo edition only)
# Allows operator plugin management on the demo instance via x-wwv-admin-secret header.
# Generate any random string. Only set this on the demo deployment.
+42
View File
@@ -0,0 +1,42 @@
name: Playwright Tests
on:
push:
branches: [ main, master ]
pull_request:
branches: [ main, master ]
permissions:
contents: read
jobs:
test:
timeout-minutes: 60
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
with:
version: 9.15.4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'pnpm'
- name: Install dependencies
run: pnpm install
- name: Install Playwright Browsers
run: pnpm exec playwright install --with-deps
- name: Run Project Setup
run: pnpm run setup
- name: Run Playwright tests
run: pnpm test:e2e
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with:
name: playwright-report
path: playwright-report/
retention-days: 30
+60
View File
@@ -0,0 +1,60 @@
name: Test Local Dev Environment
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test-dev:
name: Test Local Dev Startup
runs-on: ubuntu-latest
env:
NEXT_PUBLIC_WWV_EDITION: local
AUTH_SECRET: ci-placeholder-secret-not-used-in-tests
steps:
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v6
with:
node-version: 22
cache: pnpm
- name: Create coolify docker network
# Needed because docker-compose.yml references external coolify network
run: docker network create coolify || true
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Setup environment
run: cp .env.example .env
- name: Test predev setup
# Tests that Docker DB boots, port mappings work, Prisma pushes schema, and plugins sync
run: pnpm run predev
- name: Test dev server startup
run: |
# Start the dev server in the background
pnpm run dev &
DEV_PID=$!
echo "Waiting for Next.js to respond on port 3000..."
# Wait up to 120 seconds for the dev server to return a response
timeout 120 bash -c 'until curl -s http://localhost:3000 > /dev/null; do sleep 5; done'
# Check if the process is still running
if ! kill -0 $DEV_PID 2>/dev/null; then
echo "Dev server crashed or failed to start within timeout!"
exit 1
fi
echo "Dev server started successfully!"
# Graceful shutdown
kill $DEV_PID
+6 -1
View File
@@ -127,4 +127,9 @@ skills-lock.json
/wwv-seeders/
/wwv-seeders-private/
/wwv-test/
worldwideview.code-workspace
worldwideview.code-workspace
# Playwright
/playwright-report/
/test-results/
/playwright/.auth/
+4 -1
View File
@@ -155,6 +155,7 @@ Read the relevant rule file when working in that domain:
| `continuous-improvement` | When to create/update rules, skills, or workflows | `.agents/rules/continuous-improvement.md` |
| `context-and-memory` | How to orient and maintain project context between sessions | `.agents/rules/context-and-memory.md` |
| `troubleshooting-and-debugging` | Resolving plugin latency, namespace collisions, or deployment issues | `.agents/rules/troubleshooting-and-debugging.md` |
| `e2e-testing` | Guidelines and architecture for the Playwright End-to-End (E2E) testing infrastructure | `.agents/rules/e2e-testing.md` |
---
@@ -208,7 +209,9 @@ Refer to these skill documents for specialized tasks:
- **Workflow**: You **MUST** use the `/commit` workflow before every git commit to ensure proper semantic versioning bumps.
- **Required Checks**: Ensure `pnpm test` and `pnpm build` complete successfully before proposing a merge.
- **Review Process**: Use `/pr-review` to conduct a comprehensive multi-role review on any pull request.
- **Git Worktrees**: We use [Worktrunk](https://github.com/max-sixty/worktrunk) to manage parallel branches and avoid relative path breakage in the monorepo. Use `git-wt switch --create <branch>` to provision isolated sibling worktrees automatically configured with `.env` files and `pnpm install`. Use `git-wt remove` to clean up.
- **Git Worktrees & Database Lifecycle**: We use [Worktrunk](https://github.com/max-sixty/worktrunk) to manage parallel branches and avoid relative path breakage. `git-wt switch --create <branch>` provisions isolated sibling worktrees configured with `.env` files and `pnpm install`. The database port is assigned deterministically based on the directory hash.
> [!CAUTION]
> You MUST use `git-wt remove` to clean up worktrees. Manually deleting a worktree folder (`rm -rf`) will orphan the associated PostgreSQL Docker volume. If this happens, you must manually run `pnpm run db:prune` in the main repository to reclaim disk space.
---
+2 -2
View File
@@ -42,8 +42,8 @@ services:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: worldwideview
expose:
- "5432"
ports:
- "${WWV_DB_PORT:-5432}:5432"
volumes:
- postgres-data:/var/lib/postgresql/data
healthcheck:
+6 -2
View File
@@ -1,6 +1,6 @@
{
"name": "worldwideview",
"version": "2.11.0",
"version": "2.14.4",
"private": true,
"type": "module",
"packageManager": "[email protected]",
@@ -8,7 +8,7 @@
"setup": "node scripts/setup.mjs",
"test-worktree": "node scripts/test-worktree.mjs",
"clean": "node -e \"const fs=require('fs');fs.rmSync('.next',{recursive:true,force:true})\"",
"dev": "concurrently \"pnpm run dev:plugins\" \"next dev\"",
"dev": "node scripts/dev.mjs",
"dev:all": "concurrently -n \"dev,backends\" -c \"magenta,blue\" \"pnpm dev\" \"pnpm dev:backends\"",
"dev:backends": "docker compose --profile engine up wwv-data-engine wwv-redis",
"dev:plugins": "node scripts/watch-local-plugins.mjs",
@@ -18,9 +18,11 @@
"build": "next build --webpack",
"start": "next start",
"test": "vitest run",
"test:e2e": "playwright test",
"test:mutate": "stryker run",
"lint": "eslint .",
"db:reset": "npx prisma migrate reset --force",
"db:prune": "node scripts/db-prune.mjs",
"generate": "prisma generate"
},
"dependencies": {
@@ -59,6 +61,7 @@
"zustand": "^5.0.13"
},
"devDependencies": {
"@playwright/test": "^1.60.0",
"@stryker-mutator/core": "^9.6.1",
"@stryker-mutator/vitest-runner": "^9.6.1",
"@testing-library/dom": "^10.4.1",
@@ -78,6 +81,7 @@
"fast-check": "^4.8.0",
"jsdom": "^28.1.0",
"rollup-plugin-external-globals": "^0.13.0",
"tree-kill": "^1.2.2",
"tsx": "^4.21.0",
"typescript": "^5",
"vite": "^8.0.12",
+6
View File
@@ -277,6 +277,12 @@ export interface WorldPlugin {
getSettingsComponent?(): ComponentType<{ pluginId: string }>;
/** Custom React component injected into the Globe view for rendering primitives/data sources (e.g. GeoJSON). */
getGlobeComponent?(): ComponentType<{ viewer: any; enabled: boolean }>;
/**
* Returns a React component to be rendered inside the Bottom Panel when this plugin's
* dock button is selected. The panel is resizable and can be expanded to fullscreen.
* If not provided, the plugin will not appear in the bottom dock.
*/
getBottomPanelComponent?(): ComponentType<{ pluginId: string }>;
requiresConfiguration?(settings: unknown): boolean;
/** Map raw websocket payload into GeoEntity array. Optional existingEntities is provided so plugins can merge state (e.g. historical trails). */
mapWebsocketPayload?(payload: any, existingEntities?: GeoEntity[]): GeoEntity[];
+52
View File
@@ -0,0 +1,52 @@
import { defineConfig, devices } from '@playwright/test';
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
timeout: 60000,
expect: {
timeout: 10000,
},
globalSetup: './tests/global.setup.ts',
globalTeardown: './tests/global.teardown.ts',
testDir: './tests',
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. Restrict to 2 locally to prevent Next.js compilation overload. */
workers: process.env.CI ? 1 : 2,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: 'http://localhost:3001',
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
},
/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
storageState: 'playwright/.auth/user.json'
},
},
],
/* Run your local dev server before starting the tests */
webServer: {
command: 'pnpm dev',
env: { PORT: '3001' },
url: 'http://localhost:3001',
reuseExistingServer: !process.env.CI,
timeout: 120 * 1000,
},
});
+53 -967
View File
File diff suppressed because it is too large. Load diff
+14
View File
@@ -0,0 +1,14 @@
{
"id": "e2e-mock-plugin",
"name": "E2E Mock Plugin",
"version": "1.0.0",
"description": "A static mock plugin used for Playwright E2E tests.",
"author": "WorldWideView Automated Tests",
"type": "extension",
"format": "bundle",
"trust": "unverified",
"entry": "/e2e-fixtures/mock-plugin.js",
"capabilities": ["ui:sidebar"],
"category": "utility",
"extends": ["sidebar"]
}
+64
View File
@@ -0,0 +1,64 @@
// This file is loaded by the plugin manager in the E2E test environment.
// It bypasses the build step and directly uses the host's injected React instance.
export default {
// Basic plugin metadata required by WorldPlugin interface
id: "e2e-mock-plugin",
name: "E2E Mock Plugin",
description: "A mock plugin for E2E testing.",
icon: "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=", // Empty SVG as fallback
category: "custom",
version: "1.0.0",
// Lifecycle
initialize: async (ctx) => {
console.log("[e2e-mock-plugin] Initialized");
},
destroy: () => {
console.log("[e2e-mock-plugin] Destroyed");
},
// Data
fetch: async (timeRange) => {
return []; // No entities for this mock
},
getPollingInterval: () => {
return 60000;
},
// Rendering
getLayerConfig: () => {
return {
color: "#00FF00",
clusterEnabled: false,
clusterDistance: 50
};
},
renderEntity: (entity) => {
return {
type: "point",
color: "#00FF00",
size: 5
};
},
// Provide a UI component using the host's React instance
getSidebarComponent: () => {
// Access React from the global host object injected by WorldWideView
const React = globalThis.__WWV_HOST__.React;
if (!React) {
console.error("[e2e-mock-plugin] Failed to resolve React from __WWV_HOST__");
return null;
}
// Return a component function, not just an element
return function MockSidebar() {
return React.createElement(
"div",
{ "data-testid": "e2e-mock-panel", style: { padding: "16px", background: "rgba(0, 255, 0, 0.1)", border: "1px solid green" } },
"Mock Panel (E2E Test)"
);
};
}
};
+78
View File
@@ -9,6 +9,7 @@
import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
// Load environment variables manually since dotenv might not be installed globally
/**
@@ -46,6 +47,83 @@ if (skipLocalDb) {
process.exit(0);
}
// Deterministic Port Assignment
const cwd = process.cwd();
const folderName = path.basename(cwd);
let port = 5432; // Default for main repo
if (folderName !== 'worldwideview') {
const hash = crypto.createHash('sha256').update(cwd).digest('hex');
const portOffset = parseInt(hash.substring(0, 4), 16) % 1000;
port = 5433 + portOffset;
}
process.env.WWV_DB_PORT = port.toString();
console.log(`🔌 Assigned deterministic database port: ${port}`);
// Robust rewrite of DATABASE_URL in .env
const envPath = path.resolve(cwd, '.env');
if (fs.existsSync(envPath)) {
const envContent = fs.readFileSync(envPath, 'utf8');
const lines = envContent.split(/\r?\n/);
const targetUrl = `DATABASE_URL="postgresql://postgres:[email protected]:${port}/worldwideview?schema=public"`;
let foundTargetActive = false;
let linesModified = false;
const newLines = lines.map(line => {
// Check if line is an active DATABASE_URL
if (/^\s*DATABASE_URL\s*=/.test(line)) {
if (line.trim() === targetUrl) {
foundTargetActive = true;
return line;
} else {
console.warn(`⚠️ [Telemetry] Commenting out conflicting DATABASE_URL: ${line.trim()}`);
linesModified = true;
return `# ${line}`;
}
}
return line;
});
if (!foundTargetActive) {
console.log(`🔌 [Telemetry] Injecting correct local DATABASE_URL for port ${port}.`);
newLines.push(``);
newLines.push(`# Dynamically injected by boot-db.mjs for worktree`);
newLines.push(targetUrl);
linesModified = true;
}
if (linesModified) {
const newContent = newLines.join('\n');
// File write with retries and telemetry
const maxRetries = 3;
let attempt = 0;
while (attempt < maxRetries) {
try {
fs.writeFileSync(envPath, newContent, 'utf8');
break; // Success
} catch (err) {
attempt++;
if (err.code === 'EBUSY' || err.code === 'EPERM' || err.message.includes('os error 32')) {
console.warn(`⚠️ [Telemetry] File lock encountered on .env (attempt ${attempt}/${maxRetries}). Retrying in 100ms...`);
if (attempt >= maxRetries) {
console.error('❌ Failed to write .env after multiple attempts due to file locks.');
throw err;
}
// Synchronous sleep since boot-db.mjs isn't currently inside an async IIFE
const start = Date.now();
while (Date.now() - start < 100) {}
} else {
throw err;
}
}
}
}
}
console.log('🚀 Checking local PostgreSQL database...');
try {
+72
View File
@@ -0,0 +1,72 @@
/**
* @file db-prune.mjs
* @description Garbage collects orphaned Docker volumes from deleted git worktrees.
* Resolves the issue where manually deleting a worktree folder (rm -rf) leaves
* behind persistent database and data volumes.
*/
import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
console.log('🧹 Starting Garbage Collection for orphaned WorldWideView Docker volumes...');
try {
// Get all docker volumes
const volumesOutput = execSync('docker volume ls --format "{{.Name}}"').toString();
const volumes = volumesOutput.split('\n').map(v => v.trim()).filter(Boolean);
// Identify WorldWideView volumes
const wwvVolumes = volumes.filter(v =>
(v.startsWith('worldwideview') && v.endsWith('_postgres-data')) ||
(v.startsWith('worldwideview') && v.endsWith('_wwv-data'))
);
if (wwvVolumes.length === 0) {
console.log('✅ No WorldWideView volumes found.');
process.exit(0);
}
// Get active worktree folders in the parent directory
const parentDir = path.resolve(process.cwd(), '..');
const folders = fs.readdirSync(parentDir, { withFileTypes: true })
.filter(dirent => dirent.isDirectory() && dirent.name.startsWith('worldwideview'))
.map(dirent => dirent.name);
// Compute their expected Docker project names (lowercase, alphanumeric only)
// Docker Compose defaults to this sanitization for project names based on directories
const activeProjectNames = new Set(
folders.map(folder => folder.replace(/[^a-zA-Z0-9]/g, '').toLowerCase())
);
let orphanedCount = 0;
for (const volume of wwvVolumes) {
let projectName = '';
if (volume.endsWith('_postgres-data')) {
projectName = volume.slice(0, -'_postgres-data'.length);
} else if (volume.endsWith('_wwv-data')) {
projectName = volume.slice(0, -'_wwv-data'.length);
}
if (!activeProjectNames.has(projectName)) {
console.log(`🗑️ Deleting orphaned volume: ${volume}`);
try {
execSync(`docker volume rm ${volume}`, { stdio: 'inherit' });
orphanedCount++;
} catch (rmError) {
console.warn(`⚠️ Could not remove volume ${volume}. It may still be in use.`);
}
}
}
if (orphanedCount === 0) {
console.log('✅ All existing volumes belong to active worktrees. Nothing to prune.');
} else {
console.log(`✅ Successfully pruned ${orphanedCount} orphaned volume(s).`);
}
} catch (error) {
console.error('❌ Failed to prune volumes:', error.message);
process.exit(1);
}
+86
View File
@@ -0,0 +1,86 @@
/**
* @file dev.mjs
* @description Orchestrator for the local development environment.
* Replaces direct usage of 'concurrently' via CLI to allow for optional,
* cross-platform graceful teardown of the Docker database on exit.
* @module scripts
*/
import concurrently from 'concurrently';
import kill from 'tree-kill/index.js';
import { execSync } from 'child_process';
import fs from 'fs';
import process from 'process';
// Manually parse .env to avoid external dependencies early in the boot process
const loadEnv = (file) => {
try {
if (fs.existsSync(file)) {
const content = fs.readFileSync(file, 'utf8');
content.split('\n').forEach(line => {
const match = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/);
if (match) {
const key = match[1];
let value = match[2] || '';
if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
if (value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
process.env[key] = value;
}
});
}
} catch (e) {
// Ignore read errors
}
};
loadEnv('.env');
const teardownDbOnExit = process.env.WWV_TEARDOWN_DB_ON_EXIT === 'true' || process.env.WWV_TEARDOWN_DB_ON_EXIT === '1';
const { result, commands } = concurrently(
[
{ command: 'pnpm run dev:plugins', name: 'plugins', prefixColor: 'magenta' },
{ command: 'pnpm exec next dev', name: 'next', prefixColor: 'blue' }
],
{
prefix: 'name',
killOthers: ['failure', 'success']
}
);
let isShuttingDown = false;
const shutdown = () => {
if (isShuttingDown) return;
isShuttingDown = true;
console.log('\n🛑 Shutting down dev servers...');
// Forcefully kill the process tree of each command cross-platform
commands.forEach(cmd => {
if (cmd.pid) {
kill(cmd.pid, 'SIGKILL');
}
});
if (teardownDbOnExit) {
console.log('📦 Tearing down local PostgreSQL database...');
try {
execSync('docker compose stop db', { stdio: 'inherit' });
console.log('✅ Local database stopped.');
} catch (e) {
console.error('⚠️ Failed to stop database container.');
}
}
process.exit(0);
};
// Listen for termination signals
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
result.then(
() => process.exit(0),
() => process.exit(1)
);
+7
View File
@@ -1,6 +1,13 @@
import { execSync } from 'child_process';
const dbUrl = process.env.DATABASE_URL || '';
if (!dbUrl) {
console.error("❌ ERROR: DATABASE_URL is missing.");
console.error(" Did you forget to run 'pnpm run setup' to generate your .env file?");
process.exit(1);
}
const isLocal = dbUrl.includes('localhost') || dbUrl.includes('127.0.0.1') || dbUrl.includes('host.docker.internal') || dbUrl.includes('postgres:postgres@db:5432');
if (!isLocal) {
+35 -6
View File
@@ -13,29 +13,58 @@ if (!fs.existsSync(LOCAL_PLUGINS_DIR)) {
}
let debounceTimeout = null;
let isSyncing = false;
let pendingSync = false;
function handleFileChange(eventType, filename) {
if (filename && (filename.includes("dist") || filename.includes("node_modules") || filename.endsWith(".map"))) return; // ignore build artifacts
if (filename && (
filename.includes("dist") ||
filename.includes("node_modules") ||
filename.endsWith(".map") ||
filename.includes(".git")
)) return; // ignore build artifacts and git internals
if (debounceTimeout) {
clearTimeout(debounceTimeout);
}
debounceTimeout = setTimeout(async () => {
console.log(`\n[watch] Change detected in local plugins (file: ${filename}). Syncing...`);
try {
await syncAll();
} catch (err) {
console.error(`[watch] Sync failed:`, err);
if (isSyncing) {
pendingSync = true;
return;
}
await runSync(filename);
}, 500);
}
async function runSync(filename) {
isSyncing = true;
console.log(`\n[watch] Change detected in local plugins (file: ${filename}). Syncing...`);
try {
await syncAll();
} catch (err) {
console.error(`[watch] Sync failed:`, err);
} finally {
isSyncing = false;
if (pendingSync) {
pendingSync = false;
await runSync("pending changes");
}
}
}
// Initial sync
console.log(`[watch] Starting initial sync...`);
isSyncing = true;
syncAll().then(() => {
isSyncing = false;
if (pendingSync) {
pendingSync = false;
runSync("pending changes").catch(console.error);
}
console.log(`[watch] Watching ${LOCAL_PLUGINS_DIR} for changes...`);
fs.watch(LOCAL_PLUGINS_DIR, { recursive: true }, handleFileChange);
}).catch(err => {
isSyncing = false;
console.error(`[watch] Initial sync failed:`, err);
});
+4 -5
View File
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import * as client from "openid-client";
import { encryptCredential } from "@/lib/auth/encryption";
import db from "@/lib/db";
import { prisma as db } from "@/lib/db";
export async function GET(req: NextRequest) {
const isHttps = req.nextUrl.protocol === "https:";
const cookiePrefix = isHttps ? "__Host-" : "";
@@ -25,12 +25,11 @@ export async function GET(req: NextRequest) {
authorization_endpoint: new URL("/oauth/authorize", issuer).toString(),
token_endpoint: new URL("/api/tickets/exchange", issuer).toString(),
};
const config = { client_id: "local-app" };
const config = { server, clientId: "local-app" };
try {
const tokens = await client.processAuthCodeResponse(
server,
config,
const tokens = await client.authorizationCodeGrant(
config as any,
new URL(req.url),
{ expectedState: stateCookie, pkceCodeVerifier: verifierCookie }
);
+18 -1
View File
@@ -10,7 +10,24 @@ vi.mock("openid-client", () => ({
discoveryRequest: vi.fn(),
processAuthorizationResponse: vi.fn(),
validateAuthResponse: vi.fn(),
processAuthCodeResponse: vi.fn()
authorizationCodeGrant: vi.fn().mockResolvedValue({ access_token: "mock-token" })
}));
vi.mock("@/lib/auth/encryption", () => ({
encryptCredential: vi.fn().mockResolvedValue({
version: 1,
salt: "mock-salt",
nonce: "mock-nonce",
ciphertext: "mock-ciphertext"
})
}));
vi.mock("@/lib/db", () => ({
prisma: {
marketplaceCredential: {
upsert: vi.fn().mockResolvedValue({})
}
}
}));
describe("PKCE Flow", () => {
+5 -5
View File
@@ -14,7 +14,7 @@ import { LayerPanel } from "@/components/panels/LayerPanel";
import { EntityInfoCard } from "@/components/panels/EntityInfoCard";
import { DataConfigPanel } from "@/components/panels/DataConfig";
import CameraStatsPanel from "@/components/panels/CameraStatsPanel";
import { Timeline } from "@/components/timeline/Timeline";
import { BottomPanelManager } from "@/components/layout/BottomPanelManager";
import { TimelineSync } from "@/core/globe/TimelineSync";
import { pluginManager } from "@/core/plugins/PluginManager";
import { pluginRegistry } from "@/core/plugins/PluginRegistry";
@@ -156,7 +156,7 @@ export function AppShell() {
trackEvent("platform-boot", { duration });
}
}, [boot.phase]);
const timelineOpen = useStore((s) => s.timelineOpen);
const activeBottomPanel = useStore((s) => s.activeBottomPanel);
const rootClasses = [
"app-shell",
@@ -165,11 +165,11 @@ export function AppShell() {
isBooting && boot.timelineReady ? "boot-timeline" : "",
isBooting && boot.controlsReady ? "boot-controls" : "",
!isBooting ? "boot-done" : "",
!timelineOpen ? "timeline-closed" : "",
!activeBottomPanel ? "timeline-closed" : "",
].filter(Boolean).join(" ");
return (
<div className={rootClasses}>
<div className={rootClasses} data-testid={!isBooting ? "app-ready" : undefined}>
<BootOverlay visible={boot.phase === "loading"} />
<div className="app-shell__globe">
@@ -188,7 +188,7 @@ export function AppShell() {
<DataConfigPanel />
{!isMobile && <CameraStatsPanel />}
<EntityInfoCard />
<Timeline />
<BottomPanelManager />
<FloatingVideoManager />
{needsReload && <ReloadToast />}
<ErrorToast />
@@ -0,0 +1,135 @@
.bottom-panel-system {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
flex-direction: column;
align-items: center;
z-index: 1000;
pointer-events: none;
width: calc(100% - 40px);
max-width: 1200px;
}
.bottom-panel-dock {
display: flex;
gap: 8px;
margin-bottom: 12px;
pointer-events: auto;
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.dock-btn {
width: 48px;
height: 48px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 0.7);
cursor: pointer;
transition: all 0.2s ease;
}
.dock-btn:hover {
background: rgba(255, 255, 255, 0.15);
color: white;
}
.dock-btn.active {
background: rgba(43, 115, 255, 0.2);
border-color: rgba(43, 115, 255, 0.5);
color: #4b8df8;
box-shadow: 0 0 15px rgba(43, 115, 255, 0.3);
}
.bottom-panel {
width: 100%;
border-radius: 12px;
display: flex;
flex-direction: column;
pointer-events: auto;
overflow: hidden;
position: relative;
/* Transition applied to height in style, but we can animate opacity/transform too */
transition: height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s ease;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.bottom-panel.closed {
opacity: 0;
pointer-events: none;
border: none;
}
.bottom-panel.open {
opacity: 1;
}
.bottom-panel-resize-handle {
height: 12px;
width: 100%;
cursor: ns-resize;
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 0;
left: 0;
background: transparent;
z-index: 10;
}
.bottom-panel-resize-handle:hover .resize-grip {
background: rgba(255, 255, 255, 0.5);
}
.resize-grip {
width: 40px;
height: 4px;
border-radius: 2px;
background: rgba(255, 255, 255, 0.2);
transition: background 0.2s;
}
.bottom-panel-close-btn {
position: absolute;
top: 12px;
right: 12px;
background: transparent;
border: none;
color: rgba(255, 255, 255, 0.5);
cursor: pointer;
padding: 4px;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
z-index: 10;
transition: all 0.2s ease;
}
.bottom-panel-close-btn:hover {
color: white;
background: rgba(255, 255, 255, 0.1);
}
.bottom-panel-content {
padding: 24px;
flex: 1;
overflow-y: auto;
/* Ensure the content sits below the resize handle */
margin-top: 12px;
display: flex;
flex-direction: column;
}
/* Timeline adjustments inside the new panel */
.timeline__content {
display: flex;
flex-direction: column;
gap: 12px;
height: 100%;
}
@@ -0,0 +1,132 @@
"use client";
import React, { useRef, useState, useEffect } from "react";
import { useStore } from "@/core/state/store";
import { pluginManager } from "@/core/plugins/PluginManager";
import { Timeline } from "@/components/timeline/Timeline";
import "./BottomPanelManager.css";
export function BottomPanelManager() {
const activeBottomPanel = useStore((s) => s.activeBottomPanel);
const setActiveBottomPanel = useStore((s) => s.setActiveBottomPanel);
const bottomPanelHeight = useStore((s) => s.bottomPanelHeight);
const setBottomPanelHeight = useStore((s) => s.setBottomPanelHeight);
const [isDragging, setIsDragging] = useState(false);
const resizeRef = useRef<HTMLDivElement>(null);
// Get all registered plugins that provide a bottom panel component
const plugins = pluginManager.getAllPlugins().map((p) => p.plugin);
const dockablePlugins = plugins.filter((p) => p.getBottomPanelComponent !== undefined);
// Handle mouse drag for resizing the panel
useEffect(() => {
if (!isDragging) return;
const handleMouseMove = (e: MouseEvent) => {
// Calculate new height based on distance from bottom of window
const newHeight = window.innerHeight - e.clientY;
// Clamp between min 200px and max window height - 100px
const clampedHeight = Math.max(200, Math.min(newHeight, window.innerHeight - 100));
setBottomPanelHeight(clampedHeight);
};
const handleMouseUp = () => {
setIsDragging(false);
};
window.addEventListener("mousemove", handleMouseMove);
window.addEventListener("mouseup", handleMouseUp);
return () => {
window.removeEventListener("mousemove", handleMouseMove);
window.removeEventListener("mouseup", handleMouseUp);
};
}, [isDragging, setBottomPanelHeight]);
// Handle mobile auto-close on load (legacy behavior from Timeline)
useEffect(() => {
if (window.innerWidth < 768 && activeBottomPanel !== null) {
setActiveBottomPanel(null);
}
}, []);
// Render active panel content
const renderActivePanelContent = () => {
if (activeBottomPanel === "timeline") {
return <Timeline />;
}
const activePlugin = dockablePlugins.find(p => p.id === activeBottomPanel);
if (activePlugin && activePlugin.getBottomPanelComponent) {
const Component = activePlugin.getBottomPanelComponent();
return <Component pluginId={activePlugin.id} />;
}
return null;
};
return (
<div className="bottom-panel-system">
{/* Dock: Always visible above the panel */}
<div className="bottom-panel-dock">
<button
className={`dock-btn glass-panel ${activeBottomPanel === "timeline" ? "active" : ""}`}
onClick={() => setActiveBottomPanel(activeBottomPanel === "timeline" ? null : "timeline")}
title="Timeline"
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<circle cx="12" cy="12" r="10" />
<polyline points="12 6 12 12 16 14" />
</svg>
</button>
{dockablePlugins.map((plugin) => (
<button
key={plugin.id}
className={`dock-btn glass-panel ${activeBottomPanel === plugin.id ? "active" : ""}`}
onClick={() => setActiveBottomPanel(activeBottomPanel === plugin.id ? null : plugin.id)}
title={plugin.name || plugin.id}
>
{/* Placeholder icon, a real implementation might use an icon provided by the plugin metadata */}
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
<path d="M3 9h18" />
</svg>
</button>
))}
</div>
{/* Active Panel Shell */}
<div
className={`bottom-panel glass-panel ${activeBottomPanel ? "open" : "closed"}`}
style={{ height: activeBottomPanel ? `${bottomPanelHeight}px` : "0px" }}
>
{activeBottomPanel && (
<>
<div
className="bottom-panel-resize-handle"
ref={resizeRef}
onMouseDown={() => setIsDragging(true)}
>
<div className="resize-grip" />
</div>
<button
className="bottom-panel-close-btn"
onClick={() => setActiveBottomPanel(null)}
title="Close Panel"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M18 6 6 18" />
<path d="m6 6 12 12" />
</svg>
</button>
<div className="bottom-panel-content">
{renderActivePanelContent()}
</div>
</>
)}
</div>
</div>
);
}
@@ -48,6 +48,7 @@ export function PanelToggleArrows() {
className={`panel-toggle-btn panel-toggle-btn--left ${isLeftOpen ? "panel-toggle-btn--open" : ""} ${isMobile ? "panel-toggle-btn--mobile" : ""}`}
onClick={handleLeftToggle}
title="Toggle Layers Panel"
data-testid="panel-toggle-left"
>
{isLeftOpen ? <ChevronLeft size={24} /> : <ChevronRight size={24} />}
</button>
@@ -57,6 +58,7 @@ export function PanelToggleArrows() {
className={`panel-toggle-btn panel-toggle-btn--right ${isRightOpen ? "panel-toggle-btn--open" : ""} ${isMobile ? "panel-toggle-btn--mobile" : ""} ${isMobile && mobileRightPanelGlow ? "panel-toggle-btn--glow" : ""}`}
onClick={handleRightToggle}
title="Toggle Data Configuration"
data-testid="panel-toggle-right"
>
{isRightOpen ? <ChevronRight size={24} /> : <ChevronLeft size={24} />}
+2 -28
View File
@@ -30,17 +30,12 @@ export function Timeline() {
const setPlaybackSpeed = useStore((s) => s.setPlaybackSpeed);
const setPlaybackMode = useStore((s) => s.setPlaybackMode);
const timeRange = useStore((s) => s.timeRange);
const timelineOpen = useStore((s) => s.timelineOpen);
const setTimelineOpen = useStore((s) => s.setTimelineOpen);
const [mounted, setMounted] = useState(false);
const [isDemoAdmin, setIsDemoAdmin] = useState(false);
useEffect(() => {
setMounted(true);
if (window.innerWidth < 768) {
setTimelineOpen(false);
}
if (!isDemo) return;
fetch("/api/auth/session")
.then((r) => r.json())
@@ -65,31 +60,10 @@ export function Timeline() {
const formatTime = (date: Date) =>
mounted ? `${date.toLocaleTimeString()} — ${date.toLocaleDateString()}` : "...";
if (!timelineOpen) {
return (
<div className="timeline-toggle-wrapper">
<button
className="timeline-toggle-btn glass-panel"
onClick={() => setTimelineOpen(true)}
title="Open Timeline"
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<circle cx="12" cy="12" r="10"/>
<polyline points="12 6 12 12 16 14"/>
</svg>
</button>
</div>
);
}
return (
<div className="timeline glass-panel">
<button className="timeline-close-btn" onClick={() => setTimelineOpen(false)} title="Hide Timeline">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M18 6 6 18"/>
<path d="m6 6 12 12"/>
</svg>
</button>
<div className="timeline__content">
{/* Row 1: Controls */}
<div className="timeline__controls-row">
+7 -3
View File
@@ -31,7 +31,8 @@ describe('uiSlice', () => {
expect(state.selectedEntity).toBeNull();
expect(state.floatingStreams).toEqual([]);
expect(state.activeConfigTab).toBe('filters');
expect(state.timelineOpen).toBe(true);
expect(state.activeBottomPanel).toBeNull();
expect(state.bottomPanelHeight).toBe(220);
});
it('toggles simple boolean states', () => {
@@ -47,8 +48,11 @@ describe('uiSlice', () => {
store.getState().toggleFilterPanel();
expect(store.getState().filterPanelOpen).toBe(true);
store.getState().setTimelineOpen(false);
expect(store.getState().timelineOpen).toBe(false);
store.getState().setActiveBottomPanel('timeline');
expect(store.getState().activeBottomPanel).toBe('timeline');
store.getState().setBottomPanelHeight(300);
expect(store.getState().bottomPanelHeight).toBe(300);
store.getState().setFeedbackDialogOpen(true);
expect(store.getState().feedbackDialogOpen).toBe(true);
+15 -6
View File
@@ -105,10 +105,17 @@ export interface UISlice {
showErrorToast: (message: string) => void;
/** Dismisses the active error toast. */
clearErrorToast: () => void;
/** Visibility of the temporal timeline controller. */
timelineOpen: boolean;
/** Sets the timeline visibility. */
setTimelineOpen: (open: boolean) => void;
/**
* The ID of the currently active bottom panel, or null when the dock is shown without
* an active panel. The built-in timeline uses the reserved ID "timeline".
*/
activeBottomPanel: string | null;
/** Opens a specific bottom panel by ID, or closes all panels if null is passed. */
setActiveBottomPanel: (id: string | null) => void;
/** Height of the bottom panel in pixels. Clamped between 200 and window height. */
bottomPanelHeight: number;
/** Sets the bottom panel height (used by the resize drag handle). */
setBottomPanelHeight: (height: number) => void;
}
export const createUISlice: StateCreator<AppStore, [], [], UISlice> = (set) => ({
@@ -127,7 +134,8 @@ export const createUISlice: StateCreator<AppStore, [], [], UISlice> = (set) => (
openMobilePanel: null,
mobileRightPanelGlow: false,
feedbackDialogOpen: false,
timelineOpen: true,
activeBottomPanel: null,
bottomPanelHeight: 220,
toggleTheme: () => set((state) => {
const nextTheme = {
"dark": "black",
@@ -207,6 +215,7 @@ export const createUISlice: StateCreator<AppStore, [], [], UISlice> = (set) => (
errorToastMessage: null,
showErrorToast: (message) => set({ errorToastMessage: message }),
clearErrorToast: () => set({ errorToastMessage: null }),
setTimelineOpen: (open) => set({ timelineOpen: open }),
setActiveBottomPanel: (id) => set({ activeBottomPanel: id }),
setBottomPanelHeight: (height) => set({ bottomPanelHeight: height }),
});
+15
View File
@@ -0,0 +1,15 @@
import { test, expect } from '@playwright/test';
test('has title and boots app completely', async ({ page }) => {
await page.goto('/');
// Expect a title "to contain" a substring.
await expect(page).toHaveTitle(/WorldWideView/i);
// Wait for the boot sequence to finish and plugins to load
await page.waitForSelector('[data-testid="app-ready"]', { state: 'attached', timeout: 30000 });
// Verify that the element is actually present
const appReady = await page.locator('[data-testid="app-ready"]');
await expect(appReady).toBeAttached();
});
+140
View File
@@ -0,0 +1,140 @@
import { chromium, type FullConfig } from '@playwright/test';
import { PrismaClient } from '../src/generated/prisma/index.js';
import { PrismaPg } from "@prisma/adapter-pg";
import { Pool } from "pg";
import bcrypt from 'bcryptjs';
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
export const TEST_USER_EMAIL = '[email protected]';
function loadEnv() {
try {
const envPath = path.resolve(process.cwd(), '.env');
if (fs.existsSync(envPath)) {
const content = fs.readFileSync(envPath, 'utf8');
content.split('\n').forEach(line => {
const match = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/);
if (match) {
const key = match[1];
let value = match[2] || '';
if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
if (value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
process.env[key] = value;
}
});
}
} catch (e) {
// Ignore read errors
}
}
async function globalSetup(config: FullConfig) {
loadEnv();
const { storageState, baseURL } = config.projects[0].use;
if (!baseURL) {
throw new Error('baseURL is not defined in Playwright config');
}
const pool = new Pool({ connectionString: process.env.DATABASE_URL || "postgresql://postgres:[email protected]:5432/worldwideview?schema=public" });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });
try {
// 1. Retry/poll mechanism for database connectivity
let dbConnected = false;
for (let i = 0; i < 5; i++) {
try {
await prisma.$queryRaw`SELECT 1`;
dbConnected = true;
break;
} catch (e) {
console.log(`[Setup] Waiting for database (attempt ${i + 1}/5)...`);
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
if (!dbConnected) {
throw new Error('[Setup] Could not connect to database after 5 attempts.');
}
// 2. Generate a secure random password and hash it
const password = crypto.randomUUID();
const hashedPassword = await bcrypt.hash(password, 10);
// 2.5 Defensive Cleanup for Mock Plugin
console.log(`[Setup] Cleaning up any existing mock plugins...`);
await prisma.installedPlugin.deleteMany({
where: { pluginId: 'e2e-mock-plugin' }
});
// 3. Clean up any orphaned user and create the test user
console.log(`[Setup] Upserting test user: ${TEST_USER_EMAIL}`);
await prisma.user.deleteMany({
where: { email: TEST_USER_EMAIL }
});
await prisma.user.create({
data: {
email: TEST_USER_EMAIL,
name: 'Playwright E2E Tester',
hashedPassword: hashedPassword,
role: 'ADMIN',
},
});
// 3.5 Inject the mock plugin for the test environment
console.log(`[Setup] Injecting mock plugin into database...`);
const manifestPath = path.join(process.cwd(), 'public', 'e2e-fixtures', 'manifest.json');
const manifestStr = fs.readFileSync(manifestPath, 'utf-8');
await prisma.installedPlugin.create({
data: {
pluginId: 'e2e-mock-plugin',
version: '1.0.0',
config: manifestStr,
enabled: true
}
});
// Ensure playwright auth directory exists
if (typeof storageState === 'string') {
const authDir = path.dirname(storageState);
if (!fs.existsSync(authDir)) {
fs.mkdirSync(authDir, { recursive: true });
}
}
// 4. Perform UI Login
console.log(`[Setup] Logging in via UI to generate storage state...`);
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(`${baseURL}/login`);
await page.fill('input[name="email"]', TEST_USER_EMAIL);
await page.fill('input[name="password"]', password);
await page.click('button[type="submit"]');
// Wait for redirect to home
await page.waitForURL(baseURL);
// 5. Save storage state
if (typeof storageState === 'string') {
await page.context().storageState({ path: storageState });
} else {
console.warn("Storage state path is not a string, skipping saving context.")
}
await browser.close();
console.log(`[Setup] Global setup complete.`);
} catch (error) {
console.error(`[Setup] Error during global setup:`, error);
throw error;
} finally {
await prisma.$disconnect();
await pool.end();
}
}
export default globalSetup;
+53
View File
@@ -0,0 +1,53 @@
import { type FullConfig } from '@playwright/test';
import { PrismaClient } from '../src/generated/prisma/index.js';
import { PrismaPg } from "@prisma/adapter-pg";
import { Pool } from "pg";
import fs from 'fs';
import path from 'path';
export const TEST_USER_EMAIL = '[email protected]';
function loadEnv() {
try {
const envPath = path.resolve(process.cwd(), '.env');
if (fs.existsSync(envPath)) {
const content = fs.readFileSync(envPath, 'utf8');
content.split('\n').forEach(line => {
const match = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/);
if (match) {
const key = match[1];
let value = match[2] || '';
if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
if (value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
process.env[key] = value;
}
});
}
} catch (e) {
// Ignore read errors
}
}
async function globalTeardown(config: FullConfig) {
loadEnv();
const pool = new Pool({ connectionString: process.env.DATABASE_URL || "postgresql://postgres:[email protected]:5432/worldwideview?schema=public" });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });
console.log(`[Teardown] Cleaning up test user: ${TEST_USER_EMAIL}`);
try {
console.log(`[Teardown] Cleaning up mock plugin...`);
await prisma.installedPlugin.deleteMany({
where: { pluginId: 'e2e-mock-plugin' }
});
await prisma.user.deleteMany({
where: { email: TEST_USER_EMAIL },
});
} catch (e) {
console.error(`[Teardown] Failed to delete test user:`, e);
} finally {
await prisma.$disconnect();
await pool.end();
}
}
export default globalTeardown;
+60
View File
@@ -0,0 +1,60 @@
import { test, expect } from '@playwright/test';
test.describe('Dynamic Plugin System', () => {
test.beforeEach(async ({ page }) => {
// Navigate to root and wait for app to be completely booted
await page.goto('/');
await page.waitForSelector('[data-testid="app-ready"]', { state: 'attached', timeout: 45000 });
});
test('successfully discovers, loads, and renders a mock dynamic plugin', async ({ page }) => {
// Log console messages from the browser
page.on('console', msg => {
console.log(`[Browser Console] ${msg.type()}: ${msg.text()}`);
if (msg.type() === 'error') {
console.log(`[Browser Error] ${msg.location().url}:${msg.location().lineNumber}`);
}
});
// We expect the mock plugin to register its component in the sidebar.
// The LeftPanel or RightPanel (depending on how the plugin manager handles generic 'sidebar' capabilities)
// should render the component returned by getSidebarComponent().
// The mock plugin returns: <div data-testid="e2e-mock-panel">Mock Panel (E2E Test)</div>
const mockPanel = page.locator('[data-testid="e2e-mock-panel"]');
// The unverified plugin dialog might appear for the mock plugin.
const installBtn = page.getByRole('button', { name: /Install Selected/ });
try {
// Wait a short time for the dialog to appear
await installBtn.waitFor({ state: 'visible', timeout: 5000 });
await installBtn.click();
console.log('Clicked "Install Selected" in unverified plugin dialog.');
} catch (e) {
// Dialog didn't appear, possibly because it's a verified plugin or already approved
console.log('Unverified plugin dialog did not appear.');
}
// To ensure the UI is in a state where it might be visible,
// let's check if we need to open the right panel first. Plugins might inject into the right panel.
const rightToggle = page.locator('[data-testid="panel-toggle-right"]');
if (await rightToggle.count() > 0) {
const isInitiallyOpen = await rightToggle.evaluate((node) => node.classList.contains('panel-toggle-btn--open'));
if (!isInitiallyOpen) {
await rightToggle.click();
}
}
// Click the layer item in the left panel to select it and display its config in the right panel
const layerItem = page.locator('.layer-item', { hasText: 'E2E Mock Plugin' });
await expect(layerItem).toBeVisible({ timeout: 10000 });
await layerItem.click();
// Wait for the mock panel to be visible or attached.
// Plugins might take a moment to dynamically load their chunks over HTTP.
await expect(mockPanel).toBeAttached({ timeout: 10000 });
// Assert it contains the expected text
await expect(mockPanel).toContainText('Mock Panel (E2E Test)');
});
});
+84
View File
@@ -0,0 +1,84 @@
import { test, expect } from '@playwright/test';
test.describe('UI Navigation and Panels', () => {
test.beforeEach(async ({ page }) => {
// Navigate to root and wait for app to be completely booted
await page.goto('/');
await page.waitForSelector('[data-testid="app-ready"]', { state: 'attached', timeout: 45000 });
// Dismiss unverified plugin dialog if it appears
const installBtn = page.getByRole('button', { name: /Install Selected/ });
try {
await installBtn.waitFor({ state: 'visible', timeout: 2000 });
await installBtn.click();
} catch (e) {
// Ignore if it doesn't appear
}
});
test('can toggle left layers panel', async ({ page }) => {
const leftToggle = page.locator('[data-testid="panel-toggle-left"]');
await expect(leftToggle).toBeVisible();
// The left panel should open/close. We can check the class or state.
// If we click it, it should toggle the 'panel-toggle-btn--open' class.
// Check initial state (should probably be open by default on desktop, but let's just toggle it and verify class changes)
const isInitiallyOpen = await leftToggle.evaluate((node) => node.classList.contains('panel-toggle-btn--open'));
await leftToggle.click();
if (isInitiallyOpen) {
await expect(leftToggle).not.toHaveClass(/panel-toggle-btn--open/);
} else {
await expect(leftToggle).toHaveClass(/panel-toggle-btn--open/);
}
});
test('can toggle right config panel', async ({ page }) => {
const rightToggle = page.locator('[data-testid="panel-toggle-right"]');
await expect(rightToggle).toBeVisible();
const isInitiallyOpen = await rightToggle.evaluate((node) => node.classList.contains('panel-toggle-btn--open'));
await rightToggle.click();
if (isInitiallyOpen) {
await expect(rightToggle).not.toHaveClass(/panel-toggle-btn--open/);
} else {
await expect(rightToggle).toHaveClass(/panel-toggle-btn--open/);
}
});
test('can interact with timeline controls', async ({ page }) => {
// The browser subagent identified button.timeline-close-btn
const timelineCloseBtn = page.locator('button.timeline-close-btn');
// Ensure it exists in the DOM. Wait for it just in case.
if (await timelineCloseBtn.count() > 0) {
await expect(timelineCloseBtn).toBeVisible();
await timelineCloseBtn.click();
// Test timeline mode toggle
const modeToggle = page.locator('label.timeline__mode-toggle');
if (await modeToggle.count() > 0) {
await expect(modeToggle).toBeVisible();
}
}
});
test('can switch left panel tabs', async ({ page }) => {
// The panel tabs
const dataLayersTab = page.locator('button.panel-tab[title="Data Layers"]');
const imageryTab = page.locator('button.panel-tab[title="Imagery"]');
if (await dataLayersTab.count() > 0 && await imageryTab.count() > 0) {
await expect(dataLayersTab).toBeVisible();
await expect(imageryTab).toBeVisible();
await imageryTab.click();
await expect(imageryTab).toHaveClass(/panel-tab--active/);
await dataLayersTab.click();
await expect(dataLayersTab).toHaveClass(/panel-tab--active/);
}
});
});