diff --git a/.claude/agents/browser-check.md b/.claude/agents/browser-check.md new file mode 100644 index 00000000..919cb1cd --- /dev/null +++ b/.claude/agents/browser-check.md @@ -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 diff --git a/.claude/agents/code-quality.md b/.claude/agents/code-quality.md new file mode 100644 index 00000000..a6f904ff --- /dev/null +++ b/.claude/agents/code-quality.md @@ -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 -- `) 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 diff --git a/.claude/agents/plan-implementer.md b/.claude/agents/plan-implementer.md new file mode 100644 index 00000000..0a5e3931 --- /dev/null +++ b/.claude/agents/plan-implementer.md @@ -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 -- `) 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` diff --git a/.claude/agents/profiler.md b/.claude/agents/profiler.md new file mode 100644 index 00000000..bbebe144 --- /dev/null +++ b/.claude/agents/profiler.md @@ -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 | 300–1000ms | >1000ms | +| LCP | 2.5–4s | >4s | +| Long task | 50–100ms | >100ms | +| CLS total | 0.1–0.25 | >0.25 | +| Resource load | 200–500ms | >500ms | +| JS heap | 50–100MB | >100MB | + +**React-level thresholds:** + +| Metric | Warning | Critical | +|--------|---------|----------| +| Commits per route load | 5–15 | >15 | +| Commits per scroll (3 wheels) | 10–30 | >30 | +| Render burst (>5 commits in 100ms) | 1+ burst | 3+ bursts | +| Component renders (react-scan) | 10–30 | >30 | +| Component render time (react-scan) | 16–50ms | >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 diff --git a/.claude/agents/react-doctor-fixer.md b/.claude/agents/react-doctor-fixer.md new file mode 100644 index 00000000..5c34f869 --- /dev/null +++ b/.claude/agents/react-doctor-fixer.md @@ -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 -- `) 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 + + +### Files Modified +- `path/to/file.tsx` — + +### Fix Applied + + +### Verification +- **Original issue resolved:** YES/NO +- **New issues introduced:** YES (list them) / NO +- **react-doctor output (relevant lines):** + +### 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` diff --git a/.claude/agents/react-patterns-enforcer.md b/.claude/agents/react-patterns-enforcer.md new file mode 100644 index 00000000..26205957 --- /dev/null +++ b/.claude/agents/react-patterns-enforcer.md @@ -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 -- `) 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` diff --git a/.claude/agents/test-apk.md b/.claude/agents/test-apk.md new file mode 100644 index 00000000..4f01c023 --- /dev/null +++ b/.claude/agents/test-apk.md @@ -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=""` | +| 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. diff --git a/.claude/agents/translator.md b/.claude/agents/translator.md new file mode 100644 index 00000000..946a9df6 --- /dev/null +++ b/.claude/agents/translator.md @@ -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 --map translations-temp.json --include-en --dry +``` + +Verify the output looks correct. + +### Step 5 — Apply + +```bash +node scripts/update-translations.js --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. diff --git a/.claude/hooks.json b/.claude/hooks.json new file mode 100644 index 00000000..f328ec43 --- /dev/null +++ b/.claude/hooks.json @@ -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 + } + ] + } +} diff --git a/.claude/hooks/format.sh b/.claude/hooks/format.sh new file mode 100755 index 00000000..ea7a57ae --- /dev/null +++ b/.claude/hooks/format.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +repo_root="$(cd "$(dirname "$0")/../.." && pwd)" +exec "$repo_root/scripts/agent-hooks/format.sh" "$@" diff --git a/.claude/hooks/sync-git-branches.sh b/.claude/hooks/sync-git-branches.sh new file mode 100755 index 00000000..88de2ced --- /dev/null +++ b/.claude/hooks/sync-git-branches.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +repo_root="$(cd "$(dirname "$0")/../.." && pwd)" +exec "$repo_root/scripts/agent-hooks/sync-git-branches.sh" "$@" diff --git a/.claude/hooks/verify.sh b/.claude/hooks/verify.sh new file mode 100755 index 00000000..3ca8aaec --- /dev/null +++ b/.claude/hooks/verify.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +repo_root="$(cd "$(dirname "$0")/../.." && pwd)" +exec "$repo_root/scripts/agent-hooks/verify.sh" "$@" diff --git a/.claude/hooks/yarn-install.sh b/.claude/hooks/yarn-install.sh new file mode 100755 index 00000000..ff44ea19 --- /dev/null +++ b/.claude/hooks/yarn-install.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +repo_root="$(cd "$(dirname "$0")/../.." && pwd)" +exec "$repo_root/scripts/agent-hooks/yarn-install.sh" "$@" diff --git a/.claude/skills/commit-format/SKILL.md b/.claude/skills/commit-format/SKILL.md new file mode 100644 index 00000000..d07a8776 --- /dev/null +++ b/.claude/skills/commit-format/SKILL.md @@ -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 diff --git a/.claude/skills/commit/SKILL.md b/.claude/skills/commit/SKILL.md new file mode 100644 index 00000000..53895607 --- /dev/null +++ b/.claude/skills/commit/SKILL.md @@ -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 + 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. diff --git a/.claude/skills/context7/SKILL.md b/.claude/skills/context7/SKILL.md new file mode 100644 index 00000000..66e93c1c --- /dev/null +++ b/.claude/skills/context7/SKILL.md @@ -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) diff --git a/.claude/skills/deslop/SKILL.md b/.claude/skills/deslop/SKILL.md new file mode 100644 index 00000000..48c3f02e --- /dev/null +++ b/.claude/skills/deslop/SKILL.md @@ -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. diff --git a/.claude/skills/find-skills/SKILL.md b/.claude/skills/find-skills/SKILL.md new file mode 100644 index 00000000..c797184e --- /dev/null +++ b/.claude/skills/find-skills/SKILL.md @@ -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 ` - 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 + +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 -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 +``` diff --git a/.claude/skills/fix-merge-conflicts/SKILL.md b/.claude/skills/fix-merge-conflicts/SKILL.md new file mode 100644 index 00000000..9c1ef632 --- /dev/null +++ b/.claude/skills/fix-merge-conflicts/SKILL.md @@ -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 ` 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 diff --git a/.claude/skills/implement-plan/SKILL.md b/.claude/skills/implement-plan/SKILL.md new file mode 100644 index 00000000..c95942ad --- /dev/null +++ b/.claude/skills/implement-plan/SKILL.md @@ -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. diff --git a/.claude/skills/inspect-elements/SKILL.md b/.claude/skills/inspect-elements/SKILL.md new file mode 100644 index 00000000..06ff3919 --- /dev/null +++ b/.claude/skills/inspect-elements/SKILL.md @@ -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. diff --git a/.claude/skills/inspect-elements/agents/openai.yaml b/.claude/skills/inspect-elements/agents/openai.yaml new file mode 100644 index 00000000..944982d9 --- /dev/null +++ b/.claude/skills/inspect-elements/agents/openai.yaml @@ -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." diff --git a/.claude/skills/issue-format/SKILL.md b/.claude/skills/issue-format/SKILL.md new file mode 100644 index 00000000..14f07aa5 --- /dev/null +++ b/.claude/skills/issue-format/SKILL.md @@ -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 diff --git a/.claude/skills/make-closed-issue/SKILL.md b/.claude/skills/make-closed-issue/SKILL.md new file mode 100644 index 00000000..c61c6091 --- /dev/null +++ b/.claude/skills/make-closed-issue/SKILL.md @@ -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 < 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) diff --git a/.claude/skills/playwright-cli/references/request-mocking.md b/.claude/skills/playwright-cli/references/request-mocking.md new file mode 100644 index 00000000..9005fda6 --- /dev/null +++ b/.claude/skills/playwright-cli/references/request-mocking.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' }) }); + }); +}" +``` diff --git a/.claude/skills/playwright-cli/references/running-code.md b/.claude/skills/playwright-cli/references/running-code.md new file mode 100644 index 00000000..7d6d22fd --- /dev/null +++ b/.claude/skills/playwright-cli/references/running-code.md @@ -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; +}" +``` diff --git a/.claude/skills/playwright-cli/references/session-management.md b/.claude/skills/playwright-cli/references/session-management.md new file mode 100644 index 00000000..08c8c90c --- /dev/null +++ b/.claude/skills/playwright-cli/references/session-management.md @@ -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 +``` diff --git a/.claude/skills/playwright-cli/references/storage-state.md b/.claude/skills/playwright-cli/references/storage-state.md new file mode 100644 index 00000000..c856db5e --- /dev/null +++ b/.claude/skills/playwright-cli/references/storage-state.md @@ -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 diff --git a/.claude/skills/playwright-cli/references/test-generation.md b/.claude/skills/playwright-cli/references/test-generation.md new file mode 100644 index 00000000..7a09df38 --- /dev/null +++ b/.claude/skills/playwright-cli/references/test-generation.md @@ -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(); +``` diff --git a/.claude/skills/playwright-cli/references/tracing.md b/.claude/skills/playwright-cli/references/tracing.md new file mode 100644 index 00000000..7ce7babb --- /dev/null +++ b/.claude/skills/playwright-cli/references/tracing.md @@ -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 diff --git a/.claude/skills/playwright-cli/references/video-recording.md b/.claude/skills/playwright-cli/references/video-recording.md new file mode 100644 index 00000000..38391b37 --- /dev/null +++ b/.claude/skills/playwright-cli/references/video-recording.md @@ -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 diff --git a/.claude/skills/profile-browsing/SKILL.md b/.claude/skills/profile-browsing/SKILL.md new file mode 100644 index 00000000..6087c385 --- /dev/null +++ b/.claude/skills/profile-browsing/SKILL.md @@ -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 2–4 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). diff --git a/.claude/skills/readme/SKILL.md b/.claude/skills/readme/SKILL.md new file mode 100644 index 00000000..cbb57dc8 --- /dev/null +++ b/.claude/skills/readme/SKILL.md @@ -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= +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() + 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. diff --git a/.claude/skills/refactor-pass/SKILL.md b/.claude/skills/refactor-pass/SKILL.md new file mode 100644 index 00000000..70d13aaa --- /dev/null +++ b/.claude/skills/refactor-pass/SKILL.md @@ -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 ` after changes +- If the build/lint/type-check fails after refactoring, fix it before finishing diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md new file mode 100644 index 00000000..d14426b4 --- /dev/null +++ b/.claude/skills/release/SKILL.md @@ -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 ..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 ~60–80 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; 2–4 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 "" +``` + +### 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" +git push +git tag v +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 1–7 but **skip Step 8** (git operations). Print a summary of what would be committed so the user can review. diff --git a/.claude/skills/review-and-merge-pr/SKILL.md b/.claude/skills/review-and-merge-pr/SKILL.md new file mode 100644 index 00000000..5fe74515 --- /dev/null +++ b/.claude/skills/review-and-merge-pr/SKILL.md @@ -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/` 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 --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 --repo bitsocialnet/5chan --json number,title,url,headRefName,baseRefName,isDraft,reviewDecision,mergeStateStatus +gh pr checks +gh api "repos/bitsocialnet/5chan/issues//comments?per_page=100" +gh api "repos/bitsocialnet/5chan/pulls//reviews?per_page=100" +gh api "repos/bitsocialnet/5chan/pulls//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 +git fetch origin +git status --short --branch +git add +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 --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 --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 --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 2>/dev/null || true +git branch -D "pr/" 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/` 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/` alias, and any worktree were cleaned up diff --git a/.claude/skills/review-and-merge-pr/agents/openai.yaml b/.claude/skills/review-and-merge-pr/agents/openai.yaml new file mode 100644 index 00000000..b6f83e84 --- /dev/null +++ b/.claude/skills/review-and-merge-pr/agents/openai.yaml @@ -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." diff --git a/.claude/skills/test-apk/SKILL.md b/.claude/skills/test-apk/SKILL.md new file mode 100644 index 00000000..a4299e1f --- /dev/null +++ b/.claude/skills/test-apk/SKILL.md @@ -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: +``` + +### 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 | diff --git a/.claude/skills/translate/SKILL.md b/.claude/skills/translate/SKILL.md new file mode 100644 index 00000000..59baf00e --- /dev/null +++ b/.claude/skills/translate/SKILL.md @@ -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 ` | Translation key to update/delete | +| `--map ` | JSON file with per-language values | +| `--include-en` | Include English in updates (required when using `--map`) | +| `--from ` | 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 diff --git a/.claude/skills/vercel-react-best-practices/AGENTS.md b/.claude/skills/vercel-react-best-practices/AGENTS.md new file mode 100644 index 00000000..e53dde10 --- /dev/null +++ b/.claude/skills/vercel-react-best-practices/AGENTS.md @@ -0,0 +1,2934 @@ +# React Best Practices + +**Version 1.0.0** +Vercel Engineering +January 2026 + +> **Note:** +> This document is mainly for agents and LLMs to follow when maintaining, +> generating, or refactoring React and Next.js codebases at Vercel. Humans +> may also find it useful, but guidance here is optimized for automation +> and consistency by AI-assisted workflows. + +--- + +## Abstract + +Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation. + +--- + +## Table of Contents + +1. [Eliminating Waterfalls](#1-eliminating-waterfalls) — **CRITICAL** + - 1.1 [Defer Await Until Needed](#11-defer-await-until-needed) + - 1.2 [Dependency-Based Parallelization](#12-dependency-based-parallelization) + - 1.3 [Prevent Waterfall Chains in API Routes](#13-prevent-waterfall-chains-in-api-routes) + - 1.4 [Promise.all() for Independent Operations](#14-promiseall-for-independent-operations) + - 1.5 [Strategic Suspense Boundaries](#15-strategic-suspense-boundaries) +2. [Bundle Size Optimization](#2-bundle-size-optimization) — **CRITICAL** + - 2.1 [Avoid Barrel File Imports](#21-avoid-barrel-file-imports) + - 2.2 [Conditional Module Loading](#22-conditional-module-loading) + - 2.3 [Defer Non-Critical Third-Party Libraries](#23-defer-non-critical-third-party-libraries) + - 2.4 [Dynamic Imports for Heavy Components](#24-dynamic-imports-for-heavy-components) + - 2.5 [Preload Based on User Intent](#25-preload-based-on-user-intent) +3. [Server-Side Performance](#3-server-side-performance) — **HIGH** + - 3.1 [Authenticate Server Actions Like API Routes](#31-authenticate-server-actions-like-api-routes) + - 3.2 [Avoid Duplicate Serialization in RSC Props](#32-avoid-duplicate-serialization-in-rsc-props) + - 3.3 [Cross-Request LRU Caching](#33-cross-request-lru-caching) + - 3.4 [Minimize Serialization at RSC Boundaries](#34-minimize-serialization-at-rsc-boundaries) + - 3.5 [Parallel Data Fetching with Component Composition](#35-parallel-data-fetching-with-component-composition) + - 3.6 [Per-Request Deduplication with React.cache()](#36-per-request-deduplication-with-reactcache) + - 3.7 [Use after() for Non-Blocking Operations](#37-use-after-for-non-blocking-operations) +4. [Client-Side Data Fetching](#4-client-side-data-fetching) — **MEDIUM-HIGH** + - 4.1 [Deduplicate Global Event Listeners](#41-deduplicate-global-event-listeners) + - 4.2 [Use Passive Event Listeners for Scrolling Performance](#42-use-passive-event-listeners-for-scrolling-performance) + - 4.3 [Use SWR for Automatic Deduplication](#43-use-swr-for-automatic-deduplication) + - 4.4 [Version and Minimize localStorage Data](#44-version-and-minimize-localstorage-data) +5. [Re-render Optimization](#5-re-render-optimization) — **MEDIUM** + - 5.1 [Calculate Derived State During Rendering](#51-calculate-derived-state-during-rendering) + - 5.2 [Defer State Reads to Usage Point](#52-defer-state-reads-to-usage-point) + - 5.3 [Do not wrap a simple expression with a primitive result type in useMemo](#53-do-not-wrap-a-simple-expression-with-a-primitive-result-type-in-usememo) + - 5.4 [Extract Default Non-primitive Parameter Value from Memoized Component to Constant](#54-extract-default-non-primitive-parameter-value-from-memoized-component-to-constant) + - 5.5 [Extract to Memoized Components](#55-extract-to-memoized-components) + - 5.6 [Narrow Effect Dependencies](#56-narrow-effect-dependencies) + - 5.7 [Put Interaction Logic in Event Handlers](#57-put-interaction-logic-in-event-handlers) + - 5.8 [Subscribe to Derived State](#58-subscribe-to-derived-state) + - 5.9 [Use Functional setState Updates](#59-use-functional-setstate-updates) + - 5.10 [Use Lazy State Initialization](#510-use-lazy-state-initialization) + - 5.11 [Use Transitions for Non-Urgent Updates](#511-use-transitions-for-non-urgent-updates) + - 5.12 [Use useRef for Transient Values](#512-use-useref-for-transient-values) +6. [Rendering Performance](#6-rendering-performance) — **MEDIUM** + - 6.1 [Animate SVG Wrapper Instead of SVG Element](#61-animate-svg-wrapper-instead-of-svg-element) + - 6.2 [CSS content-visibility for Long Lists](#62-css-content-visibility-for-long-lists) + - 6.3 [Hoist Static JSX Elements](#63-hoist-static-jsx-elements) + - 6.4 [Optimize SVG Precision](#64-optimize-svg-precision) + - 6.5 [Prevent Hydration Mismatch Without Flickering](#65-prevent-hydration-mismatch-without-flickering) + - 6.6 [Suppress Expected Hydration Mismatches](#66-suppress-expected-hydration-mismatches) + - 6.7 [Use Activity Component for Show/Hide](#67-use-activity-component-for-showhide) + - 6.8 [Use Explicit Conditional Rendering](#68-use-explicit-conditional-rendering) + - 6.9 [Use useTransition Over Manual Loading States](#69-use-usetransition-over-manual-loading-states) +7. [JavaScript Performance](#7-javascript-performance) — **LOW-MEDIUM** + - 7.1 [Avoid Layout Thrashing](#71-avoid-layout-thrashing) + - 7.2 [Build Index Maps for Repeated Lookups](#72-build-index-maps-for-repeated-lookups) + - 7.3 [Cache Property Access in Loops](#73-cache-property-access-in-loops) + - 7.4 [Cache Repeated Function Calls](#74-cache-repeated-function-calls) + - 7.5 [Cache Storage API Calls](#75-cache-storage-api-calls) + - 7.6 [Combine Multiple Array Iterations](#76-combine-multiple-array-iterations) + - 7.7 [Early Length Check for Array Comparisons](#77-early-length-check-for-array-comparisons) + - 7.8 [Early Return from Functions](#78-early-return-from-functions) + - 7.9 [Hoist RegExp Creation](#79-hoist-regexp-creation) + - 7.10 [Use Loop for Min/Max Instead of Sort](#710-use-loop-for-minmax-instead-of-sort) + - 7.11 [Use Set/Map for O(1) Lookups](#711-use-setmap-for-o1-lookups) + - 7.12 [Use toSorted() Instead of sort() for Immutability](#712-use-tosorted-instead-of-sort-for-immutability) +8. [Advanced Patterns](#8-advanced-patterns) — **LOW** + - 8.1 [Initialize App Once, Not Per Mount](#81-initialize-app-once-not-per-mount) + - 8.2 [Store Event Handlers in Refs](#82-store-event-handlers-in-refs) + - 8.3 [useEffectEvent for Stable Callback Refs](#83-useeffectevent-for-stable-callback-refs) + +--- + +## 1. Eliminating Waterfalls + +**Impact: CRITICAL** + +Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains. + +### 1.1 Defer Await Until Needed + +**Impact: HIGH (avoids blocking unused code paths)** + +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. + +### 1.2 Dependency-Based Parallelization + +**Impact: CRITICAL (2-10× improvement)** + +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:** + +```typescript +const userPromise = fetchUser() +const profilePromise = userPromise.then(user => fetchProfile(user.id)) + +const [user, config, profile] = await Promise.all([ + userPromise, + fetchConfig(), + profilePromise +]) +``` + +We can also create all the promises first, and do `Promise.all()` at the end. + +Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all) + +### 1.3 Prevent Waterfall Chains in API Routes + +**Impact: CRITICAL (2-10× improvement)** + +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). + +### 1.4 Promise.all() for Independent Operations + +**Impact: CRITICAL (2-10× improvement)** + +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() +]) +``` + +### 1.5 Strategic Suspense Boundaries + +**Impact: HIGH (faster initial paint)** + +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 ( +
+
Sidebar
+
Header
+
+ +
+
Footer
+
+ ) +} +``` + +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 ( +
+
Sidebar
+
Header
+
+ }> + + +
+
Footer
+
+ ) +} + +async function DataDisplay() { + const data = await fetchData() // Only blocks this component + return
{data.content}
+} +``` + +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 ( +
+
Sidebar
+
Header
+ }> + + + +
Footer
+
+ ) +} + +function DataDisplay({ dataPromise }: { dataPromise: Promise }) { + const data = use(dataPromise) // Unwraps the promise + return
{data.content}
+} + +function DataSummary({ dataPromise }: { dataPromise: Promise }) { + const data = use(dataPromise) // Reuses the same promise + return
{data.summary}
+} +``` + +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. + +--- + +## 2. Bundle Size Optimization + +**Impact: CRITICAL** + +Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint. + +### 2.1 Avoid Barrel File Imports + +**Impact: CRITICAL (200-800ms import cost, slow builds)** + +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: [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js) + +### 2.2 Conditional Module Loading + +**Impact: HIGH (loads large data only when needed)** + +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> }) { + const [frames, setFrames] = useState(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 + return +} +``` + +The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed. + +### 2.3 Defer Non-Critical Third-Party Libraries + +**Impact: MEDIUM (loads after hydration)** + +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 ( + + + {children} + + + + ) +} +``` + +**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 ( + + + {children} + + + + ) +} +``` + +### 2.4 Dynamic Imports for Heavy Components + +**Impact: CRITICAL (directly affects TTI and LCP)** + +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 +} +``` + +**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 +} +``` + +### 2.5 Preload Based on User Intent + +**Impact: MEDIUM (reduces perceived latency)** + +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 ( + + ) +} +``` + +**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 + {children} + +} +``` + +The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed. + +--- + +## 3. Server-Side Performance + +**Impact: HIGH** + +Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times. + +### 3.1 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) + +### 3.2 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) + +``` + +**Correct: sends 3 strings** + +```tsx +// RSC: send once + + +// Client: transform there +'use client' +const sorted = useMemo(() => [...usernames].sort(), [usernames]) +``` + +**Nested deduplication behavior:** + +```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) +``` + +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 + +**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 + u.active)} /> + + +// ✅ Good + + +// Do filtering/destructuring in client +``` + +**Exception:** Pass derived data when transformation is expensive or client doesn't need original. + +### 3.3 Cross-Request LRU Caching + +**Impact: HIGH (caches across requests)** + +`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({ + 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) + +### 3.4 Minimize Serialization at RSC Boundaries + +**Impact: HIGH (reduces data transfer size)** + +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 +} + +'use client' +function Profile({ user }: { user: User }) { + return
{user.name}
// uses 1 field +} +``` + +**Correct: serializes only 1 field** + +```tsx +async function Page() { + const user = await fetchUser() + return +} + +'use client' +function Profile({ name }: { name: string }) { + return
{name}
+} +``` + +### 3.5 Parallel Data Fetching with Component Composition + +**Impact: CRITICAL (eliminates server-side waterfalls)** + +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 ( +
+
{header}
+ +
+ ) +} + +async function Sidebar() { + const items = await fetchSidebarItems() + return +} +``` + +**Correct: both fetch simultaneously** + +```tsx +async function Header() { + const data = await fetchHeader() + return
{data}
+} + +async function Sidebar() { + const items = await fetchSidebarItems() + return +} + +export default function Page() { + return ( +
+
+ +
+ ) +} +``` + +**Alternative with children prop:** + +```tsx +async function Header() { + const data = await fetchHeader() + return
{data}
+} + +async function Sidebar() { + const items = await fetchSidebarItems() + return +} + +function Layout({ children }: { children: ReactNode }) { + return ( +
+
+ {children} +
+ ) +} + +export default function Page() { + return ( + + + + ) +} +``` + +### 3.6 Per-Request Deduplication with React.cache() + +**Impact: MEDIUM (deduplicates within request)** + +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 params = { uid: 1 } +getUser(params) // Query runs +getUser(params) // Cache hit (same reference) +``` + +If you must pass objects, pass the 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: [https://react.dev/reference/react/cache](https://react.dev/reference/react/cache) + +### 3.7 Use after() for Non-Blocking Operations + +**Impact: MEDIUM (faster response times)** + +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) + +--- + +## 4. Client-Side Data Fetching + +**Impact: MEDIUM-HIGH** + +Automatic deduplication and efficient data fetching patterns reduce redundant network requests. + +### 4.1 Deduplicate Global Event Listeners + +**Impact: LOW (single listener for N components)** + +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 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', () => { /* ... */ }) + // ... +} +``` + +### 4.2 Use Passive Event Listeners for Scrolling Performance + +**Impact: MEDIUM (eliminates scroll delay caused by event listeners)** + +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()`. + +### 4.3 Use SWR for Automatic Deduplication + +**Impact: MEDIUM-HIGH (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 +} +``` + +Reference: [https://swr.vercel.app](https://swr.vercel.app) + +### 4.4 Version and Minimize localStorage Data + +**Impact: MEDIUM (prevents schema conflicts, reduces storage size)** + +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. + +--- + +## 5. Re-render Optimization + +**Impact: MEDIUM** + +Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness. + +### 5.1 Calculate Derived State During Rendering + +**Impact: MEDIUM (avoids redundant renders and state drift)** + +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

