FelixNg1022/cf_ai_code_review
Acerca de
AI-powered code review application built on Cloudflare Workers
Herramientas de desarrolloWhat you can do
- AI-Powered Code Review: Uses Llama 3.3 70B (via Cloudflare Workers AI) to analyze code across multiple dimensions
- Comprehensive Feedback: Reviews security, performance, code quality, best practices, and potential bugs
- Multi-Language Support: Supports 12 programming languages (JavaScript, TypeScript, Python, Java, Go, Rust, C++, C, PHP, Ruby, Swift, Kotlin)
- Conversation Memory: Maintains review history and allows follow-up questions using Durable Objects
Crecimiento de estrellas medido
- in 24h
- 0
- in 7 days
- +5
- in 15 days
- +11
- in 1 month
- Recopilando historial
Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.
README.md
OriginalAI Code Review Assistant
An AI-powered code review application built on Cloudflare Workers, featuring real-time code analysis, detailed feedback, and conversation history.
🌐 Live Demo
Try it now: https://cf-ai-code-review-frontend.pages.dev
| Component | URL |
|---|---|
| Frontend | https://cf-ai-code-review-frontend.pages.dev |
| Backend API | https://cf-ai-code-review.wuchuoxi.workers.dev |
📖 Table of Contents
- Live Demo
- Features
- Requirements
- Setup Instructions
- Project Structure
- Usage
- Components
- Testing
- API Endpoints
- Troubleshooting
- Architecture & Improvements
- Technologies Used
- Documentation
🚀 Features
Core Features
- AI-Powered Code Review: Uses Llama 3.3 70B (via Cloudflare Workers AI) to analyze code across multiple dimensions
- Comprehensive Feedback: Reviews security, performance, code quality, best practices, and potential bugs
- Multi-Language Support: Supports 12 programming languages (JavaScript, TypeScript, Python, Java, Go, Rust, C++, C, PHP, Ruby, Swift, Kotlin)
- Conversation Memory: Maintains review history and allows follow-up questions using Durable Objects
- Export Functionality: Export reviews as Markdown or JSON
- Search & Filter: Search review history by code, language, summary, or score
- Caching: In-memory caching for instant repeated reviews
New Features
- Diff Review: Review unified diffs with file-by-file analysis and line-specific feedback
- GitHub PR Integration: Review pull requests directly from GitHub URLs with automatic diff extraction
- GitHub Authentication: OAuth 2.0 authentication for accessing private repositories
- Review Sharing: Generate shareable links for code reviews (30-day expiration)
- Analytics Dashboard: Track review statistics, score trends, category breakdowns, and language usage
- Dark/Light Theme: System-aware theme switching with smooth transitions
- Multi-Mode Interface: Switch between Code, Diff, and GitHub PR review modes
- User Management: User profiles, session linking, and authentication state management
UI/UX
- Modern UI: Built with React, Tailwind CSS, and shadcn/ui components with React Bits-inspired animations
- Real-time Analysis: Fast, responsive code review with detailed categorization
- Enhanced Animations: Scroll-triggered reveals, floating effects, skeleton loaders, and smooth micro-interactions
- Responsive Design: Mobile-friendly layouts and adaptive components
📋 Requirements
- Node.js 18+ and npm
- Cloudflare account with Workers AI enabled
- Wrangler CLI installed globally or locally
🛠️ Setup Instructions
1. Install Dependencies
From the project root:
npm install
cd frontend && npm install
2. Cloudflare Configuration
Login to Cloudflare:
npx wrangler loginUpdate
wrangler.toml:- Ensure your Cloudflare account ID is set (optional, can be auto-detected)
- The Durable Objects binding is already configured
Deploy Durable Objects (first time only):
npx wrangler deploy
3. Environment Variables
Create a .dev.vars file in the root directory (for local development):
# Optional: Add any environment variables here
ENVIRONMENT=development
# GitHub OAuth (optional, for GitHub PR reviews and authentication)
GITHUB_CLIENT_ID=your_github_client_id
GITHUB_CLIENT_SECRET=your_github_client_secret
AUTH_SECRET=your_random_secret_key_for_jwt_signing
# Optional: GitHub token for public PR reviews (fallback if user not authenticated)
GITHUB_TOKEN=your_github_personal_access_token
Setting up GitHub OAuth:
- Go to GitHub Settings → Developer settings → OAuth Apps
- Create a new OAuth App
- Set Authorization callback URL to:
- Development:
http://localhost:8787/api/auth/github/callback - Production:
https://cf-ai-code-review.wuchuoxi.workers.dev/api/auth/github/callback
- Development:
- Copy Client ID and Client Secret to
.dev.vars(dev) or usewrangler secret put(production) - Generate a random secret for
AUTH_SECRET(e.g., usingopenssl rand -base64 32)
4. Run Locally
Option A: Run Frontend and Worker Separately
Terminal 1 - Frontend:
cd frontend
npm run dev
Frontend will run on http://localhost:5173
Terminal 2 - Worker:
npx wrangler dev
Worker will run on http://localhost:8787
Update Frontend API URL:
Create frontend/.env.local:
VITE_API_URL=http://localhost:8787
Option B: Run Both Together (from root)
npm run dev
This uses concurrently to run both frontend and worker.
5. Build for Production
# Build frontend
cd frontend && npm run build
# Deploy worker
npx wrangler deploy
6. Deploy to Cloudflare
The application is deployed to Cloudflare with the following URLs:
- Frontend: https://cf-ai-code-review-frontend.pages.dev
- Backend: https://cf-ai-code-review.wuchuoxi.workers.dev
Deploy the Worker (Backend)
# Build and deploy
npm run build
npx wrangler deploy
Deploy the Frontend (Cloudflare Pages)
# Build with production API URL
cd frontend
VITE_API_URL=https://cf-ai-code-review.wuchuoxi.workers.dev npm run build
cd ..
# Deploy to Pages
npx wrangler pages deploy frontend/dist --project-name cf-ai-code-review-frontend
Set Production Secrets
npx wrangler secret put GITHUB_CLIENT_ID
npx wrangler secret put GITHUB_CLIENT_SECRET
npx wrangler secret put AUTH_SECRET
GitHub OAuth Configuration
For production, configure your GitHub OAuth App with:
- Homepage URL:
https://cf-ai-code-review-frontend.pages.dev - Authorization callback URL:
https://cf-ai-code-review.wuchuoxi.workers.dev/api/auth/github/callback
📁 Project Structure
cf_ai_code_review/
├── frontend/ # React + Vite frontend
│ ├── src/
│ │ ├── components/ # React components
│ │ │ ├── ui/ # shadcn/ui components
│ │ │ ├── analytics/ # Analytics components
│ │ │ │ ├── StatCard.tsx
│ │ │ │ ├── ScoreChart.tsx
│ │ │ │ └── CategoryBreakdown.tsx
│ │ │ ├── CodeInput.tsx
│ │ │ ├── ReviewDisplay.tsx
│ │ │ ├── DiffInput.tsx
│ │ │ ├── DiffViewer.tsx
│ │ │ ├── DiffReviewDisplay.tsx
│ │ │ ├── GitHubPRInput.tsx
│ │ │ ├── AnalyticsDashboard.tsx
│ │ │ ├── ShareButton.tsx
│ │ │ ├── SharedReviewPage.tsx
│ │ │ ├── LoginButton.tsx
│ │ │ ├── UserMenu.tsx
│ │ │ ├── ThemeToggle.tsx
│ │ │ ├── ConversationHistory.tsx
│ │ │ ├── FollowUpInput.tsx
│ │ │ ├── ScoreCounter.tsx
│ │ │ ├── SkeletonLoader.tsx
│ │ │ ├── BackgroundGrid.tsx
│ │ │ └── TextReveal.tsx
│ │ ├── context/ # React contexts
│ │ │ └── AuthContext.tsx
│ │ ├── hooks/ # Custom React hooks
│ │ │ ├── useScrollReveal.ts
│ │ │ ├── useAuth.ts
│ │ │ ├── useTheme.ts
│ │ │ └── useAnalytics.ts
│ │ ├── lib/ # Utilities
│ │ │ ├── api.ts # API client
│ │ │ ├── cache.ts # Review caching
│ │ │ └── export.ts # Export functionality
│ │ ├── types/ # TypeScript types
│ │ ├── App.tsx # Main app component
│ │ └── main.tsx # Entry point
├── src/
│ └── worker/ # Cloudflare Worker
│ ├── index.ts # Main entry point
│ ├── routes.ts # API route handlers
│ ├── llm.ts # LLM integration (code review)
│ ├── llm-diff.ts # LLM integration (diff review)
│ ├── diff.ts # Diff parsing utilities
│ ├── github.ts # GitHub API integration
│ ├── auth.ts # Authentication utilities
│ ├── auth-routes.ts # Authentication routes
│ ├── share.ts # Review sharing utilities
│ ├── analytics.ts # Analytics calculations
│ ├── durable-object.ts # Session Durable Object
│ ├── user-durable-object.ts # User Durable Object
│ ├── config.ts # Configuration management
│ ├── errors.ts # Custom error classes
│ ├── validation.ts # Input validation
│ ├── cors.ts # CORS handling
│ └── types.ts # TypeScript types
├── wrangler.toml # Cloudflare configuration
├── package.json
├── README.md # This file
└── PROMPTS.md # AI prompts documentation
🎯 Usage
Quick Start
Start the application:
npm run devOpen the frontend in your browser:
http://localhost:5173Try out the components:
LLM (Workers AI):
- Submit code for review to see Llama 3.3 70B analyze your code
- Try the test code below to see security vulnerability detection
User Input (Pages/Frontend):
- Paste code in the text area
- Select programming language
- Click "Review Code" to submit
Memory/State (Durable Objects):
- All reviews are automatically saved
- View review history in the sidebar
- Click any review to view it again
- Follow-up questions maintain conversation context
Workflow/Coordination (Workers + Durable Objects):
- Worker coordinates between AI, storage, and frontend
- Durable Objects manage session state and review history
- Request timeouts and error handling ensure reliability
Example: Submit Code for Review
Paste this test code:
function login(username, password) { const query = `SELECT * FROM users WHERE username='${username}' AND password='${password}'`; return db.query(query); }Select "Javascript" from the language dropdown
Click "Review Code"
View results:
- Review score (1-10)
- Categorized feedback (Security, Performance, Quality, Best Practices, Bugs)
- Detailed suggestions with code examples
Try follow-up questions:
- Scroll to "Ask a Follow-up Question"
- Ask: "Can you explain the SQL injection vulnerability?"
- Get detailed explanations
Explore features:
- Export reviews (MD or JSON buttons)
- Search review history
- Submit same code twice to see caching in action
- Share reviews with shareable links
- View analytics dashboard
- Switch between Code, Diff, and GitHub PR modes
- Toggle dark/light theme
🔧 Components
Frontend Components
Core Review Components:
- CodeInput: Code input area with language selection
- DiffInput: Unified diff input with file upload support
- GitHubPRInput: GitHub PR URL input with authenticated user PR selector
- ReviewDisplay: Displays review results in categorized tabs
- DiffReviewDisplay: File-by-file diff review results
- DiffViewer: Visual diff display with syntax highlighting
- ConversationHistory: Sidebar showing all past reviews
- FollowUpInput: Input for asking follow-up questions
Feature Components:
- AnalyticsDashboard: Review statistics and trends
- ShareButton: Generate and copy shareable review links
- SharedReviewPage: Public view for shared reviews
- LoginButton: GitHub OAuth authentication
- UserMenu: User profile and logout menu
- ThemeToggle: Light/dark mode switcher
UI Components:
- SkeletonLoader: Loading state placeholders
- BackgroundGrid: Animated background effects
- TextReveal: Scroll-triggered text animations
- ScoreCounter: Animated score display
Backend Components
- Worker (index.ts): Main API gateway
- Routes: Handles all API endpoints (review, diff, PR, auth, share, analytics)
- LLM Integration: Interfaces with Llama 3.3 via Workers AI
llm.ts: Code review promptsllm-diff.ts: Diff review prompts
- Durable Objects:
durable-object.ts: Session state and review historyuser-durable-object.ts: User profiles and tokens
- GitHub Integration:
github.ts- PR fetching, user PRs, comment posting - Authentication:
auth.ts- OAuth flow, JWT tokens, user management - Sharing:
share.ts- Short ID generation, KV storage - Analytics:
analytics.ts- Statistics calculation - Diff Parsing:
diff.ts- Unified diff parser
🧪 Testing
Quick Test
Try this sample JavaScript code:
function login(username, password) {
const query = `SELECT * FROM users WHERE username='${username}' AND password='${password}'`;
return db.query(query);
}
The AI should identify:
- SQL injection vulnerability (Security)
- Missing input validation (Best Practices)
- Plain text password storage (Security)
Comprehensive Testing
Test the following features:
- Code Review: Export functionality (Markdown and JSON), follow-up questions, search/filter in review history, caching (submit same code twice), multiple programming languages
- Diff Review: Upload a .diff file, paste a unified diff, review with context
- GitHub PR Review: Review a public PR, authenticate and review private PRs, select from your open PRs
- Sharing: Share a review and access it via the shareable link
- Analytics: View dashboard with statistics, score trends, and category breakdowns
- Authentication: Sign in with GitHub, access private repos, logout
- Theme: Toggle between light and dark modes
📝 API Endpoints
Code Review
POST /api/review
Submit code for review.
Request:
{
"code": "function test() { return true; }",
"language": "javascript",
"sessionId": "optional-session-id"
}
Response:
{
"review": {
"score": 8,
"summary": "...",
"categories": { ... }
},
"sessionId": "uuid"
}
GET /api/session/:sessionId
Get review history for a session.
Response:
{
"reviews": [...]
}
POST /api/session/:sessionId/followup
Ask a follow-up question.
Request:
{
"question": "Can you explain the security issue?",
"reviewId": "review-uuid"
}
Response:
{
"answer": "..."
}
Diff Review
POST /api/diff/review
Review a unified diff.
Request:
{
"diff": "diff --git a/file.js b/file.js\n...",
"context": "optional context",
"sessionId": "optional-session-id"
}
Response:
{
"review": {
"score": 7,
"summary": "...",
"fileReviews": [...],
"overallSuggestions": [...]
},
"parsedDiff": { ... },
"sessionId": "uuid"
}
GitHub PR Review
POST /api/github/pr/review
Review a GitHub pull request.
Request:
{
"prUrl": "https://github.com/owner/repo/pull/123",
"sessionId": "optional-session-id"
}
Response:
{
"review": { ... },
"parsedDiff": { ... },
"prInfo": {
"title": "...",
"author": "...",
"baseBranch": "...",
"headBranch": "...",
"additions": 100,
"deletions": 50,
"changedFiles": 5
},
"sessionId": "uuid"
}
GET /api/github/user/pulls
Get authenticated user's open pull requests.
Response:
{
"pulls": [...],
"totalCount": 10
}
POST /api/github/pr/comment
Post a comment to a GitHub PR.
Request:
{
"prUrl": "https://github.com/owner/repo/pull/123",
"comment": "Review comment text"
}
Response:
{
"success": true,
"commentUrl": "https://github.com/...",
"commentId": 123456
}
Authentication
GET /api/auth/github
Initiate GitHub OAuth flow.
Query Parameters:
redirectUrl: Frontend redirect URL after authsessionId: Optional session ID to link
Response: Redirects to GitHub OAuth
GET /api/auth/callback
OAuth callback endpoint (handled by GitHub redirect).
GET /api/auth/me
Get current authenticated user.
Response:
{
"user": {
"id": "github:123",
"githubLogin": "username",
"displayName": "User Name",
"avatarUrl": "...",
"email": "..."
}
}
POST /api/auth/logout
Logout current user.
Response:
{
"success": true
}
Sharing
POST /api/share
Create a shareable link for a review.
Request:
{
"reviewId": "review-uuid",
"sessionId": "session-uuid"
}
Response:
{
"shortId": "abc123",
"shareUrl": "https://..."
}
GET /api/shared/:shortId
Get a shared review by short ID.
Response:
{
"shortId": "abc123",
"sessionId": "...",
"reviewId": "...",
"codeReview": { ... },
"createdAt": "...",
"expiresAt": "..."
}
Analytics
GET /api/analytics
Get analytics data for a session.
Query Parameters:
sessionId: Session ID
Response:
{
"totalReviews": 10,
"averageScore": 7.5,
"scoreDistribution": { ... },
"categoryBreakdown": { ... },
"languageStats": { ... },
"reviewsOverTime": [ ... ]
}
🚨 Troubleshooting
Worker not starting
- Ensure you're logged in:
npx wrangler login - Check
wrangler.tomlconfiguration - Verify Workers AI is enabled in your Cloudflare account
Frontend can't connect to API
- Check
VITE_API_URLinfrontend/.env.local - Ensure worker is running on the correct port
- Check CORS headers in worker responses
LLM errors
- Verify Workers AI is enabled in your Cloudflare account
- Check API rate limits
- Review worker logs:
npx wrangler tail
Durable Objects errors
- Ensure Durable Objects are deployed:
npx wrangler deploy - Check binding name matches in
wrangler.toml
🏗️ Architecture & Improvements
Key Improvements Implemented
- Security: Configurable CORS, input validation, request timeouts
- Type Safety: Full TypeScript with proper interfaces (no
anytypes) - Error Handling: Custom error classes with user-friendly messages
- Performance: In-memory caching, optimized data storage, request timeouts
- User Experience: Export functionality, search/filter, better error messages
- Configuration: Environment-aware configuration management
Architecture
- Frontend: React 19 + TypeScript + Vite + Tailwind CSS + shadcn/ui
- UI Enhancements: React Bits-inspired animations (scroll reveals, skeleton loaders, background effects)
- Backend: Cloudflare Workers + Durable Objects + KV Storage
- AI: Llama 3.3 70B via Cloudflare Workers AI (
@cf/meta/llama-3.3-70b-instruct-fp8-fast) - Storage:
- Durable Objects for session persistence (30-day TTL, max 50 reviews per session)
- Durable Objects for user data and authentication tokens
- KV Storage for OAuth state (10-minute TTL) and shared reviews (30-day TTL)
- Caching: In-memory cache (1-hour TTL, max 50 entries)
- Authentication: GitHub OAuth 2.0 with JWT tokens stored in HttpOnly cookies
- External APIs: GitHub API for PR fetching and commenting
📚 Documentation
- README.md - Complete project documentation with setup and running instructions
- PROMPTS.md - All AI prompts used in the application (required for assessment submission)
✅ Assessment Requirements Checklist
This project meets all Cloudflare AI assignment requirements:
- ✅ LLM: Uses Llama 3.3 70B via Cloudflare Workers AI
- ✅ Workflow/Coordination: Cloudflare Workers + Durable Objects for state management
- ✅ User Input: React frontend (Cloudflare Pages compatible) with code input interface
- ✅ Memory/State: Durable Objects for session persistence and review history
- ✅ Repository Name: Prefixed with
cf_ai_(cf_ai_code_review) - ✅ README.md: Includes project documentation and clear running instructions
- ✅ PROMPTS.md: Documents all AI prompts used in the application
📚 Additional Resources
- Cloudflare Workers Documentation
- Workers AI Documentation
- Durable Objects Documentation
- shadcn/ui Documentation
📄 License
MIT License
🙏 Acknowledgments
- Built with Cloudflare Workers
- UI components from shadcn/ui
- AI powered by Llama 3.3 via Cloudflare Workers AI
Explorar proyectos relacionados
Cargando…