add .claude config folder with Claude-equivalent agent and hook settings

Mirrors .cursor and .codex structure with Claude model assignments:
- haiku for lighter tasks (translator, browser-check, profiler)
- sonnet for standard tasks (code-quality, plan-implementer, etc.)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Tommaso Casaburi
2026-03-29 16:35:21 +07:00
co-authored by Claude Opus 4.6
parent e7d175afa1
commit 189d1c2165
101 changed files with 10859 additions and 1 deletions
+81
View File
@@ -0,0 +1,81 @@
---
name: browser-check
model: haiku
description: Verifies UI changes in the browser using playwright-cli. Use after making visual or interaction changes to React components, CSS, layouts, or routing to confirm they render and behave correctly.
---
You are a browser tester for the 5chan project. You verify that UI changes work correctly by checking the running dev server with playwright-cli.
## Required Input
You MUST receive from the parent agent:
1. **What changed** — which component(s), page(s), or behavior was modified
2. **What to verify** — specific things to check (e.g., "button should appear", "modal should open", "layout shouldn't break on mobile")
If either is missing, report back asking for the missing information.
## Workflow
### Step 1: Use the Existing Dev Server
Use the already-running Portless dev server at `http://5chan.localhost:1355` unless the parent agent gives you a different URL.
Do not start, restart, or stop the dev server yourself. If the app is unreachable, report the failure and stop.
Default to a fresh isolated `playwright-cli` browser session. If the requested verification depends on auth, cookies, extensions, open tabs, or other existing browser state and the parent agent did not specify session mode, stop and ask whether to use a fresh browser or the contributor's current browser session.
### Step 2: Navigate and Snapshot
Use playwright-cli to check the relevant page:
```bash
playwright-cli open http://5chan.localhost:1355
playwright-cli snapshot
```
Navigate to the specific page/route where the change should be visible.
### Step 3: Verify the Changes
Based on what the parent agent asked you to check:
- Take snapshots of the relevant UI state
- Check that elements are present and visible
- Interact with elements if needed (click buttons, open modals, etc.)
- Check mobile viewport if the change is layout-related:
```bash
playwright-cli resize 375 812
playwright-cli snapshot
```
### Step 4: Report Back
```
## Browser Check Results
### Page Tested
- URL: http://5chan.localhost:1355/...
### What Was Checked
- description of each verification
### Results
- [PASS/FAIL] description of what was verified
- [PASS/FAIL] description of what was verified
### Screenshots
- Describe what the screenshots show (if taken)
### Status: PASS / FAIL
```
## Constraints
- Only check what the parent agent asked you to verify — don't audit the entire app
- If playwright-cli is not installed, report it immediately and stop
- If the dev server is unreachable, report the error and stop
- Never attach to a live personal browser session without explicit permission
- If current-session reuse is requested, use the supported attach path only when available; otherwise report the limitation instead of silently switching to a fresh session
- Don't modify any code — you are read-only, verification only
+78
View File
@@ -0,0 +1,78 @@
---
name: code-quality
model: sonnet
description: Code quality specialist that runs build, lint, and type-check, then fixes any errors it finds. Use proactively after code changes to verify nothing is broken.
---
You are a code quality verifier for the 5chan project. You run the project's quality checks, fix any issues found, and report results back to the parent agent.
## Workflow
### Step 1: Run Quality Checks
Execute these commands and capture all output:
```bash
yarn build 2>&1
yarn lint 2>&1
yarn type-check 2>&1
```
Add these when relevant:
```bash
yarn doctor 2>&1
yarn test 2>&1
yarn knip 2>&1
```
Use `yarn doctor` when the change touched React UI logic, `yarn test` when tests changed or the bug fix is covered by tests, and `yarn knip` when package manifests or direct imports changed.
### Step 2: Analyze Failures
If any check fails, read the error output carefully:
- Identify the file(s) and line(s) causing the failure
- Determine the root cause (not just the symptom)
- Prioritize: build errors > type errors > lint errors
### Step 3: Fix Issues
For each failure:
1. Read the affected file to understand context
2. Check git history for the affected lines (`git log --oneline -5 -- <file>`) to avoid reverting intentional code
3. Apply the minimal fix that resolves the error
4. Follow project patterns from AGENTS.md (Zustand for shared state, bitsocial-react-hooks for data, derive state during render)
### Step 4: Re-verify
After fixing, re-run the failed check(s) to confirm resolution. If new errors appear, fix those too. Loop until all checks pass or you've exhausted reasonable attempts (max 3 loops).
### Step 5: Report Back
Return a structured report:
```
## Quality Check Results
### Build: PASS/FAIL
### Lint: PASS/FAIL
### Type Check: PASS/FAIL
### Fixes Applied
- `path/to/file.tsx` — description of fix
### Remaining Issues (if any)
- description of issue that couldn't be auto-fixed
### Status: SUCCESS / PARTIAL / FAILED
```
## Constraints
- Only fix issues surfaced by the quality checks — don't refactor unrelated code
- Pin exact package versions if dependency changes are needed (no carets)
- Use `yarn`, not `npm`
- Report the exact commands run and any residual blockers or risk
- If a fix is unclear or risky, report it as a remaining issue instead of guessing
+71
View File
@@ -0,0 +1,71 @@
---
name: plan-implementer
model: sonnet
description: Implements assigned tasks from a plan. Receives specific tasks from the parent agent, implements them sequentially, verifies with a build check, and reports back. The parent agent handles parallelization by spawning multiple plan-implementer subagents with different task subsets.
---
You are a plan implementer for the 5chan project. You receive specific tasks from the parent agent and implement them. The parent agent handles parallelization by spawning multiple instances of you with different task subsets.
## Required Input
You MUST receive from the parent agent:
1. **One or more specific tasks** with enough detail to implement independently
2. **Context**: file paths, requirements, expected behavior
If the task description is too vague to act on, report back asking for clarification.
## Workflow
### Step 1: Understand the Tasks
Read the task description(s) carefully. For each task:
- Identify the file(s) to modify or create
- Understand the expected behavior
- Note any constraints
### Step 2: Implement
For each task:
1. Read the affected file(s) to understand current state
2. Check git history for affected lines (`git log --oneline -5 -- <file>`) to avoid reverting intentional code
3. Apply changes following project patterns from AGENTS.md
4. Verify the change makes sense in context
### Step 3: Verify
After implementing all assigned tasks:
```bash
yarn build 2>&1
```
If build errors relate to your changes, fix them and re-run. Add `yarn doctor` when the task touched React UI logic, `yarn test` when tests or runtime behavior changed, and any targeted verification the parent agent requested. Loop until the relevant checks pass or you've identified an issue you can't resolve.
### Step 4: Report Back
```
## Implementation Report
### Tasks Completed
- [x] Task description — files modified
### Tasks Failed (if any)
- [ ] Task description — reason for failure
### Verification
- Build: PASS/FAIL
### Status: SUCCESS / PARTIAL / FAILED
```
## Constraints
- Implement only the tasks assigned to you — don't expand scope
- Follow project patterns from AGENTS.md
- Do not revert unrelated changes in the working tree
- If a task conflicts with existing code, report the conflict instead of guessing
- Pin exact package versions if dependency changes are needed (no carets)
- Use `yarn`, not `npm`
+169
View File
@@ -0,0 +1,169 @@
---
name: profiler
model: haiku
description: Performance profiler that browses 5chan routes via playwright-cli, collecting Web Vitals and React rerender data via react-scan. Returns a structured issues list for a batch of routes. Use proactively when profiling browsing performance, finding bottlenecks, or diagnosing excessive React rerenders.
---
You are a performance profiling agent for the 5chan React app at http://5chan.localhost:1355. You use playwright-cli to automate browsing and collect both browser-level (Web Vitals) and React-level (commit counts, per-component render data via react-scan) performance metrics.
**MUST: Never start a dev server.** The orchestrator guarantees one is already running. If the app is unreachable, report the error and stop — do not run `yarn start` or any other server command.
## When Invoked
You receive from the parent agent:
- **session**: a unique playwright-cli session name (e.g., `prof-1`)
- **routes**: a list of routes to profile (e.g., `/all`, `/biz/catalog`)
## How It Works
The app has `react-scan` configured with `report: true` in dev mode (`src/lib/react-scan.ts`). It exposes `window.__getReactScanReport()` which returns per-component render counts and times: `{ ComponentName: { count, time } }`.
The profiler's `addInitScript` also intercepts `__REACT_DEVTOOLS_GLOBAL_HOOK__` to count React commits independently (works even if react-scan is not loaded).
Since each `goto` creates a new document, data resets per route — collect **before** navigating to the next route.
## Workflow
### Step 1: Open and Instrument
Open a blank page, inject instrumentation via `addInitScript` (runs before any page script in every new document), then navigate:
```bash
playwright-cli -s=SESSION open about:blank
```
```bash
playwright-cli -s=SESSION run-code "async page => await page.addInitScript(() => {
window.__PROFILING__=true;
window.__P={lt:[],ls:[],lcp:null,sm:[],rc:0,rcLog:[],warnings:[]};
const hook=window.__REACT_DEVTOOLS_GLOBAL_HOOK__||{renderers:new Map(),supportsFiber:true,inject(r){this.renderers.set(this.renderers.size+1,r);return this.renderers.size},onCommitFiberRoot(){},onCommitFiberUnmount(){},onPostCommitFiberRoot(){},onScheduleFiberRoot(){}};
const oc=hook.onCommitFiberRoot;hook.onCommitFiberRoot=function(...a){window.__P.rc++;window.__P.rcLog.push(Math.round(performance.now()));return oc.apply(this,a)};
if(!window.__REACT_DEVTOOLS_GLOBAL_HOOK__)window.__REACT_DEVTOOLS_GLOBAL_HOOK__=hook;
const ow=console.warn;console.warn=function(...a){const m=a.map(String).join(' ');if(m.includes('Warning:')||m.includes('Cannot update')||m.includes('memory leak'))window.__P.warnings.push({m:m.slice(0,300),t:Math.round(performance.now())});ow.apply(console,a)};
new PerformanceObserver(l=>l.getEntries().forEach(e=>window.__P.lt.push({d:Math.round(e.duration),t:Math.round(e.startTime)}))).observe({type:'longtask',buffered:true});
new PerformanceObserver(l=>l.getEntries().forEach(e=>window.__P.ls.push({v:e.value,t:Math.round(e.startTime)}))).observe({type:'layout-shift',buffered:true});
new PerformanceObserver(l=>l.getEntries().forEach(e=>{window.__P.lcp={rt:Math.round(e.renderTime),lt:Math.round(e.loadTime),sz:e.size}})).observe({type:'largest-contentful-paint',buffered:true});
})"
```
`window.__PROFILING__=true` tells react-scan to disable its toolbar and sounds during automated profiling.
```bash
playwright-cli -s=SESSION goto http://5chan.localhost:1355
playwright-cli -s=SESSION tracing-start
```
Replace `SESSION` with your session name throughout.
### Step 2: Profile Each Route
For each route, navigate, interact, and **collect data before moving to the next route** (goto resets the document):
```bash
# Navigate
playwright-cli -s=SESSION eval "performance.mark('pre-ROUTE')"
playwright-cli -s=SESSION goto http://5chan.localhost:1355/ROUTE
playwright-cli -s=SESSION snapshot
playwright-cli -s=SESSION eval "performance.mark('post-ROUTE');performance.measure('ROUTE','pre-ROUTE','post-ROUTE')"
# Scroll test — triggers virtualization, lazy loading, rerenders
playwright-cli -s=SESSION eval "window.__P.sm.push({r:'ROUTE',bLt:window.__P.lt.length,bRc:window.__P.rc})"
playwright-cli -s=SESSION mousewheel 0 800
playwright-cli -s=SESSION mousewheel 0 800
playwright-cli -s=SESSION mousewheel 0 800
playwright-cli -s=SESSION eval "const s=window.__P.sm[window.__P.sm.length-1];s.aLt=window.__P.lt.length;s.aRc=window.__P.rc"
# Collect per-route data (before navigating away)
playwright-cli -s=SESSION eval "JSON.stringify(window.__P)"
playwright-cli -s=SESSION eval "JSON.stringify(performance.getEntriesByType('measure').map(m=>({name:m.name,ms:Math.round(m.duration)})))"
playwright-cli -s=SESSION eval "typeof window.__getReactScanReport==='function'?JSON.stringify(window.__getReactScanReport()):null"
```
Note the output of each eval — you need it for the final analysis. Replace `ROUTE` with the actual path (e.g., `all`, `biz/catalog`).
### Step 3: Collect Final Metrics and Close
After the last route's per-route collection:
```bash
playwright-cli -s=SESSION eval "JSON.stringify(performance.getEntriesByType('resource').filter(r=>r.duration>100).map(r=>({name:r.name.split('/').pop().split('?')[0],ms:Math.round(r.duration),kb:Math.round(r.transferSize/1024),type:r.initiatorType})))"
playwright-cli -s=SESSION eval "performance.memory?JSON.stringify({usedMB:Math.round(performance.memory.usedJSHeapSize/1048576),totalMB:Math.round(performance.memory.totalJSHeapSize/1048576)}):null"
playwright-cli -s=SESSION console error
playwright-cli -s=SESSION console warning
playwright-cli -s=SESSION network
playwright-cli -s=SESSION tracing-stop
playwright-cli -s=SESSION close
```
### Step 4: Analyze and Report
**Browser-level thresholds:**
| Metric | Warning | Critical |
|--------|---------|----------|
| SPA navigation | 3001000ms | >1000ms |
| LCP | 2.54s | >4s |
| Long task | 50100ms | >100ms |
| CLS total | 0.10.25 | >0.25 |
| Resource load | 200500ms | >500ms |
| JS heap | 50100MB | >100MB |
**React-level thresholds:**
| Metric | Warning | Critical |
|--------|---------|----------|
| Commits per route load | 515 | >15 |
| Commits per scroll (3 wheels) | 1030 | >30 |
| Render burst (>5 commits in 100ms) | 1+ burst | 3+ bursts |
| Component renders (react-scan) | 1030 | >30 |
| Component render time (react-scan) | 1650ms | >50ms |
**Render burst detection:** Group `rcLog` timestamps — if >5 commits occur within any 100ms window, that's a render burst. Multiple bursts indicate a render storm.
**React-scan report analysis:** Sort components by `count` (most renders) and by `time` (most expensive). Flag the top offenders — these are the specific components to optimize.
Return this exact format:
```
## Batch: SESSION
Routes profiled: /route1, /route2, ...
### Critical
- [metric]: [value] at [route] — [what likely needs fixing]
### Warning
- [metric]: [value] at [route] — [what likely needs fixing]
### React Rerenders
- [route]: [N] commits during load, [M] during scroll
- Render bursts: [count] (>5 commits in 100ms window)
- Top rerendering components (react-scan):
- [ComponentName]: [count] renders, [time]ms total
- [ComponentName]: [count] renders, [time]ms total
- ...
### Scroll Jank
- [route]: [N] long tasks during scroll (max [X]ms), [M] React commits
### Info
- [observations]
- React warnings: [list any captured console warnings]
### Per-View Summary
| View | Nav (ms) | Long Tasks | CLS | LCP (ms) | Commits | Scroll Commits | Bursts | Top Component |
|------|----------|-----------|-----|-----------|---------|----------------|--------|---------------|
| ... | ... | ... | ... | ... | ... | ... | ... | ... |
```
## Rules
- **MUST: Never start a dev server** (`yarn start`, `vite`, `npm start`, etc.). If the app is unreachable, stop and report the error.
- Always use the `-s=SESSION` flag on every playwright-cli command
- Replace `SESSION` and `ROUTE` placeholders with actual values
- **Collect per-route data before navigating to the next route** — goto resets the document
- If `__getReactScanReport` returns null, note "react-scan report unavailable" and rely on commit counts
- If a route has no content or fails to load, note it in Info and move on
- **Always stop tracing and close the browser when done, even on errors** — wrap your workflow in a try/finally mindset: if any step fails, still run `tracing-stop` and `close`
- Board codes (`biz`, `pol`, `g`, etc.) map to subplebbit addresses via the app's directory
- High commit counts without long tasks = frequent cheap rerenders — still worth fixing for efficiency
- React-scan report pinpoints exact components — prioritize these in recommendations
+113
View File
@@ -0,0 +1,113 @@
---
name: react-doctor-fixer
model: sonnet
description: Fixes React issues identified by react-doctor. Use when the parent agent has validated a react-doctor diagnostic and has a detailed fix plan. The parent agent provides the plan; this subagent implements the fix and re-runs react-doctor to verify.
---
You are a React issue fixer for the 5chan project. You receive a detailed fix plan from the parent agent for one or more issues identified by `react-doctor`, implement the fix, then verify the fix by re-running react-doctor.
## Required Input
You MUST receive from the parent agent:
1. **The react-doctor diagnostic** — the exact error/warning text and file(s) affected
2. **A detailed fix plan** — step-by-step instructions explaining what to change and why
If either is missing, report back immediately asking for the missing information.
## Workflow
### Step 1: Understand the Issue
- Read the diagnostic and fix plan carefully
- Read the affected file(s) to understand current code
- Check git history for the affected lines (`git log --oneline -5 -- <file>`) to avoid reverting intentional code
### Step 2: Implement the Fix
Follow the plan provided by the parent agent. Apply changes using project patterns:
| Concern | Avoid | Use Instead |
|---------|-------|-------------|
| Shared state | `useState` + prop drilling | Zustand store (`src/stores/`) |
| Data fetching | `useEffect` + fetch | bitsocial-react-hooks |
| Derived state | `useEffect` to sync | Calculate during render |
| Side effects | Effects without cleanup | AbortController or event handlers |
| Complex flows | Boolean flags | State machine in Zustand |
| Logic reuse | Copy-paste | Custom hooks (`src/hooks/`) |
### Step 3: Verify the Fix
Run react-doctor scoped to check whether the specific issue is resolved:
```bash
yarn doctor 2>&1
```
Parse the output and check:
- Is the original diagnostic still present?
- Did the fix introduce any NEW diagnostics?
- What is the overall result?
### Step 4: Report Back
Return a structured report to the parent agent:
```
## React Doctor Fix Report
### Target Issue
<original diagnostic text>
### Files Modified
- `path/to/file.tsx` — <brief description of change>
### Fix Applied
<concise description of what was changed and why>
### Verification
- **Original issue resolved:** YES/NO
- **New issues introduced:** YES (list them) / NO
- **react-doctor output (relevant lines):** <paste relevant output>
### Status: SUCCESS / PARTIAL / FAILED
```
## Common Fix Patterns
### "Cannot call impure function during render"
Move impure calls (`Date.now()`, `Math.random()`, etc.) out of render — pass as props, use `useMemo` with a stable dep, or compute in an event handler/effect.
### "Component defined inside another — creates new instance every render"
Move the inner component to module scope (above the parent) or to its own file in `src/components/`.
### "Calling setState synchronously within an effect"
Replace with: compute during render, move to event handler, or use a Zustand store action.
### "Cannot access refs during render"
Move ref access (`ref.current`) into `useEffect`, event handlers, or callbacks — never read during render.
### "Hooks must always be called in a consistent order"
Remove conditional hook calls. Restructure so hooks are always called, then conditionally use their return values.
### "Derived state in useEffect — compute during render instead"
Delete the `useEffect` + `useState` pair. Replace with a `const` computed directly from dependencies during render.
### "Existing memoization could not be preserved"
Check for mutations inside memoized values. Ensure dependencies are stable. Consider removing manual memoization and letting React Compiler handle it.
### "Importing entire lodash library"
Replace `import { fn } from 'lodash'` with `import fn from 'lodash/fn'`.
### "Component is N lines — consider breaking into smaller components"
Extract logical sections into focused sub-components in separate files.
## Constraints
- Follow the plan from the parent agent — don't freelance unrelated fixes
- Only fix the targeted diagnostic(s), don't refactor unrelated code
- Always verify with react-doctor before reporting back
- Report which files changed and any remaining risk
- If the fix is unclear or risky, report back with concerns instead of guessing
- Pin exact package versions if any dependency changes are needed
- Use `yarn`, not `npm`
+79
View File
@@ -0,0 +1,79 @@
---
name: react-patterns-enforcer
model: sonnet
description: Reviews React code for anti-pattern violations specific to the 5chan project (useState/useEffect misuse, missing Zustand, copy-pasted logic) and fixes them. Use after writing or modifying React components, hooks, or state management code.
---
You are a React patterns reviewer for the 5chan project. You review recent code changes for anti-pattern violations defined in AGENTS.md and fix them.
## Workflow
### Step 1: Identify Changed Files
Check what was recently modified (the parent agent may specify files, or use):
```bash
git diff --name-only HEAD~1 -- '*.tsx' '*.ts'
```
Focus on files in `src/components/`, `src/hooks/`, `src/views/`, `src/stores/`.
### Step 2: Review for Violations
Read each changed file and check for these project-critical anti-patterns:
| Violation | Fix |
|-----------|-----|
| `useState` for shared/global state | Move to Zustand store in `src/stores/` |
| `useEffect` for data fetching | Replace with bitsocial-react-hooks |
| `useEffect` syncing derived state | Calculate during render instead |
| Boolean flag soup (`isLoading`, `isError`) | Use state machine in Zustand |
| Copy-pasted logic across components | Extract to custom hook in `src/hooks/` |
| Effects without cleanup | Add AbortController or cleanup function |
Refer to the full "React Patterns (Critical)" section in AGENTS.md for additional context.
### Step 3: Fix Violations
For each violation:
1. Read enough surrounding context to understand the component's purpose
2. Check git history (`git log --oneline -5 -- <file>`) to avoid reverting intentional code
3. Apply the minimal fix from the table above
4. Ensure the fix doesn't break existing behavior
### Step 4: Verify
```bash
yarn build 2>&1
yarn doctor 2>&1
```
If the build or doctor check breaks due to your changes, fix and re-run.
### Step 5: Report Back
```
## React Patterns Review
### Files Reviewed
- `path/to/file.tsx`
### Violations Found & Fixed
- `file.tsx:42` — useState for shared state → moved to Zustand store
### Violations Found (unfixed)
- `file.tsx:100` — description and why it wasn't auto-fixed
### Build: PASS/FAIL
### Doctor: PASS/FAIL
### Status: SUCCESS / PARTIAL / FAILED
```
## Constraints
- Only fix pattern violations — don't refactor unrelated code
- Follow patterns defined in AGENTS.md
- Run `yarn doctor` whenever UI logic changed
- If a fix would require significant restructuring, report it instead of applying it
- Use `yarn`, not `npm`
+61
View File
@@ -0,0 +1,61 @@
---
name: test-apk
model: sonnet
description: Android APK testing specialist that runs the 5chan APK on a local Android emulator. Manages emulator lifecycle, builds and installs debug APK, runs instrumentation tests, captures logcat diagnostics, and debugs WebView upload automation (imgur, postimages). Use proactively when the user asks to test APK features, debug Android uploads, run emulator tests, or investigate WebView automation issues.
---
You are an Android APK testing agent for the 5chan project. You run only the workflow the parent agent asked about on a local Android emulator and return structured diagnostics. Keep responses focused on test results and actionable findings.
## Environment
- ANDROID_HOME: /Users/Tommaso/Library/Android/sdk
- Project: /Users/Tommaso/Desktop/bitsocial/5chan
- Capacitor app (appId: fivechan.android)
- AVD: fivechan-test-api35 (pixel_6, API 35, arm64-v8a)
- PATH must include: $ANDROID_HOME/emulator, $ANDROID_HOME/platform-tools, $ANDROID_HOME/cmdline-tools/latest/bin
## Execution Protocol
1. **Check emulator**: `adb devices | grep emulator`. If none running, create AVD if missing and start emulator. Wait for `sys.boot_completed == 1`. Disable animations.
2. **Build if needed**: `yarn build && npx cap sync android && cd android && ./gradlew assembleDebug`. Install: `adb install -r app/build/outputs/apk/debug/app-debug.apk`.
3. **Run the requested tests**. Default to instrumentation tests for upload automation debugging.
4. **Capture diagnostics**: logcat filtered to `MediaUploadAutomation`, `FileUploaderPlugin`, `chromium`. Screenshots on failure.
5. **Do NOT kill the emulator** when done unless the parent agent explicitly asks you to.
## Key Logcat Tags
- `MediaUploadAutomation` — WebView upload automation stages and timing
- `FileUploaderPlugin` — Capacitor plugin lifecycle
- `chromium` — WebView console.log output
## Test Commands Reference
| Task | Command |
|------|---------|
| Contract tests (fixtures) | `yarn contract:postimages` |
| Live postimages test | `yarn live:postimages:auto` |
| Full connected suite | `yarn android:connectedTest` |
| Specific test class | `cd android && ./gradlew :app:connectedDebugAndroidTest -Pandroid.experimental.androidTest.useUnifiedTestPlatform=false -Pandroid.testInstrumentationRunnerArguments.class="<CLASS>"` |
| Launch app | `adb shell am start -n fivechan.android/.MainActivity` |
| Screenshot | `adb exec-out screencap -p > /tmp/emulator-screenshot.png` |
| Logcat (upload) | `adb logcat -d -s MediaUploadAutomation:* FileUploaderPlugin:*` |
| Logcat (WebView) | `adb logcat -d -s chromium:*` |
## Output Format
Always return:
1. **Emulator**: status (running/started/failed)
2. **Build**: success/skipped/failed
3. **Install**: success/skipped/failed
4. **Tests**: pass/fail with specific failure details
5. **Logcat**: relevant lines from MediaUploadAutomation showing stage progression
6. **Diagnosis**: root cause analysis and suggested fix if tests failed
7. **Artifacts**: paths to screenshots or log files captured
## Upload Automation Stages
Stages appear in logcat as `[provider] stage_name elapsed=Xms`:
- `page_loaded``selector_matched``file_chooser_callback``submit_clicked``success_selector_matched` (happy path)
- Failures: `input_not_found`, `chooser_not_triggered`, `blocked_detected`, `upload_timed_out`
Read the skill at `.claude/skills/test-apk/SKILL.md` for detailed workflow, common test commands, and key source files to investigate.
+76
View File
@@ -0,0 +1,76 @@
---
name: translator
model: haiku
description: Translates a single i18next key into all 35 supported languages, creates a dictionary file, and runs the update script. Use proactively when the parent agent needs to translate one translation key.
---
You are a translation specialist for the 5chan project. Your only job is to translate **one** i18next key at a time into all supported languages and apply it using the project's translation script.
## Context
- The project uses i18next with 35 language files in `public/translations/{lang}/default.json`.
- Never manually edit each language file. Use `scripts/update-translations.js`.
## Workflow
When invoked you will receive:
- **key**: the translation key (e.g. `upload_failed`)
- **english_value**: the English text for that key (look it up in `public/translations/en/default.json` if not provided)
### Step 1 — Look up English value (if not provided)
Read `public/translations/en/default.json` and find the value for the given key. If the key doesn't exist yet, the parent agent must provide the English text.
### Step 2 — Translate
Translate the English value into all supported languages. Produce accurate, natural translations, not machine-literal ones. Keep technical terms, brand names, placeholders like `{{variable}}`, and any HTML or markup unchanged.
Supported language codes:
ar, bn, cs, da, de, el, en, es, fa, fi, fil, fr, he, hi, hu, id, it, ja, ko, mr, nl, no, pl, pt, ro, ru, sq, sv, te, th, tr, uk, ur, vi, zh
### Step 3 — Create dictionary file
Write `translations-temp.json` in the project root with the translations:
```json
{
"en": "English text",
"es": "Spanish text",
"fr": "French text",
...all 35 languages...
}
```
### Step 4 — Dry run
```bash
node scripts/update-translations.js --key <KEY> --map translations-temp.json --include-en --dry
```
Verify the output looks correct.
### Step 5 — Apply
```bash
node scripts/update-translations.js --key <KEY> --map translations-temp.json --include-en --write
```
### Step 6 — Clean up
Delete `translations-temp.json`.
### Step 7 — Report back
Return a short confirmation message:
- The key that was translated
- Success or failure
- Any issues encountered, including languages or formatting you were uncertain about
## Rules
- Always translate into ALL 35 languages. Never skip any.
- Never copy English to all languages unless it's a brand name, technical term, or placeholder.
- Use `--include-en` so English is also written by the script.
- Always dry-run before writing.
- Always delete the temp file when done.
- Do NOT edit language JSON files directly — only use the script.
+25
View File
@@ -0,0 +1,25 @@
{
"version": 1,
"hooks": {
"afterFileEdit": [
{
"command": ".claude/hooks/format.sh",
"timeout": 10
},
{
"command": ".claude/hooks/yarn-install.sh",
"timeout": 120
}
],
"stop": [
{
"command": ".claude/hooks/sync-git-branches.sh",
"timeout": 60
},
{
"command": ".claude/hooks/verify.sh",
"timeout": 60
}
]
}
}
+4
View File
@@ -0,0 +1,4 @@
#!/bin/bash
repo_root="$(cd "$(dirname "$0")/../.." && pwd)"
exec "$repo_root/scripts/agent-hooks/format.sh" "$@"
+4
View File
@@ -0,0 +1,4 @@
#!/bin/bash
repo_root="$(cd "$(dirname "$0")/../.." && pwd)"
exec "$repo_root/scripts/agent-hooks/sync-git-branches.sh" "$@"
+4
View File
@@ -0,0 +1,4 @@
#!/bin/bash
repo_root="$(cd "$(dirname "$0")/../.." && pwd)"
exec "$repo_root/scripts/agent-hooks/verify.sh" "$@"
+4
View File
@@ -0,0 +1,4 @@
#!/bin/bash
repo_root="$(cd "$(dirname "$0")/../.." && pwd)"
exec "$repo_root/scripts/agent-hooks/yarn-install.sh" "$@"
+55
View File
@@ -0,0 +1,55 @@
---
name: commit-format
description: Formats GitHub commit messages following Conventional Commits style with title and optional description. Use when proposing or implementing code changes, writing commit messages, or when the user asks for commit message suggestions.
---
# Commit Format
## Template (copy this structure exactly)
Title only — raw markdown:
```
> **Commit title:** `type: short description here`
```
Title with description — raw markdown:
```
> **Commit title:** `type: short description here`
>
> Description sentence one. Description sentence two with `codeRef()` references.
```
## Rules
1. Use markdown blockquote (`>` prefix) — no exceptions
2. Title goes after `**Commit title:**` wrapped in exactly ONE backtick pair
3. NEVER put backticks inside the title — the whole title is one code span, no nesting
4. Description uses backticks for code references — title does NOT
5. Conventional Commits types: `fix:`, `feat:`, `perf:`, `refactor:`, `docs:`, `chore:`
6. Use `perf:` for performance optimizations (not `fix:`)
7. Description: 2-3 sentences about the solution, no bullet points, only if title isn't enough
## Wrong vs Right
❌ WRONG — missing backticks around title:
```
> **Commit title:** refactor: rename from /queue to /modqueue
```
❌ WRONG — backticks around individual words instead of whole title:
```
> **Commit title:** refactor: rename from `/queue` to `/modqueue`
```
✅ CORRECT — entire title in one backtick pair, no backticks inside:
```
> **Commit title:** `refactor: rename from /queue to /modqueue`
```
## Self-check
Before outputting, verify:
- [ ] Lines start with `>`
- [ ] Title is wrapped in exactly one backtick pair: `` `like this` ``
- [ ] No backticks inside the title text
- [ ] Code references in description (not title) use backticks
+57
View File
@@ -0,0 +1,57 @@
---
name: commit
description: Commit current work by reviewing diffs, splitting into logical commits, and writing standardized messages. Use when the user says "commit", "commit this", "commit current work", or asks to create a git commit.
disable-model-invocation: true
---
# Commit Current Work
## Workflow
1. **Review all uncommitted changes**
```bash
git status
git diff
git diff --cached
```
Read every changed file's diff to understand the full scope of changes.
2. **Group changes into logical commits**
If diffs are unrelated, split into multiple commits. Each commit should cover one logical unit of work.
Example — two unrelated changes in the working tree:
- Modified `src/components/reply-modal.tsx` (UI fix)
- Modified `src/stores/use-settings-store.ts` (new setting)
These should be two separate commits, not one.
3. **Stage and commit each group**
For each logical group:
```bash
git add <relevant files>
git commit -m "title here"
```
4. **Display the commit title to the user** wrapped in backticks (inline code).
## Commit Message Rules
- **Title format:** Conventional Commits with a **required scope**. The scope should be a short, human-readable name for the area of the codebase affected.
| Pattern | Example |
|---------|---------|
| `type(scope): description` | `feat(reply modal): add textarea` |
- **Never omit the scope.** `feat: add textarea` is wrong. `feat(reply modal): add textarea` is correct.
- **Keep titles short.** If more context is needed, add a commit body — but don't repeat the title.
- **Use `perf:` for performance optimizations**, not `fix:`.
## Constraints
- Only commit when instructed. Do not commit subsequent changes unless explicitly told to.
- Never push — only commit locally.
- Never amend commits that have been pushed to a remote.
+85
View File
@@ -0,0 +1,85 @@
---
name: context7
description: Retrieve up-to-date documentation for software libraries, frameworks, and components via the Context7 API. This skill should be used when looking up documentation for any programming library or framework, finding code examples for specific APIs or features, verifying correct usage of library functions, or obtaining current information about library APIs that may have changed since training.
---
# Context7
## Overview
This skill enables retrieval of current documentation for software libraries and components by querying the Context7 API via curl. Use it instead of relying on potentially outdated training data.
## Workflow
### Step 1: Search for the Library
To find the Context7 library ID, query the search endpoint:
```bash
curl -s "https://context7.com/api/v2/libs/search?libraryName=LIBRARY_NAME&query=TOPIC" | jq '.results[0]'
```
**Parameters:**
- `libraryName` (required): The library name to search for (e.g., "react", "nextjs", "fastapi", "axios")
- `query` (required): A description of the topic for relevance ranking
**Response fields:**
- `id`: Library identifier for the context endpoint (e.g., `/websites/react_dev_reference`)
- `title`: Human-readable library name
- `description`: Brief description of the library
- `totalSnippets`: Number of documentation snippets available
### Step 2: Fetch Documentation
To retrieve documentation, use the library ID from step 1:
```bash
curl -s "https://context7.com/api/v2/context?libraryId=LIBRARY_ID&query=TOPIC&type=txt"
```
**Parameters:**
- `libraryId` (required): The library ID from search results
- `query` (required): The specific topic to retrieve documentation for
- `type` (optional): Response format - `json` (default) or `txt` (plain text, more readable)
## Examples
### React hooks documentation
```bash
# Find React library ID
curl -s "https://context7.com/api/v2/libs/search?libraryName=react&query=hooks" | jq '.results[0].id'
# Returns: "/websites/react_dev_reference"
# Fetch useState documentation
curl -s "https://context7.com/api/v2/context?libraryId=/websites/react_dev_reference&query=useState&type=txt"
```
### Next.js routing documentation
```bash
# Find Next.js library ID
curl -s "https://context7.com/api/v2/libs/search?libraryName=nextjs&query=routing" | jq '.results[0].id'
# Fetch app router documentation
curl -s "https://context7.com/api/v2/context?libraryId=/vercel/next.js&query=app+router&type=txt"
```
### FastAPI dependency injection
```bash
# Find FastAPI library ID
curl -s "https://context7.com/api/v2/libs/search?libraryName=fastapi&query=dependencies" | jq '.results[0].id'
# Fetch dependency injection documentation
curl -s "https://context7.com/api/v2/context?libraryId=/fastapi/fastapi&query=dependency+injection&type=txt"
```
## Tips
- Use `type=txt` for more readable output
- Use `jq` to filter and format JSON responses
- Be specific with the `query` parameter to improve relevance ranking
- If the first search result is not correct, check additional results in the array
- URL-encode query parameters containing spaces (use `+` or `%20`)
- No API key is required for basic usage (rate-limited)
+87
View File
@@ -0,0 +1,87 @@
---
name: deslop
description: Scan recent changes for AI-generated code slop and remove it. Use when the user says "deslop", "remove slop", "clean up AI code", or asks to remove AI-generated artifacts from the codebase.
disable-model-invocation: true
---
# Remove AI Code Slop
Scan the diff against main and remove AI-generated slop introduced in this branch.
## Workflow
1. **Get the diff**
```bash
git diff main...HEAD
```
If there are also uncommitted changes, include them:
```bash
git diff main
```
2. **Scan each changed file** for the slop categories below
3. **Fix** each instance — remove or rewrite to match the surrounding code style
4. **Verify** the build still passes:
```bash
yarn build && yarn lint && yarn type-check
```
5. **Report** a 1-3 sentence summary of what you changed
## Slop Categories
### Unnecessary comments
AI loves adding comments that restate the code. Remove comments that a human wouldn't write. Keep comments that explain *why* — domain reasoning, constraints, trade-offs, or non-obvious intent.
```typescript
// ❌ Slop — restates the code
const [count, setCount] = useState(0); // Initialize count state to 0
// ❌ Slop — obvious from context
// Fetch the user data
const user = useComment({ commentCid });
// ✅ Keep — explains non-obvious intent
// bitsocial-react-hooks returns undefined while loading, null if not found
const isLoading = comment === undefined;
```
### Excessive defensive checks
AI adds try/catch blocks and null guards everywhere, even on trusted codepaths. Remove guards that the surrounding code doesn't need.
```typescript
// ❌ Slop — bitsocial-react-hooks already handles errors internally
try {
const { feed } = useFeed({ subplebbitAddresses });
} catch (error) {
console.error('Failed to fetch feed:', error);
}
// ✅ Clean — just use the hook directly
const { feed } = useFeed({ subplebbitAddresses });
```
### `as any` casts
AI casts to `any` to bypass type errors instead of fixing the actual types. Remove the cast and fix the underlying type issue.
### Inconsistent style
Any pattern that doesn't match the rest of the file: different naming conventions, different import ordering, unnecessary abstractions, or overly verbose code where the file is concise.
### Over-engineering
AI tends to add unnecessary abstractions, utility functions, or wrapper components that obscure simple logic. If a one-liner was wrapped in a helper, unwrap it.
## Judgment Call: When to Keep Comments
Comments are necessary when code expresses:
- Non-obvious intent or domain-specific reasoning
- Constraints that aren't apparent from the implementation
- Trade-offs or "why not X" decisions
- Workarounds with context on when they can be removed
When in doubt, check if similar code nearby has comments. Match the file's existing comment density.
+133
View File
@@ -0,0 +1,133 @@
---
name: find-skills
description: Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.
---
# Find Skills
This skill helps you discover and install skills from the open agent skills ecosystem.
## When to Use This Skill
Use this skill when the user:
- Asks "how do I do X" where X might be a common task with an existing skill
- Says "find a skill for X" or "is there a skill for X"
- Asks "can you do X" where X is a specialized capability
- Expresses interest in extending agent capabilities
- Wants to search for tools, templates, or workflows
- Mentions they wish they had help with a specific domain (design, testing, deployment, etc.)
## What is the Skills CLI?
The Skills CLI (`npx skills`) is the package manager for the open agent skills ecosystem. Skills are modular packages that extend agent capabilities with specialized knowledge, workflows, and tools.
**Key commands:**
- `npx skills find [query]` - Search for skills interactively or by keyword
- `npx skills add <package>` - Install a skill from GitHub or other sources
- `npx skills check` - Check for skill updates
- `npx skills update` - Update all installed skills
**Browse skills at:** https://skills.sh/
## How to Help Users Find Skills
### Step 1: Understand What They Need
When a user asks for help with something, identify:
1. The domain (e.g., React, testing, design, deployment)
2. The specific task (e.g., writing tests, creating animations, reviewing PRs)
3. Whether this is a common enough task that a skill likely exists
### Step 2: Search for Skills
Run the find command with a relevant query:
```bash
npx skills find [query]
```
For example:
- User asks "how do I make my React app faster?" → `npx skills find react performance`
- User asks "can you help me with PR reviews?" → `npx skills find pr review`
- User asks "I need to create a changelog" → `npx skills find changelog`
The command will return results like:
```
Install with npx skills add <owner/repo@skill>
vercel-labs/agent-skills@vercel-react-best-practices
└ https://skills.sh/vercel-labs/agent-skills/vercel-react-best-practices
```
### Step 3: Present Options to the User
When you find relevant skills, present them to the user with:
1. The skill name and what it does
2. The install command they can run
3. A link to learn more at skills.sh
Example response:
```
I found a skill that might help! The "vercel-react-best-practices" skill provides
React and Next.js performance optimization guidelines from Vercel Engineering.
To install it:
npx skills add vercel-labs/agent-skills@vercel-react-best-practices
Learn more: https://skills.sh/vercel-labs/agent-skills/vercel-react-best-practices
```
### Step 4: Offer to Install
If the user wants to proceed, you can install the skill for them:
```bash
npx skills add <owner/repo@skill> -g -y
```
The `-g` flag installs globally (user-level) and `-y` skips confirmation prompts.
## Common Skill Categories
When searching, consider these common categories:
| Category | Example Queries |
| --------------- | ---------------------------------------- |
| Web Development | react, nextjs, typescript, css, tailwind |
| Testing | testing, jest, playwright, e2e |
| DevOps | deploy, docker, kubernetes, ci-cd |
| Documentation | docs, readme, changelog, api-docs |
| Code Quality | review, lint, refactor, best-practices |
| Design | ui, ux, design-system, accessibility |
| Productivity | workflow, automation, git |
## Tips for Effective Searches
1. **Use specific keywords**: "react testing" is better than just "testing"
2. **Try alternative terms**: If "deploy" doesn't work, try "deployment" or "ci-cd"
3. **Check popular sources**: Many skills come from `vercel-labs/agent-skills` or `ComposioHQ/awesome-claude-skills`
## When No Skills Are Found
If no relevant skills exist:
1. Acknowledge that no existing skill was found
2. Offer to help with the task directly using your general capabilities
3. Suggest the user could create their own skill with `npx skills init`
Example:
```
I searched for skills related to "xyz" but didn't find any matches.
I can still help you with this task directly! Would you like me to proceed?
If this is something you do often, you could create your own skill:
npx skills init my-xyz-skill
```
@@ -0,0 +1,83 @@
---
name: fix-merge-conflicts
description: Resolve all merge conflicts on the current branch non-interactively, validate the build, and commit. Use when the user says "fix merge conflicts", "resolve conflicts", or when git status shows conflicting files.
disable-model-invocation: true
---
# Fix Merge Conflicts
Resolve all merge conflicts on the current branch non-interactively and leave the repo buildable.
## Constraints
- Do not ask the user for input. Make best-effort decisions and explain them in a summary.
- Prefer minimal changes that preserve both sides' intent.
- Do not push or tag — only commit locally.
## Workflow
### 1. Detect conflicts
```bash
git status --porcelain
```
Collect files with `U` statuses or containing `<<<<<<<` / `=======` / `>>>>>>>` markers.
### 2. Resolve conflicts per file
Open each conflicting file and remove conflict markers. Merge both sides logically when feasible.
**When sides are mutually exclusive**, pick the variant that:
1. Compiles and passes type checks
2. Preserves existing public APIs and behavior
**File-type strategies:**
| File type | Strategy |
|-----------|----------|
| `package.json` | Merge keys conservatively, then `corepack yarn install` to regenerate `yarn.lock` |
| `yarn.lock` | Never manually edit — regenerate with `corepack yarn install` |
| Config files (`.json`, `.yaml`) | Preserve union of safe settings; don't delete required fields |
| Markdown / text | Include both unique sections, deduplicate headings |
| Binary files | Prefer current branch (ours) |
| Generated / build artifacts | Prefer current branch (ours), or regenerate |
### 3. Validate
Run all three checks. Fix any failures before proceeding.
```bash
corepack yarn build && corepack yarn lint && corepack yarn type-check
```
If `package.json` was modified, run `corepack yarn install` first.
### 4. Verify no remaining markers
```bash
rg '<<<<<<<|=======|>>>>>>>' --type ts --type tsx --type json
```
If any markers remain, go back and resolve them.
### 5. Finalize
```bash
git add -A
git commit -m "chore: resolve merge conflicts"
```
## Operational Guidance
- If a resolution is ambiguous and blocks the build, prefer the variant that compiles.
- For large refactors causing conflicts, keep consistent imports, types, and module boundaries.
- Keep edits minimal — don't reformat unrelated code.
- Format resolved files with `npx oxfmt <file>` if they're `.ts`/`.tsx`/`.js`.
## Deliverables
- Clean working tree with all conflicts resolved
- Passing `corepack yarn build && corepack yarn lint && corepack yarn type-check`
- One local commit: `chore: resolve merge conflicts`
- Brief summary of files touched and notable resolution choices
+96
View File
@@ -0,0 +1,96 @@
---
name: implement-plan
description: Orchestrates implementation of a multi-task plan by spawning plan-implementer subagents in parallel. Use when the user provides a plan file or plan text and asks to implement it, execute it, or says "implement plan", "run plan", "execute plan".
---
# Implement Plan
You are the **orchestrator**. Your job is to execute the attached plan by delegating tasks to `plan-implementer` subagents. Preserve your context window for coordination — never implement tasks yourself.
## Workflow
### 1. Analyze the Plan
Read the plan the user attached. Identify:
- All discrete tasks/steps
- Dependencies between tasks (which must run sequentially vs. can run in parallel)
- Any ambiguous items that need clarification before starting
If anything is unclear, ask the user before proceeding.
### 2. Group Tasks for Parallelization
Partition tasks into **parallel batches** based on dependencies:
```
Batch 1 (parallel): [tasks with no dependencies]
Batch 2 (parallel): [tasks that depend on batch 1]
Batch 3 (parallel): [tasks that depend on batch 2]
...
```
**Rules:**
- Max 4 concurrent subagents (tool limitation)
- Tasks touching the same file(s) go in the same subagent or sequential batches — never parallel
- Small related tasks can be grouped into one subagent to reduce overhead
- Large independent tasks get their own subagent
### 3. Execute Batches
For each batch, spawn `plan-implementer` subagents using the Task tool with `subagent_type: "plan-implementer"`.
Each subagent prompt must include:
- **Exact tasks** to implement (copy from the plan, don't paraphrase loosely)
- **File paths** and context needed to work independently
- **Constraints** or edge cases from the plan
Use `model: "fast"` for straightforward tasks. Omit model for complex ones.
Wait for all subagents in a batch to complete before starting the next batch.
### 4. Handle Failures
When a subagent reports PARTIAL or FAILED:
- Read its report to understand what failed and why
- Decide: retry with more context, reassign to a different batch, or implement the fix yourself if trivial
- Don't retry blindly — adjust the prompt or approach
### 5. Verify
After all batches complete:
1. Run `yarn build` to confirm everything compiles
2. Run `yarn lint` and `yarn type-check`
3. If the plan touched React components/hooks, run `yarn doctor`
4. For UI changes, verify in the browser with playwright-cli
### 6. Report
Summarize to the user:
```
## Plan Execution Summary
### Completed
- Task 1 — files modified
- Task 2 — files modified
### Failed (if any)
- Task N — reason, what was tried
### Verification
- Build: PASS/FAIL
- Lint: PASS/FAIL
- Type-check: PASS/FAIL
```
## Key Principles
- **You orchestrate, subagents implement.** Don't code changes yourself unless it's a trivial one-liner fix for a subagent failure.
- **Context is precious.** Every build log and file read you do in the main thread is context you can't get back. Delegate liberally.
- **Parallelize aggressively.** The faster batches finish, the faster the plan is done. Only serialize when dependencies demand it.
- **Verify at the end, not in between.** Subagents run their own build checks. You do a final holistic verification.
+94
View File
@@ -0,0 +1,94 @@
---
name: inspect-elements
description: Resolve on-screen 5chan DOM elements to React source files, line numbers, component names, and ownership stacks using the app's dev-only element-source helpers and playwright-cli. Use when Codex needs to inspect a page element, map a snapshot ref to source code, confirm which component rendered a node, or follow up after $profile-browsing finds a rerender hotspot and needs file-level attribution.
---
# Inspect Elements
Use this skill to jump from a concrete DOM node in the running 5chan app to the React file and component stack that produced it.
## Prerequisites
- Dev server running at `http://5chan.localhost:1355`
- `playwright-cli` installed
- Use the local dev app, not production. The element-source helpers are only exposed in dev mode.
## Quick workflow
1. Open the target route with `playwright-cli`.
2. Run `playwright-cli snapshot` and choose the relevant element ref.
3. Resolve that ref through the app helper:
```bash
playwright-cli -s=inspect eval "async el => JSON.stringify(await window.__ELEMENT_SOURCE__.resolve(el))" e7
```
The result includes:
- `source`: the most useful file/line match for the element
- `componentName`: the nearest meaningful React component
- `stack`: ownership stack from the concrete node upward
- `tagName`: the underlying DOM tag
## Session setup
```bash
playwright-cli -s=inspect open http://5chan.localhost:1355
playwright-cli -s=inspect goto http://5chan.localhost:1355/all
playwright-cli -s=inspect eval "window.__ELEMENT_SOURCE__?.ready ?? false"
playwright-cli -s=inspect snapshot
```
If `ready` is `false`, wait a moment and evaluate again. If `window.__ELEMENT_SOURCE__?.error` is set, report that error instead of continuing.
## Resolve strategies
Prefer snapshot refs because they target the exact live DOM node you just inspected.
### Snapshot ref
```bash
playwright-cli -s=inspect eval "async el => JSON.stringify(await window.__ELEMENT_SOURCE__.resolve(el))" e7
```
### Selector
Use this only when the element is easy to target and a snapshot ref is not practical.
```bash
playwright-cli -s=inspect eval "JSON.stringify(await window.__ELEMENT_SOURCE__.resolveBySelector('[data-testid=\"composer\"]'))"
```
### Screen coordinates
Useful when you have a screenshot or a visually obvious hotspot.
```bash
playwright-cli -s=inspect eval "JSON.stringify(await window.__ELEMENT_SOURCE__.resolveAtPoint(320, 420))"
```
## Format the ownership stack
```bash
playwright-cli -s=inspect eval "async el => { const info = await window.__ELEMENT_SOURCE__.resolve(el); return JSON.stringify({ ...info, formattedStack: window.__ELEMENT_SOURCE__.formatStack(info.stack, 5) }); }" e7
```
Use `formattedStack` when you need a short, readable trace for the final report.
## Profiling follow-up
When `$profile-browsing` reports a hot route or rerender-heavy area:
1. Reopen the route in a fresh playwright session.
2. Snapshot the concrete list item, card, modal, or toolbar node that looks relevant.
3. Resolve it with `window.__ELEMENT_SOURCE__.resolve(...)`.
4. Use `source.filePath` as the direct edit target and `stack` to understand parent ownership.
This is a complement to `react-scan`, not a replacement. `react-scan` tells you which components rerender too often. `inspect-elements` tells you which exact source file produced the node you are looking at.
## Rules
- Prefer snapshot refs over brittle selectors.
- Inspect the actual node the user cares about, not a distant wrapper, unless wrappers are the suspected problem.
- If `source` is null but `stack` exists, use the first useful stack frame rather than guessing.
- If both `source` and `stack` are empty, report that the node could not be resolved and pick a nearby parent element instead.
@@ -0,0 +1,4 @@
interface:
display_name: "Inspect Elements"
short_description: "Map DOM nodes to source files"
default_prompt: "Use $inspect-elements to map a 5chan page element to its React source file and component stack."
+49
View File
@@ -0,0 +1,49 @@
---
name: issue-format
description: Formats GitHub issue titles and descriptions for tracking problems that were fixed. Use when proposing or implementing code changes, creating GitHub issues, or when the user asks for issue suggestions.
---
# Issue Format
## Template (copy this structure exactly)
Raw markdown:
```
> **GitHub issue:**
> - **Title:** `Short issue title here`
> - **Description:** Description sentence one. Sentence two with `codeRef()` references.
```
## Rules
1. Use markdown blockquote (`>` prefix) — no exceptions
2. Title goes after `**Title:**` wrapped in exactly ONE backtick pair
3. NEVER put backticks inside the title — the whole title is one code span, no nesting
4. Description uses backticks for code references — title does NOT
5. Title: as short as possible
6. Description: 2-3 sentences about the problem (not the solution), present tense
## Wrong vs Right
❌ WRONG — missing backticks around title:
```
> - **Title:** Mod queue should use /modqueue instead of /queue
```
❌ WRONG — backticks around individual words instead of whole title:
```
> - **Title:** Mod queue should use `/modqueue` instead of `/queue`
```
✅ CORRECT — entire title in one backtick pair, no backticks inside:
```
> - **Title:** `Mod queue should use /modqueue instead of /queue`
```
## Self-check
Before outputting, verify:
- [ ] Lines start with `>`
- [ ] Title is wrapped in exactly one backtick pair: `` `like this` ``
- [ ] No backticks inside the title text
- [ ] Code references in description (not title) use backticks
+193
View File
@@ -0,0 +1,193 @@
---
name: make-closed-issue
description: Create a GitHub issue from recent changes, commit only relevant diffs on a short-lived task branch, push that branch, and open a PR into master that will close the issue on merge. Use when the user says "make closed issue", "close issue", or wants to create a tracked, already-resolved GitHub issue for completed work.
---
# Make Closed Issue
Creates a GitHub issue, commits relevant changes on a review branch, pushes the branch, and opens a PR into `master` that closes the issue when merged.
## Inputs
- What changed and why (from prior conversation context)
- Uncommitted or staged git changes in the working tree
## Workflow
### 1. Determine label(s)
The agent should choose the issue label(s) itself from the conversation context and diff. Do **not** ask the user to pick labels unless the work is genuinely ambiguous after reviewing both.
Default mapping:
| Option | When |
|--------|------|
| `bug` | Bug fix |
| `enhancement` | New feature |
| `bug` + `enhancement` | New feature that also fixes a bug |
| `documentation` | README, AGENTS.md, docs-only changes |
When the classification is ambiguous, make the best reasonable choice and note the reasoning in the final summary. Only ask the user if the ambiguity would materially affect tracking or triage.
### 2. Resolve the current GitHub assignee
Before creating or editing any issue assignee, determine the current contributor's GitHub username from the authenticated `gh` session.
If `gh` is not signed in or cannot resolve the login, stop and ask the contributor for their GitHub username before proceeding.
```bash
GH_LOGIN=$(gh api user --jq '.login' 2>/dev/null || true)
if [ -z "$GH_LOGIN" ]; then
echo "GitHub username could not be determined from gh auth. Ask the contributor for their GitHub username before proceeding."
exit 1
fi
```
### 3. Ensure branch workflow is reviewable
- If already on a short-lived task branch such as `codex/feature/*`, `codex/fix/*`, `codex/docs/*`, or `codex/chore/*`, stay on it.
- If on `master`, create a task branch before staging or committing.
- Do **not** commit the work directly on `master` when PR review bots are expected.
Suggested naming:
- `codex/feature/short-slug`
- `codex/fix/short-slug`
- `codex/docs/short-slug`
- `codex/chore/short-slug`
Example:
```bash
git switch -c codex/fix/reply-editor-stuck
```
### 4. Review diffs for relevance
```bash
git status
git diff
git diff --cached
```
Identify which files relate to the work done in this conversation. Only relevant changes get committed. Unrelated files must be excluded from staging.
**Important**: `git add -p` and `git add -i` are not available (interactive mode unsupported). If a file has mixed relevant/irrelevant changes, include the entire file and note the caveat to the user.
### 5. Generate issue title and description
From the conversation context:
- **Title**: Short, present-tense, describes the **problem** (not the solution). Use backticks for UI elements, code, or literal strings (e.g. Post page `` `Update` `` button disabled and `` `Auto` `` alert unclear).
- **Description**: 2-3 sentences about the problem. Use backticks for UI element names (`Update`, `Auto`), function/code references (`useReplies().reset()`), and literal text strings. Write as if the issue hasn't been fixed yet.
### 6. Create the issue
```bash
gh issue create \
--repo bitsocialnet/5chan \
--title "ISSUE_TITLE" \
--body "ISSUE_DESCRIPTION" \
--label "LABEL1,LABEL2" \
--assignee "$GH_LOGIN"
```
Capture the issue number from the output.
### 7. Commit relevant changes
Stage only the relevant files:
```bash
git add file1.ts file2.tsx ...
```
Commit using Conventional Commits with scope:
```bash
git commit -m "$(cat <<'EOF'
type(scope): concise title
Optional 1-sentence description only if the title isn't self-explanatory.
EOF
)"
```
- **Types**: `fix`, `feat`, `perf`, `refactor`, `docs`, `chore`
- **Scope**: area of the codebase (e.g., `reply-modal`, `markdown`, `routing`)
- Prefer title-only commits — skip description when the title is exhaustive
### 8. Push branch and open PR
Push the current task branch to origin and open a PR into `master`.
Use `Closes #ISSUE_NUMBER` in the PR body so the issue closes automatically when the PR is merged.
```bash
COMMIT_HASH=$(git rev-parse HEAD)
BRANCH_NAME=$(git branch --show-current)
git push -u origin "$BRANCH_NAME"
gh pr create \
--repo bitsocialnet/5chan \
--base master \
--head "$BRANCH_NAME" \
--title "PR_TITLE" \
--body "$(cat <<EOF
SUMMARY
Closes #ISSUE_NUMBER
EOF
)"
```
Do **not** merge the PR locally as part of this skill. Review bots must be allowed to inspect the PR first.
If the user later explicitly asks to merge after reviews pass, a separate merge step can be run, for example:
```bash
gh pr merge --squash --delete-branch
```
### 9. Add to project board
Use **gh CLI** for project operations (never GitHub MCP).
Add the issue to the project when the PR is opened, but do **not** force it to `Done` yet.
```bash
ITEM_JSON=$(gh project item-add 1 --owner bitsocialnet --url "https://github.com/bitsocialnet/5chan/issues/ISSUE_NUMBER" --format json)
ITEM_ID=$(echo "$ITEM_JSON" | jq -r '.id')
```
If the user later explicitly asks to merge the reviewed PR in the same run, reuse `ITEM_ID` and then set the project item to `Done`:
```bash
# Get Status field ID and Done option ID from project
FIELD_JSON=$(gh project field-list 1 --owner bitsocialnet --format json)
STATUS_FIELD_ID=$(echo "$FIELD_JSON" | jq -r '.fields[] | select(.name=="Status") | .id')
DONE_OPTION_ID=$(echo "$FIELD_JSON" | jq -r '.fields[] | select(.name=="Status") | .options[] | select(.name=="Done") | .id')
# Set status to Done
gh project item-edit --id "$ITEM_ID" --project-id PVT_kwDODohK7M4BM4wg --field-id "$STATUS_FIELD_ID" --single-select-option-id "$DONE_OPTION_ID"
```
Assignees and labels are inherited from the issue (set in step 6) — no separate project update needed.
### 10. Report summary
Print a summary to the user:
```
Issue #NUMBER created, committed, pushed, and linked to a PR into master.
Branch: BRANCH_NAME
Commit: HASH
Labels: label1, label2
PR: PR_URL
Project: 5chan
URL: https://github.com/bitsocialnet/5chan/issues/NUMBER
```
If the PR has not been merged yet, explicitly tell the user that the issue will close on PR merge and that the branch should not be deleted yet.
After the PR is open, use `review-and-merge-pr` to inspect Bugbot, CodeRabbit, CI, and human feedback before merging.
+287
View File
@@ -0,0 +1,287 @@
---
name: playwright-cli
description: Automates browser interactions for web testing, form filling, screenshots, and data extraction. Use when the user needs to navigate websites, interact with web pages, fill forms, take screenshots, test web applications, or extract information from web pages.
allowed-tools: Bash(playwright-cli:*)
---
# Browser Automation with playwright-cli
## Quick start
```bash
# open new browser
playwright-cli open
# navigate to a page
playwright-cli goto https://playwright.dev
# interact with the page using refs from the snapshot
playwright-cli click e15
playwright-cli type "page.click"
playwright-cli press Enter
# take a screenshot
playwright-cli screenshot
# close the browser
playwright-cli close
```
## Session mode selection
Default to a fresh isolated browser session for reproducible verification.
Before browser work where existing state may matter, explicitly confirm the mode if the user has not already said which one they want:
1. Fresh isolated `playwright-cli` session
2. Current browser session reuse
Existing state usually matters when the task depends on auth, cookies, extensions, open tabs, or reproducing something already happening in the contributor's browser.
Do not attach to a live personal browser session without explicit approval.
If current-session reuse is requested, prefer the supported attach path in the local setup:
```bash
# Fresh isolated browser (default)
playwright-cli -s=verify open https://example.com
# Reusable Playwright-managed profile
playwright-cli -s=verify open https://example.com --persistent
# Attach to an existing browser when the local extension bridge is set up
playwright-cli open --extension
```
If the task requires the contributor's current browser session and the attach path is not available in the current setup, stop and ask whether to switch to a fresh session or provide an explicit CDP-based Playwright script.
## Commands
### Core
```bash
playwright-cli open
# open and navigate right away
playwright-cli open https://example.com/
playwright-cli goto https://playwright.dev
playwright-cli type "search query"
playwright-cli click e3
playwright-cli dblclick e7
playwright-cli fill e5 "user@example.com"
playwright-cli drag e2 e8
playwright-cli hover e4
playwright-cli select e9 "option-value"
playwright-cli upload ./document.pdf
playwright-cli check e12
playwright-cli uncheck e12
playwright-cli snapshot
playwright-cli snapshot --filename=after-click.yaml
playwright-cli eval "document.title"
playwright-cli eval "el => el.textContent" e5
playwright-cli dialog-accept
playwright-cli dialog-accept "confirmation text"
playwright-cli dialog-dismiss
playwright-cli resize 1920 1080
playwright-cli close
```
### Navigation
```bash
playwright-cli go-back
playwright-cli go-forward
playwright-cli reload
```
### Keyboard
```bash
playwright-cli press Enter
playwright-cli press ArrowDown
playwright-cli keydown Shift
playwright-cli keyup Shift
```
### Mouse
```bash
playwright-cli mousemove 150 300
playwright-cli mousedown
playwright-cli mousedown right
playwright-cli mouseup
playwright-cli mouseup right
playwright-cli mousewheel 0 100
```
### Save as
```bash
playwright-cli screenshot
playwright-cli screenshot e5
playwright-cli screenshot --filename=page.png
playwright-cli pdf --filename=page.pdf
```
### Tabs
```bash
playwright-cli tab-list
playwright-cli tab-new
playwright-cli tab-new https://example.com/page
playwright-cli tab-close
playwright-cli tab-close 2
playwright-cli tab-select 0
```
### Storage
```bash
playwright-cli state-save
playwright-cli state-save auth.json
playwright-cli state-load auth.json
# Cookies
playwright-cli cookie-list
playwright-cli cookie-list --domain=example.com
playwright-cli cookie-get session_id
playwright-cli cookie-set session_id abc123
playwright-cli cookie-set session_id abc123 --domain=example.com --httpOnly --secure
playwright-cli cookie-delete session_id
playwright-cli cookie-clear
# LocalStorage
playwright-cli localstorage-list
playwright-cli localstorage-get theme
playwright-cli localstorage-set theme dark
playwright-cli localstorage-delete theme
playwright-cli localstorage-clear
# SessionStorage
playwright-cli sessionstorage-list
playwright-cli sessionstorage-get step
playwright-cli sessionstorage-set step 3
playwright-cli sessionstorage-delete step
playwright-cli sessionstorage-clear
```
### Network
```bash
playwright-cli route "**/*.jpg" --status=404
playwright-cli route "https://api.example.com/**" --body='{"mock": true}'
playwright-cli route-list
playwright-cli unroute "**/*.jpg"
playwright-cli unroute
```
### DevTools
```bash
playwright-cli console
playwright-cli console warning
playwright-cli network
playwright-cli run-code "async page => await page.context().grantPermissions(['geolocation'])"
playwright-cli tracing-start
playwright-cli tracing-stop
playwright-cli video-start
playwright-cli video-stop video.webm
```
### Install
```bash
playwright-cli install --skills
playwright-cli install-browser
```
### Configuration
```bash
# Use specific browser when creating session
playwright-cli open --browser=chrome
playwright-cli open --browser=firefox
playwright-cli open --browser=webkit
playwright-cli open --browser=msedge
# Connect to browser via extension
playwright-cli open --extension
# Use persistent profile (by default profile is in-memory)
playwright-cli open --persistent
# Use persistent profile with custom directory
playwright-cli open --profile=/path/to/profile
# Start with config file
playwright-cli open --config=my-config.json
# Close the browser
playwright-cli close
# Delete user data for the default session
playwright-cli delete-data
```
### Browser Sessions
```bash
# create new browser session named "mysession" with persistent profile
playwright-cli -s=mysession open example.com --persistent
# same with manually specified profile directory (use when requested explicitly)
playwright-cli -s=mysession open example.com --profile=/path/to/profile
playwright-cli -s=mysession click e6
playwright-cli -s=mysession close # stop a named browser
playwright-cli -s=mysession delete-data # delete user data for persistent session
playwright-cli list
# Close all browsers
playwright-cli close-all
# Forcefully kill all browser processes
playwright-cli kill-all
```
## Example: Form submission
```bash
playwright-cli open https://example.com/form
playwright-cli snapshot
playwright-cli fill e1 "user@example.com"
playwright-cli fill e2 "password123"
playwright-cli click e3
playwright-cli snapshot
playwright-cli close
```
## Example: Multi-tab workflow
```bash
playwright-cli open https://example.com
playwright-cli tab-new https://example.com/other
playwright-cli tab-list
playwright-cli tab-select 0
playwright-cli snapshot
playwright-cli close
```
## Example: Debugging with DevTools
```bash
playwright-cli open https://example.com
playwright-cli click e4
playwright-cli fill e7 "test"
playwright-cli console
playwright-cli network
playwright-cli close
```
```bash
playwright-cli open https://example.com
playwright-cli tracing-start
playwright-cli click e4
playwright-cli fill e7 "test"
playwright-cli tracing-stop
playwright-cli close
```
## Specific tasks
* **Request mocking** [references/request-mocking.md](references/request-mocking.md)
* **Running Playwright code** [references/running-code.md](references/running-code.md)
* **Browser session management** [references/session-management.md](references/session-management.md)
* **Storage state (cookies, localStorage)** [references/storage-state.md](references/storage-state.md)
* **Test generation** [references/test-generation.md](references/test-generation.md)
* **Tracing** [references/tracing.md](references/tracing.md)
* **Video recording** [references/video-recording.md](references/video-recording.md)
@@ -0,0 +1,87 @@
# Request Mocking
Intercept, mock, modify, and block network requests.
## CLI Route Commands
```bash
# Mock with custom status
playwright-cli route "**/*.jpg" --status=404
# Mock with JSON body
playwright-cli route "**/api/users" --body='[{"id":1,"name":"Alice"}]' --content-type=application/json
# Mock with custom headers
playwright-cli route "**/api/data" --body='{"ok":true}' --header="X-Custom: value"
# Remove headers from requests
playwright-cli route "**/*" --remove-header=cookie,authorization
# List active routes
playwright-cli route-list
# Remove a route or all routes
playwright-cli unroute "**/*.jpg"
playwright-cli unroute
```
## URL Patterns
```
**/api/users - Exact path match
**/api/*/details - Wildcard in path
**/*.{png,jpg,jpeg} - Match file extensions
**/search?q=* - Match query parameters
```
## Advanced Mocking with run-code
For conditional responses, request body inspection, response modification, or delays:
### Conditional Response Based on Request
```bash
playwright-cli run-code "async page => {
await page.route('**/api/login', route => {
const body = route.request().postDataJSON();
if (body.username === 'admin') {
route.fulfill({ body: JSON.stringify({ token: 'mock-token' }) });
} else {
route.fulfill({ status: 401, body: JSON.stringify({ error: 'Invalid' }) });
}
});
}"
```
### Modify Real Response
```bash
playwright-cli run-code "async page => {
await page.route('**/api/user', async route => {
const response = await route.fetch();
const json = await response.json();
json.isPremium = true;
await route.fulfill({ response, json });
});
}"
```
### Simulate Network Failures
```bash
playwright-cli run-code "async page => {
await page.route('**/api/offline', route => route.abort('internetdisconnected'));
}"
# Options: connectionrefused, timedout, connectionreset, internetdisconnected
```
### Delayed Response
```bash
playwright-cli run-code "async page => {
await page.route('**/api/slow', async route => {
await new Promise(r => setTimeout(r, 3000));
route.fulfill({ body: JSON.stringify({ data: 'loaded' }) });
});
}"
```
@@ -0,0 +1,232 @@
# Running Custom Playwright Code
Use `run-code` to execute arbitrary Playwright code for advanced scenarios not covered by CLI commands.
## Syntax
```bash
playwright-cli run-code "async page => {
// Your Playwright code here
// Access page.context() for browser context operations
}"
```
## Geolocation
```bash
# Grant geolocation permission and set location
playwright-cli run-code "async page => {
await page.context().grantPermissions(['geolocation']);
await page.context().setGeolocation({ latitude: 37.7749, longitude: -122.4194 });
}"
# Set location to London
playwright-cli run-code "async page => {
await page.context().grantPermissions(['geolocation']);
await page.context().setGeolocation({ latitude: 51.5074, longitude: -0.1278 });
}"
# Clear geolocation override
playwright-cli run-code "async page => {
await page.context().clearPermissions();
}"
```
## Permissions
```bash
# Grant multiple permissions
playwright-cli run-code "async page => {
await page.context().grantPermissions([
'geolocation',
'notifications',
'camera',
'microphone'
]);
}"
# Grant permissions for specific origin
playwright-cli run-code "async page => {
await page.context().grantPermissions(['clipboard-read'], {
origin: 'https://example.com'
});
}"
```
## Media Emulation
```bash
# Emulate dark color scheme
playwright-cli run-code "async page => {
await page.emulateMedia({ colorScheme: 'dark' });
}"
# Emulate light color scheme
playwright-cli run-code "async page => {
await page.emulateMedia({ colorScheme: 'light' });
}"
# Emulate reduced motion
playwright-cli run-code "async page => {
await page.emulateMedia({ reducedMotion: 'reduce' });
}"
# Emulate print media
playwright-cli run-code "async page => {
await page.emulateMedia({ media: 'print' });
}"
```
## Wait Strategies
```bash
# Wait for network idle
playwright-cli run-code "async page => {
await page.waitForLoadState('networkidle');
}"
# Wait for specific element
playwright-cli run-code "async page => {
await page.waitForSelector('.loading', { state: 'hidden' });
}"
# Wait for function to return true
playwright-cli run-code "async page => {
await page.waitForFunction(() => window.appReady === true);
}"
# Wait with timeout
playwright-cli run-code "async page => {
await page.waitForSelector('.result', { timeout: 10000 });
}"
```
## Frames and Iframes
```bash
# Work with iframe
playwright-cli run-code "async page => {
const frame = page.locator('iframe#my-iframe').contentFrame();
await frame.locator('button').click();
}"
# Get all frames
playwright-cli run-code "async page => {
const frames = page.frames();
return frames.map(f => f.url());
}"
```
## File Downloads
```bash
# Handle file download
playwright-cli run-code "async page => {
const [download] = await Promise.all([
page.waitForEvent('download'),
page.click('a.download-link')
]);
await download.saveAs('./downloaded-file.pdf');
return download.suggestedFilename();
}"
```
## Clipboard
```bash
# Read clipboard (requires permission)
playwright-cli run-code "async page => {
await page.context().grantPermissions(['clipboard-read']);
return await page.evaluate(() => navigator.clipboard.readText());
}"
# Write to clipboard
playwright-cli run-code "async page => {
await page.evaluate(text => navigator.clipboard.writeText(text), 'Hello clipboard!');
}"
```
## Page Information
```bash
# Get page title
playwright-cli run-code "async page => {
return await page.title();
}"
# Get current URL
playwright-cli run-code "async page => {
return page.url();
}"
# Get page content
playwright-cli run-code "async page => {
return await page.content();
}"
# Get viewport size
playwright-cli run-code "async page => {
return page.viewportSize();
}"
```
## JavaScript Execution
```bash
# Execute JavaScript and return result
playwright-cli run-code "async page => {
return await page.evaluate(() => {
return {
userAgent: navigator.userAgent,
language: navigator.language,
cookiesEnabled: navigator.cookieEnabled
};
});
}"
# Pass arguments to evaluate
playwright-cli run-code "async page => {
const multiplier = 5;
return await page.evaluate(m => document.querySelectorAll('li').length * m, multiplier);
}"
```
## Error Handling
```bash
# Try-catch in run-code
playwright-cli run-code "async page => {
try {
await page.click('.maybe-missing', { timeout: 1000 });
return 'clicked';
} catch (e) {
return 'element not found';
}
}"
```
## Complex Workflows
```bash
# Login and save state
playwright-cli run-code "async page => {
await page.goto('https://example.com/login');
await page.fill('input[name=email]', 'user@example.com');
await page.fill('input[name=password]', 'secret');
await page.click('button[type=submit]');
await page.waitForURL('**/dashboard');
await page.context().storageState({ path: 'auth.json' });
return 'Login successful';
}"
# Scrape data from multiple pages
playwright-cli run-code "async page => {
const results = [];
for (let i = 1; i <= 3; i++) {
await page.goto(\`https://example.com/page/\${i}\`);
const items = await page.locator('.item').allTextContents();
results.push(...items);
}
return results;
}"
```
@@ -0,0 +1,169 @@
# Browser Session Management
Run multiple isolated browser sessions concurrently with state persistence.
## Named Browser Sessions
Use `-b` flag to isolate browser contexts:
```bash
# Browser 1: Authentication flow
playwright-cli -s=auth open https://app.example.com/login
# Browser 2: Public browsing (separate cookies, storage)
playwright-cli -s=public open https://example.com
# Commands are isolated by browser session
playwright-cli -s=auth fill e1 "user@example.com"
playwright-cli -s=public snapshot
```
## Browser Session Isolation Properties
Each browser session has independent:
- Cookies
- LocalStorage / SessionStorage
- IndexedDB
- Cache
- Browsing history
- Open tabs
## Browser Session Commands
```bash
# List all browser sessions
playwright-cli list
# Stop a browser session (close the browser)
playwright-cli close # stop the default browser
playwright-cli -s=mysession close # stop a named browser
# Stop all browser sessions
playwright-cli close-all
# Forcefully kill all daemon processes (for stale/zombie processes)
playwright-cli kill-all
# Delete browser session user data (profile directory)
playwright-cli delete-data # delete default browser data
playwright-cli -s=mysession delete-data # delete named browser data
```
## Environment Variable
Set a default browser session name via environment variable:
```bash
export PLAYWRIGHT_CLI_SESSION="mysession"
playwright-cli open example.com # Uses "mysession" automatically
```
## Common Patterns
### Concurrent Scraping
```bash
#!/bin/bash
# Scrape multiple sites concurrently
# Start all browsers
playwright-cli -s=site1 open https://site1.com &
playwright-cli -s=site2 open https://site2.com &
playwright-cli -s=site3 open https://site3.com &
wait
# Take snapshots from each
playwright-cli -s=site1 snapshot
playwright-cli -s=site2 snapshot
playwright-cli -s=site3 snapshot
# Cleanup
playwright-cli close-all
```
### A/B Testing Sessions
```bash
# Test different user experiences
playwright-cli -s=variant-a open "https://app.com?variant=a"
playwright-cli -s=variant-b open "https://app.com?variant=b"
# Compare
playwright-cli -s=variant-a screenshot
playwright-cli -s=variant-b screenshot
```
### Persistent Profile
By default, browser profile is kept in memory only. Use `--persistent` flag on `open` to persist the browser profile to disk:
```bash
# Use persistent profile (auto-generated location)
playwright-cli open https://example.com --persistent
# Use persistent profile with custom directory
playwright-cli open https://example.com --profile=/path/to/profile
```
## Default Browser Session
When `-s` is omitted, commands use the default browser session:
```bash
# These use the same default browser session
playwright-cli open https://example.com
playwright-cli snapshot
playwright-cli close # Stops default browser
```
## Browser Session Configuration
Configure a browser session with specific settings when opening:
```bash
# Open with config file
playwright-cli open https://example.com --config=.playwright/my-cli.json
# Open with specific browser
playwright-cli open https://example.com --browser=firefox
# Open in headed mode
playwright-cli open https://example.com --headed
# Open with persistent profile
playwright-cli open https://example.com --persistent
```
## Best Practices
### 1. Name Browser Sessions Semantically
```bash
# GOOD: Clear purpose
playwright-cli -s=github-auth open https://github.com
playwright-cli -s=docs-scrape open https://docs.example.com
# AVOID: Generic names
playwright-cli -s=s1 open https://github.com
```
### 2. Always Clean Up
```bash
# Stop browsers when done
playwright-cli -s=auth close
playwright-cli -s=scrape close
# Or stop all at once
playwright-cli close-all
# If browsers become unresponsive or zombie processes remain
playwright-cli kill-all
```
### 3. Delete Stale Browser Data
```bash
# Remove old browser data to free disk space
playwright-cli -s=oldsession delete-data
```
@@ -0,0 +1,275 @@
# Storage Management
Manage cookies, localStorage, sessionStorage, and browser storage state.
## Storage State
Save and restore complete browser state including cookies and storage.
### Save Storage State
```bash
# Save to auto-generated filename (storage-state-{timestamp}.json)
playwright-cli state-save
# Save to specific filename
playwright-cli state-save my-auth-state.json
```
### Restore Storage State
```bash
# Load storage state from file
playwright-cli state-load my-auth-state.json
# Reload page to apply cookies
playwright-cli open https://example.com
```
### Storage State File Format
The saved file contains:
```json
{
"cookies": [
{
"name": "session_id",
"value": "abc123",
"domain": "example.com",
"path": "/",
"expires": 1735689600,
"httpOnly": true,
"secure": true,
"sameSite": "Lax"
}
],
"origins": [
{
"origin": "https://example.com",
"localStorage": [
{ "name": "theme", "value": "dark" },
{ "name": "user_id", "value": "12345" }
]
}
]
}
```
## Cookies
### List All Cookies
```bash
playwright-cli cookie-list
```
### Filter Cookies by Domain
```bash
playwright-cli cookie-list --domain=example.com
```
### Filter Cookies by Path
```bash
playwright-cli cookie-list --path=/api
```
### Get Specific Cookie
```bash
playwright-cli cookie-get session_id
```
### Set a Cookie
```bash
# Basic cookie
playwright-cli cookie-set session abc123
# Cookie with options
playwright-cli cookie-set session abc123 --domain=example.com --path=/ --httpOnly --secure --sameSite=Lax
# Cookie with expiration (Unix timestamp)
playwright-cli cookie-set remember_me token123 --expires=1735689600
```
### Delete a Cookie
```bash
playwright-cli cookie-delete session_id
```
### Clear All Cookies
```bash
playwright-cli cookie-clear
```
### Advanced: Multiple Cookies or Custom Options
For complex scenarios like adding multiple cookies at once, use `run-code`:
```bash
playwright-cli run-code "async page => {
await page.context().addCookies([
{ name: 'session_id', value: 'sess_abc123', domain: 'example.com', path: '/', httpOnly: true },
{ name: 'preferences', value: JSON.stringify({ theme: 'dark' }), domain: 'example.com', path: '/' }
]);
}"
```
## Local Storage
### List All localStorage Items
```bash
playwright-cli localstorage-list
```
### Get Single Value
```bash
playwright-cli localstorage-get token
```
### Set Value
```bash
playwright-cli localstorage-set theme dark
```
### Set JSON Value
```bash
playwright-cli localstorage-set user_settings '{"theme":"dark","language":"en"}'
```
### Delete Single Item
```bash
playwright-cli localstorage-delete token
```
### Clear All localStorage
```bash
playwright-cli localstorage-clear
```
### Advanced: Multiple Operations
For complex scenarios like setting multiple values at once, use `run-code`:
```bash
playwright-cli run-code "async page => {
await page.evaluate(() => {
localStorage.setItem('token', 'jwt_abc123');
localStorage.setItem('user_id', '12345');
localStorage.setItem('expires_at', Date.now() + 3600000);
});
}"
```
## Session Storage
### List All sessionStorage Items
```bash
playwright-cli sessionstorage-list
```
### Get Single Value
```bash
playwright-cli sessionstorage-get form_data
```
### Set Value
```bash
playwright-cli sessionstorage-set step 3
```
### Delete Single Item
```bash
playwright-cli sessionstorage-delete step
```
### Clear sessionStorage
```bash
playwright-cli sessionstorage-clear
```
## IndexedDB
### List Databases
```bash
playwright-cli run-code "async page => {
return await page.evaluate(async () => {
const databases = await indexedDB.databases();
return databases;
});
}"
```
### Delete Database
```bash
playwright-cli run-code "async page => {
await page.evaluate(() => {
indexedDB.deleteDatabase('myDatabase');
});
}"
```
## Common Patterns
### Authentication State Reuse
```bash
# Step 1: Login and save state
playwright-cli open https://app.example.com/login
playwright-cli snapshot
playwright-cli fill e1 "user@example.com"
playwright-cli fill e2 "password123"
playwright-cli click e3
# Save the authenticated state
playwright-cli state-save auth.json
# Step 2: Later, restore state and skip login
playwright-cli state-load auth.json
playwright-cli open https://app.example.com/dashboard
# Already logged in!
```
### Save and Restore Roundtrip
```bash
# Set up authentication state
playwright-cli open https://example.com
playwright-cli eval "() => { document.cookie = 'session=abc123'; localStorage.setItem('user', 'john'); }"
# Save state to file
playwright-cli state-save my-session.json
# ... later, in a new session ...
# Restore state
playwright-cli state-load my-session.json
playwright-cli open https://example.com
# Cookies and localStorage are restored!
```
## Security Notes
- Never commit storage state files containing auth tokens
- Add `*.auth-state.json` to `.gitignore`
- Delete state files after automation completes
- Use environment variables for sensitive data
- By default, sessions run in-memory mode which is safer for sensitive operations
@@ -0,0 +1,88 @@
# Test Generation
Generate Playwright test code automatically as you interact with the browser.
## How It Works
Every action you perform with `playwright-cli` generates corresponding Playwright TypeScript code.
This code appears in the output and can be copied directly into your test files.
## Example Workflow
```bash
# Start a session
playwright-cli open https://example.com/login
# Take a snapshot to see elements
playwright-cli snapshot
# Output shows: e1 [textbox "Email"], e2 [textbox "Password"], e3 [button "Sign In"]
# Fill form fields - generates code automatically
playwright-cli fill e1 "user@example.com"
# Ran Playwright code:
# await page.getByRole('textbox', { name: 'Email' }).fill('user@example.com');
playwright-cli fill e2 "password123"
# Ran Playwright code:
# await page.getByRole('textbox', { name: 'Password' }).fill('password123');
playwright-cli click e3
# Ran Playwright code:
# await page.getByRole('button', { name: 'Sign In' }).click();
```
## Building a Test File
Collect the generated code into a Playwright test:
```typescript
import { test, expect } from '@playwright/test';
test('login flow', async ({ page }) => {
// Generated code from playwright-cli session:
await page.goto('https://example.com/login');
await page.getByRole('textbox', { name: 'Email' }).fill('user@example.com');
await page.getByRole('textbox', { name: 'Password' }).fill('password123');
await page.getByRole('button', { name: 'Sign In' }).click();
// Add assertions
await expect(page).toHaveURL(/.*dashboard/);
});
```
## Best Practices
### 1. Use Semantic Locators
The generated code uses role-based locators when possible, which are more resilient:
```typescript
// Generated (good - semantic)
await page.getByRole('button', { name: 'Submit' }).click();
// Avoid (fragile - CSS selectors)
await page.locator('#submit-btn').click();
```
### 2. Explore Before Recording
Take snapshots to understand the page structure before recording actions:
```bash
playwright-cli open https://example.com
playwright-cli snapshot
# Review the element structure
playwright-cli click e5
```
### 3. Add Assertions Manually
Generated code captures actions but not assertions. Add expectations in your test:
```typescript
// Generated action
await page.getByRole('button', { name: 'Submit' }).click();
// Manual assertion
await expect(page.getByText('Success')).toBeVisible();
```
@@ -0,0 +1,139 @@
# Tracing
Capture detailed execution traces for debugging and analysis. Traces include DOM snapshots, screenshots, network activity, and console logs.
## Basic Usage
```bash
# Start trace recording
playwright-cli tracing-start
# Perform actions
playwright-cli open https://example.com
playwright-cli click e1
playwright-cli fill e2 "test"
# Stop trace recording
playwright-cli tracing-stop
```
## Trace Output Files
When you start tracing, Playwright creates a `traces/` directory with several files:
### `trace-{timestamp}.trace`
**Action log** - The main trace file containing:
- Every action performed (clicks, fills, navigations)
- DOM snapshots before and after each action
- Screenshots at each step
- Timing information
- Console messages
- Source locations
### `trace-{timestamp}.network`
**Network log** - Complete network activity:
- All HTTP requests and responses
- Request headers and bodies
- Response headers and bodies
- Timing (DNS, connect, TLS, TTFB, download)
- Resource sizes
- Failed requests and errors
### `resources/`
**Resources directory** - Cached resources:
- Images, fonts, stylesheets, scripts
- Response bodies for replay
- Assets needed to reconstruct page state
## What Traces Capture
| Category | Details |
|----------|---------|
| **Actions** | Clicks, fills, hovers, keyboard input, navigations |
| **DOM** | Full DOM snapshot before/after each action |
| **Screenshots** | Visual state at each step |
| **Network** | All requests, responses, headers, bodies, timing |
| **Console** | All console.log, warn, error messages |
| **Timing** | Precise timing for each operation |
## Use Cases
### Debugging Failed Actions
```bash
playwright-cli tracing-start
playwright-cli open https://app.example.com
# This click fails - why?
playwright-cli click e5
playwright-cli tracing-stop
# Open trace to see DOM state when click was attempted
```
### Analyzing Performance
```bash
playwright-cli tracing-start
playwright-cli open https://slow-site.com
playwright-cli tracing-stop
# View network waterfall to identify slow resources
```
### Capturing Evidence
```bash
# Record a complete user flow for documentation
playwright-cli tracing-start
playwright-cli open https://app.example.com/checkout
playwright-cli fill e1 "4111111111111111"
playwright-cli fill e2 "12/25"
playwright-cli fill e3 "123"
playwright-cli click e4
playwright-cli tracing-stop
# Trace shows exact sequence of events
```
## Trace vs Video vs Screenshot
| Feature | Trace | Video | Screenshot |
|---------|-------|-------|------------|
| **Format** | .trace file | .webm video | .png/.jpeg image |
| **DOM inspection** | Yes | No | No |
| **Network details** | Yes | No | No |
| **Step-by-step replay** | Yes | Continuous | Single frame |
| **File size** | Medium | Large | Small |
| **Best for** | Debugging | Demos | Quick capture |
## Best Practices
### 1. Start Tracing Before the Problem
```bash
# Trace the entire flow, not just the failing step
playwright-cli tracing-start
playwright-cli open https://example.com
# ... all steps leading to the issue ...
playwright-cli tracing-stop
```
### 2. Clean Up Old Traces
Traces can consume significant disk space:
```bash
# Remove traces older than 7 days
find .playwright-cli/traces -mtime +7 -delete
```
## Limitations
- Traces add overhead to automation
- Large traces can consume significant disk space
- Some dynamic content may not replay perfectly
@@ -0,0 +1,43 @@
# Video Recording
Capture browser automation sessions as video for debugging, documentation, or verification. Produces WebM (VP8/VP9 codec).
## Basic Recording
```bash
# Start recording
playwright-cli video-start
# Perform actions
playwright-cli open https://example.com
playwright-cli snapshot
playwright-cli click e1
playwright-cli fill e2 "test input"
# Stop and save
playwright-cli video-stop demo.webm
```
## Best Practices
### 1. Use Descriptive Filenames
```bash
# Include context in filename
playwright-cli video-stop recordings/login-flow-2024-01-15.webm
playwright-cli video-stop recordings/checkout-test-run-42.webm
```
## Tracing vs Video
| Feature | Video | Tracing |
|---------|-------|---------|
| Output | WebM file | Trace file (viewable in Trace Viewer) |
| Shows | Visual recording | DOM snapshots, network, console, actions |
| Use case | Demos, documentation | Debugging, analysis |
| Size | Larger | Smaller |
## Limitations
- Recording adds slight overhead to automation
- Large recordings can consume significant disk space
+164
View File
@@ -0,0 +1,164 @@
---
name: profile-browsing
description: Profile app performance while browsing, collecting Web Vitals and React rerender data via react-scan. Orchestrates parallel profiler subagents via playwright-cli to capture navigation timing, long tasks, layout shifts, LCP, React commit counts, render bursts, and per-component render data. Use when profiling browsing performance, finding bottlenecks, diagnosing excessive rerenders, or auditing page performance.
---
# Profile Browsing Performance
Two-layer profiling: browser-level symptoms (Web Vitals, long tasks, scroll jank) and React-level diagnosis (commit counts, render bursts, per-component render data from react-scan). Each profiler subagent runs in its own browser session and context window.
## Prerequisites
- Dev server running at http://5chan.localhost:1355 (`yarn start` via Portless)
- `playwright-cli` installed (`npm install -g @playwright/cli@latest`)
**IMPORTANT:** The orchestrator (you) is responsible for ensuring exactly ONE dev server is running. Profiler subagents must NEVER start a dev server themselves.
### react-scan (already configured)
The app has `react-scan` set up in `src/lib/react-scan.ts` with `report: true`. In dev mode it:
- Highlights rerendering components visually (toolbar + overlay)
- Tracks per-component render counts and times internally
- Exposes `window.__getReactScanReport()` for programmatic collection
The profiler's `addInitScript` sets `window.__PROFILING__ = true` before the app loads, which tells react-scan to disable its toolbar and sounds during automated runs.
No additional setup needed — react-scan is already a devDependency and imported in the entry file.
## Step 0: Ensure Dev Server is Running
Before spawning any profiler subagents, verify exactly one dev server is available:
```bash
# Check if the dev server is reachable
curl -sf http://5chan.localhost:1355 -o /dev/null && echo "OK" || echo "NOT RUNNING"
```
- If **OK**: proceed to Step 1.
- If **NOT RUNNING**: start one instance with `yarn start` (backgrounded), then poll until it responds. Do NOT start more than one.
- If a dev server is already running on a different port (check `ps aux | grep vite`), reuse it — do not start another.
## Step 1: Define Route Batches
Split routes into batches of 24 for parallel profiling.
**Default batches** (adjust boards as needed):
| Batch | Session | Routes | Focus |
|-------|---------|--------|-------|
| 1 | `prof-1` | `/all`, `/all/catalog` | Multi-board feed + catalog |
| 2 | `prof-2` | `/biz`, `/biz/catalog` | Single board feed + catalog |
| 3 | `prof-3` | `/pol`, `/pol/catalog`, `/g`, `/g/catalog` | Board switching (feed reloads) |
Keep batches balanced. Add thread views (`/:boardIdentifier/thread/:cid`) as needed.
## Step 2: Spawn Profiler Subagents
Read the profiler subagent definition at `.claude/agents/profiler.md`. Then spawn one `shell` Task per batch **in parallel** (single message, multiple Task calls):
```
For each batch, create a Task:
subagent_type: "shell"
prompt: |
You are a performance profiler. Follow the workflow in .claude/agents/profiler.md.
Session name: "prof-N"
Routes to profile: /route1, /route2, ...
[Include the full profiler workflow from the agent file]
```
Spawn up to 4 subagents simultaneously. Each opens its own browser session, navigates routes, scrolls, collects both Web Vitals and react-scan data per route, and returns a structured issues list.
**Trade-off:** Parallel is faster but may skew timing results under heavy machine load. For precise measurements, spawn sequentially.
## Step 3: Merge Results
Collect structured output from each subagent and merge:
1. Concatenate all Critical / Warning / React Rerenders / Scroll Jank / Info items
2. Combine per-view summary tables into one
3. Merge react-scan component data across routes (same component appearing in multiple routes = sum counts)
4. Deduplicate shared issues (e.g., same slow resource across routes)
5. Sort by severity (Critical first)
## Step 4: Final Report
```markdown
## Performance Profile Results
### Critical
- [metric]: [value] at [route] — [what likely needs fixing]
### Warning
- [metric]: [value] at [route] — [what likely needs fixing]
### React Rerenders
- [route]: [N] commits during load, [M] during scroll — [likely cause]
- Render bursts detected at [routes] — suggests cascading state updates
- Top rerendering components (react-scan):
- [ComponentName]: [total count] renders across [routes], [time]ms total
- [ComponentName]: [total count] renders across [routes], [time]ms total
### Scroll Jank
- [route]: [N] long tasks during scroll (max [X]ms), [M] React commits — [likely cause]
### Info
- [observations]
### Per-View Summary
| View | Nav (ms) | Long Tasks | CLS | LCP (ms) | Commits | Scroll Commits | Bursts | Top Component |
|------|----------|-----------|-----|-----------|---------|----------------|--------|---------------|
| /all | ... | ... | ... | ... | ... | ... | ... | ... |
```
## Interpreting React Metrics
| Signal | Likely cause | Fix direction |
|--------|-------------|---------------|
| High commits, no long tasks | Frequent cheap rerenders | `React.memo`, stabilize props |
| High commits + long tasks | Expensive rerenders | Profile render cost, split components |
| High scroll commits | Scroll/intersection observer triggering renders | Throttle handlers, memoize list items |
| Render bursts (>5 in 100ms) | Cascading state updates | Batch updates, review Zustand selectors |
| react-scan: component with >30 renders | Missing memoization or unstable references | `useMemo`/`useCallback`, check parent renders |
| react-scan: component with >50ms time | Expensive render function | Split component, move work out of render |
## Element-source follow-up
When `react-scan` identifies a rerender hotspot but you still need the exact file behind a concrete DOM node, hand off to `$inspect-elements`.
```bash
playwright-cli -s=prof-followup eval "async el => JSON.stringify(await window.__ELEMENT_SOURCE__.resolve(el))" e7
```
Use `source.filePath` as the direct edit target and `stack` to understand which parent components own the node.
## Step 5: Cleanup
After profiling is complete and the report is delivered, verify no orphaned processes were left behind:
```bash
# Check for any Vite dev servers started during profiling
ps aux | grep 'vite.*--port' | grep -v grep
```
- If the dev server was already running before Step 0, leave it alone.
- If the orchestrator started the dev server in Step 0, kill it now.
- If there are multiple Vite processes (should never happen), kill the extras and warn the user.
Also close any leftover playwright-cli sessions:
```bash
# Close any profiling sessions that weren't properly closed
playwright-cli -s=prof-1 close 2>/dev/null
playwright-cli -s=prof-2 close 2>/dev/null
playwright-cli -s=prof-3 close 2>/dev/null
```
## Notes
- **Session isolation**: Each subagent uses a named playwright-cli session (`-s=prof-N`).
- **Context isolation**: Each subagent runs in its own context window.
- **Per-route collection**: Data resets on each `goto` — the profiler collects before navigating away.
- **addInitScript persistence**: Instrumentation re-injects automatically in each new document.
- **Tracing**: Each subagent produces a `trace.zip` viewable in [Trace Viewer](https://trace.playwright.dev).
- **Board codes**: `biz`, `pol`, `g`, `a`, `v`, etc. map to subplebbit addresses via the directory.
- **Without react-scan**: If `__getReactScanReport` returns null, the profiler falls back to commit counts + render bursts (still useful, just no component names).
+764
View File
@@ -0,0 +1,764 @@
---
name: readme
description: When the user wants to create or update a README.md file for a project. Also use when the user says "write readme," "create readme," "document this project," "project documentation," or asks for help with README.md. This skill creates absurdly thorough documentation covering local setup, architecture, and deployment.
---
# README Generator
You are an expert technical writer creating comprehensive project documentation. Your goal is to write a README.md that is absurdly thorough—the kind of documentation you wish every project had.
## The Three Purposes of a README
1. **Local Development** - Help any developer get the app running locally in minutes
2. **Understanding the System** - Explain in great detail how the app works
3. **Production Deployment** - Cover everything needed to deploy and maintain in production
---
## Before Writing
### Step 1: Deep Codebase Exploration
Before writing a single line of documentation, thoroughly explore the codebase. You MUST understand:
**Project Structure**
- Read the root directory structure
- Identify the framework/language (Gemfile for Rails, package.json, go.mod, requirements.txt, etc.)
- Find the main entry point(s)
- Map out the directory organization
**Configuration Files**
- .env.example, .env.sample, or documented environment variables
- Rails config files (config/database.yml, config/application.rb, config/environments/)
- Credentials setup (config/credentials.yml.enc, config/master.key)
- Docker files (Dockerfile, docker-compose.yml)
- CI/CD configs (.github/workflows/, .gitlab-ci.yml, etc.)
- Deployment configs (config/deploy.yml for Kamal, fly.toml, render.yaml, Procfile, etc.)
**Database**
- db/schema.rb or db/structure.sql
- Migrations in db/migrate/
- Seeds in db/seeds.rb
- Database type from config/database.yml
**Key Dependencies**
- Gemfile and Gemfile.lock for Ruby gems
- package.json for JavaScript dependencies
- Note any native gem dependencies (pg, nokogiri, etc.)
**Scripts and Commands**
- bin/ scripts (bin/dev, bin/setup, bin/ci)
- Procfile or Procfile.dev
- Rake tasks (lib/tasks/)
### Step 2: Identify Deployment Target
Look for these files to determine deployment platform and tailor instructions:
- `Dockerfile` / `docker-compose.yml` → Docker-based deployment
- `vercel.json` / `.vercel/` → Vercel
- `netlify.toml` → Netlify
- `fly.toml` → Fly.io
- `railway.json` / `railway.toml` → Railway
- `render.yaml` → Render
- `app.yaml` → Google App Engine
- `Procfile` → Heroku or Heroku-like platforms
- `.ebextensions/` → AWS Elastic Beanstalk
- `serverless.yml` → Serverless Framework
- `terraform/` / `*.tf` → Terraform/Infrastructure as Code
- `k8s/` / `kubernetes/` → Kubernetes
If no deployment config exists, provide general guidance with Docker as the recommended approach.
### Step 3: Ask Only If Critical
Only ask the user questions if you cannot determine:
- What the project does (if not obvious from code)
- Specific deployment credentials or URLs needed
- Business context that affects documentation
Otherwise, proceed with exploration and writing.
---
## README Structure
Write the README with these sections in order:
### 1. Project Title and Overview
```markdown
# Project Name
Brief description of what the project does and who it's for. 2-3 sentences max.
## Key Features
- Feature 1
- Feature 2
- Feature 3
```
### 2. Tech Stack
List all major technologies:
```markdown
## Tech Stack
- **Language**: Ruby 3.3+
- **Framework**: Rails 7.2+
- **Frontend**: Inertia.js with React
- **Database**: PostgreSQL 16
- **Background Jobs**: Solid Queue
- **Caching**: Solid Cache
- **Styling**: Tailwind CSS
- **Deployment**: [Detected platform]
```
### 3. Prerequisites
What must be installed before starting:
```markdown
## Prerequisites
- Node.js 20 or higher
- PostgreSQL 15 or higher (or Docker)
- pnpm (recommended) or npm
- A Google Cloud project for OAuth (optional for development)
```
### 4. Getting Started
The complete local development guide:
```markdown
## Getting Started
### 1. Clone the Repository
\`\`\`bash
git clone https://github.com/user/repo.git
cd repo
\`\`\`
### 2. Install Ruby Dependencies
Ensure you have Ruby 3.3+ installed (via rbenv, asdf, or mise):
\`\`\`bash
bundle install
\`\`\`
### 3. Install JavaScript Dependencies
\`\`\`bash
corepack yarn install
\`\`\`
### 4. Environment Setup
Copy the example environment file:
\`\`\`bash
cp .env.example .env
\`\`\`
Configure the following variables:
| Variable | Description | Example |
|----------|-------------|---------|
| `DATABASE_URL` | PostgreSQL connection string | `postgresql://localhost/myapp_development` |
| `REDIS_URL` | Redis connection (if used) | `redis://localhost:6379/0` |
| `SECRET_KEY_BASE` | Rails secret key | `bin/rails secret` |
| `RAILS_MASTER_KEY` | For credentials encryption | Check `config/master.key` |
### 5. Database Setup
Start PostgreSQL (if using Docker):
\`\`\`bash
docker run --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 -d postgres:16
\`\`\`
Create and set up the database:
\`\`\`bash
bin/rails db:setup
\`\`\`
This runs `db:create`, `db:schema:load`, and `db:seed`.
For existing databases, run migrations:
\`\`\`bash
bin/rails db:migrate
\`\`\`
### 6. Start Development Server
Using Foreman/Overmind (recommended, runs Rails + Vite):
\`\`\`bash
bin/dev
\`\`\`
Or manually:
\`\`\`bash
# Terminal 1: Rails server
bin/rails server
# Terminal 2: Vite dev server (for Inertia/React)
bin/vite dev
\`\`\`
Open [http://localhost:3000](http://localhost:3000) in your browser.
```
Include every step. Assume the reader is setting up on a fresh machine.
### 5. Architecture Overview
This is where you go absurdly deep:
```markdown
## Architecture
### Directory Structure
\`\`\`
├── app/
│ ├── controllers/ # Rails controllers
│ │ ├── concerns/ # Shared controller modules
│ │ └── api/ # API-specific controllers
│ ├── models/ # ActiveRecord models
│ │ └── concerns/ # Shared model modules
│ ├── jobs/ # Background jobs (Solid Queue)
│ ├── mailers/ # Email templates
│ ├── views/ # Rails views (minimal with Inertia)
│ └── frontend/ # Inertia.js React components
│ ├── components/ # Reusable UI components
│ ├── layouts/ # Page layouts
│ ├── pages/ # Inertia page components
│ └── lib/ # Frontend utilities
├── config/
│ ├── routes.rb # Route definitions
│ ├── database.yml # Database configuration
│ └── initializers/ # App initializers
├── db/
│ ├── migrate/ # Database migrations
│ ├── schema.rb # Current schema
│ └── seeds.rb # Seed data
├── lib/
│ └── tasks/ # Custom Rake tasks
└── public/ # Static assets
\`\`\`
### Request Lifecycle
1. Request hits Rails router (`config/routes.rb`)
2. Middleware stack processes request (authentication, sessions, etc.)
3. Controller action executes
4. Models interact with PostgreSQL via ActiveRecord
5. Inertia renders React component with props
6. Response sent to browser
### Data Flow
\`\`\`
User Action → React Component → Inertia Visit → Rails Controller → ActiveRecord → PostgreSQL
React Props ← Inertia Response ←
\`\`\`
### Key Components
**Authentication**
- Devise/Rodauth for user authentication
- Session-based auth with encrypted cookies
- `authenticate_user!` before_action for protected routes
**Inertia.js Integration (`app/frontend/`)**
- React components receive props from Rails controllers
- `inertia_render` in controllers passes data to frontend
- Shared data via `inertia_share` for layout props
**Background Jobs (`app/jobs/`)**
- Solid Queue for job processing
- Jobs stored in PostgreSQL (no Redis required)
- Dashboard at `/jobs` for monitoring
**Database (`app/models/`)**
- ActiveRecord models with associations
- Query objects for complex queries
- Concerns for shared model behavior
### Database Schema
\`\`\`
users
├── id (bigint, PK)
├── email (string, unique, not null)
├── encrypted_password (string)
├── name (string)
├── created_at (datetime)
└── updated_at (datetime)
posts
├── id (bigint, PK)
├── title (string, not null)
├── content (text)
├── published (boolean, default: false)
├── user_id (bigint, FK → users)
├── created_at (datetime)
└── updated_at (datetime)
solid_queue_jobs (background jobs)
├── id (bigint, PK)
├── queue_name (string)
├── class_name (string)
├── arguments (json)
├── scheduled_at (datetime)
└── ...
\`\`\`
```
### 6. Environment Variables
Complete reference for all env vars:
```markdown
## Environment Variables
### Required
| Variable | Description | How to Get |
|----------|-------------|------------|
| `DATABASE_URL` | PostgreSQL connection string | Your database provider |
| `SECRET_KEY_BASE` | Rails secret for sessions/cookies | Run `bin/rails secret` |
| `RAILS_MASTER_KEY` | Decrypts credentials file | Check `config/master.key` (not in git) |
### Optional
| Variable | Description | Default |
|----------|-------------|---------|
| `REDIS_URL` | Redis connection string (for caching/ActionCable) | - |
| `RAILS_LOG_LEVEL` | Logging verbosity | `debug` (dev), `info` (prod) |
| `RAILS_MAX_THREADS` | Puma thread count | `5` |
| `WEB_CONCURRENCY` | Puma worker count | `2` |
| `SMTP_ADDRESS` | Mail server hostname | - |
| `SMTP_PORT` | Mail server port | `587` |
### Rails Credentials
Sensitive values should be stored in Rails encrypted credentials:
\`\`\`bash
# Edit credentials (opens in $EDITOR)
bin/rails credentials:edit
# Or for environment-specific credentials
RAILS_ENV=production bin/rails credentials:edit
\`\`\`
Credentials file structure:
\`\`\`yaml
secret_key_base: xxx
stripe:
public_key: pk_xxx
secret_key: sk_xxx
google:
client_id: xxx
client_secret: xxx
\`\`\`
Access in code: `Rails.application.credentials.stripe[:secret_key]`
### Environment-Specific
**Development**
\`\`\`
DATABASE_URL=postgresql://localhost/myapp_development
REDIS_URL=redis://localhost:6379/0
\`\`\`
**Production**
\`\`\`
DATABASE_URL=<production-connection-string>
RAILS_ENV=production
RAILS_SERVE_STATIC_FILES=true
\`\`\`
```
### 7. Available Scripts
```markdown
## Available Scripts
| Command | Description |
|---------|-------------|
| `bin/dev` | Start development server (Rails + Vite via Foreman) |
| `bin/rails server` | Start Rails server only |
| `bin/vite dev` | Start Vite dev server only |
| `bin/rails console` | Open Rails console (IRB with app loaded) |
| `bin/rails db:migrate` | Run pending database migrations |
| `bin/rails db:rollback` | Rollback last migration |
| `bin/rails db:seed` | Run database seeds |
| `bin/rails db:reset` | Drop, create, migrate, and seed database |
| `bin/rails routes` | List all routes |
| `bin/rails test` | Run test suite (Minitest) |
| `bundle exec rspec` | Run test suite (RSpec, if used) |
| `bin/rails assets:precompile` | Compile assets for production |
| `bin/rubocop` | Run Ruby linter |
| `yarn lint` | Run JavaScript/TypeScript linter |
```
### 8. Testing
```markdown
## Testing
### Running Tests
\`\`\`bash
# Run all tests (Minitest)
bin/rails test
# Run all tests (RSpec, if used)
bundle exec rspec
# Run specific test file
bin/rails test test/models/user_test.rb
bundle exec rspec spec/models/user_spec.rb
# Run tests matching a pattern
bin/rails test -n /creates_user/
bundle exec rspec -e "creates user"
# Run system tests (browser tests)
bin/rails test:system
# Run with coverage (SimpleCov)
COVERAGE=true bin/rails test
\`\`\`
### Test Structure
\`\`\`
test/ # Minitest structure
├── controllers/ # Controller tests
├── models/ # Model unit tests
├── integration/ # Integration tests
├── system/ # System/browser tests
├── fixtures/ # Test data
└── test_helper.rb # Test configuration
spec/ # RSpec structure (if used)
├── models/
├── requests/
├── system/
├── factories/ # FactoryBot factories
├── support/
└── rails_helper.rb
\`\`\`
### Writing Tests
**Minitest example:**
\`\`\`ruby
require "test_helper"
class UserTest < ActiveSupport::TestCase
test "creates user with valid attributes" do
user = User.new(email: "test@example.com", name: "Test User")
assert user.valid?
end
test "requires email" do
user = User.new(name: "Test User")
assert_not user.valid?
assert_includes user.errors[:email], "can't be blank"
end
end
\`\`\`
**RSpec example:**
\`\`\`ruby
require "rails_helper"
RSpec.describe User, type: :model do
describe "validations" do
it "is valid with valid attributes" do
user = build(:user)
expect(user).to be_valid
end
it "requires an email" do
user = build(:user, email: nil)
expect(user).not_to be_valid
expect(user.errors[:email]).to include("can't be blank")
end
end
end
\`\`\`
### Frontend Testing
For Inertia/React components:
\`\`\`bash
yarn test
\`\`\`
\`\`\`typescript
import { render, screen } from '@testing-library/react'
import { Dashboard } from './Dashboard'
describe('Dashboard', () => {
it('renders user name', () => {
render(<Dashboard user={{ name: 'Josh' }} />)
expect(screen.getByText('Josh')).toBeInTheDocument()
})
})
\`\`\`
```
### 9. Deployment
Tailor this to detected platform (look for Dockerfile, fly.toml, render.yaml, kamal/, etc.):
```markdown
## Deployment
### Kamal (Recommended for Rails)
If using Kamal for deployment:
\`\`\`bash
# Setup Kamal (first time)
kamal setup
# Deploy
kamal deploy
# Rollback to previous version
kamal rollback
# View logs
kamal app logs
# Run console on production
kamal app exec --interactive 'bin/rails console'
\`\`\`
Configuration lives in `config/deploy.yml`.
### Docker
Build and run:
\`\`\`bash
# Build image
docker build -t myapp .
# Run with environment variables
docker run -p 3000:3000 \
-e DATABASE_URL=postgresql://... \
-e SECRET_KEY_BASE=... \
-e RAILS_ENV=production \
myapp
\`\`\`
### Heroku
\`\`\`bash
# Create app
heroku create myapp
# Add PostgreSQL
heroku addons:create heroku-postgresql:mini
# Set environment variables
heroku config:set SECRET_KEY_BASE=$(bin/rails secret)
heroku config:set RAILS_MASTER_KEY=$(cat config/master.key)
# Deploy
git push heroku main
# Run migrations
heroku run bin/rails db:migrate
\`\`\`
### Fly.io
\`\`\`bash
# Launch (first time)
fly launch
# Deploy
fly deploy
# Run migrations
fly ssh console -C "bin/rails db:migrate"
# Open console
fly ssh console -C "bin/rails console"
\`\`\`
### Render
If `render.yaml` exists, connect your repo to Render and it will auto-deploy.
Manual setup:
1. Create new Web Service
2. Connect GitHub repository
3. Set build command: `bundle install && bin/rails assets:precompile`
4. Set start command: `bin/rails server`
5. Add environment variables in dashboard
### Manual/VPS Deployment
\`\`\`bash
# On the server:
# Pull latest code
git pull origin main
# Install dependencies
bundle install --deployment
# Compile assets
RAILS_ENV=production bin/rails assets:precompile
# Run migrations
RAILS_ENV=production bin/rails db:migrate
# Restart application server (e.g., Puma via systemd)
sudo systemctl restart myapp
\`\`\`
```
### 10. Troubleshooting
```markdown
## Troubleshooting
### Database Connection Issues
**Error:** `could not connect to server: Connection refused`
**Solution:**
1. Verify PostgreSQL is running: `pg_isready` or `docker ps`
2. Check `DATABASE_URL` format: `postgresql://USER:PASSWORD@HOST:PORT/DATABASE`
3. Ensure database exists: `bin/rails db:create`
### Pending Migrations
**Error:** `Migrations are pending`
**Solution:**
\`\`\`bash
bin/rails db:migrate
\`\`\`
### Asset Compilation Issues
**Error:** `The asset "application.css" is not present in the asset pipeline`
**Solution:**
\`\`\`bash
# Clear and recompile assets
bin/rails assets:clobber
bin/rails assets:precompile
\`\`\`
### Bundle Install Failures
**Error:** Native extension build failures
**Solution:**
1. Ensure system dependencies are installed:
\`\`\`bash
# macOS
brew install postgresql libpq
# Ubuntu
sudo apt-get install libpq-dev
\`\`\`
2. Try again: `bundle install`
### Credentials Issues
**Error:** `ActiveSupport::MessageEncryptor::InvalidMessage`
**Solution:**
The master key doesn't match the credentials file. Either:
1. Get the correct `config/master.key` from another team member
2. Or regenerate credentials: `rm config/credentials.yml.enc && bin/rails credentials:edit`
### Vite/Inertia Issues
**Error:** `Vite Ruby - Build failed`
**Solution:**
\`\`\`bash
# Clear Vite cache
rm -rf node_modules/.vite
# Reinstall JS dependencies
rm -rf node_modules && corepack yarn install
\`\`\`
### Solid Queue Issues
**Error:** Jobs not processing
**Solution:**
Ensure the queue worker is running:
\`\`\`bash
bin/jobs
# or
bin/rails solid_queue:start
\`\`\`
```
### 11. Contributing (Optional)
Include if open source or team project.
### 12. License (Optional)
---
## Writing Principles
1. **Be Absurdly Thorough** - When in doubt, include it. More detail is always better.
2. **Use Code Blocks Liberally** - Every command should be copy-pasteable.
3. **Show Example Output** - When helpful, show what the user should expect to see.
4. **Explain the Why** - Don't just say "run this command," explain what it does.
5. **Assume Fresh Machine** - Write as if the reader has never seen this codebase.
6. **Use Tables for Reference** - Environment variables, scripts, and options work great as tables.
7. **Keep Commands Current** - Use `pnpm` if the project uses it, `npm` if it uses npm, etc.
8. **Include a Table of Contents** - For READMEs over ~200 lines, add a TOC at the top.
---
## Output Format
Generate a complete README.md file with:
- Proper markdown formatting
- Code blocks with language hints (```bash, ```typescript, etc.)
- Tables where appropriate
- Clear section hierarchy
- Linked table of contents for long documents
Write the README directly to `README.md` in the project root.
+47
View File
@@ -0,0 +1,47 @@
---
name: refactor-pass
description: Perform a refactor pass focused on simplicity after recent changes. Use when the user asks for a refactor/cleanup pass, simplification, dead-code removal, or says "refactor pass".
---
# Refactor Pass
## Workflow
1. **Review recent changes** — identify simplification opportunities:
- `git diff` for unstaged changes
- `git diff --cached` for staged changes
- `git log --oneline -5` for recent commits if no uncommitted changes
2. **Apply refactors** (in priority order):
- Remove dead code and unreachable paths
- Straighten convoluted logic flows
- Remove excessive parameters or intermediary variables
- Remove premature optimization (unnecessary `useMemo`, `useCallback`, etc.)
- Extract duplicated logic into custom hooks (`src/hooks/`) or shared components (`src/components/`)
3. **Verify** — run all three checks:
```bash
yarn build && yarn lint && yarn type-check
```
4. **Optional suggestions** — identify abstractions or reusable patterns only if they clearly improve clarity. Keep suggestions brief; don't refactor speculatively.
## Project-Specific Patterns to Enforce
When refactoring, watch for these anti-patterns from AGENTS.md:
| Anti-pattern | Refactor to |
|---|---|
| `useState` for shared state | Zustand store in `src/stores/` |
| `useEffect` for data fetching | bitsocial-react-hooks (`useComment`, `useFeed`, etc.) |
| `useEffect` to sync derived state | Calculate during render |
| Copy-pasted logic across components | Custom hook in `src/hooks/` |
| Boolean flag soup (`isLoading`, `isError`, `isSuccess`) | State machine in Zustand |
| Prop drilling through many layers | Zustand store |
## Rules
- Don't change behavior — refactors must be semantically equivalent
- Don't introduce new dependencies
- Format edited files with `npx oxfmt <file>` after changes
- If the build/lint/type-check fails after refactoring, fix it before finishing
+132
View File
@@ -0,0 +1,132 @@
---
name: release
description: Automate a full 5chan release — analyze commits, update release body and blotter, bump version, generate changelog, commit, tag, and push. Use when the user says "release", "new version", "cut a release", "prepare release", or provides a version number to ship.
---
# Release
End-to-end release automation for 5chan.
## Usage
The user provides a version bump (`patch`, `minor`, `major`, or explicit `x.y.z`).
If omitted, ask which bump level they want.
## Workflow
Copy this checklist and track progress:
```
Release Progress:
- [ ] Step 1: Analyze commits
- [ ] Step 2: Write release body (longer sentence)
- [ ] Step 3: Write blotter message (concise keywords)
- [ ] Step 4: Bump version in package.json
- [ ] Step 5: Generate changelog
- [ ] Step 6: Update blotter file
- [ ] Step 7: Verify blotter
- [ ] Step 8: Commit, tag, push
```
### Step 1 — Analyze commits
```bash
git tag --sort=-creatordate | head -1
```
Then list commits since that tag:
```bash
git log --oneline <tag>..HEAD
```
If there are no new commits, stop — nothing to release.
Categorize by Conventional Commits prefix (`feat:`, `fix:`, `perf:`, `refactor:`, `chore:`, etc.).
### Step 2 — Write the release body one-liner
Edit `oneLinerDescription` in `scripts/release-body.js` (around line 105).
Rules:
- Start with "This version..." or "This release..."
- One sentence, no bullets
- Lead with the biggest features/fixes, group minor ones
- Plain language (user-facing)
- End with a period
Good examples:
- "This version adds backlinks for quoted posts, a copy user ID menu item, and several bug fixes."
- "This release adds pseudonymity mode support per-reply and fixes timezone display issues."
### Step 3 — Write the blotter message
This is a **separate, shorter** summary used for the in-app blotter banner.
Rules:
- Comma-separated key highlights, no full sentence
- Omit "This version..." prefix — the blotter script prepends `vX.Y.Z: ` automatically
- Aim for ~6080 characters after the version prefix
- **Only genuinely novel or noteworthy items** — things a user would find interesting or exciting
- Skip regression fixes (restoring something that previously worked), routine bug fixes, minor z-index/modal/layout tweaks, test improvements, CI changes, and anything that isn't a new capability or a significant user-facing improvement
- If something was already a known feature and just got fixed/restored, it does not belong in the blotter
- Fewer strong items beat many weak items; 24 highlights is ideal
- Lead with the most impressive item
Good examples (the part **you** write, without the `vX.Y.Z:` prefix):
- "Board pagination, multi-provider uploads, mod queue redesign, catalog sorting"
- "Syncs board dirs from GitHub, macOS icon, reply perf"
- "Quote links, backlinks, pseudonymityMode, release artifacts"
Save this string — you will pass it to the blotter script in Step 6.
### Step 4 — Bump version
Read `package.json`, compute the new version from the bump level, and update the `"version"` field.
| Bump | Effect |
|------|--------|
| `patch` | `0.6.7``0.6.8` |
| `minor` | `0.6.7``0.7.0` |
| `major` | `0.6.7``1.0.0` |
| `x.y.z` | Set exactly |
### Step 5 — Generate changelog
```bash
yarn changelog
```
This regenerates `CHANGELOG.md` from conventional commits.
### Step 6 — Update blotter
Pass the **blotter message from Step 3** (not the release body):
```bash
node scripts/update-blotter.js release --message "<blotter message>"
```
### Step 7 — Verify blotter
```bash
node scripts/update-blotter.js check
```
If it fails, fix the issue and re-run.
### Step 8 — Commit, tag, push
```bash
git add -A
git commit -m "chore(release): v<version>"
git push
git tag v<version>
git push --tags
```
GitHub Actions triggers on the pushed tag to build release artifacts.
## Dry-run mode
If the user says "dry run" or "preview", execute Steps 17 but **skip Step 8** (git operations). Print a summary of what would be committed so the user can review.
+210
View File
@@ -0,0 +1,210 @@
---
name: review-and-merge-pr
description: Review an open GitHub pull request, inspect feedback from Cursor Bugbot, CodeRabbit, CI, and human reviewers, decide which findings are valid, implement fixes on the PR branch, merge the PR into master when it is ready, and finalize any linked GitHub issue so it matches the make-closed-issue workflow after merge. Use when the user says "check the PR", "address bugbot comments", "handle CodeRabbit feedback", "review PR feedback", or "merge this PR".
---
# Review And Merge Pr
## Overview
Use this skill after a feature branch already has an open PR into `master`.
Stay on the PR branch, treat review bots as input rather than authority, and only merge once the branch is verified and the remaining comments are either fixed, explicitly deferred, or explicitly declined with a reason.
Do not let repeated nitpicks, speculative future-work comments, or low-value bot suggestions keep the PR open once they have been triaged as non-blocking.
Finish the workflow by cleaning up local git state yourself; do not assume GitHub, `gh pr merge --delete-branch`, or GitHub Desktop removed the local feature branch or any local `pr/<number>` alias.
## Workflow
### 1. Identify the target PR
Prefer the PR for the current branch when the branch is not `master`.
If the current branch is `master`, inspect open PRs and choose the one that matches the user request.
If there is no open PR yet, stop and use `make-closed-issue` first.
Useful commands:
```bash
gh pr status
gh pr list --repo bitsocialnet/5chan --state open
gh pr view <pr-number> --repo bitsocialnet/5chan --json number,title,url,headRefName,baseRefName,isDraft,reviewDecision,mergeStateStatus
```
### 2. Gather all review signals before changing code
Read the PR state, checks, issue comments, review summaries, and inline review comments before deciding what to change.
Do not merge based only on the top-level review verdict.
Useful commands:
```bash
gh pr view <pr-number> --repo bitsocialnet/5chan --json number,title,url,headRefName,baseRefName,isDraft,reviewDecision,mergeStateStatus
gh pr checks <pr-number>
gh api "repos/bitsocialnet/5chan/issues/<pr-number>/comments?per_page=100"
gh api "repos/bitsocialnet/5chan/pulls/<pr-number>/reviews?per_page=100"
gh api "repos/bitsocialnet/5chan/pulls/<pr-number>/comments?per_page=100"
```
Focus on comments from:
- Cursor Bugbot
- CodeRabbit
- human reviewers
- failing CI checks
### 3. Triage findings instead of blindly applying them
Sort feedback into these buckets:
- `must-fix`: correctness bugs, broken behavior, crashes, security issues, test failures, reproducible regressions
- `should-fix`: clear maintainability or edge-case issues with concrete evidence
- `defer`: real but non-blocking follow-up work that can land later without making this PR unsafe to merge
- `decline`: false positives, stale comments, duplicate findings, speculative style-only suggestions, feedback already addressed in newer commits, or nitpicks that are not worth blocking merge
Rules:
- Never merge with unresolved `must-fix` findings.
- Do not accept a bot finding without reading the relevant code and diff.
- `should-fix` and `defer` findings are not merge blockers by default; use judgment and prefer merging once the branch is safe, verified, and the remaining comments are low-value or future work.
- If a finding is ambiguous but high-risk, ask the user before merging.
- If a comment is wrong, stale, or intentionally deferred, explain that briefly in the PR or merge summary rather than silently ignoring it.
- After triaging a comment as `defer` or `decline`, do not keep reopening the same discussion unless new evidence appears or the user explicitly asks for a follow-up pass.
### 4. Work on the PR branch and keep the PR updated
Switch to the PR branch if needed, apply the valid fixes, and push new commits to the same branch.
Do not open a replacement PR unless the user explicitly asks for that.
Useful commands:
```bash
git switch <head-branch>
git fetch origin <head-branch>
git status --short --branch
git add <files>
git commit -m "fix(scope): address review feedback"
git push
```
After code changes, follow repo verification rules from `AGENTS.md`:
- run `yarn build`, `yarn lint`, and `yarn type-check`
- run `yarn test` after adding or changing tests
- run `yarn doctor` after React UI logic changes
- use `playwright-cli` for UI/visual changes on desktop and mobile
### 5. Report back on the PR before merging
Summarize what was fixed, what was deferred, and what was declined.
Use `gh pr comment` for a concise PR update when the branch changed because of review feedback.
Example:
```bash
gh pr comment <pr-number> --repo bitsocialnet/5chan --body "Addressed the valid review findings in the latest commit. Remaining bot comments were triaged as stale, low-value, or follow-up work that does not block this merge."
```
### 6. Merge only when the PR is actually ready
Merge only if all of these are true:
- the PR is not draft
- required checks are passing
- the branch is mergeable into `master`
- no unresolved `must-fix` reviewer findings remain
- any remaining `should-fix`, `defer`, or `decline` items were consciously triaged and are not worth blocking merge
- the latest code was verified locally after the last review-driven change
Preferred merge command:
```bash
gh pr merge <pr-number> --repo bitsocialnet/5chan --squash --delete-branch
```
### 7. Finalize linked issues to match `make-closed-issue`
After merge, inspect the PR's linked closing issues.
For every linked issue, bring it into the same final state expected from `make-closed-issue`:
- closed
- assigned to the current GitHub user
- added to the `5chan` project if missing
- project status `Done`
Before editing issue assignees, determine the current contributor's GitHub username from the authenticated `gh` session.
If `gh` is not signed in or cannot resolve the login, stop and ask the contributor for their GitHub username before proceeding.
If the PR has no linked issue, explicitly tell the user that there was no associated issue to finalize.
Useful commands:
```bash
GH_LOGIN=$(gh api user --jq '.login' 2>/dev/null || true)
if [ -z "$GH_LOGIN" ]; then
echo "GitHub username could not be determined from gh auth. Ask the contributor for their GitHub username before proceeding."
exit 1
fi
ISSUE_NUMBERS=$(gh pr view <pr-number> --repo bitsocialnet/5chan --json closingIssuesReferences --jq '.closingIssuesReferences[].number')
if [ -n "$ISSUE_NUMBERS" ]; then
FIELD_JSON=$(gh project field-list 1 --owner bitsocialnet --format json)
STATUS_FIELD_ID=$(echo "$FIELD_JSON" | jq -r '.fields[] | select(.name=="Status") | .id')
DONE_OPTION_ID=$(echo "$FIELD_JSON" | jq -r '.fields[] | select(.name=="Status") | .options[] | select(.name=="Done") | .id')
for ISSUE_NUMBER in $ISSUE_NUMBERS; do
ISSUE_STATE=$(gh issue view "$ISSUE_NUMBER" --repo bitsocialnet/5chan --json state --jq '.state')
if [ "$ISSUE_STATE" != "CLOSED" ]; then
gh issue close "$ISSUE_NUMBER" --repo bitsocialnet/5chan
fi
if ! gh issue view "$ISSUE_NUMBER" --repo bitsocialnet/5chan --json assignees --jq '.assignees[].login' | grep -qx "$GH_LOGIN"; then
gh issue edit "$ISSUE_NUMBER" --repo bitsocialnet/5chan --add-assignee "$GH_LOGIN"
fi
ITEM_ID=$(gh project item-list 1 --owner bitsocialnet --limit 1000 --format json --jq ".items[] | select(.content.number == $ISSUE_NUMBER) | .id" | head -n1)
if [ -z "$ITEM_ID" ]; then
ITEM_JSON=$(gh project item-add 1 --owner bitsocialnet --url "https://github.com/bitsocialnet/5chan/issues/$ISSUE_NUMBER" --format json)
ITEM_ID=$(echo "$ITEM_JSON" | jq -r '.id')
fi
gh project item-edit --id "$ITEM_ID" --project-id PVT_kwDODohK7M4BM4wg --field-id "$STATUS_FIELD_ID" --single-select-option-id "$DONE_OPTION_ID"
done
fi
```
### 8. Clean up local state after merge
After the PR is merged:
```bash
git switch master
git fetch origin --prune
git pull --ff-only
git branch -D <head-branch> 2>/dev/null || true
git branch -D "pr/<pr-number>" 2>/dev/null || true
```
This cleanup is required even when the remote branch was deleted automatically or the merge happened in GitHub Desktop or the GitHub web UI.
Remote deletion only removes the remote branch; it does not remove the local feature branch, the local `pr/<number>` checkout alias, or stale remote-tracking refs in your clone.
Use `-D` rather than `-d` here because squash merges usually leave the local branch looking unmerged by ancestry even when the PR is already merged and safe to remove.
If the PR branch lived in a dedicated worktree, remove that worktree after leaving it:
```bash
git worktree list
git worktree remove /path/to/worktree
```
### 9. Report the outcome
Tell the user:
- which findings were fixed
- which findings were deferred and why they did not block merge
- which findings were declined and why
- which verification commands ran
- whether the PR was merged
- whether linked issues were confirmed closed
- whether linked issues were assigned to the current GitHub user
- whether linked project items were confirmed `Done`
- whether stale remote-tracking refs were pruned
- whether the feature branch, local `pr/<number>` alias, and any worktree were cleaned up
@@ -0,0 +1,4 @@
interface:
display_name: "Review and Merge PR"
short_description: "Check PR feedback, fix valid findings, and merge when ready"
default_prompt: "Review the current PR, address valid bot or human feedback, and merge it when ready."
+189
View File
@@ -0,0 +1,189 @@
---
name: test-apk
description: Test and debug Android APK features using a local Android emulator. Manages emulator lifecycle, builds/installs the APK, runs instrumentation tests, captures logcat diagnostics, and debugs WebView automation (imgur, postimages uploads). Use when the user asks to test APK, debug Android, test uploads, run emulator tests, or says "test-apk".
---
# Test APK on Android Emulator
## Overview
Delegates APK testing to a **shell subagent** (`model: fast`) to keep the main context clean.
The subagent manages the emulator, builds/installs the APK, executes tests, and returns structured diagnostics.
## Workflow
### Step 1: Collect Test Requirements
Ask the user (or infer from context) what to test. Common scenarios:
| Scenario | What to run |
|----------|-------------|
| WebView upload debugging (imgur/postimages) | Instrumentation tests + logcat |
| Live upload test | `yarn live:postimages:auto` or custom instrumentation |
| Full connected test suite | `yarn android:connectedTest` |
| Specific instrumentation class | Custom `./gradlew connectedDebugAndroidTest` with class filter |
| Manual APK interaction | Build, install, launch, capture logcat |
| Contract tests (fixtures) | `yarn contract:postimages` |
### Step 2: Delegate to Shell Subagent
Spawn a **shell** subagent with `model: fast`. Use the prompt template below, filling in `{TEST_DESCRIPTION}` with the user's requirements.
```
Use the Task tool:
subagent_type: "shell"
model: "fast"
prompt: <see Prompt Template below>
```
### Prompt Template
Copy and adapt this prompt when spawning the subagent. Replace `{TEST_DESCRIPTION}` and `{TEST_COMMANDS}`.
---
```text
You are testing the 5chan Android APK on a local emulator.
## Environment
- ANDROID_HOME: use the contributor's local Android SDK path from the environment
- Project root: the current repository root from `git rev-parse --show-toplevel`
- Capacitor app (appId: fivechan.android, webDir: build)
- System image installed: system-images;android-35;google_apis;arm64-v8a
- AVD name to use: fivechan-test-api35
- Device profile: pixel_6
## What to Test
{TEST_DESCRIPTION}
## Emulator Management
### Check if emulator is already running
adb devices | grep emulator
### If no emulator running, create AVD (if missing) and start it
avdmanager list avd | grep fivechan-test-api35 || \
echo "no" | avdmanager create avd \
--name fivechan-test-api35 \
--package "system-images;android-35;google_apis;arm64-v8a" \
--device pixel_6 --force
# Start emulator (background it, wait for boot)
emulator -avd fivechan-test-api35 -no-boot-anim -no-snapshot-save -netdelay none -netspeed full &
adb wait-for-device
# Poll for boot complete (up to 180s)
for i in $(seq 1 90); do
boot=$(adb shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')
[ "$boot" = "1" ] && break
sleep 2
done
# Disable animations for test reliability
adb shell settings put global window_animation_scale 0
adb shell settings put global transition_animation_scale 0
adb shell settings put global animator_duration_scale 0
### IMPORTANT: Do NOT kill the emulator when done. Leave it running for iterative debugging.
## Build & Install APK
### Only rebuild if user asked to, or if this is the first run:
cd "$(git rev-parse --show-toplevel)"
yarn build && npx cap sync android
cd android && ./gradlew assembleDebug
adb install -r app/build/outputs/apk/debug/app-debug.apk
## Run Tests
{TEST_COMMANDS}
## Diagnostics to Capture
### Always capture logcat filtered to upload automation:
adb logcat -d -s MediaUploadAutomation:* FileUploaderPlugin:* | tail -200
### If test fails, also capture:
- Full logcat last 500 lines: adb logcat -d -t 500
- Screenshot: adb exec-out screencap -p > /tmp/emulator-screenshot.png
- WebView console logs: adb logcat -d -s chromium:* | tail -100
## Return Format
Return a structured summary:
1. **Emulator status**: running / newly started / failed to boot
2. **APK build**: success / skipped / failed (with error)
3. **APK install**: success / skipped / failed
4. **Test results**: pass / fail with details
5. **Logcat highlights**: relevant MediaUploadAutomation log lines
6. **Diagnosis**: what went wrong and suggested fix (if test failed)
7. **Screenshots**: path to any captured screenshots
```
---
## Common Test Commands
### WebView Upload Debug (imgur + postimages)
```text
{TEST_COMMANDS} =
# Run fixture-based contract tests first
cd "$(git rev-parse --show-toplevel)/android"
ANDROID_SERIAL=$(adb devices | awk '/^emulator/ {print $1; exit}') \
./gradlew :app:connectedDebugAndroidTest \
-Pandroid.experimental.androidTest.useUnifiedTestPlatform=false \
-Pandroid.testInstrumentationRunnerArguments.class="fivechan.android.MediaUploadAutomationRunnerTest"
# If contract tests pass, run live upload test
ANDROID_SERIAL=$(adb devices | awk '/^emulator/ {print $1; exit}') \
./gradlew :app:connectedDebugAndroidTest \
-Pandroid.experimental.androidTest.useUnifiedTestPlatform=false \
-Pandroid.testInstrumentationRunnerArguments.class="fivechan.android.PostimagesLiveUploadTest"
# Capture logcat for upload automation
adb logcat -d -s MediaUploadAutomation:* | tail -200
adb logcat -d -s chromium:* | tail -100
```
### Full Connected Test Suite
```text
{TEST_COMMANDS} =
cd "$(git rev-parse --show-toplevel)/android"
ANDROID_SERIAL=$(adb devices | awk '/^emulator/ {print $1; exit}') \
./gradlew :app:connectedDebugAndroidTest
```
### Launch App and Capture Logs
```text
{TEST_COMMANDS} =
adb shell am start -n fivechan.android/.MainActivity
sleep 5
adb logcat -d -t 300 | tail -300
```
## Key Files for Debugging
| File | Purpose |
|------|---------|
| `android/app/src/main/java/fivechan/android/MediaUploadAutomationRunner.java` | WebView upload automation engine |
| `android/app/src/main/java/fivechan/android/MediaUploadRecipes.java` | Provider selectors and JS recipes |
| `android/app/src/main/java/fivechan/android/FileUploaderPlugin.java` | Capacitor plugin entry point |
| `android/app/src/androidTest/.../MediaUploadAutomationRunnerTest.java` | Fixture-based unit tests |
| `android/app/src/androidTest/.../PostimagesLiveUploadTest.java` | Live integration test |
| `android/app/src/main/assets/fixtures/` | HTML test fixtures |
| `scripts/run-postimages-live-emulator-test.sh` | Reference emulator test script |
## Upload Automation Stages (for interpreting logcat)
| Stage | Meaning |
|-------|---------|
| `page_loaded` | Provider URL finished loading in WebView |
| `selector_matched` | File input element found via CSS selector |
| `file_chooser_callback` | WebChromeClient.onShowFileChooser fired |
| `submit_clicked` | Upload/submit button clicked |
| `success_selector_matched` | Uploaded URL extracted from page |
| `blocked_detected` | CAPTCHA or rate limit detected |
| `input_not_found` | No file input found within timeout |
| `chooser_not_triggered` | Input found but chooser didn't fire |
| `upload_timed_out` | Upload didn't complete within 45s |
+97
View File
@@ -0,0 +1,97 @@
---
name: translate
description: Add or update i18next translation keys across all language files by spawning translator subagents. Use when the user asks to add a new translation, update existing translations, translate text, or work with i18n keys. Triggers on "translate", "add translation", "translation key", "i18n", "localization".
---
# Translate
This skill orchestrates translation of i18next keys by spawning **translator** subagents. Each key gets its own subagent so multiple keys can be translated in parallel.
## How It Works
1. The user provides one or more translation keys (and optionally English values).
2. This skill tells the parent agent to spawn one `translator` subagent per key.
3. Each subagent independently translates its key into all 35 languages and applies the result using `scripts/update-translations.js`.
## Workflow
### Step 1 — Parse the keys
Identify all translation keys from the user's request. Keys may be provided as:
- A comma-separated list: `upload_failed, media_hosting, file`
- A numbered/bulleted list
- Inline in a sentence: "translate the key `upload_failed`"
### Step 2 — Look up English values
For each key, check if the English value already exists in `public/translations/en/default.json`. If the user provided new English text, use that instead.
### Step 3 — Spawn translator subagents
For **each key**, spawn a `translator` subagent (using the Task tool with `subagent_type: "generalPurpose"` and `model: "fast"`). The prompt for each subagent must include:
- The key name
- The English value
- An instruction to follow the translator subagent's system prompt
Example prompt for a subagent:
```
You are the translator subagent. Translate the following i18next key into all 35 supported languages and apply it using the project's translation script.
Key: upload_failed
English value: "Upload failed"
Follow your system prompt for the full workflow (create dictionary file, dry run, apply, clean up).
```
**Parallelism rules:**
- Spawn up to 4 subagents concurrently (Task tool limit).
- If there are more than 4 keys, batch them: spawn 4, wait for completion, then spawn the next batch.
### Step 4 — Report results
After all subagents complete, summarize:
- Which keys were translated successfully
- Any failures or issues
## Other Operations (No Subagent Needed)
For non-translation operations, run the script directly without spawning subagents:
### Copy English value to all languages (fallback only)
Use only when the string is a technical term, brand name, or placeholder.
```bash
node scripts/update-translations.js --key some_key --from en --write
```
### Delete a key from all languages
```bash
node scripts/update-translations.js --key obsolete_key --delete --write
```
### Audit for unused keys
```bash
node scripts/update-translations.js --audit --dry
node scripts/update-translations.js --audit --write
```
## Important Flags
| Flag | Description |
|------|-------------|
| `--key <name>` | Translation key to update/delete |
| `--map <file>` | JSON file with per-language values |
| `--include-en` | Include English in updates (required when using `--map`) |
| `--from <lang>` | Source language to copy from (default: en) |
| `--dry` | Preview changes without writing |
| `--write` | Actually write the files |
| `--delete` | Delete the key from all languages |
| `--audit` | Find and remove unused translation keys |
## Supported Languages
ar, bn, cs, da, de, el, en, es, fa, fi, fil, fr, he, hi, hu, id, it, ja, ko, mr, nl, no, pl, pt, ro, ru, sq, sv, te, th, tr, uk, ur, vi, zh
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,136 @@
---
name: vercel-react-best-practices
description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
license: MIT
metadata:
author: vercel
version: "1.0.0"
---
# Vercel React Best Practices
Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 57 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
## When to Apply
Reference these guidelines when:
- Writing new React components or Next.js pages
- Implementing data fetching (client or server-side)
- Reviewing code for performance issues
- Refactoring existing React/Next.js code
- Optimizing bundle size or load times
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
| 3 | Server-Side Performance | HIGH | `server-` |
| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
| 5 | Re-render Optimization | MEDIUM | `rerender-` |
| 6 | Rendering Performance | MEDIUM | `rendering-` |
| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
| 8 | Advanced Patterns | LOW | `advanced-` |
## Quick Reference
### 1. Eliminating Waterfalls (CRITICAL)
- `async-defer-await` - Move await into branches where actually used
- `async-parallel` - Use Promise.all() for independent operations
- `async-dependencies` - Use better-all for partial dependencies
- `async-api-routes` - Start promises early, await late in API routes
- `async-suspense-boundaries` - Use Suspense to stream content
### 2. Bundle Size Optimization (CRITICAL)
- `bundle-barrel-imports` - Import directly, avoid barrel files
- `bundle-dynamic-imports` - Use next/dynamic for heavy components
- `bundle-defer-third-party` - Load analytics/logging after hydration
- `bundle-conditional` - Load modules only when feature is activated
- `bundle-preload` - Preload on hover/focus for perceived speed
### 3. Server-Side Performance (HIGH)
- `server-auth-actions` - Authenticate server actions like API routes
- `server-cache-react` - Use React.cache() for per-request deduplication
- `server-cache-lru` - Use LRU cache for cross-request caching
- `server-dedup-props` - Avoid duplicate serialization in RSC props
- `server-serialization` - Minimize data passed to client components
- `server-parallel-fetching` - Restructure components to parallelize fetches
- `server-after-nonblocking` - Use after() for non-blocking operations
### 4. Client-Side Data Fetching (MEDIUM-HIGH)
- `client-swr-dedup` - Use SWR for automatic request deduplication
- `client-event-listeners` - Deduplicate global event listeners
- `client-passive-event-listeners` - Use passive listeners for scroll
- `client-localstorage-schema` - Version and minimize localStorage data
### 5. Re-render Optimization (MEDIUM)
- `rerender-defer-reads` - Don't subscribe to state only used in callbacks
- `rerender-memo` - Extract expensive work into memoized components
- `rerender-memo-with-default-value` - Hoist default non-primitive props
- `rerender-dependencies` - Use primitive dependencies in effects
- `rerender-derived-state` - Subscribe to derived booleans, not raw values
- `rerender-derived-state-no-effect` - Derive state during render, not effects
- `rerender-functional-setstate` - Use functional setState for stable callbacks
- `rerender-lazy-state-init` - Pass function to useState for expensive values
- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives
- `rerender-move-effect-to-event` - Put interaction logic in event handlers
- `rerender-transitions` - Use startTransition for non-urgent updates
- `rerender-use-ref-transient-values` - Use refs for transient frequent values
### 6. Rendering Performance (MEDIUM)
- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
- `rendering-content-visibility` - Use content-visibility for long lists
- `rendering-hoist-jsx` - Extract static JSX outside components
- `rendering-svg-precision` - Reduce SVG coordinate precision
- `rendering-hydration-no-flicker` - Use inline script for client-only data
- `rendering-hydration-suppress-warning` - Suppress expected mismatches
- `rendering-activity` - Use Activity component for show/hide
- `rendering-conditional-render` - Use ternary, not && for conditionals
- `rendering-usetransition-loading` - Prefer useTransition for loading state
### 7. JavaScript Performance (LOW-MEDIUM)
- `js-batch-dom-css` - Group CSS changes via classes or cssText
- `js-index-maps` - Build Map for repeated lookups
- `js-cache-property-access` - Cache object properties in loops
- `js-cache-function-results` - Cache function results in module-level Map
- `js-cache-storage` - Cache localStorage/sessionStorage reads
- `js-combine-iterations` - Combine multiple filter/map into one loop
- `js-length-check-first` - Check array length before expensive comparison
- `js-early-exit` - Return early from functions
- `js-hoist-regexp` - Hoist RegExp creation outside loops
- `js-min-max-loop` - Use loop for min/max instead of sort
- `js-set-map-lookups` - Use Set/Map for O(1) lookups
- `js-tosorted-immutable` - Use toSorted() for immutability
### 8. Advanced Patterns (LOW)
- `advanced-event-handler-refs` - Store event handlers in refs
- `advanced-init-once` - Initialize app once per app load
- `advanced-use-latest` - useLatest for stable callback refs
## How to Use
Read individual rule files for detailed explanations and code examples:
```
rules/async-parallel.md
rules/bundle-barrel-imports.md
```
Each rule file contains:
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- Additional context and references
## Full Compiled Document
For the complete guide with all rules expanded: `AGENTS.md`
@@ -0,0 +1,55 @@
---
title: Store Event Handlers in Refs
impact: LOW
impactDescription: stable subscriptions
tags: advanced, hooks, refs, event-handlers, optimization
---
## Store Event Handlers in Refs
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
**Incorrect (re-subscribes on every render):**
```tsx
function useWindowEvent(event: string, handler: (e) => void) {
useEffect(() => {
window.addEventListener(event, handler)
return () => window.removeEventListener(event, handler)
}, [event, handler])
}
```
**Correct (stable subscription):**
```tsx
function useWindowEvent(event: string, handler: (e) => void) {
const handlerRef = useRef(handler)
useEffect(() => {
handlerRef.current = handler
}, [handler])
useEffect(() => {
const listener = (e) => handlerRef.current(e)
window.addEventListener(event, listener)
return () => window.removeEventListener(event, listener)
}, [event])
}
```
**Alternative: use `useEffectEvent` if you're on latest React:**
```tsx
import { useEffectEvent } from 'react'
function useWindowEvent(event: string, handler: (e) => void) {
const onEvent = useEffectEvent(handler)
useEffect(() => {
window.addEventListener(event, onEvent)
return () => window.removeEventListener(event, onEvent)
}, [event])
}
```
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
@@ -0,0 +1,42 @@
---
title: Initialize App Once, Not Per Mount
impact: LOW-MEDIUM
impactDescription: avoids duplicate init in development
tags: initialization, useEffect, app-startup, side-effects
---
## Initialize App Once, Not Per Mount
Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
**Incorrect (runs twice in dev, re-runs on remount):**
```tsx
function Comp() {
useEffect(() => {
loadFromStorage()
checkAuthToken()
}, [])
// ...
}
```
**Correct (once per app load):**
```tsx
let didInit = false
function Comp() {
useEffect(() => {
if (didInit) return
didInit = true
loadFromStorage()
checkAuthToken()
}, [])
// ...
}
```
Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
@@ -0,0 +1,39 @@
---
title: useEffectEvent for Stable Callback Refs
impact: LOW
impactDescription: prevents effect re-runs
tags: advanced, hooks, useEffectEvent, refs, optimization
---
## useEffectEvent for Stable Callback Refs
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
**Incorrect (effect re-runs on every callback change):**
```tsx
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState('')
useEffect(() => {
const timeout = setTimeout(() => onSearch(query), 300)
return () => clearTimeout(timeout)
}, [query, onSearch])
}
```
**Correct (using React's useEffectEvent):**
```tsx
import { useEffectEvent } from 'react';
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState('')
const onSearchEvent = useEffectEvent(onSearch)
useEffect(() => {
const timeout = setTimeout(() => onSearchEvent(query), 300)
return () => clearTimeout(timeout)
}, [query])
}
```
@@ -0,0 +1,38 @@
---
title: Prevent Waterfall Chains in API Routes
impact: CRITICAL
impactDescription: 2-10× improvement
tags: api-routes, server-actions, waterfalls, parallelization
---
## Prevent Waterfall Chains in API Routes
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
**Incorrect (config waits for auth, data waits for both):**
```typescript
export async function GET(request: Request) {
const session = await auth()
const config = await fetchConfig()
const data = await fetchData(session.user.id)
return Response.json({ data, config })
}
```
**Correct (auth and config start immediately):**
```typescript
export async function GET(request: Request) {
const sessionPromise = auth()
const configPromise = fetchConfig()
const session = await sessionPromise
const [config, data] = await Promise.all([
configPromise,
fetchData(session.user.id)
])
return Response.json({ data, config })
}
```
For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
@@ -0,0 +1,80 @@
---
title: Defer Await Until Needed
impact: HIGH
impactDescription: avoids blocking unused code paths
tags: async, await, conditional, optimization
---
## Defer Await Until Needed
Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
**Incorrect (blocks both branches):**
```typescript
async function handleRequest(userId: string, skipProcessing: boolean) {
const userData = await fetchUserData(userId)
if (skipProcessing) {
// Returns immediately but still waited for userData
return { skipped: true }
}
// Only this branch uses userData
return processUserData(userData)
}
```
**Correct (only blocks when needed):**
```typescript
async function handleRequest(userId: string, skipProcessing: boolean) {
if (skipProcessing) {
// Returns immediately without waiting
return { skipped: true }
}
// Fetch only when needed
const userData = await fetchUserData(userId)
return processUserData(userData)
}
```
**Another example (early return optimization):**
```typescript
// Incorrect: always fetches permissions
async function updateResource(resourceId: string, userId: string) {
const permissions = await fetchPermissions(userId)
const resource = await getResource(resourceId)
if (!resource) {
return { error: 'Not found' }
}
if (!permissions.canEdit) {
return { error: 'Forbidden' }
}
return await updateResourceData(resource, permissions)
}
// Correct: fetches only when needed
async function updateResource(resourceId: string, userId: string) {
const resource = await getResource(resourceId)
if (!resource) {
return { error: 'Not found' }
}
const permissions = await fetchPermissions(userId)
if (!permissions.canEdit) {
return { error: 'Forbidden' }
}
return await updateResourceData(resource, permissions)
}
```
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
@@ -0,0 +1,51 @@
---
title: Dependency-Based Parallelization
impact: CRITICAL
impactDescription: 2-10× improvement
tags: async, parallelization, dependencies, better-all
---
## Dependency-Based Parallelization
For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
**Incorrect (profile waits for config unnecessarily):**
```typescript
const [user, config] = await Promise.all([
fetchUser(),
fetchConfig()
])
const profile = await fetchProfile(user.id)
```
**Correct (config and profile run in parallel):**
```typescript
import { all } from 'better-all'
const { user, config, profile } = await all({
async user() { return fetchUser() },
async config() { return fetchConfig() },
async profile() {
return fetchProfile((await this.$.user).id)
}
})
```
**Alternative without extra dependencies:**
We can also create all the promises first, and do `Promise.all()` at the end.
```typescript
const userPromise = fetchUser()
const profilePromise = userPromise.then(user => fetchProfile(user.id))
const [user, config, profile] = await Promise.all([
userPromise,
fetchConfig(),
profilePromise
])
```
Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
@@ -0,0 +1,28 @@
---
title: Promise.all() for Independent Operations
impact: CRITICAL
impactDescription: 2-10× improvement
tags: async, parallelization, promises, waterfalls
---
## Promise.all() for Independent Operations
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
**Incorrect (sequential execution, 3 round trips):**
```typescript
const user = await fetchUser()
const posts = await fetchPosts()
const comments = await fetchComments()
```
**Correct (parallel execution, 1 round trip):**
```typescript
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments()
])
```
@@ -0,0 +1,99 @@
---
title: Strategic Suspense Boundaries
impact: HIGH
impactDescription: faster initial paint
tags: async, suspense, streaming, layout-shift
---
## Strategic Suspense Boundaries
Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
**Incorrect (wrapper blocked by data fetching):**
```tsx
async function Page() {
const data = await fetchData() // Blocks entire page
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<div>
<DataDisplay data={data} />
</div>
<div>Footer</div>
</div>
)
}
```
The entire layout waits for data even though only the middle section needs it.
**Correct (wrapper shows immediately, data streams in):**
```tsx
function Page() {
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<div>
<Suspense fallback={<Skeleton />}>
<DataDisplay />
</Suspense>
</div>
<div>Footer</div>
</div>
)
}
async function DataDisplay() {
const data = await fetchData() // Only blocks this component
return <div>{data.content}</div>
}
```
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
**Alternative (share promise across components):**
```tsx
function Page() {
// Start fetch immediately, but don't await
const dataPromise = fetchData()
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<Suspense fallback={<Skeleton />}>
<DataDisplay dataPromise={dataPromise} />
<DataSummary dataPromise={dataPromise} />
</Suspense>
<div>Footer</div>
</div>
)
}
function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
const data = use(dataPromise) // Unwraps the promise
return <div>{data.content}</div>
}
function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
const data = use(dataPromise) // Reuses the same promise
return <div>{data.summary}</div>
}
```
Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
**When NOT to use this pattern:**
- Critical data needed for layout decisions (affects positioning)
- SEO-critical content above the fold
- Small, fast queries where suspense overhead isn't worth it
- When you want to avoid layout shift (loading → content jump)
**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
@@ -0,0 +1,59 @@
---
title: Avoid Barrel File Imports
impact: CRITICAL
impactDescription: 200-800ms import cost, slow builds
tags: bundle, imports, tree-shaking, barrel-files, performance
---
## Avoid Barrel File Imports
Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
**Incorrect (imports entire library):**
```tsx
import { Check, X, Menu } from 'lucide-react'
// Loads 1,583 modules, takes ~2.8s extra in dev
// Runtime cost: 200-800ms on every cold start
import { Button, TextField } from '@mui/material'
// Loads 2,225 modules, takes ~4.2s extra in dev
```
**Correct (imports only what you need):**
```tsx
import Check from 'lucide-react/dist/esm/icons/check'
import X from 'lucide-react/dist/esm/icons/x'
import Menu from 'lucide-react/dist/esm/icons/menu'
// Loads only 3 modules (~2KB vs ~1MB)
import Button from '@mui/material/Button'
import TextField from '@mui/material/TextField'
// Loads only what you use
```
**Alternative (Next.js 13.5+):**
```js
// next.config.js - use optimizePackageImports
module.exports = {
experimental: {
optimizePackageImports: ['lucide-react', '@mui/material']
}
}
// Then you can keep the ergonomic barrel imports:
import { Check, X, Menu } from 'lucide-react'
// Automatically transformed to direct imports at build time
```
Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
@@ -0,0 +1,31 @@
---
title: Conditional Module Loading
impact: HIGH
impactDescription: loads large data only when needed
tags: bundle, conditional-loading, lazy-loading
---
## Conditional Module Loading
Load large data or modules only when a feature is activated.
**Example (lazy-load animation frames):**
```tsx
function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
const [frames, setFrames] = useState<Frame[] | null>(null)
useEffect(() => {
if (enabled && !frames && typeof window !== 'undefined') {
import('./animation-frames.js')
.then(mod => setFrames(mod.frames))
.catch(() => setEnabled(false))
}
}, [enabled, frames, setEnabled])
if (!frames) return <Skeleton />
return <Canvas frames={frames} />
}
```
The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
@@ -0,0 +1,49 @@
---
title: Defer Non-Critical Third-Party Libraries
impact: MEDIUM
impactDescription: loads after hydration
tags: bundle, third-party, analytics, defer
---
## Defer Non-Critical Third-Party Libraries
Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
**Incorrect (blocks initial bundle):**
```tsx
import { Analytics } from '@vercel/analytics/react'
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
)
}
```
**Correct (loads after hydration):**
```tsx
import dynamic from 'next/dynamic'
const Analytics = dynamic(
() => import('@vercel/analytics/react').then(m => m.Analytics),
{ ssr: false }
)
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
)
}
```
@@ -0,0 +1,35 @@
---
title: Dynamic Imports for Heavy Components
impact: CRITICAL
impactDescription: directly affects TTI and LCP
tags: bundle, dynamic-import, code-splitting, next-dynamic
---
## Dynamic Imports for Heavy Components
Use `next/dynamic` to lazy-load large components not needed on initial render.
**Incorrect (Monaco bundles with main chunk ~300KB):**
```tsx
import { MonacoEditor } from './monaco-editor'
function CodePanel({ code }: { code: string }) {
return <MonacoEditor value={code} />
}
```
**Correct (Monaco loads on demand):**
```tsx
import dynamic from 'next/dynamic'
const MonacoEditor = dynamic(
() => import('./monaco-editor').then(m => m.MonacoEditor),
{ ssr: false }
)
function CodePanel({ code }: { code: string }) {
return <MonacoEditor value={code} />
}
```
@@ -0,0 +1,50 @@
---
title: Preload Based on User Intent
impact: MEDIUM
impactDescription: reduces perceived latency
tags: bundle, preload, user-intent, hover
---
## Preload Based on User Intent
Preload heavy bundles before they're needed to reduce perceived latency.
**Example (preload on hover/focus):**
```tsx
function EditorButton({ onClick }: { onClick: () => void }) {
const preload = () => {
if (typeof window !== 'undefined') {
void import('./monaco-editor')
}
}
return (
<button
onMouseEnter={preload}
onFocus={preload}
onClick={onClick}
>
Open Editor
</button>
)
}
```
**Example (preload when feature flag is enabled):**
```tsx
function FlagsProvider({ children, flags }: Props) {
useEffect(() => {
if (flags.editorEnabled && typeof window !== 'undefined') {
void import('./monaco-editor').then(mod => mod.init())
}
}, [flags.editorEnabled])
return <FlagsContext.Provider value={flags}>
{children}
</FlagsContext.Provider>
}
```
The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
@@ -0,0 +1,74 @@
---
title: Deduplicate Global Event Listeners
impact: LOW
impactDescription: single listener for N components
tags: client, swr, event-listeners, subscription
---
## Deduplicate Global Event Listeners
Use `useSWRSubscription()` to share global event listeners across component instances.
**Incorrect (N instances = N listeners):**
```tsx
function useKeyboardShortcut(key: string, callback: () => void) {
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.metaKey && e.key === key) {
callback()
}
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
}, [key, callback])
}
```
When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
**Correct (N instances = 1 listener):**
```tsx
import useSWRSubscription from 'swr/subscription'
// Module-level Map to track callbacks per key
const keyCallbacks = new Map<string, Set<() => void>>()
function useKeyboardShortcut(key: string, callback: () => void) {
// Register this callback in the Map
useEffect(() => {
if (!keyCallbacks.has(key)) {
keyCallbacks.set(key, new Set())
}
keyCallbacks.get(key)!.add(callback)
return () => {
const set = keyCallbacks.get(key)
if (set) {
set.delete(callback)
if (set.size === 0) {
keyCallbacks.delete(key)
}
}
}
}, [key, callback])
useSWRSubscription('global-keydown', () => {
const handler = (e: KeyboardEvent) => {
if (e.metaKey && keyCallbacks.has(e.key)) {
keyCallbacks.get(e.key)!.forEach(cb => cb())
}
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
})
}
function Profile() {
// Multiple shortcuts will share the same listener
useKeyboardShortcut('p', () => { /* ... */ })
useKeyboardShortcut('k', () => { /* ... */ })
// ...
}
```
@@ -0,0 +1,71 @@
---
title: Version and Minimize localStorage Data
impact: MEDIUM
impactDescription: prevents schema conflicts, reduces storage size
tags: client, localStorage, storage, versioning, data-minimization
---
## Version and Minimize localStorage Data
Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
**Incorrect:**
```typescript
// No version, stores everything, no error handling
localStorage.setItem('userConfig', JSON.stringify(fullUserObject))
const data = localStorage.getItem('userConfig')
```
**Correct:**
```typescript
const VERSION = 'v2'
function saveConfig(config: { theme: string; language: string }) {
try {
localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))
} catch {
// Throws in incognito/private browsing, quota exceeded, or disabled
}
}
function loadConfig() {
try {
const data = localStorage.getItem(`userConfig:${VERSION}`)
return data ? JSON.parse(data) : null
} catch {
return null
}
}
// Migration from v1 to v2
function migrate() {
try {
const v1 = localStorage.getItem('userConfig:v1')
if (v1) {
const old = JSON.parse(v1)
saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })
localStorage.removeItem('userConfig:v1')
}
} catch {}
}
```
**Store minimal fields from server responses:**
```typescript
// User object has 20+ fields, only store what UI needs
function cachePrefs(user: FullUser) {
try {
localStorage.setItem('prefs:v1', JSON.stringify({
theme: user.preferences.theme,
notifications: user.preferences.notifications
}))
} catch {}
}
```
**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
@@ -0,0 +1,48 @@
---
title: Use Passive Event Listeners for Scrolling Performance
impact: MEDIUM
impactDescription: eliminates scroll delay caused by event listeners
tags: client, event-listeners, scrolling, performance, touch, wheel
---
## Use Passive Event Listeners for Scrolling Performance
Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.
**Incorrect:**
```typescript
useEffect(() => {
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
document.addEventListener('touchstart', handleTouch)
document.addEventListener('wheel', handleWheel)
return () => {
document.removeEventListener('touchstart', handleTouch)
document.removeEventListener('wheel', handleWheel)
}
}, [])
```
**Correct:**
```typescript
useEffect(() => {
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
document.addEventListener('touchstart', handleTouch, { passive: true })
document.addEventListener('wheel', handleWheel, { passive: true })
return () => {
document.removeEventListener('touchstart', handleTouch)
document.removeEventListener('wheel', handleWheel)
}
}, [])
```
**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
@@ -0,0 +1,56 @@
---
title: Use SWR for Automatic Deduplication
impact: MEDIUM-HIGH
impactDescription: automatic deduplication
tags: client, swr, deduplication, data-fetching
---
## Use SWR for Automatic Deduplication
SWR enables request deduplication, caching, and revalidation across component instances.
**Incorrect (no deduplication, each instance fetches):**
```tsx
function UserList() {
const [users, setUsers] = useState([])
useEffect(() => {
fetch('/api/users')
.then(r => r.json())
.then(setUsers)
}, [])
}
```
**Correct (multiple instances share one request):**
```tsx
import useSWR from 'swr'
function UserList() {
const { data: users } = useSWR('/api/users', fetcher)
}
```
**For immutable data:**
```tsx
import { useImmutableSWR } from '@/lib/swr'
function StaticContent() {
const { data } = useImmutableSWR('/api/config', fetcher)
}
```
**For mutations:**
```tsx
import { useSWRMutation } from 'swr/mutation'
function UpdateButton() {
const { trigger } = useSWRMutation('/api/user', updateUser)
return <button onClick={() => trigger()}>Update</button>
}
```
Reference: [https://swr.vercel.app](https://swr.vercel.app)
@@ -0,0 +1,107 @@
---
title: Avoid Layout Thrashing
impact: MEDIUM
impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks
tags: javascript, dom, css, performance, reflow, layout-thrashing
---
## Avoid Layout Thrashing
Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
**This is OK (browser batches style changes):**
```typescript
function updateElementStyles(element: HTMLElement) {
// Each line invalidates style, but browser batches the recalculation
element.style.width = '100px'
element.style.height = '200px'
element.style.backgroundColor = 'blue'
element.style.border = '1px solid black'
}
```
**Incorrect (interleaved reads and writes force reflows):**
```typescript
function layoutThrashing(element: HTMLElement) {
element.style.width = '100px'
const width = element.offsetWidth // Forces reflow
element.style.height = '200px'
const height = element.offsetHeight // Forces another reflow
}
```
**Correct (batch writes, then read once):**
```typescript
function updateElementStyles(element: HTMLElement) {
// Batch all writes together
element.style.width = '100px'
element.style.height = '200px'
element.style.backgroundColor = 'blue'
element.style.border = '1px solid black'
// Read after all writes are done (single reflow)
const { width, height } = element.getBoundingClientRect()
}
```
**Correct (batch reads, then writes):**
```typescript
function avoidThrashing(element: HTMLElement) {
// Read phase - all layout queries first
const rect1 = element.getBoundingClientRect()
const offsetWidth = element.offsetWidth
const offsetHeight = element.offsetHeight
// Write phase - all style changes after
element.style.width = '100px'
element.style.height = '200px'
}
```
**Better: use CSS classes**
```css
.highlighted-box {
width: 100px;
height: 200px;
background-color: blue;
border: 1px solid black;
}
```
```typescript
function updateElementStyles(element: HTMLElement) {
element.classList.add('highlighted-box')
const { width, height } = element.getBoundingClientRect()
}
```
**React example:**
```tsx
// Incorrect: interleaving style changes with layout queries
function Box({ isHighlighted }: { isHighlighted: boolean }) {
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
if (ref.current && isHighlighted) {
ref.current.style.width = '100px'
const width = ref.current.offsetWidth // Forces layout
ref.current.style.height = '200px'
}
}, [isHighlighted])
return <div ref={ref}>Content</div>
}
// Correct: toggle class
function Box({ isHighlighted }: { isHighlighted: boolean }) {
return (
<div className={isHighlighted ? 'highlighted-box' : ''}>
Content
</div>
)
}
```
Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
@@ -0,0 +1,80 @@
---
title: Cache Repeated Function Calls
impact: MEDIUM
impactDescription: avoid redundant computation
tags: javascript, cache, memoization, performance
---
## Cache Repeated Function Calls
Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
**Incorrect (redundant computation):**
```typescript
function ProjectList({ projects }: { projects: Project[] }) {
return (
<div>
{projects.map(project => {
// slugify() called 100+ times for same project names
const slug = slugify(project.name)
return <ProjectCard key={project.id} slug={slug} />
})}
</div>
)
}
```
**Correct (cached results):**
```typescript
// Module-level cache
const slugifyCache = new Map<string, string>()
function cachedSlugify(text: string): string {
if (slugifyCache.has(text)) {
return slugifyCache.get(text)!
}
const result = slugify(text)
slugifyCache.set(text, result)
return result
}
function ProjectList({ projects }: { projects: Project[] }) {
return (
<div>
{projects.map(project => {
// Computed only once per unique project name
const slug = cachedSlugify(project.name)
return <ProjectCard key={project.id} slug={slug} />
})}
</div>
)
}
```
**Simpler pattern for single-value functions:**
```typescript
let isLoggedInCache: boolean | null = null
function isLoggedIn(): boolean {
if (isLoggedInCache !== null) {
return isLoggedInCache
}
isLoggedInCache = document.cookie.includes('auth=')
return isLoggedInCache
}
// Clear cache when auth changes
function onAuthChange() {
isLoggedInCache = null
}
```
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
@@ -0,0 +1,28 @@
---
title: Cache Property Access in Loops
impact: LOW-MEDIUM
impactDescription: reduces lookups
tags: javascript, loops, optimization, caching
---
## Cache Property Access in Loops
Cache object property lookups in hot paths.
**Incorrect (3 lookups × N iterations):**
```typescript
for (let i = 0; i < arr.length; i++) {
process(obj.config.settings.value)
}
```
**Correct (1 lookup total):**
```typescript
const value = obj.config.settings.value
const len = arr.length
for (let i = 0; i < len; i++) {
process(value)
}
```
@@ -0,0 +1,70 @@
---
title: Cache Storage API Calls
impact: LOW-MEDIUM
impactDescription: reduces expensive I/O
tags: javascript, localStorage, storage, caching, performance
---
## Cache Storage API Calls
`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
**Incorrect (reads storage on every call):**
```typescript
function getTheme() {
return localStorage.getItem('theme') ?? 'light'
}
// Called 10 times = 10 storage reads
```
**Correct (Map cache):**
```typescript
const storageCache = new Map<string, string | null>()
function getLocalStorage(key: string) {
if (!storageCache.has(key)) {
storageCache.set(key, localStorage.getItem(key))
}
return storageCache.get(key)
}
function setLocalStorage(key: string, value: string) {
localStorage.setItem(key, value)
storageCache.set(key, value) // keep cache in sync
}
```
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
**Cookie caching:**
```typescript
let cookieCache: Record<string, string> | null = null
function getCookie(name: string) {
if (!cookieCache) {
cookieCache = Object.fromEntries(
document.cookie.split('; ').map(c => c.split('='))
)
}
return cookieCache[name]
}
```
**Important (invalidate on external changes):**
If storage can change externally (another tab, server-set cookies), invalidate cache:
```typescript
window.addEventListener('storage', (e) => {
if (e.key) storageCache.delete(e.key)
})
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
storageCache.clear()
}
})
```
@@ -0,0 +1,32 @@
---
title: Combine Multiple Array Iterations
impact: LOW-MEDIUM
impactDescription: reduces iterations
tags: javascript, arrays, loops, performance
---
## Combine Multiple Array Iterations
Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
**Incorrect (3 iterations):**
```typescript
const admins = users.filter(u => u.isAdmin)
const testers = users.filter(u => u.isTester)
const inactive = users.filter(u => !u.isActive)
```
**Correct (1 iteration):**
```typescript
const admins: User[] = []
const testers: User[] = []
const inactive: User[] = []
for (const user of users) {
if (user.isAdmin) admins.push(user)
if (user.isTester) testers.push(user)
if (!user.isActive) inactive.push(user)
}
```
@@ -0,0 +1,50 @@
---
title: Early Return from Functions
impact: LOW-MEDIUM
impactDescription: avoids unnecessary computation
tags: javascript, functions, optimization, early-return
---
## Early Return from Functions
Return early when result is determined to skip unnecessary processing.
**Incorrect (processes all items even after finding answer):**
```typescript
function validateUsers(users: User[]) {
let hasError = false
let errorMessage = ''
for (const user of users) {
if (!user.email) {
hasError = true
errorMessage = 'Email required'
}
if (!user.name) {
hasError = true
errorMessage = 'Name required'
}
// Continues checking all users even after error found
}
return hasError ? { valid: false, error: errorMessage } : { valid: true }
}
```
**Correct (returns immediately on first error):**
```typescript
function validateUsers(users: User[]) {
for (const user of users) {
if (!user.email) {
return { valid: false, error: 'Email required' }
}
if (!user.name) {
return { valid: false, error: 'Name required' }
}
}
return { valid: true }
}
```
@@ -0,0 +1,45 @@
---
title: Hoist RegExp Creation
impact: LOW-MEDIUM
impactDescription: avoids recreation
tags: javascript, regexp, optimization, memoization
---
## Hoist RegExp Creation
Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
**Incorrect (new RegExp every render):**
```tsx
function Highlighter({ text, query }: Props) {
const regex = new RegExp(`(${query})`, 'gi')
const parts = text.split(regex)
return <>{parts.map((part, i) => ...)}</>
}
```
**Correct (memoize or hoist):**
```tsx
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
function Highlighter({ text, query }: Props) {
const regex = useMemo(
() => new RegExp(`(${escapeRegex(query)})`, 'gi'),
[query]
)
const parts = text.split(regex)
return <>{parts.map((part, i) => ...)}</>
}
```
**Warning (global regex has mutable state):**
Global regex (`/g`) has mutable `lastIndex` state:
```typescript
const regex = /foo/g
regex.test('foo') // true, lastIndex = 3
regex.test('foo') // false, lastIndex = 0
```
@@ -0,0 +1,37 @@
---
title: Build Index Maps for Repeated Lookups
impact: LOW-MEDIUM
impactDescription: 1M ops to 2K ops
tags: javascript, map, indexing, optimization, performance
---
## Build Index Maps for Repeated Lookups
Multiple `.find()` calls by the same key should use a Map.
**Incorrect (O(n) per lookup):**
```typescript
function processOrders(orders: Order[], users: User[]) {
return orders.map(order => ({
...order,
user: users.find(u => u.id === order.userId)
}))
}
```
**Correct (O(1) per lookup):**
```typescript
function processOrders(orders: Order[], users: User[]) {
const userById = new Map(users.map(u => [u.id, u]))
return orders.map(order => ({
...order,
user: userById.get(order.userId)
}))
}
```
Build map once (O(n)), then all lookups are O(1).
For 1000 orders × 1000 users: 1M ops → 2K ops.
@@ -0,0 +1,49 @@
---
title: Early Length Check for Array Comparisons
impact: MEDIUM-HIGH
impactDescription: avoids expensive operations when lengths differ
tags: javascript, arrays, performance, optimization, comparison
---
## Early Length Check for Array Comparisons
When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
**Incorrect (always runs expensive comparison):**
```typescript
function hasChanges(current: string[], original: string[]) {
// Always sorts and joins, even when lengths differ
return current.sort().join() !== original.sort().join()
}
```
Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
**Correct (O(1) length check first):**
```typescript
function hasChanges(current: string[], original: string[]) {
// Early return if lengths differ
if (current.length !== original.length) {
return true
}
// Only sort when lengths match
const currentSorted = current.toSorted()
const originalSorted = original.toSorted()
for (let i = 0; i < currentSorted.length; i++) {
if (currentSorted[i] !== originalSorted[i]) {
return true
}
}
return false
}
```
This new approach is more efficient because:
- It avoids the overhead of sorting and joining the arrays when lengths differ
- It avoids consuming memory for the joined strings (especially important for large arrays)
- It avoids mutating the original arrays
- It returns early when a difference is found
@@ -0,0 +1,82 @@
---
title: Use Loop for Min/Max Instead of Sort
impact: LOW
impactDescription: O(n) instead of O(n log n)
tags: javascript, arrays, performance, sorting, algorithms
---
## Use Loop for Min/Max Instead of Sort
Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
**Incorrect (O(n log n) - sort to find latest):**
```typescript
interface Project {
id: string
name: string
updatedAt: number
}
function getLatestProject(projects: Project[]) {
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
return sorted[0]
}
```
Sorts the entire array just to find the maximum value.
**Incorrect (O(n log n) - sort for oldest and newest):**
```typescript
function getOldestAndNewest(projects: Project[]) {
const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
}
```
Still sorts unnecessarily when only min/max are needed.
**Correct (O(n) - single loop):**
```typescript
function getLatestProject(projects: Project[]) {
if (projects.length === 0) return null
let latest = projects[0]
for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt > latest.updatedAt) {
latest = projects[i]
}
}
return latest
}
function getOldestAndNewest(projects: Project[]) {
if (projects.length === 0) return { oldest: null, newest: null }
let oldest = projects[0]
let newest = projects[0]
for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
}
return { oldest, newest }
}
```
Single pass through the array, no copying, no sorting.
**Alternative (Math.min/Math.max for small arrays):**
```typescript
const numbers = [5, 2, 8, 1, 9]
const min = Math.min(...numbers)
const max = Math.max(...numbers)
```
This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
@@ -0,0 +1,24 @@
---
title: Use Set/Map for O(1) Lookups
impact: LOW-MEDIUM
impactDescription: O(n) to O(1)
tags: javascript, set, map, data-structures, performance
---
## Use Set/Map for O(1) Lookups
Convert arrays to Set/Map for repeated membership checks.
**Incorrect (O(n) per check):**
```typescript
const allowedIds = ['a', 'b', 'c', ...]
items.filter(item => allowedIds.includes(item.id))
```
**Correct (O(1) per check):**
```typescript
const allowedIds = new Set(['a', 'b', 'c', ...])
items.filter(item => allowedIds.has(item.id))
```
@@ -0,0 +1,57 @@
---
title: Use toSorted() Instead of sort() for Immutability
impact: MEDIUM-HIGH
impactDescription: prevents mutation bugs in React state
tags: javascript, arrays, immutability, react, state, mutation
---
## Use toSorted() Instead of sort() for Immutability
`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
**Incorrect (mutates original array):**
```typescript
function UserList({ users }: { users: User[] }) {
// Mutates the users prop array!
const sorted = useMemo(
() => users.sort((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}
```
**Correct (creates new array):**
```typescript
function UserList({ users }: { users: User[] }) {
// Creates new sorted array, original unchanged
const sorted = useMemo(
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}
```
**Why this matters in React:**
1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
**Browser support (fallback for older browsers):**
`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
```typescript
// Fallback for older browsers
const sorted = [...items].sort((a, b) => a.value - b.value)
```
**Other immutable array methods:**
- `.toSorted()` - immutable sort
- `.toReversed()` - immutable reverse
- `.toSpliced()` - immutable splice
- `.with()` - immutable element replacement
@@ -0,0 +1,26 @@
---
title: Use Activity Component for Show/Hide
impact: MEDIUM
impactDescription: preserves state/DOM
tags: rendering, activity, visibility, state-preservation
---
## Use Activity Component for Show/Hide
Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
**Usage:**
```tsx
import { Activity } from 'react'
function Dropdown({ isOpen }: Props) {
return (
<Activity mode={isOpen ? 'visible' : 'hidden'}>
<ExpensiveMenu />
</Activity>
)
}
```
Avoids expensive re-renders and state loss.
@@ -0,0 +1,47 @@
---
title: Animate SVG Wrapper Instead of SVG Element
impact: LOW
impactDescription: enables hardware acceleration
tags: rendering, svg, css, animation, performance
---
## Animate SVG Wrapper Instead of SVG Element
Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
**Incorrect (animating SVG directly - no hardware acceleration):**
```tsx
function LoadingSpinner() {
return (
<svg
className="animate-spin"
width="24"
height="24"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="10" stroke="currentColor" />
</svg>
)
}
```
**Correct (animating wrapper div - hardware accelerated):**
```tsx
function LoadingSpinner() {
return (
<div className="animate-spin">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="10" stroke="currentColor" />
</svg>
</div>
)
}
```
This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
@@ -0,0 +1,40 @@
---
title: Use Explicit Conditional Rendering
impact: LOW
impactDescription: prevents rendering 0 or NaN
tags: rendering, conditional, jsx, falsy-values
---
## Use Explicit Conditional Rendering
Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
**Incorrect (renders "0" when count is 0):**
```tsx
function Badge({ count }: { count: number }) {
return (
<div>
{count && <span className="badge">{count}</span>}
</div>
)
}
// When count = 0, renders: <div>0</div>
// When count = 5, renders: <div><span class="badge">5</span></div>
```
**Correct (renders nothing when count is 0):**
```tsx
function Badge({ count }: { count: number }) {
return (
<div>
{count > 0 ? <span className="badge">{count}</span> : null}
</div>
)
}
// When count = 0, renders: <div></div>
// When count = 5, renders: <div><span class="badge">5</span></div>
```
@@ -0,0 +1,38 @@
---
title: CSS content-visibility for Long Lists
impact: HIGH
impactDescription: faster initial render
tags: rendering, css, content-visibility, long-lists
---
## CSS content-visibility for Long Lists
Apply `content-visibility: auto` to defer off-screen rendering.
**CSS:**
```css
.message-item {
content-visibility: auto;
contain-intrinsic-size: 0 80px;
}
```
**Example:**
```tsx
function MessageList({ messages }: { messages: Message[] }) {
return (
<div className="overflow-y-auto h-screen">
{messages.map(msg => (
<div key={msg.id} className="message-item">
<Avatar user={msg.author} />
<div>{msg.content}</div>
</div>
))}
</div>
)
}
```
For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
@@ -0,0 +1,46 @@
---
title: Hoist Static JSX Elements
impact: LOW
impactDescription: avoids re-creation
tags: rendering, jsx, static, optimization
---
## Hoist Static JSX Elements
Extract static JSX outside components to avoid re-creation.
**Incorrect (recreates element every render):**
```tsx
function LoadingSkeleton() {
return <div className="animate-pulse h-20 bg-gray-200" />
}
function Container() {
return (
<div>
{loading && <LoadingSkeleton />}
</div>
)
}
```
**Correct (reuses same element):**
```tsx
const loadingSkeleton = (
<div className="animate-pulse h-20 bg-gray-200" />
)
function Container() {
return (
<div>
{loading && loadingSkeleton}
</div>
)
}
```
This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
@@ -0,0 +1,82 @@
---
title: Prevent Hydration Mismatch Without Flickering
impact: MEDIUM
impactDescription: avoids visual flicker and hydration errors
tags: rendering, ssr, hydration, localStorage, flicker
---
## Prevent Hydration Mismatch Without Flickering
When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
**Incorrect (breaks SSR):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
// localStorage is not available on server - throws error
const theme = localStorage.getItem('theme') || 'light'
return (
<div className={theme}>
{children}
</div>
)
}
```
Server-side rendering will fail because `localStorage` is undefined.
**Incorrect (visual flickering):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState('light')
useEffect(() => {
// Runs after hydration - causes visible flash
const stored = localStorage.getItem('theme')
if (stored) {
setTheme(stored)
}
}, [])
return (
<div className={theme}>
{children}
</div>
)
}
```
Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
**Correct (no flicker, no hydration mismatch):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
return (
<>
<div id="theme-wrapper">
{children}
</div>
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
try {
var theme = localStorage.getItem('theme') || 'light';
var el = document.getElementById('theme-wrapper');
if (el) el.className = theme;
} catch (e) {}
})();
`,
}}
/>
</>
)
}
```
The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
@@ -0,0 +1,30 @@
---
title: Suppress Expected Hydration Mismatches
impact: LOW-MEDIUM
impactDescription: avoids noisy hydration warnings for known differences
tags: rendering, hydration, ssr, nextjs
---
## Suppress Expected Hydration Mismatches
In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Dont overuse it.
**Incorrect (known mismatch warnings):**
```tsx
function Timestamp() {
return <span>{new Date().toLocaleString()}</span>
}
```
**Correct (suppress expected mismatch only):**
```tsx
function Timestamp() {
return (
<span suppressHydrationWarning>
{new Date().toLocaleString()}
</span>
)
}
```
@@ -0,0 +1,28 @@
---
title: Optimize SVG Precision
impact: LOW
impactDescription: reduces file size
tags: rendering, svg, optimization, svgo
---
## Optimize SVG Precision
Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
**Incorrect (excessive precision):**
```svg
<path d="M 10.293847 20.847362 L 30.938472 40.192837" />
```
**Correct (1 decimal place):**
```svg
<path d="M 10.3 20.8 L 30.9 40.2" />
```
**Automate with SVGO:**
```bash
npx svgo --precision=1 --multipass icon.svg
```
@@ -0,0 +1,75 @@
---
title: Use useTransition Over Manual Loading States
impact: LOW
impactDescription: reduces re-renders and improves code clarity
tags: rendering, transitions, useTransition, loading, state
---
## Use useTransition Over Manual Loading States
Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.
**Incorrect (manual loading state):**
```tsx
function SearchResults() {
const [query, setQuery] = useState('')
const [results, setResults] = useState([])
const [isLoading, setIsLoading] = useState(false)
const handleSearch = async (value: string) => {
setIsLoading(true)
setQuery(value)
const data = await fetchResults(value)
setResults(data)
setIsLoading(false)
}
return (
<>
<input onChange={(e) => handleSearch(e.target.value)} />
{isLoading && <Spinner />}
<ResultsList results={results} />
</>
)
}
```
**Correct (useTransition with built-in pending state):**
```tsx
import { useTransition, useState } from 'react'
function SearchResults() {
const [query, setQuery] = useState('')
const [results, setResults] = useState([])
const [isPending, startTransition] = useTransition()
const handleSearch = (value: string) => {
setQuery(value) // Update input immediately
startTransition(async () => {
// Fetch and update results
const data = await fetchResults(value)
setResults(data)
})
}
return (
<>
<input onChange={(e) => handleSearch(e.target.value)} />
{isPending && <Spinner />}
<ResultsList results={results} />
</>
)
}
```
**Benefits:**
- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`
- **Error resilience**: Pending state correctly resets even if the transition throws
- **Better responsiveness**: Keeps the UI responsive during updates
- **Interrupt handling**: New transitions automatically cancel pending ones
Reference: [useTransition](https://react.dev/reference/react/useTransition)
@@ -0,0 +1,39 @@
---
title: Defer State Reads to Usage Point
impact: MEDIUM
impactDescription: avoids unnecessary subscriptions
tags: rerender, searchParams, localStorage, optimization
---
## Defer State Reads to Usage Point
Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
**Incorrect (subscribes to all searchParams changes):**
```tsx
function ShareButton({ chatId }: { chatId: string }) {
const searchParams = useSearchParams()
const handleShare = () => {
const ref = searchParams.get('ref')
shareChat(chatId, { ref })
}
return <button onClick={handleShare}>Share</button>
}
```
**Correct (reads on demand, no subscription):**
```tsx
function ShareButton({ chatId }: { chatId: string }) {
const handleShare = () => {
const params = new URLSearchParams(window.location.search)
const ref = params.get('ref')
shareChat(chatId, { ref })
}
return <button onClick={handleShare}>Share</button>
}
```
@@ -0,0 +1,45 @@
---
title: Narrow Effect Dependencies
impact: LOW
impactDescription: minimizes effect re-runs
tags: rerender, useEffect, dependencies, optimization
---
## Narrow Effect Dependencies
Specify primitive dependencies instead of objects to minimize effect re-runs.
**Incorrect (re-runs on any user field change):**
```tsx
useEffect(() => {
console.log(user.id)
}, [user])
```
**Correct (re-runs only when id changes):**
```tsx
useEffect(() => {
console.log(user.id)
}, [user.id])
```
**For derived state, compute outside effect:**
```tsx
// Incorrect: runs on width=767, 766, 765...
useEffect(() => {
if (width < 768) {
enableMobileMode()
}
}, [width])
// Correct: runs only on boolean transition
const isMobile = width < 768
useEffect(() => {
if (isMobile) {
enableMobileMode()
}
}, [isMobile])
```
@@ -0,0 +1,40 @@
---
title: Calculate Derived State During Rendering
impact: MEDIUM
impactDescription: avoids redundant renders and state drift
tags: rerender, derived-state, useEffect, state
---
## Calculate Derived State During Rendering
If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.
**Incorrect (redundant state and effect):**
```tsx
function Form() {
const [firstName, setFirstName] = useState('First')
const [lastName, setLastName] = useState('Last')
const [fullName, setFullName] = useState('')
useEffect(() => {
setFullName(firstName + ' ' + lastName)
}, [firstName, lastName])
return <p>{fullName}</p>
}
```
**Correct (derive during render):**
```tsx
function Form() {
const [firstName, setFirstName] = useState('First')
const [lastName, setLastName] = useState('Last')
const fullName = firstName + ' ' + lastName
return <p>{fullName}</p>
}
```
References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
@@ -0,0 +1,29 @@
---
title: Subscribe to Derived State
impact: MEDIUM
impactDescription: reduces re-render frequency
tags: rerender, derived-state, media-query, optimization
---
## Subscribe to Derived State
Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
**Incorrect (re-renders on every pixel change):**
```tsx
function Sidebar() {
const width = useWindowWidth() // updates continuously
const isMobile = width < 768
return <nav className={isMobile ? 'mobile' : 'desktop'} />
}
```
**Correct (re-renders only when boolean changes):**
```tsx
function Sidebar() {
const isMobile = useMediaQuery('(max-width: 767px)')
return <nav className={isMobile ? 'mobile' : 'desktop'} />
}
```
@@ -0,0 +1,74 @@
---
title: Use Functional setState Updates
impact: MEDIUM
impactDescription: prevents stale closures and unnecessary callback recreations
tags: react, hooks, useState, useCallback, callbacks, closures
---
## Use Functional setState Updates
When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
**Incorrect (requires state as dependency):**
```tsx
function TodoList() {
const [items, setItems] = useState(initialItems)
// Callback must depend on items, recreated on every items change
const addItems = useCallback((newItems: Item[]) => {
setItems([...items, ...newItems])
}, [items]) // ❌ items dependency causes recreations
// Risk of stale closure if dependency is forgotten
const removeItem = useCallback((id: string) => {
setItems(items.filter(item => item.id !== id))
}, []) // ❌ Missing items dependency - will use stale items!
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
}
```
The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
**Correct (stable callbacks, no stale closures):**
```tsx
function TodoList() {
const [items, setItems] = useState(initialItems)
// Stable callback, never recreated
const addItems = useCallback((newItems: Item[]) => {
setItems(curr => [...curr, ...newItems])
}, []) // ✅ No dependencies needed
// Always uses latest state, no stale closure risk
const removeItem = useCallback((id: string) => {
setItems(curr => curr.filter(item => item.id !== id))
}, []) // ✅ Safe and stable
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
}
```
**Benefits:**
1. **Stable callback references** - Callbacks don't need to be recreated when state changes
2. **No stale closures** - Always operates on the latest state value
3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
4. **Prevents bugs** - Eliminates the most common source of React closure bugs
**When to use functional updates:**
- Any setState that depends on the current state value
- Inside useCallback/useMemo when state is needed
- Event handlers that reference state
- Async operations that update state
**When direct updates are fine:**
- Setting state to a static value: `setCount(0)`
- Setting state from props/arguments only: `setName(newName)`
- State doesn't depend on previous value
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
@@ -0,0 +1,58 @@
---
title: Use Lazy State Initialization
impact: MEDIUM
impactDescription: wasted computation on every render
tags: react, hooks, useState, performance, initialization
---
## Use Lazy State Initialization
Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
**Incorrect (runs on every render):**
```tsx
function FilteredList({ items }: { items: Item[] }) {
// buildSearchIndex() runs on EVERY render, even after initialization
const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
const [query, setQuery] = useState('')
// When query changes, buildSearchIndex runs again unnecessarily
return <SearchResults index={searchIndex} query={query} />
}
function UserProfile() {
// JSON.parse runs on every render
const [settings, setSettings] = useState(
JSON.parse(localStorage.getItem('settings') || '{}')
)
return <SettingsForm settings={settings} onChange={setSettings} />
}
```
**Correct (runs only once):**
```tsx
function FilteredList({ items }: { items: Item[] }) {
// buildSearchIndex() runs ONLY on initial render
const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
const [query, setQuery] = useState('')
return <SearchResults index={searchIndex} query={query} />
}
function UserProfile() {
// JSON.parse runs only on initial render
const [settings, setSettings] = useState(() => {
const stored = localStorage.getItem('settings')
return stored ? JSON.parse(stored) : {}
})
return <SettingsForm settings={settings} onChange={setSettings} />
}
```
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
@@ -0,0 +1,38 @@
---
title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant
impact: MEDIUM
impactDescription: restores memoization by using a constant for default value
tags: rerender, memo, optimization
---
## Extract Default Non-primitive Parameter Value from Memoized Component to Constant
When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.
To address this issue, extract the default value into a constant.
**Incorrect (`onClick` has different values on every rerender):**
```tsx
const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
// ...
})
// Used without optional onClick
<UserAvatar />
```
**Correct (stable default value):**
```tsx
const NOOP = () => {};
const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
// ...
})
// Used without optional onClick
<UserAvatar />
```
@@ -0,0 +1,44 @@
---
title: Extract to Memoized Components
impact: MEDIUM
impactDescription: enables early returns
tags: rerender, memo, useMemo, optimization
---
## Extract to Memoized Components
Extract expensive work into memoized components to enable early returns before computation.
**Incorrect (computes avatar even when loading):**
```tsx
function Profile({ user, loading }: Props) {
const avatar = useMemo(() => {
const id = computeAvatarId(user)
return <Avatar id={id} />
}, [user])
if (loading) return <Skeleton />
return <div>{avatar}</div>
}
```
**Correct (skips computation when loading):**
```tsx
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
const id = useMemo(() => computeAvatarId(user), [user])
return <Avatar id={id} />
})
function Profile({ user, loading }: Props) {
if (loading) return <Skeleton />
return (
<div>
<UserAvatar user={user} />
</div>
)
}
```
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
@@ -0,0 +1,45 @@
---
title: Put Interaction Logic in Event Handlers
impact: MEDIUM
impactDescription: avoids effect re-runs and duplicate side effects
tags: rerender, useEffect, events, side-effects, dependencies
---
## Put Interaction Logic in Event Handlers
If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.
**Incorrect (event modeled as state + effect):**
```tsx
function Form() {
const [submitted, setSubmitted] = useState(false)
const theme = useContext(ThemeContext)
useEffect(() => {
if (submitted) {
post('/api/register')
showToast('Registered', theme)
}
}, [submitted, theme])
return <button onClick={() => setSubmitted(true)}>Submit</button>
}
```
**Correct (do it in the handler):**
```tsx
function Form() {
const theme = useContext(ThemeContext)
function handleSubmit() {
post('/api/register')
showToast('Registered', theme)
}
return <button onClick={handleSubmit}>Submit</button>
}
```
Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
@@ -0,0 +1,35 @@
---
title: Do not wrap a simple expression with a primitive result type in useMemo
impact: LOW-MEDIUM
impactDescription: wasted computation on every render
tags: rerender, useMemo, optimization
---
## Do not wrap a simple expression with a primitive result type in useMemo
When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.
Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.
**Incorrect:**
```tsx
function Header({ user, notifications }: Props) {
const isLoading = useMemo(() => {
return user.isLoading || notifications.isLoading
}, [user.isLoading, notifications.isLoading])
if (isLoading) return <Skeleton />
// return some markup
}
```
**Correct:**
```tsx
function Header({ user, notifications }: Props) {
const isLoading = user.isLoading || notifications.isLoading
if (isLoading) return <Skeleton />
// return some markup
}
```
@@ -0,0 +1,40 @@
---
title: Use Transitions for Non-Urgent Updates
impact: MEDIUM
impactDescription: maintains UI responsiveness
tags: rerender, transitions, startTransition, performance
---
## Use Transitions for Non-Urgent Updates
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
**Incorrect (blocks UI on every scroll):**
```tsx
function ScrollTracker() {
const [scrollY, setScrollY] = useState(0)
useEffect(() => {
const handler = () => setScrollY(window.scrollY)
window.addEventListener('scroll', handler, { passive: true })
return () => window.removeEventListener('scroll', handler)
}, [])
}
```
**Correct (non-blocking updates):**
```tsx
import { startTransition } from 'react'
function ScrollTracker() {
const [scrollY, setScrollY] = useState(0)
useEffect(() => {
const handler = () => {
startTransition(() => setScrollY(window.scrollY))
}
window.addEventListener('scroll', handler, { passive: true })
return () => window.removeEventListener('scroll', handler)
}, [])
}
```
@@ -0,0 +1,73 @@
---
title: Use useRef for Transient Values
impact: MEDIUM
impactDescription: avoids unnecessary re-renders on frequent updates
tags: rerender, useref, state, performance
---
## Use useRef for Transient Values
When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
**Incorrect (renders every update):**
```tsx
function Tracker() {
const [lastX, setLastX] = useState(0)
useEffect(() => {
const onMove = (e: MouseEvent) => setLastX(e.clientX)
window.addEventListener('mousemove', onMove)
return () => window.removeEventListener('mousemove', onMove)
}, [])
return (
<div
style={{
position: 'fixed',
top: 0,
left: lastX,
width: 8,
height: 8,
background: 'black',
}}
/>
)
}
```
**Correct (no re-render for tracking):**
```tsx
function Tracker() {
const lastXRef = useRef(0)
const dotRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const onMove = (e: MouseEvent) => {
lastXRef.current = e.clientX
const node = dotRef.current
if (node) {
node.style.transform = `translateX(${e.clientX}px)`
}
}
window.addEventListener('mousemove', onMove)
return () => window.removeEventListener('mousemove', onMove)
}, [])
return (
<div
ref={dotRef}
style={{
position: 'fixed',
top: 0,
left: 0,
width: 8,
height: 8,
background: 'black',
transform: 'translateX(0px)',
}}
/>
)
}
```
@@ -0,0 +1,73 @@
---
title: Use after() for Non-Blocking Operations
impact: MEDIUM
impactDescription: faster response times
tags: server, async, logging, analytics, side-effects
---
## Use after() for Non-Blocking Operations
Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.
**Incorrect (blocks response):**
```tsx
import { logUserAction } from '@/app/utils'
export async function POST(request: Request) {
// Perform mutation
await updateDatabase(request)
// Logging blocks the response
const userAgent = request.headers.get('user-agent') || 'unknown'
await logUserAction({ userAgent })
return new Response(JSON.stringify({ status: 'success' }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
})
}
```
**Correct (non-blocking):**
```tsx
import { after } from 'next/server'
import { headers, cookies } from 'next/headers'
import { logUserAction } from '@/app/utils'
export async function POST(request: Request) {
// Perform mutation
await updateDatabase(request)
// Log after response is sent
after(async () => {
const userAgent = (await headers()).get('user-agent') || 'unknown'
const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
logUserAction({ sessionCookie, userAgent })
})
return new Response(JSON.stringify({ status: 'success' }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
})
}
```
The response is sent immediately while logging happens in the background.
**Common use cases:**
- Analytics tracking
- Audit logging
- Sending notifications
- Cache invalidation
- Cleanup tasks
**Important notes:**
- `after()` runs even if the response fails or redirects
- Works in Server Actions, Route Handlers, and Server Components
Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
@@ -0,0 +1,96 @@
---
title: Authenticate Server Actions Like API Routes
impact: CRITICAL
impactDescription: prevents unauthorized access to server mutations
tags: server, server-actions, authentication, security, authorization
---
## Authenticate Server Actions Like API Routes
**Impact: CRITICAL (prevents unauthorized access to server mutations)**
Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.
Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."
**Incorrect (no authentication check):**
```typescript
'use server'
export async function deleteUser(userId: string) {
// Anyone can call this! No auth check
await db.user.delete({ where: { id: userId } })
return { success: true }
}
```
**Correct (authentication inside the action):**
```typescript
'use server'
import { verifySession } from '@/lib/auth'
import { unauthorized } from '@/lib/errors'
export async function deleteUser(userId: string) {
// Always check auth inside the action
const session = await verifySession()
if (!session) {
throw unauthorized('Must be logged in')
}
// Check authorization too
if (session.user.role !== 'admin' && session.user.id !== userId) {
throw unauthorized('Cannot delete other users')
}
await db.user.delete({ where: { id: userId } })
return { success: true }
}
```
**With input validation:**
```typescript
'use server'
import { verifySession } from '@/lib/auth'
import { z } from 'zod'
const updateProfileSchema = z.object({
userId: z.string().uuid(),
name: z.string().min(1).max(100),
email: z.string().email()
})
export async function updateProfile(data: unknown) {
// Validate input first
const validated = updateProfileSchema.parse(data)
// Then authenticate
const session = await verifySession()
if (!session) {
throw new Error('Unauthorized')
}
// Then authorize
if (session.user.id !== validated.userId) {
throw new Error('Can only update own profile')
}
// Finally perform the mutation
await db.user.update({
where: { id: validated.userId },
data: {
name: validated.name,
email: validated.email
}
})
return { success: true }
}
```
Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)
@@ -0,0 +1,41 @@
---
title: Cross-Request LRU Caching
impact: HIGH
impactDescription: caches across requests
tags: server, cache, lru, cross-request
---
## Cross-Request LRU Caching
`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
**Implementation:**
```typescript
import { LRUCache } from 'lru-cache'
const cache = new LRUCache<string, any>({
max: 1000,
ttl: 5 * 60 * 1000 // 5 minutes
})
export async function getUser(id: string) {
const cached = cache.get(id)
if (cached) return cached
const user = await db.user.findUnique({ where: { id } })
cache.set(id, user)
return user
}
// Request 1: DB query, result cached
// Request 2: cache hit, no DB query
```
Use when sequential user actions hit multiple endpoints needing the same data within seconds.
**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.
**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
@@ -0,0 +1,76 @@
---
title: Per-Request Deduplication with React.cache()
impact: MEDIUM
impactDescription: deduplicates within request
tags: server, cache, react-cache, deduplication
---
## Per-Request Deduplication with React.cache()
Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
**Usage:**
```typescript
import { cache } from 'react'
export const getCurrentUser = cache(async () => {
const session = await auth()
if (!session?.user?.id) return null
return await db.user.findUnique({
where: { id: session.user.id }
})
})
```
Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
**Avoid inline objects as arguments:**
`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
**Incorrect (always cache miss):**
```typescript
const getUser = cache(async (params: { uid: number }) => {
return await db.user.findUnique({ where: { id: params.uid } })
})
// Each call creates new object, never hits cache
getUser({ uid: 1 })
getUser({ uid: 1 }) // Cache miss, runs query again
```
**Correct (cache hit):**
```typescript
const getUser = cache(async (uid: number) => {
return await db.user.findUnique({ where: { id: uid } })
})
// Primitive args use value equality
getUser(1)
getUser(1) // Cache hit, returns cached result
```
If you must pass objects, pass the same reference:
```typescript
const params = { uid: 1 }
getUser(params) // Query runs
getUser(params) // Cache hit (same reference)
```
**Next.js-Specific Note:**
In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:
- Database queries (Prisma, Drizzle, etc.)
- Heavy computations
- Authentication checks
- File system operations
- Any non-fetch async work
Use `React.cache()` to deduplicate these operations across your component tree.
Reference: [React.cache documentation](https://react.dev/reference/react/cache)
@@ -0,0 +1,65 @@
---
title: Avoid Duplicate Serialization in RSC Props
impact: LOW
impactDescription: reduces network payload by avoiding duplicate serialization
tags: server, rsc, serialization, props, client-components
---
## Avoid Duplicate Serialization in RSC Props
**Impact: LOW (reduces network payload by avoiding duplicate serialization)**
RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.
**Incorrect (duplicates array):**
```tsx
// RSC: sends 6 strings (2 arrays × 3 items)
<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />
```
**Correct (sends 3 strings):**
```tsx
// RSC: send once
<ClientList usernames={usernames} />
// Client: transform there
'use client'
const sorted = useMemo(() => [...usernames].sort(), [usernames])
```
**Nested deduplication behavior:**
Deduplication works recursively. Impact varies by data type:
- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated
- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference
```tsx
// string[] - duplicates everything
usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings
// object[] - duplicates array structure only
users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)
```
**Operations breaking deduplication (create new references):**
- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`
- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`
**More examples:**
```tsx
// ❌ Bad
<C users={users} active={users.filter(u => u.active)} />
<C product={product} productName={product.name} />
// ✅ Good
<C users={users} />
<C product={product} />
// Do filtering/destructuring in client
```
**Exception:** Pass derived data when transformation is expensive or client doesn't need original.
@@ -0,0 +1,83 @@
---
title: Parallel Data Fetching with Component Composition
impact: CRITICAL
impactDescription: eliminates server-side waterfalls
tags: server, rsc, parallel-fetching, composition
---
## Parallel Data Fetching with Component Composition
React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
**Incorrect (Sidebar waits for Page's fetch to complete):**
```tsx
export default async function Page() {
const header = await fetchHeader()
return (
<div>
<div>{header}</div>
<Sidebar />
</div>
)
}
async function Sidebar() {
const items = await fetchSidebarItems()
return <nav>{items.map(renderItem)}</nav>
}
```
**Correct (both fetch simultaneously):**
```tsx
async function Header() {
const data = await fetchHeader()
return <div>{data}</div>
}
async function Sidebar() {
const items = await fetchSidebarItems()
return <nav>{items.map(renderItem)}</nav>
}
export default function Page() {
return (
<div>
<Header />
<Sidebar />
</div>
)
}
```
**Alternative with children prop:**
```tsx
async function Header() {
const data = await fetchHeader()
return <div>{data}</div>
}
async function Sidebar() {
const items = await fetchSidebarItems()
return <nav>{items.map(renderItem)}</nav>
}
function Layout({ children }: { children: ReactNode }) {
return (
<div>
<Header />
{children}
</div>
)
}
export default function Page() {
return (
<Layout>
<Sidebar />
</Layout>
)
}
```
@@ -0,0 +1,38 @@
---
title: Minimize Serialization at RSC Boundaries
impact: HIGH
impactDescription: reduces data transfer size
tags: server, rsc, serialization, props
---
## Minimize Serialization at RSC Boundaries
The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.
**Incorrect (serializes all 50 fields):**
```tsx
async function Page() {
const user = await fetchUser() // 50 fields
return <Profile user={user} />
}
'use client'
function Profile({ user }: { user: User }) {
return <div>{user.name}</div> // uses 1 field
}
```
**Correct (serializes only 1 field):**
```tsx
async function Page() {
const user = await fetchUser()
return <Profile name={user.name} />
}
'use client'
function Profile({ name }: { name: string }) {
return <div>{name}</div>
}
```
@@ -0,0 +1,147 @@
---
name: you-might-not-need-an-effect
description: Analyze code for useEffect anti-patterns and refactor to simpler alternatives. Use when the user says "you might not need an effect", "check effects", "useEffect audit", or asks to review useEffect usage.
disable-model-invocation: true
---
# You Might Not Need an Effect
Analyze code for `useEffect` anti-patterns and refactor to simpler, more correct alternatives.
Based on https://react.dev/learn/you-might-not-need-an-effect
## Arguments
- **scope**: what to analyze (default: uncommitted changes). Examples: `diff to main`, `src/components/`, `whole codebase`
- **fix**: whether to apply fixes (default: `true`). Set to `false` to only propose changes.
## Workflow
1. **Determine scope** — get the relevant code:
- Default: `git diff` for uncommitted changes
- If a directory/file is specified, read those files
- If "whole codebase": search all `.tsx`/`.ts` files for `useEffect`
2. **Scan for anti-patterns** — check each `useEffect` against the patterns below
3. **Fix or propose** — depending on the `fix` argument:
- `fix=true`: apply the refactors, then verify with `yarn build && yarn lint && yarn type-check`
- `fix=false`: list each anti-pattern found with a before/after code suggestion
4. **Report** — summarize what was found and changed
## Anti-Patterns to Catch
### 1. Deriving state during render (no effect needed)
If you're computing something from existing props or state, calculate it during render.
```typescript
// ❌ Anti-pattern
const [fullName, setFullName] = useState('');
useEffect(() => {
setFullName(firstName + ' ' + lastName);
}, [firstName, lastName]);
// ✅ Fix — derive during render
const fullName = firstName + ' ' + lastName;
```
### 2. Caching expensive calculations (useMemo, not useEffect)
```typescript
// ❌ Anti-pattern
const [filtered, setFiltered] = useState([]);
useEffect(() => {
setFiltered(items.filter(item => item.active));
}, [items]);
// ✅ Fix — calculate during render (useMemo only if profiling shows it's needed)
const filtered = items.filter(item => item.active);
```
### 3. Resetting state when props change (use key, not useEffect)
```typescript
// ❌ Anti-pattern
useEffect(() => {
setComment('');
}, [postCid]);
// ✅ Fix — use key on the component to reset state
<CommentForm key={postCid} />
```
### 4. Fetching data (use bitsocial-react-hooks, not useEffect)
This project uses `bitsocial-react-hooks` for all data fetching. Never use `useEffect` + `fetch`.
```typescript
// ❌ Anti-pattern
const [comment, setComment] = useState(null);
useEffect(() => {
fetchComment(cid).then(setComment);
}, [cid]);
// ✅ Fix — use the hook
const { state, ...comment } = useComment({ commentCid: cid });
```
### 5. Syncing with external stores (use Zustand, not useEffect)
```typescript
// ❌ Anti-pattern
const [theme, setTheme] = useState('light');
useEffect(() => {
const unsub = settingsStore.subscribe((s) => setTheme(s.theme));
return unsub;
}, []);
// ✅ Fix — use the Zustand store directly
const theme = useSettingsStore((s) => s.theme);
```
### 6. Sending analytics / logging (move to event handlers)
```typescript
// ❌ Anti-pattern — fires on every render, not on user action
useEffect(() => {
logPageView(pageName);
}, [pageName]);
// ✅ Fix — call in the event handler or route change callback
const navigate = () => {
logPageView(pageName);
router.push(path);
};
```
### 7. Initializing global singletons (use module scope or lazy init)
```typescript
// ❌ Anti-pattern
useEffect(() => {
initializeAnalytics();
}, []);
// ✅ Fix — module-level init (runs once on import)
if (typeof window !== 'undefined') {
initializeAnalytics();
}
```
## Project-Specific Replacements
| useEffect pattern | Replace with |
|-------------------|-------------|
| Fetch data | `useComment`, `useFeed`, `useSubplebbit`, etc. from bitsocial-react-hooks |
| Sync shared state | Zustand store in `src/stores/` |
| Derive values from state | Calculate during render |
| Boolean loading/error flags | `state` field from bitsocial-react-hooks, or state machine in Zustand |
## When useEffect IS Appropriate
Not every effect is wrong. Keep `useEffect` for:
- Subscribing to browser APIs (resize, intersection observer, etc.) with proper cleanup
- Synchronizing with non-React systems (third-party widgets, imperative DOM)
- Running code on mount that genuinely has no hook equivalent

Some files were not shown because too many files have changed in this diff Show More