/ opencodehub / src / components / pulls / AIReviewSummary.tsx
swadhinbiswas feat: implement air-gapped mode, UI fixes, and project management integrations · 7/9/2026
e3bd4a1
229 lines · 9.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229

import React, { useEffect, useState } from "react";
import {
    AlertTriangle,
    CheckCircle,
    Info,
    XCircle,
    Sparkles,
    ChevronDown,
    ChevronUp,
    FileCode,
    Check,
    Loader2,
    Wand2
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";

interface Suggestion {
    id: string;
    path: string;
    line?: number;
    severity: "info" | "warning" | "error" | "critical";
    type: string;
    title: string;
    message: string;
    suggestedFix?: string;
    isDismissed: boolean;
    isApplied?: boolean;
}

interface Review {
    id: string;
    status: string;
    summary: string;
    overallSeverity: "info" | "warning" | "error" | "critical";
    updatedAt: string;
}

interface AIReviewSummaryProps {
    owner: string;
    repo: string;
    prNumber: number;
}

export function AIReviewSummary({ owner, repo, prNumber }: AIReviewSummaryProps) {
    const [review, setReview] = useState<Review | null>(null);
    const [suggestions, setSuggestions] = useState<Suggestion[]>([]);
    const [loading, setLoading] = useState(true);
    const [expanded, setExpanded] = useState(true);
    const [applyingIds, setApplyingIds] = useState<Set<string>>(new Set());

    const handleApply = async (suggestionId: string) => {
        if (!confirm("Are you sure you want to apply this AI suggestion?")) return;

        setApplyingIds(prev => new Set(prev).add(suggestionId));
        try {
            const res = await fetch(`/api/repos/${owner}/${repo}/pulls/${prNumber}/ai-suggestions/${suggestionId}/apply`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    commitMessage: "Apply AI code patch"
                })
            });

            if (!res.ok) {
                const data = await res.json();
                throw new Error(data.message || data.error || "Failed to apply AI suggestion");
            }

            toast.success("AI code patch applied successfully!");
            // Mark locally as applied
            setSuggestions(prev => prev.map(s => 
                s.id === suggestionId ? { ...s, isDismissed: false, isApplied: true } as any : s
            ));
            
            // Reload to show changes after a brief delay
            setTimeout(() => window.location.reload(), 1000);
        } catch (e: any) {
            toast.error(e.message);
        } finally {
            setApplyingIds(prev => {
                const next = new Set(prev);
                next.delete(suggestionId);
                return next;
            });
        }
    };

    const fetchReview = async () => {
        try {
            const res = await fetch(`/api/repos/${owner}/${repo}/pulls/${prNumber}/ai-review`);
            if (res.ok) {
                const data = await res.json();
                if (data) {
                    setReview(data.review);
                    setSuggestions(data.suggestions || []);
                }
            }
        } catch (e) {
            console.error("Failed to fetch AI review", e);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchReview();
        // Poll every 5s if status is running
        const interval = setInterval(() => {
            if (review?.status === 'running' || review?.status === 'pending') {
                fetchReview();
            }
        }, 5000);
        return () => clearInterval(interval);
    }, [review?.status]);

    if (loading && !review) return null;
    if (!review && !loading) return null; // No review yet

    const severityColor = {
        info: "text-blue-500 border-blue-200 bg-blue-50",
        warning: "text-yellow-600 border-yellow-200 bg-yellow-50",
        error: "text-red-600 border-red-200 bg-red-50",
        critical: "text-red-700 border-red-400 bg-red-100",
    };

    const StatusIcon = {
        info: Info,
        warning: AlertTriangle,
        error: XCircle,
        critical: AlertTriangle
    }[review!.overallSeverity] || Info;

    return (
        <div className="border rounded-lg mb-6 overflow-hidden bg-card">
            <div className="p-4 border-b flex items-center justify-between bg-muted/20">
                <div className="flex items-center gap-3">
                    <div className={`p-2 rounded-full ${severityColor[review!.overallSeverity].split(' ')[2]}`}>
                        {review?.status === 'running' ? (
                            <Sparkles className="h-5 w-5 text-purple-500 animate-pulse" />
                        ) : (
                            <StatusIcon className={`h-5 w-5 ${severityColor[review!.overallSeverity].split(' ')[0]}`} />
                        )}
                    </div>
                    <div>
                        <h3 className="font-semibold flex items-center gap-2">
                            AI Code Review
                            {review?.status === 'running' && <Badge variant="outline" className="animate-pulse">Analyzing...</Badge>}
                        </h3>
                        <p className="text-xs text-muted-foreground">
                            {review?.status === 'completed'
                                ? `Completed ${new Date(review.updatedAt).toLocaleString()}`
                                : "Analysis in progress..."}
                        </p>
                    </div>
                </div>
                <Button variant="ghost" size="sm" onClick={() => setExpanded(!expanded)}>
                    {expanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
                </Button>
            </div>

            {expanded && (
                <div className="p-4 space-y-4">
                    {/* Summary */}
                    {review?.summary && (
                        <div className="text-sm prose dark:prose-invert max-w-none bg-muted/50 p-3 rounded">
                            {review.summary}
                        </div>
                    )}

                    {/* Suggestions */}
                    <div className="space-y-3">
                        {suggestions.map(suggestion => (
                            <div key={suggestion.id} className={`border rounded p-3 text-sm ${severityColor[suggestion.severity].split(' ')[2]}`}>
                                <div className="flex items-start gap-2 mb-2">
                                    <Badge variant="outline" className="uppercase text-[10px] tracking-wider bg-background">
                                        {suggestion.severity}
                                    </Badge>
                                    <span className="font-medium text-foreground">{suggestion.title}</span>
                                </div>

                                <p className="text-muted-foreground mb-2">{suggestion.message}</p>

                                <div className="flex items-center gap-2 text-xs text-muted-foreground font-mono bg-background/50 p-1 rounded w-fit mb-2">
                                    <FileCode className="h-3 w-3" />
                                    {suggestion.path}
                                    {suggestion.line && <span className="bg-muted px-1 rounded">L{suggestion.line}</span>}
                                </div>

                                {suggestion.suggestedFix && (
                                    <div className="mt-2 border border-slate-800 rounded overflow-hidden">
                                        <div className="bg-slate-900 px-3 py-2 text-xs font-medium flex items-center justify-between text-slate-200">
                                            <span className="flex items-center gap-1.5"><Wand2 className="h-3.5 w-3.5 text-purple-400" /> Suggested AI Patch</span>
                                            <div className="flex items-center gap-2">
                                                {suggestion.isApplied ? (
                                                    <span className="flex items-center gap-1 text-green-400 bg-green-500/10 px-2 py-0.5 rounded border border-green-500/20">
                                                        <Check className="h-3 w-3" />
                                                        Applied
                                                    </span>
                                                ) : (
                                                    <Button
                                                        size="sm"
                                                        variant="secondary"
                                                        className="h-6 text-[10px] px-2"
                                                        onClick={() => handleApply(suggestion.id)}
                                                        disabled={applyingIds.has(suggestion.id)}
                                                    >
                                                        {applyingIds.has(suggestion.id) ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : <Check className="h-3 w-3 mr-1" />}
                                                        1-Click Apply
                                                    </Button>
                                                )}
                                            </div>
                                        </div>
                                        <div className="bg-slate-950 text-slate-50 p-3 font-mono text-[11px] overflow-x-auto m-0 leading-relaxed">
                                            <pre>{suggestion.suggestedFix}</pre>
                                        </div>
                                    </div>
                                )}
                            </div>
                        ))}
                    </div>
                </div>
            )}
        </div>
    );
}