chore: initialize frontend miniapp repository

This commit is contained in:
lyf
2026-06-09 21:08:45 +08:00
commit a90f63cef0
107 changed files with 60454 additions and 0 deletions

View File

@@ -0,0 +1,249 @@
---
name: playwright-e2e-tester
description: Expert in end-to-end testing with Playwright, the modern cross-browser testing framework. Specializes in test generation, page object patterns, visual regression testing, and CI/CD integration.
Handles complex testing scenarios including authentication flows, API mocking, and mobile emulation.
version: 1.0.0
metadata:
category: testing
tags:
- e2e
- playwright
- testing
- automation
- ci-cd
- cross-browser
pairs-with:
- skill: test-automation-expert
reason: Playwright E2E tests are one tier in a comprehensive test automation strategy
- skill: webapp-testing
reason: 'Both use Playwright but for different scopes: E2E test suites vs interactive debugging'
- skill: vitest-testing-patterns
reason: Unit tests (Vitest) and E2E tests (Playwright) form complementary test pyramid layers
- skill: github-actions-pipeline-builder
reason: E2E tests run in CI pipelines with browser installation and artifact upload steps
---
# Playwright E2E Tester
## Overview
Expert in end-to-end testing with Playwright, the modern cross-browser testing framework. Specializes in test generation, page object patterns, visual regression testing, and CI/CD integration. Handles complex testing scenarios including authentication flows, API mocking, and mobile emulation.
## When to Use
- Setting up Playwright in a new or existing project
- Writing E2E tests for critical user flows
- Debugging flaky tests or test failures
- Implementing visual regression testing
- Configuring Playwright for CI/CD pipelines
- Migrating from Cypress, Selenium, or Puppeteer
- Testing authenticated flows with session management
- Cross-browser testing (Chromium, Firefox, WebKit)
## Capabilities
### Test Generation & Writing
- Generate Playwright tests from user stories or acceptance criteria
- Write tests using best practices (locators, assertions, waits)
- Implement Page Object Model (POM) patterns
- Create reusable test fixtures and utilities
- Handle dynamic content and race conditions
### Configuration & Setup
- Configure `playwright.config.ts` for different environments
- Set up projects for multiple browsers and viewports
- Configure base URL, timeouts, and retries
- Implement global setup/teardown for auth
- Set up test reporters (HTML, JSON, JUnit)
### Advanced Patterns
- API mocking with `route()` and `fulfill()`
- Network interception and request validation
- Visual regression with `toHaveScreenshot()`
- Accessibility testing with `@axe-core/playwright`
- Mobile emulation and device testing
- Geolocation and permissions mocking
### CI/CD Integration
- GitHub Actions workflow configuration
- Parallel test execution with sharding
- Artifact collection (traces, screenshots, videos)
- Flaky test detection and retry strategies
- Test result reporting and notifications
### Debugging & Maintenance
- Use Playwright Inspector and Trace Viewer
- Debug with `page.pause()` and headed mode
- Analyze test traces for failures
- Reduce test flakiness with proper waits
- Maintain test stability over time
## Dependencies
Works well with:
- `vitest-testing-patterns` - Unit test patterns that complement E2E
- `github-actions-pipeline-builder` - CI/CD pipeline setup
- `accessibility-auditor` - Extended accessibility testing
- `api-architect` - API contract testing alongside E2E
## Examples
### Basic Test Structure
```typescript
import { test, expect } from '@playwright/test';
test.describe('User Authentication', () => {
test('should allow user to sign in', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill('user@example.com');
await page.getByLabel('Password').fill('securepassword');
await page.getByRole('button', { name: 'Sign In' }).click();
await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
await expect(page).toHaveURL('/dashboard');
});
});
```
### Page Object Pattern
```typescript
// pages/LoginPage.ts
import { Page, Locator } from '@playwright/test';
export class LoginPage {
readonly page: Page;
readonly emailInput: Locator;
readonly passwordInput: Locator;
readonly signInButton: Locator;
constructor(page: Page) {
this.page = page;
this.emailInput = page.getByLabel('Email');
this.passwordInput = page.getByLabel('Password');
this.signInButton = page.getByRole('button', { name: 'Sign In' });
}
async goto() {
await this.page.goto('/login');
}
async signIn(email: string, password: string) {
await this.emailInput.fill(email);
await this.passwordInput.fill(password);
await this.signInButton.click();
}
}
```
### Auth Setup Fixture
```typescript
// fixtures/auth.ts
import { test as base } from '@playwright/test';
export const test = base.extend({
authenticatedPage: async ({ page }, use) => {
// Perform authentication
await page.goto('/login');
await page.getByLabel('Email').fill(process.env.TEST_USER!);
await page.getByLabel('Password').fill(process.env.TEST_PASS!);
await page.getByRole('button', { name: 'Sign In' }).click();
// Wait for auth to complete
await page.waitForURL('/dashboard');
// Use the authenticated page in tests
await use(page);
},
});
```
### GitHub Actions CI
```yaml
name: E2E Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Install dependencies
run: npm ci
- name: Install Playwright browsers
run: npx playwright install --with-deps
- name: Run E2E tests
run: npx playwright test
- name: Upload test results
if: always()
uses: actions/upload-artifact@v4
with:
name: playwright-report
path: playwright-report/
```
### Visual Regression Test
```typescript
test('homepage matches snapshot', async ({ page }) => {
await page.goto('/');
// Full page screenshot comparison
await expect(page).toHaveScreenshot('homepage.png', {
fullPage: true,
maxDiffPixelRatio: 0.01,
});
// Component-level screenshot
const hero = page.getByTestId('hero-section');
await expect(hero).toHaveScreenshot('hero-section.png');
});
```
### API Mocking
```typescript
test('displays products from API', async ({ page }) => {
// Mock the API response
await page.route('**/api/products', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([
{ id: 1, name: 'Product A', price: 29.99 },
{ id: 2, name: 'Product B', price: 49.99 },
]),
});
});
await page.goto('/products');
await expect(page.getByText('Product A')).toBeVisible();
await expect(page.getByText('$29.99')).toBeVisible();
});
```
## Best Practices
1. **Use role-based locators** - Prefer `getByRole()`, `getByLabel()`, `getByText()` over CSS selectors
2. **Avoid hard waits** - Use `waitForSelector()`, `waitForURL()`, or assertions instead of `waitForTimeout()`
3. **Isolate tests** - Each test should be independent and not rely on state from other tests
4. **Use fixtures** - Share setup logic through fixtures rather than `beforeEach` hooks
5. **Keep tests focused** - Test one user flow per test, avoid testing multiple unrelated things
6. **Handle flakiness proactively** - Use proper waits, retries, and stable locators
7. **Organize with Page Objects** - Encapsulate page interactions for maintainability
8. **Run in CI** - Always run E2E tests in CI before merging
## Common Pitfalls
- **Flaky locators**: Avoid fragile selectors like `nth-child(3)` or auto-generated class names
- **Race conditions**: Always wait for elements/navigation before interacting
- **Shared state**: Tests should not depend on execution order
- **Slow tests**: Use API calls to set up state instead of UI interactions when possible
- **Missing cleanup**: Clean up test data to avoid pollution between runs

