diff --git a/.codex/agents/browser-check.toml b/.codex/agents/browser-check.toml new file mode 100644 index 00000000..e7d843f6 --- /dev/null +++ b/.codex/agents/browser-check.toml @@ -0,0 +1,9 @@ +model = "gpt-5.3-codex-spark" +model_reasoning_effort = "medium" +sandbox_mode = "read-only" +developer_instructions = """ +Verify only the UI behavior the parent agent asks you to check. +Use playwright-cli against the running local app at http://5chan.localhost:1355 unless the parent agent gives a different URL. +Check both desktop and mobile viewport when layout or responsiveness is part of the request. +Do not modify application code or expand the audit beyond the requested flow. +""" diff --git a/.codex/agents/code-quality.toml b/.codex/agents/code-quality.toml new file mode 100644 index 00000000..9398f9b9 --- /dev/null +++ b/.codex/agents/code-quality.toml @@ -0,0 +1,7 @@ +model = "gpt-5.3-codex-spark" +model_reasoning_effort = "medium" +developer_instructions = """ +Run the repo's required verification commands and fix only issues surfaced by those checks. +Prioritize failures in this order: build, type-check, lint. +Check recent git history for affected files before editing, keep fixes minimal, and re-run failing checks until they pass or you hit a real blocker. +""" diff --git a/.codex/agents/plan-implementer.toml b/.codex/agents/plan-implementer.toml new file mode 100644 index 00000000..19b9697b --- /dev/null +++ b/.codex/agents/plan-implementer.toml @@ -0,0 +1,7 @@ +model = "gpt-5.3-codex-spark" +model_reasoning_effort = "medium" +developer_instructions = """ +Implement only the concrete task or task slice assigned by the parent agent. +Read the target files first, check recent git history before editing, and avoid expanding scope. +Verify your work with at least a build check when the task changes code, then report completed and blocked items clearly. +""" diff --git a/.codex/agents/profiler.toml b/.codex/agents/profiler.toml new file mode 100644 index 00000000..e50a63e5 --- /dev/null +++ b/.codex/agents/profiler.toml @@ -0,0 +1,9 @@ +model = "gpt-5.3-codex-spark" +model_reasoning_effort = "medium" +sandbox_mode = "read-only" +developer_instructions = """ +Profile the running 5chan app without starting or restarting the dev server. +Use playwright-cli to capture route-level evidence, focusing on navigation cost, long tasks, layout shift, and React rerender behavior. +Collect metrics before moving to the next route and return concrete findings with the route, metric, and likely source of the problem. +Do not modify application code. +""" diff --git a/.codex/agents/react-doctor-fixer.toml b/.codex/agents/react-doctor-fixer.toml new file mode 100644 index 00000000..8c8c609f --- /dev/null +++ b/.codex/agents/react-doctor-fixer.toml @@ -0,0 +1,7 @@ +model = "gpt-5.3-codex-spark" +model_reasoning_effort = "medium" +developer_instructions = """ +Only act when the parent agent provides both the exact React Doctor diagnostic and a concrete fix plan. +Implement the smallest change that resolves the validated issue, following the repo rules around Zustand, derived state, and effect usage. +Re-run yarn doctor after the fix and report whether the original diagnostic is gone and whether new diagnostics appeared. +""" diff --git a/.codex/agents/react-patterns-enforcer.toml b/.codex/agents/react-patterns-enforcer.toml new file mode 100644 index 00000000..6b923490 --- /dev/null +++ b/.codex/agents/react-patterns-enforcer.toml @@ -0,0 +1,7 @@ +model = "gpt-5.3-codex-spark" +model_reasoning_effort = "medium" +developer_instructions = """ +Review recently changed React files for the repo's critical architecture rules. +Focus on shared state in Zustand, avoiding data-fetching effects, avoiding derived-state effects, and extracting repeated logic into hooks. +Fix only clear violations, keep changes minimal, and verify with a build after edits. +""" diff --git a/.codex/agents/test-apk.toml b/.codex/agents/test-apk.toml new file mode 100644 index 00000000..8f7532e5 --- /dev/null +++ b/.codex/agents/test-apk.toml @@ -0,0 +1,7 @@ +model = "gpt-5.3-codex-spark" +model_reasoning_effort = "medium" +developer_instructions = """ +Test the Android app on the local emulator, leaving the emulator running when you finish. +Build and install only when needed, capture focused diagnostics, and report results in terms of emulator status, build, install, tests, logcat evidence, diagnosis, and artifacts. +Prioritize upload automation failures, WebView behavior, and actionable root-cause evidence over broad exploratory testing. +""" diff --git a/.codex/agents/translator.toml b/.codex/agents/translator.toml new file mode 100644 index 00000000..ad5d6e2a --- /dev/null +++ b/.codex/agents/translator.toml @@ -0,0 +1,7 @@ +model = "gpt-5.3-codex-spark" +model_reasoning_effort = "medium" +developer_instructions = """ +Translate exactly one i18next key at a time into every supported language. +Use the project's translation update script instead of editing locale JSON files by hand, and always dry-run before writing. +Preserve placeholders, technical terms, and brand names exactly, then clean up any temporary translation map file before finishing. +""" diff --git a/.codex/config.toml b/.codex/config.toml new file mode 100644 index 00000000..fb4d700e --- /dev/null +++ b/.codex/config.toml @@ -0,0 +1,35 @@ +[agents] +max_threads = 8 +max_depth = 1 + +[agents.browser-check] +description = "Browser verification agent for UI changes using playwright-cli on the local 5chan app." +config_file = "agents/browser-check.toml" + +[agents.code-quality] +description = "Code quality agent that runs build, lint, and type-check, then fixes only issues surfaced by those checks." +config_file = "agents/code-quality.toml" + +[agents.plan-implementer] +description = "Implementation-focused agent for scoped tasks from a parent plan." +config_file = "agents/plan-implementer.toml" + +[agents.profiler] +description = "Performance profiling agent that inspects 5chan routes with playwright-cli and react-scan evidence." +config_file = "agents/profiler.toml" + +[agents.react-doctor-fixer] +description = "React Doctor remediation agent for a validated diagnostic plus an explicit fix plan." +config_file = "agents/react-doctor-fixer.toml" + +[agents.react-patterns-enforcer] +description = "React architecture reviewer that fixes repo-specific anti-patterns after UI logic changes." +config_file = "agents/react-patterns-enforcer.toml" + +[agents.test-apk] +description = "Android emulator and APK testing agent for 5chan mobile workflows." +config_file = "agents/test-apk.toml" + +[agents.translator] +description = "Single-key i18next translation agent that updates all supported languages through the project script." +config_file = "agents/translator.toml" diff --git a/.codex/hooks.json b/.codex/hooks.json new file mode 100644 index 00000000..fa36ec73 --- /dev/null +++ b/.codex/hooks.json @@ -0,0 +1,21 @@ +{ + "version": 1, + "hooks": { + "afterFileEdit": [ + { + "command": ".codex/hooks/format.sh", + "timeout": 10 + }, + { + "command": ".codex/hooks/yarn-install.sh", + "timeout": 120 + } + ], + "stop": [ + { + "command": ".codex/hooks/verify.sh", + "timeout": 60 + } + ] + } +} diff --git a/.codex/hooks/format.sh b/.codex/hooks/format.sh new file mode 100755 index 00000000..918b2530 --- /dev/null +++ b/.codex/hooks/format.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# afterFileEdit hook: Auto-format files after AI edits them +# Receives JSON via stdin: {"file_path": "...", "edits": [...]} + +# Read stdin (required for hooks) +input=$(cat) + +# Extract file_path using grep/sed (jq-free for portability) +file_path=$(echo "$input" | grep -o '"file_path"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/.*:.*"\([^"]*\)"/\1/') + +# Exit if no file path found +if [ -z "$file_path" ]; then + exit 0 +fi + +# Only format JS/TS files +case "$file_path" in + *.js|*.ts|*.tsx|*.mjs) + # Match the other hooks by resolving relative paths from the repo root. + cd "$(dirname "$0")/../.." || exit 0 + + # Run oxfmt on the file (silent on success) + npx oxfmt "$file_path" 2>/dev/null || true + ;; +esac + +exit 0 diff --git a/.codex/hooks/verify.sh b/.codex/hooks/verify.sh new file mode 100755 index 00000000..8ababa3c --- /dev/null +++ b/.codex/hooks/verify.sh @@ -0,0 +1,63 @@ +#!/bin/bash +# stop hook: Run build, lint, type-check, and security audit when agent finishes +# This is informational - always exits 0 + +# Consume stdin (required for hooks) +cat > /dev/null + +# Change to project directory +cd "$(dirname "$0")/../.." || exit 0 + +cleanup_generated_dir() { + local path="$1" + + if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then + return + fi + + if git ls-files --error-unmatch "$path" >/dev/null 2>&1; then + if git diff --quiet -- "$path"; then + return + fi + + echo "=== git restore --worktree $path ===" + git restore --worktree -- "$path" 2>&1 || true + echo "" + return + fi + + if [ -e "$path" ]; then + echo "=== rm -rf $path ===" + rm -rf "$path" 2>&1 || true + echo "" + fi +} + +echo "Running build, lint, type-check, and security audit..." +echo "" + +# Run build (catches compilation errors) +echo "=== yarn build ===" +yarn build 2>&1 || true +echo "" + +# Run lint +echo "=== yarn lint ===" +yarn lint 2>&1 || true +echo "" + +# Run type-check +echo "=== yarn type-check ===" +yarn type-check 2>&1 || true +echo "" + +# Run security audit +echo "=== yarn audit ===" +yarn audit 2>&1 || true +echo "" + +cleanup_generated_dir build +cleanup_generated_dir dist + +echo "Verification complete." +exit 0 diff --git a/.codex/hooks/yarn-install.sh b/.codex/hooks/yarn-install.sh new file mode 100755 index 00000000..7e917223 --- /dev/null +++ b/.codex/hooks/yarn-install.sh @@ -0,0 +1,25 @@ +#!/bin/bash +# afterFileEdit hook: Run yarn install when package.json is changed +# Receives JSON via stdin: {"file_path": "...", "edits": [...]} + +# Read stdin (required for hooks) +input=$(cat) + +# Extract file_path using grep/sed (jq-free for portability) +file_path=$(echo "$input" | grep -o '"file_path"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/.*:.*"\([^"]*\)"/\1/') + +# Exit if no file path found +if [ -z "$file_path" ]; then + exit 0 +fi + +# Only run yarn install if package.json was changed +if [ "$file_path" = "package.json" ]; then + # Change to project directory + cd "$(dirname "$0")/../.." || exit 0 + + echo "package.json changed - running yarn install to update yarn.lock..." + yarn install +fi + +exit 0 diff --git a/.codex/skills/commit-format/SKILL.md b/.codex/skills/commit-format/SKILL.md new file mode 100644 index 00000000..d07a8776 --- /dev/null +++ b/.codex/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/.codex/skills/commit/SKILL.md b/.codex/skills/commit/SKILL.md new file mode 100644 index 00000000..53895607 --- /dev/null +++ b/.codex/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/.codex/skills/context7/SKILL.md b/.codex/skills/context7/SKILL.md new file mode 100644 index 00000000..66e93c1c --- /dev/null +++ b/.codex/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/.codex/skills/deslop/SKILL.md b/.codex/skills/deslop/SKILL.md new file mode 100644 index 00000000..48c3f02e --- /dev/null +++ b/.codex/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/.codex/skills/find-skills/SKILL.md b/.codex/skills/find-skills/SKILL.md new file mode 100644 index 00000000..c797184e --- /dev/null +++ b/.codex/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/.codex/skills/fix-merge-conflicts/SKILL.md b/.codex/skills/fix-merge-conflicts/SKILL.md new file mode 100644 index 00000000..48b7939a --- /dev/null +++ b/.codex/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 `yarn install` to regenerate `yarn.lock` | +| `yarn.lock` | Never manually edit — regenerate with `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 +yarn build && yarn lint && yarn type-check +``` + +If `package.json` was modified, run `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 `yarn build && yarn lint && yarn type-check` +- One local commit: `chore: resolve merge conflicts` +- Brief summary of files touched and notable resolution choices diff --git a/.codex/skills/implement-plan/SKILL.md b/.codex/skills/implement-plan/SKILL.md new file mode 100644 index 00000000..c95942ad --- /dev/null +++ b/.codex/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/.codex/skills/issue-format/SKILL.md b/.codex/skills/issue-format/SKILL.md new file mode 100644 index 00000000..14f07aa5 --- /dev/null +++ b/.codex/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/.codex/skills/make-closed-issue/SKILL.md b/.codex/skills/make-closed-issue/SKILL.md new file mode 100644 index 00000000..8f3998ad --- /dev/null +++ b/.codex/skills/make-closed-issue/SKILL.md @@ -0,0 +1,175 @@ +--- +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) + +Ask the user using AskQuestion (multi-select): + +| Option | When | +|--------|------| +| `bug` | Bug fix | +| `enhancement` | New feature | +| `bug` + `enhancement` | New feature that also fixes a bug | +| `documentation` | README, AGENTS.md, docs-only changes | + +### 2. Ensure branch workflow is reviewable + +- If already on a short-lived task branch such as `feature/*`, `fix/*`, `docs/*`, or `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: + +- `feature/short-slug` +- `fix/short-slug` +- `docs/short-slug` +- `chore/short-slug` + +Example: + +```bash +git switch -c fix/reply-editor-stuck +``` + +### 3. 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. + +### 4. 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. + +### 5. Create the issue + +```bash +gh issue create \ + --repo bitsocialnet/5chan \ + --title "ISSUE_TITLE" \ + --body "ISSUE_DESCRIPTION" \ + --label "LABEL1,LABEL2" \ + --assignee plebe1us +``` + +Capture the issue number from the output. + +### 6. 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 + +### 7. 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/.codex/skills/playwright-cli/references/request-mocking.md b/.codex/skills/playwright-cli/references/request-mocking.md new file mode 100644 index 00000000..9005fda6 --- /dev/null +++ b/.codex/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/.codex/skills/playwright-cli/references/running-code.md b/.codex/skills/playwright-cli/references/running-code.md new file mode 100644 index 00000000..7d6d22fd --- /dev/null +++ b/.codex/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/.codex/skills/playwright-cli/references/session-management.md b/.codex/skills/playwright-cli/references/session-management.md new file mode 100644 index 00000000..08c8c90c --- /dev/null +++ b/.codex/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/.codex/skills/playwright-cli/references/storage-state.md b/.codex/skills/playwright-cli/references/storage-state.md new file mode 100644 index 00000000..c856db5e --- /dev/null +++ b/.codex/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/.codex/skills/playwright-cli/references/test-generation.md b/.codex/skills/playwright-cli/references/test-generation.md new file mode 100644 index 00000000..7a09df38 --- /dev/null +++ b/.codex/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/.codex/skills/playwright-cli/references/tracing.md b/.codex/skills/playwright-cli/references/tracing.md new file mode 100644 index 00000000..7ce7babb --- /dev/null +++ b/.codex/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/.codex/skills/playwright-cli/references/video-recording.md b/.codex/skills/playwright-cli/references/video-recording.md new file mode 100644 index 00000000..38391b37 --- /dev/null +++ b/.codex/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/.codex/skills/profile-browsing/SKILL.md b/.codex/skills/profile-browsing/SKILL.md new file mode 100644 index 00000000..dd26ce6b --- /dev/null +++ b/.codex/skills/profile-browsing/SKILL.md @@ -0,0 +1,154 @@ +--- +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 `.cursor/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 .cursor/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 | + +## 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/.codex/skills/readme/SKILL.md b/.codex/skills/readme/SKILL.md new file mode 100644 index 00000000..643d0faa --- /dev/null +++ b/.codex/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 +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 && 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. \ No newline at end of file diff --git a/.codex/skills/refactor-pass/SKILL.md b/.codex/skills/refactor-pass/SKILL.md new file mode 100644 index 00000000..70d13aaa --- /dev/null +++ b/.codex/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/.codex/skills/release-description/SKILL.md b/.codex/skills/release-description/SKILL.md new file mode 100644 index 00000000..406c57ff --- /dev/null +++ b/.codex/skills/release-description/SKILL.md @@ -0,0 +1,68 @@ +--- +name: release-description +description: Update the one-liner release description in scripts/release-body.js by analyzing commit titles since the last git tag. Use when the user asks to update the release description, release notes one-liner, or prepare release body for a new version. +--- + +# Release Description + +Update `oneLinerDescription` in `scripts/release-body.js` before each release. + +## Steps + +### 1. Find the latest release tag + +```bash +git tag --sort=-creatordate | head -1 +``` + +### 2. List commit titles since that tag + +```bash +git log --oneline ..HEAD +``` + +If there are no commits since the tag, stop — nothing to update. + +### 3. Analyze the commits + +Categorize by Conventional Commits prefix: + +| Prefix | Category | +|--------|----------| +| `feat:` | New features | +| `fix:` | Bug fixes | +| `perf:` | Performance improvements | +| `refactor:` | Refactors / internal changes | +| `chore:`, `docs:`, `ci:` | Maintenance (mention only if significant) | +| No prefix | Read the title to infer category | + +### 4. Write the one-liner + +Compose a single sentence that summarizes the release at a high level. Rules: + +- **Start with** "This version..." or "This release..." +- **Be concise** — one sentence, no bullet points +- **Highlight the most impactful changes** — lead with the biggest features or fixes +- **Group similar changes** — e.g. "several bug fixes" instead of listing each one +- **Use plain language** — this is user-facing, not developer-facing +- **Don't mention every commit** — summarize the theme + +Examples of good one-liners: +- "This version adds backlinks for quoted posts, a copy user ID menu item, and several bug fixes." +- "This version introduces mod queue improvements and performance optimizations." +- "This release adds pseudonymity mode support per-reply and fixes timezone display issues." + +### 5. Update the constant + +Edit `oneLinerDescription` in `scripts/release-body.js` (around line 104–105): + +```js +const oneLinerDescription = 'Your new one-liner here.'; +``` + +### 6. Verify + +Read the updated line back to confirm it looks right. The string should: +- Be a single sentence +- End with a period +- Not contain backticks or markdown diff --git a/.codex/skills/review-and-merge-pr/SKILL.md b/.codex/skills/review-and-merge-pr/SKILL.md new file mode 100644 index 00000000..4f837465 --- /dev/null +++ b/.codex/skills/review-and-merge-pr/SKILL.md @@ -0,0 +1,141 @@ +--- +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, and merge the PR into master when it is ready. 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 or explicitly declined with a reason. + +## 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 +- `decline`: false positives, stale comments, duplicate findings, speculative style-only suggestions, or feedback already addressed in newer commits + +Rules: + +- Never merge with unresolved `must-fix` findings. +- Do not accept a bot finding without reading the relevant code and diff. +- If a finding is ambiguous but high-risk, ask the user before merging. +- If a comment is wrong or stale, explain why in the PR rather than silently ignoring it. + +### 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 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 are stale or not applicable for the reasons checked locally." +``` + +### 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 +- 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. Clean up local state after merge + +After the PR is merged: + +```bash +git switch master +git pull --ff-only +git branch -D 2>/dev/null || true +``` + +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 +``` + +### 8. Report the outcome + +Tell the user: + +- which findings were fixed +- which findings were declined and why +- which verification commands ran +- whether the PR was merged +- whether the branch and any worktree were cleaned up diff --git a/.codex/skills/review-and-merge-pr/agents/openai.yaml b/.codex/skills/review-and-merge-pr/agents/openai.yaml new file mode 100644 index 00000000..b6f83e84 --- /dev/null +++ b/.codex/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/.codex/skills/test-apk/SKILL.md b/.codex/skills/test-apk/SKILL.md new file mode 100644 index 00000000..a4299e1f --- /dev/null +++ b/.codex/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/.codex/skills/translate/SKILL.md b/.codex/skills/translate/SKILL.md new file mode 100644 index 00000000..59baf00e --- /dev/null +++ b/.codex/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/.codex/skills/vercel-react-best-practices/AGENTS.md b/.codex/skills/vercel-react-best-practices/AGENTS.md new file mode 100644 index 00000000..e53dde10 --- /dev/null +++ b/.codex/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