Skip to content

AI-powered code review application built on Cloudflare Workers

Notifications You must be signed in to change notification settings

FelixNg1022/cf_ai_code_review

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

AI 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

πŸš€ 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

  1. Login to Cloudflare:

    npx wrangler login
  2. Update wrangler.toml:

    • Ensure your Cloudflare account ID is set (optional, can be auto-detected)
    • The Durable Objects binding is already configured
  3. 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:

  1. Go to GitHub Settings β†’ Developer settings β†’ OAuth Apps
  2. Create a new OAuth App
  3. 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
  4. Copy Client ID and Client Secret to .dev.vars (dev) or use wrangler secret put (production)
  5. Generate a random secret for AUTH_SECRET (e.g., using openssl 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:

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

  1. Start the application:

    npm run dev
  2. Open the frontend in your browser: http://localhost:5173

  3. Try 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

  1. Paste this test code:

    function login(username, password) {
      const query = `SELECT * FROM users WHERE username='${username}' AND password='${password}'`;
      return db.query(query);
    }
  2. Select "Javascript" from the language dropdown

  3. Click "Review Code"

  4. View results:

    • Review score (1-10)
    • Categorized feedback (Security, Performance, Quality, Best Practices, Bugs)
    • Detailed suggestions with code examples
  5. Try follow-up questions:

    • Scroll to "Ask a Follow-up Question"
    • Ask: "Can you explain the SQL injection vulnerability?"
    • Get detailed explanations
  6. 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 prompts
    • llm-diff.ts: Diff review prompts
  • Durable Objects:
    • durable-object.ts: Session state and review history
    • user-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 auth
  • sessionId: 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.toml configuration
  • Verify Workers AI is enabled in your Cloudflare account

Frontend can't connect to API

  • Check VITE_API_URL in frontend/.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 any types)
  • 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

πŸ“„ License

MIT License

πŸ™ Acknowledgments

About

AI-powered code review application built on Cloudflare Workers

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published