View File

@@ -0,0 +1,206 @@
---
name: production-audit
description: Local-evidence production readiness audit for shipped apps, pre-launch reviews, post-merge checks, and "what breaks in prod?" questions without sending repo data to an external audit service.
origin: community
---
# Production Audit
Use this skill when the user asks whether an application is ready to ship, what
could break in production, or what must be fixed before a launch. This is a
maintainer-safe rewrite of the stale community production-audit idea: it keeps
the useful production-readiness lens and removes unpinned external execution and
third-party data sharing.
## When to Use
- The user asks "is this production-ready", "what would break in prod", "what
did we miss", "audit this repo", or "ready to ship?"
- A feature was merged and needs a pre-deploy or post-merge risk pass.
- A public launch, demo, customer rollout, or investor walkthrough is close.
- CI is green but the user wants production risk, not only test status.
- A deployed URL, release branch, PR, or current checkout is available for
evidence gathering.
## When Not to Use
- During active implementation when the right lens is line-level secure coding;
use `security-review` first.
- For pure libraries, templates, docs-only repos, or scaffolds unless the user
wants packaging/release readiness rather than application readiness.
- When the user asks for a formal compliance audit. This skill is engineering
triage, not legal, financial, medical, or regulatory certification.
- When the only available evidence is a product idea with no repo, deployment,
CI, or runtime surface.
## How It Works
Build the audit from local and user-authorized evidence. Do not run unpinned
remote code, upload repository contents to third-party services, or call
external scanners unless the user explicitly approves that specific tool and
data flow.
Use this order:
1. Establish the release surface.
2. Read recent changes and current branch state.
3. Inspect runtime, auth, data, payment, background-job, AI, and deployment
boundaries that actually exist in the repo.
4. Check CI, tests, migrations, environment documentation, and rollback path.
5. Produce a short ship/block recommendation with specific fixes.
## Evidence Checklist
Start with cheap, local signals:
```text
git status --short --branch
git log --oneline --decorate -20
git diff --stat origin/main...HEAD
```
Then inspect the project-specific surface:
- Package scripts, CI workflows, release scripts, Docker files, and deployment
manifests.
- API routes, webhooks, auth middleware, background workers, cron jobs, and
database migrations.
- Environment variable documentation and startup checks.
- Observability hooks, error reporting, logs, health checks, and dashboards.
- Rollback, seed, migration, and backfill instructions.
- E2E coverage for the user paths that matter most.
If a deployed URL is in scope, use browser or HTTP checks only against that URL
and avoid credentialed actions unless the user supplies a safe test account.
## Risk Lenses
### Security And Auth
- Are public routes, API routes, and admin routes clearly separated?
- Are auth and authorization enforced server-side?
- Are secrets kept out of client bundles, logs, example output, and checked-in
files?
- Are rate limits, CSRF protections, CORS policy, and upload validation present
where the app needs them?
- Does the AI or agent surface defend against prompt injection, tool abuse, and
untrusted content crossing into privileged actions?
### Data Integrity
- Do migrations run forward cleanly and have a rollback or recovery plan?
- Are destructive migrations, backfills, and data imports staged safely?
- Do database policies, grants, and service-role boundaries match the app's
tenancy model?
- Are retries idempotent for writes, jobs, and webhook handlers?
### Payments And Webhooks
- Are webhook signatures verified before parsing trusted payload fields?
- Is each payment, subscription, or fulfillment webhook idempotent?
- Are replay, duplicate delivery, and out-of-order delivery handled?
- Are test-mode and live-mode credentials separated?
### Operations
- Can the app start from a clean checkout using documented commands?
- Are required environment variables named, validated, and fail-fast?
- Is there a health check that proves dependencies are reachable?
- Are deploy, rollback, and incident-owner paths documented?
- Are logs useful without leaking secrets or personal data?
### User Experience
- Are the launch-critical paths covered on desktop and mobile?
- Are forms usable on mobile without input zoom, layout overlap, or blocked
submission states?
- Do loading, empty, error, and permission-denied states tell the user what
happened?
- Is there a support or recovery path when a critical operation fails?
## Scoring
Use scores to force prioritization, not to imply mathematical certainty.
| Band | Score | Meaning |
| --- | --- | --- |
| Blocked | 0-49 | Do not ship until the top risks are fixed |
| Risky | 50-69 | Ship only behind a small rollout or internal beta |
| Launchable With Caveats | 70-84 | Ship if owners accept the listed risks |
| Strong | 85-100 | No obvious launch blockers from available evidence |
Cap the score at `69` if any of these are true:
- Authentication or authorization is missing on sensitive data.
- Payment or fulfillment webhooks are not idempotent.
- Required migrations cannot be run safely.
- Secrets are exposed in client bundles, logs, or committed files.
- There is no rollback path for a high-impact release.
Cap the score at `84` if CI is not green or the launch-critical path was not
tested end to end.
## Output Format
Lead with one sentence:
```text
Production audit: 76/100, launchable with caveats, with webhook idempotency and rollback docs as the two risks to fix before public launch.
```
Then list:
- `Blockers`: must-fix items before deploy.
- `High-value fixes`: next fixes if the user wants to improve the score.
- `Evidence checked`: files, commands, CI, deployed URL, or PRs inspected.
- `Evidence missing`: what would change confidence if provided.
- `Next action`: one concrete fix or verification step.
Keep strengths short. The user asked for readiness, so the useful answer is the
remaining risk and the next action.
## Example
User:
```text
is this ready to ship?
```
Response:
```text
Production audit: 68/100, risky, because Stripe webhooks are verified but not idempotent and there is no rollback note for the pending migration.
Blockers:
- Add idempotency for `checkout.session.completed` before fulfilling orders.
- Write and test the rollback path for `20260511_add_billing_state.sql`.
High-value fixes:
- Add a health check that verifies database and payment-provider reachability.
- Add one E2E path for upgrade, webhook fulfillment, and billing-page refresh.
Evidence checked:
- `api/stripe/webhook.ts`
- `db/migrations/20260511_add_billing_state.sql`
- GitHub Actions run for the release branch
Next action: Want me to patch webhook idempotency first?
```
## Anti-Patterns
- Running `npx <package>@latest` or a remote scanner as the default audit path.
- Uploading source, secrets, customer data, or private topology to an external
audit service without explicit approval.
- Producing a score without naming the evidence checked.
- Treating green CI as production readiness.
- Ending with a generic "let me know what you want to do."
## See Also
- Skill: `security-review`
- Skill: `deployment-patterns`
- Skill: `e2e-testing`
- Skill: `tdd-workflow`
- Skill: `verification-loop`