{fullName}

+} +``` + +**Correct: derive during render** + +```tsx +function Form() { + const [firstName, setFirstName] = useState('First') + const [lastName, setLastName] = useState('Last') + const fullName = firstName + ' ' + lastName + + return

{fullName}

+} +``` + +Reference: [https://react.dev/learn/you-might-not-need-an-effect](https://react.dev/learn/you-might-not-need-an-effect) + +### 5.2 Defer State Reads to Usage Point + +**Impact: MEDIUM (avoids unnecessary subscriptions)** + +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 +} +``` + +**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 +} +``` + +### 5.3 Do not wrap a simple expression with a primitive result type in useMemo + +**Impact: LOW-MEDIUM (wasted computation on every render)** + +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 + // return some markup +} +``` + +**Correct:** + +```tsx +function Header({ user, notifications }: Props) { + const isLoading = user.isLoading || notifications.isLoading + + if (isLoading) return + // return some markup +} +``` + +### 5.4 Extract Default Non-primitive Parameter Value from Memoized Component to Constant + +**Impact: MEDIUM (restores memoization by using a constant for default value)** + +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 + +``` + +**Correct: stable default value** + +```tsx +const NOOP = () => {}; + +const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) { + // ... +}) + +// Used without optional onClick + +``` + +### 5.5 Extract to Memoized Components + +**Impact: MEDIUM (enables early returns)** + +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 + }, [user]) + + if (loading) return + return
{avatar}
+} +``` + +**Correct: skips computation when loading** + +```tsx +const UserAvatar = memo(function UserAvatar({ user }: { user: User }) { + const id = useMemo(() => computeAvatarId(user), [user]) + return +}) + +function Profile({ user, loading }: Props) { + if (loading) return + return ( +
+ +
+ ) +} +``` + +**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. + +### 5.6 Narrow Effect Dependencies + +**Impact: LOW (minimizes effect re-runs)** + +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]) +``` + +### 5.7 Put Interaction Logic in Event Handlers + +**Impact: MEDIUM (avoids effect re-runs and duplicate side effects)** + +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 +} +``` + +**Correct: do it in the handler** + +```tsx +function Form() { + const theme = useContext(ThemeContext) + + function handleSubmit() { + post('/api/register') + showToast('Registered', theme) + } + + return +} +``` + +Reference: [https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler) + +### 5.8 Subscribe to Derived State + +**Impact: MEDIUM (reduces re-render frequency)** + +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