View File

@@ -0,0 +1,121 @@
---
name: user-flows-and-guided-paths
description: Related features and tasks — such as purchase flows, onboarding, or multi-step configuration — should be designed as natural, guided paths that feel coherent and fit the product hierarchy. Use wizards for complex sequential tasks. Use when designing flows, onboarding, checkout, setup sequences, or any multi-step user journey.
metadata:
priority: 7
pathPatterns:
- "components/**"
- "src/components/**"
- "**/*.tsx"
- "**/*.jsx"
- "design-system/**"
- "ui/**"
promptSignals:
phrases:
- "flow"
- "wizard"
- "onboarding"
- "checkout"
- "steps"
- "multi-step"
- "guided"
- "purchase flow"
- "setup"
retrieval:
aliases:
- user flow
- wizard pattern
- onboarding flow
- checkout flow
- guided steps
- multi-step form
intents:
- design a purchase flow
- build an onboarding sequence
- create a wizard
- guide the user through complex setup
- connect related features into a path
examples:
- design the checkout flow for this shop
- build a wizard for project setup
- make this onboarding feel natural
---
# User Flows and Guided Paths
Related features that belong together should be experienced as a single coherent journey — not as separate screens the user has to navigate between manually. A well-designed flow feels inevitable: each step leads naturally to the next, the user always knows where they are and what comes next, and the path fits the product's information hierarchy.
## When to Guide vs. When to Let Users Explore
| Scenario | Pattern |
|---|---|
| Linear process with a clear end goal (checkout, signup, setup) | Guided step-by-step flow or wizard |
| Complex task that benefits from breaking into stages | Wizard with progress indicator |
| Feature discovery across an existing product | Contextual tooltips or coach marks |
| User returning to complete something they started | Resume prompt with clear re-entry point |
| Open-ended exploration (dashboard, settings) | Free navigation — do not force a flow |
Only guide when the task genuinely has a natural order. Forcing a wizard onto a non-sequential task frustrates users who already know what they want.
## The Wizard Pattern
Use a wizard when:
- The task has 3 or more sequential steps
- Later steps depend on decisions made in earlier steps
- Doing all steps on one screen would overwhelm the user
### Wizard anatomy
```
[Step indicator: 1 of 4]
Step title
[Form content for this step]
[Back] [Continue →]
```
**Step indicator:** Always show the user where they are in the sequence and how many steps remain. A progress bar or numbered steps both work — numbered steps are clearer when step names are meaningful.
**Back navigation:** Always available. Users must be able to go back and change earlier decisions without losing their progress on later steps.
**Forward navigation:** Disabled until the current step is complete. Validate on Continue, not on Submit at the end.
**Exit path:** Make it clear how to abandon the flow without losing partial progress. Autosave drafts where possible.
### Step design principles
- One primary decision or input group per step — don't overfill steps
- Step titles should describe the user's goal, not the system's: "Your delivery address" not "Address input"
- Optional steps should be clearly marked and skippable
- The final step should show a summary before committing
## Purchase and Conversion Flows
Purchase flows have an additional constraint: every unnecessary step reduces conversion. Design for the shortest path to completion.
- Collect only what is required at each stage — defer optional information
- Show a persistent order summary so the user always sees what they are buying
- Surface trust signals near payment steps (security badges, return policy)
- Confirmation step before payment: show total, delivery, items — one last review
- Post-purchase: immediate confirmation with clear next steps ("Your order is confirmed. We'll email you when it ships.")
## Fitting Flows into the Product Hierarchy
A guided path should feel like it belongs to the product — not like it has opened a separate experience.
- The visual style, typography, and components inside a flow should match the rest of the product
- Navigation chrome (sidebar, top nav) can be hidden during a flow to reduce distraction, but the brand header should remain visible
- After completing a flow, return the user to a meaningful place in the hierarchy — not to a generic home screen
- Deep-linking into a flow should work: a user who arrives at step 3 via email link should see step 3, not step 1
## Review Checklist
- [ ] Does the flow have a clear start, a logical step order, and a definite end?
- [ ] Is a progress indicator visible at every step?
- [ ] Can the user go back to any previous step without losing later progress?
- [ ] Is each step focused on one decision or input group?
- [ ] Are step titles written in user language, describing their goal?
- [ ] Does the final step show a summary before the irreversible action?
- [ ] After completion, does the user land somewhere meaningful in the product?
- [ ] Does the flow visual style match the rest of the product?

View File

@@ -0,0 +1,155 @@
---
name: ux-review
description: Multi-perspective UX review combining usability heuristics, WCAG accessibility checks, and interaction design analysis. Use when reviewing UI components before release, evaluating user flows for usability issues, conducting design critiques, or auditing accessibility compliance.
tags:
- ux
- usability
- accessibility
- design-review
- heuristics
triggers:
- ux review
- usability review
- design critique
- user experience analysis
- heuristic evaluation
keywords:
- UX review
- usability review
- accessibility audit
- review
---
# UX Review
Comprehensive user experience review that coordinates usability, accessibility, and interaction design perspectives for thorough analysis of components, flows, or features.
## When to Use This Skill
- Reviewing new components or features before release
- Evaluating existing flows for usability issues
- PR reviews that touch UI/UX code
- Design system component reviews
- Onboarding flow or checkout flow optimization
- Avoid using for purely visual/aesthetic reviews — use `ui-design-aesthetics` instead
## Workflow
### Step 1: Gather Context
Answer these questions before reviewing:
1. What is the user trying to accomplish?
2. What is this component's role in the larger flow?
3. Who are the target users (personas, skill level)?
4. What are the success criteria?
### Step 2: Run Heuristic Scan (Nielsen's 10)
Evaluate the interface against each heuristic:
| Heuristic | Check |
|-----------|-------|
| Visibility of system status | Does the user always know what's happening? |
| Match with real world | Does it use familiar language and concepts? |
| User control and freedom | Can users undo, go back, escape? |
| Consistency and standards | Does it follow platform conventions? |
| Error prevention | Are mistakes prevented before they happen? |
| Recognition over recall | Is information visible rather than memorized? |
| Flexibility and efficiency | Are there shortcuts for expert users? |
| Aesthetic and minimalist design | Is every element necessary? |
| Error recovery | Are error messages helpful and actionable? |
| Help and documentation | Is guidance available when needed? |
### Step 3: Multi-Perspective Analysis
#### Usability Perspective
- **User flow**: Is the path to completion clear and efficient?
- **Information architecture**: Is content organized logically?
- **Cognitive load**: Is the interface overwhelming?
- **Mental models**: Does it work like users expect?
#### Accessibility Perspective (WCAG 2.1 AA)
- **Keyboard navigation**: Can everything be done without a mouse?
- **Screen reader**: Is the experience equivalent for assistive tech users?
- **Color contrast**: Do all text/UI elements meet 4.5:1 ratio?
- **Focus management**: Is focus order logical, visible, and never trapped?
```html
<!-- Example: Accessible button with proper ARIA -->
<button aria-label="Close dialog" aria-describedby="close-hint">
<svg aria-hidden="true"><!-- icon --></svg>
</button>
<span id="close-hint" class="sr-only">Press Escape to close</span>
```
#### Interaction Design Perspective
- **State coverage**: Are all states handled (loading, empty, error, success)?
- **Feedback**: Does the user know their action worked?
- **Transitions**: Are animations purposeful and under 300ms?
- **Progressive disclosure**: Is complexity revealed appropriately?
### Step 4: Prioritize Findings
Categorize every finding:
| Priority | Criteria | Action |
|----------|----------|--------|
| **Critical** | Blocks usability or fails WCAG AA | Must fix before release |
| **High** | Significantly degrades experience | Fix in current sprint |
| **Enhancement** | Improves delight and efficiency | Backlog for next iteration |
| **Future** | Long-term improvements | Track in roadmap |
### Step 5: Produce Review Report
```markdown
## UX Review: [Component/Flow Name]
### Summary
[2-3 sentence executive summary]
### Critical Issues
- [ ] Issue 1: [Description, impact, WCAG criterion if applicable]
- [ ] Issue 2: [Description, impact]
### Recommendations by Category
#### Usability
| Finding | Impact | Recommendation |
|---------|--------|----------------|
| [Issue] | High/Med/Low | [Fix] |
#### Accessibility
| Finding | WCAG Criterion | Recommendation |
|---------|----------------|----------------|
| [Issue] | [2.x.x Level] | [Fix] |
#### Interaction Design
| Finding | Impact | Recommendation |
|---------|--------|----------------|
| [Issue] | High/Med/Low | [Fix] |
### Next Steps
1. Create issues for critical findings
2. Add accessibility requirements to acceptance criteria
3. Schedule follow-up review after fixes
```
## Focus Area Deep Dives
Use `--focus` to narrow the review scope:
- **`--focus=ux`**: User flow mapping, task efficiency, error recovery, learnability
- **`--focus=a11y`**: WCAG 2.1 AA audit, keyboard nav, screen reader, contrast, focus management
- **`--focus=interaction`**: State coverage, feedback timing, micro-interactions, animation review
## Best Practices
- **Test with real content** — Lorem ipsum hides information architecture problems
- **Check all states** — Empty, loading, error, success, and edge-case states
- **Verify keyboard flow** — Tab through the entire component without a mouse
- **Use browser dev tools** — Lighthouse accessibility audit catches low-hanging fruit
- **Prioritize ruthlessly** — A focused list of critical fixes beats a wall of suggestions