Swadhin Biswas Feature/ai code reviewer (#73) · 8/2/2026
105a287
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
---
import BaseLayout from "@/layouts/BaseLayout.astro";
import { getDatabase, schema } from "@/db";
import { eq, desc } from "drizzle-orm";
import {
Zap,
Plus,
Trash2,
Edit2,
Play,
Pause,
GitPullRequest,
Tag,
Users,
MessageSquare,
CheckCircle2,
XCircle,
Clock,
ArrowRight,
Settings2,
History,
} from "lucide-react";
const user = Astro.locals.user;
if (!user) {
return Astro.redirect("/login");
}
const db = getDatabase();
const repoId = Astro.url.searchParams.get("repo") || "";
const view = Astro.url.searchParams.get("view") || "rules";
// Get user's repositories
let repositories: { id: string; name: string; fullName?: string }[] = [];
try {
const repos = await db.query.repositories.findMany({
where: eq(schema.repositories.ownerId, user.id),
columns: { id: true, name: true },
with: { owner: { columns: { username: true } } },
});
repositories = repos.map((r) => ({
id: r.id,
name: r.name,
fullName: `${r.owner.username}/${r.name}`,
}));
} catch (e) {}
// Get automation rules for selected repo
interface AutomationRule {
id: string;
name: string;
description?: string;
trigger: string;
conditions?: string;
actions: string;
isEnabled: boolean;
runCount: number;
lastRunAt?: string;
}
interface AutomationExecution {
id: string;
ruleName: string;
triggerEvent: string;
status: string;
createdAt: string;
durationMs?: number;
}
let rules: AutomationRule[] = [];
let executions: AutomationExecution[] = [];
try {
if (repoId) {
const dbRules = await db.query.automationRules.findMany({
where: eq(schema.automationRules.repositoryId, repoId),
orderBy: [desc(schema.automationRules.createdAt)],
});
rules = dbRules.map(r => ({
id: r.id,
name: r.name,
description: r.description || undefined,
trigger: r.trigger,
conditions: r.conditions || undefined,
actions: r.actions,
isEnabled: r.isEnabled ?? true,
runCount: r.runCount || 0,
lastRunAt: r.lastRunAt ? r.lastRunAt.toISOString() : undefined,
}));
// Get recent executions
if (view === "history") {
const ruleIds = rules.map(r => r.id);
if (ruleIds.length > 0) {
const dbExecutions = await db.query.automationExecutions.findMany({
orderBy: [desc(schema.automationExecutions.createdAt)],
limit: 50,
with: {
rule: true,
},
});
executions = dbExecutions
.filter(e => ruleIds.includes(e.ruleId))
.map(e => ({
id: e.id,
ruleName: e.rule?.name || "Unknown",
triggerEvent: e.triggerEvent,
status: e.status,
createdAt: e.createdAt.toISOString(),
durationMs: e.durationMs || undefined,
}));
}
}
}
} catch (e) {
console.error("Failed to fetch automation rules:", e);
}
const triggerLabels: Record<string, { label: string; icon: any; color: string }> = {
pr_opened: { label: "PR Opened", icon: GitPullRequest, color: "text-green-400" },
pr_merged: { label: "PR Merged", icon: GitPullRequest, color: "text-purple-400" },
pr_approved: { label: "PR Approved", icon: CheckCircle2, color: "text-green-400" },
ci_passed: { label: "CI Passed", icon: CheckCircle2, color: "text-green-400" },
ci_failed: { label: "CI Failed", icon: XCircle, color: "text-red-400" },
label_added: { label: "Label Added", icon: Tag, color: "text-blue-400" },
review_requested: { label: "Review Requested", icon: Users, color: "text-orange-400" },
comment_added: { label: "Comment Added", icon: MessageSquare, color: "text-cyan-400" },
};
const actionLabels: Record<string, string> = {
add_label: "Add Label",
remove_label: "Remove Label",
assign_reviewer: "Assign Reviewer",
add_to_merge_queue: "Add to Merge Queue",
add_comment: "Add Comment",
trigger_ai_review: "Trigger AI Review",
trigger_iac_hook: "Trigger IaC Hook",
notify_slack: "Notify Slack",
close_pr: "Close PR",
};
function timeAgo(date: string) {
const seconds = Math.floor((Date.now() - new Date(date).getTime()) / 1000);
if (seconds < 60) return "just now";
if (seconds < 3600) return Math.floor(seconds / 60) + "m ago";
if (seconds < 86400) return Math.floor(seconds / 3600) + "h ago";
return Math.floor(seconds / 86400) + "d ago";
}
function parseActions(actionsJson: string): { type: string; label: string }[] {
try {
const parsed = JSON.parse(actionsJson);
return parsed.map((a: { type: string }) => ({
type: a.type,
label: actionLabels[a.type] || a.type,
}));
} catch {
return [];
}
}
---
<BaseLayout title="Automations">
<div class="container py-8 max-w-5xl">
<div class="flex flex-col gap-6">
<!-- Header -->
<div class="flex items-center justify-between">
<div class="flex items-center gap-3">
<div class="p-2 rounded-lg bg-gradient-to-br from-yellow-500/20 to-orange-500/20 border border-yellow-500/30">
<Zap className="h-6 w-6 text-yellow-400" />
</div>
<div>
<h1 class="text-2xl font-bold text-foreground">Automations</h1>
<p class="text-sm text-muted-foreground">Automate your workflow with custom rules</p>
</div>
</div>
<div class="flex items-center gap-3">
<!-- Repo Selector -->
<select
id="repo-select"
class="bg-secondary border border-border rounded-lg px-3 py-2 text-sm text-muted-foreground"
>
<option value="">Select Repository</option>
{repositories.map((repo) => (
<option value={repo.id} selected={repoId === repo.id}>
{repo.fullName || repo.name}
</option>
))}
</select>
{repoId && (
<button
id="add-rule-btn"
class="flex items-center gap-2 px-3 py-2 bg-yellow-500/10 border border-yellow-500/30 text-yellow-400 rounded-lg text-sm hover:bg-yellow-500/20 transition-colors"
>
<Plus className="h-4 w-4" />
Add Automation
</button>
)}
</div>
</div>
{repoId && (
<!-- View Toggle -->
<div class="flex items-center gap-2">
<a
href={`/settings/automations?repo=${repoId}&view=rules`}
class:list={[
"flex items-center gap-2 px-4 py-2 rounded-lg text-sm transition-colors",
view === "rules"
? "bg-yellow-500/10 text-yellow-400 border border-yellow-500/30"
: "text-muted-foreground hover:text-foreground hover:bg-accent"
]}
>
<Settings2 className="h-4 w-4" />
Rules
</a>
<a
href={`/settings/automations?repo=${repoId}&view=history`}
class:list={[
"flex items-center gap-2 px-4 py-2 rounded-lg text-sm transition-colors",
view === "history"
? "bg-yellow-500/10 text-yellow-400 border border-yellow-500/30"
: "text-muted-foreground hover:text-foreground hover:bg-accent"
]}
>
<History className="h-4 w-4" />
History
</a>
</div>
)}
{!repoId ? (
<!-- No repo selected -->
<div class="text-center py-16 bg-secondary rounded-xl border border-border">
<Zap className="h-16 w-16 text-yellow-400 mx-auto mb-4" />
<h3 class="text-lg font-semibold text-foreground mb-2">Select a Repository</h3>
<p class="text-muted-foreground">Choose a repository to configure automations</p>
</div>
) : view === "rules" ? (
<!-- Rules List -->
<div class="relative">
<div class="absolute -inset-[1px] bg-gradient-to-r from-yellow-500/20 via-transparent to-orange-500/20 rounded-xl opacity-50"></div>
<div class="relative rounded-xl border border-border bg-card/80 backdrop-blur-sm overflow-hidden">
{rules.length === 0 ? (
<div class="text-center py-16">
<Zap className="h-12 w-12 text-yellow-400 mx-auto mb-4" />
<h3 class="text-lg font-semibold text-foreground mb-2">No Automations Yet</h3>
<p class="text-muted-foreground mb-4">Create rules to automate your workflow</p>
<button
id="add-first-rule-btn"
class="inline-flex items-center gap-2 px-4 py-2 bg-yellow-500/10 border border-yellow-500/30 text-yellow-400 rounded-lg text-sm hover:bg-yellow-500/20 transition-colors"
>
<Plus className="h-4 w-4" />
Create First Automation
</button>
</div>
) : (
<div class="divide-y divide-white/5">
{rules.map((rule) => {
const trigger = triggerLabels[rule.trigger] || { label: rule.trigger, icon: Zap, color: "text-muted-foreground" };
const TriggerIcon = trigger.icon;
const actions = parseActions(rule.actions);
return (
<div
class="group flex items-start gap-4 p-4 transition-all hover:bg-accent/50"
data-rule-id={rule.id}
data-rule-name={rule.name}
data-rule-trigger={rule.trigger}
data-rule-description={rule.description || ""}
data-rule-actions={rule.actions}
>
{/* Trigger Icon */}
<div class="flex-shrink-0 p-2 rounded-lg bg-secondary">
<TriggerIcon className={`h-5 w-5 ${trigger.color}`} />
</div>
{/* Rule Info */}
<div class="flex-1 min-w-0">
<div class="flex items-center gap-2">
<span class:list={[
"font-medium transition-colors",
rule.isEnabled ? "text-foreground" : "text-muted-foreground"
]}>
{rule.name}
</span>
{!rule.isEnabled && (
<span class="px-1.5 py-0.5 text-xs bg-gray-500/10 text-muted-foreground rounded border border-gray-500/30">
Disabled
</span>
)}
</div>
{rule.description && (
<p class="text-sm text-muted-foreground mt-1">{rule.description}</p>
)}
{/* Trigger → Actions flow */}
<div class="flex items-center gap-2 mt-2 text-sm">
<span class="px-2 py-1 rounded bg-secondary text-muted-foreground">
{trigger.label}
</span>
<ArrowRight className="h-4 w-4 text-muted-foreground" />
{actions.slice(0, 3).map((action) => (
<span class="px-2 py-1 rounded bg-yellow-500/10 text-yellow-300 text-xs">
{action.label}
</span>
))}
{actions.length > 3 && (
<span class="text-xs text-muted-foreground">+{actions.length - 3} more</span>
)}
</div>
<div class="flex items-center gap-4 mt-2 text-xs text-muted-foreground">
<span>{rule.runCount} runs</span>
{rule.lastRunAt && (
<span>Last run {timeAgo(rule.lastRunAt)}</span>
)}
</div>
</div>
{/* Actions */}
<div class="flex-shrink-0 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
<button
class="p-1.5 rounded hover:bg-secondary/80 text-muted-foreground hover:text-foreground transition-colors"
title={rule.isEnabled ? "Disable" : "Enable"}
data-action="toggle"
data-enabled={rule.isEnabled ? "true" : "false"}
>
{rule.isEnabled ? (
<Pause className="h-4 w-4" />
) : (
<Play className="h-4 w-4" />
)}
</button>
<button
class="p-1.5 rounded hover:bg-secondary/80 text-muted-foreground hover:text-foreground transition-colors"
title="Edit"
data-action="edit"
>
<Edit2 className="h-4 w-4" />
</button>
<button
class="p-1.5 rounded hover:bg-red-500/20 text-muted-foreground hover:text-red-400 transition-colors"
title="Delete"
data-action="delete"
>
<Trash2 className="h-4 w-4" />
</button>
</div>
</div>
);
})}
</div>
)}
</div>
</div>
) : (
<!-- Execution History -->
<div class="relative">
<div class="absolute -inset-[1px] bg-gradient-to-r from-yellow-500/20 via-transparent to-orange-500/20 rounded-xl opacity-50"></div>
<div class="relative rounded-xl border border-border bg-card/80 backdrop-blur-sm overflow-hidden">
{executions.length === 0 ? (
<div class="text-center py-16">
<History className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
<h3 class="text-lg font-semibold text-foreground mb-2">No Execution History</h3>
<p class="text-muted-foreground">Automation runs will appear here</p>
</div>
) : (
<div class="divide-y divide-white/5">
{executions.map((exec) => (
<div class="flex items-center gap-4 p-4">
<div class:list={[
"flex-shrink-0 p-2 rounded-lg",
exec.status === "success" ? "bg-green-500/10" :
exec.status === "failed" ? "bg-red-500/10" : "bg-gray-500/10"
]}>
{exec.status === "success" ? (
<CheckCircle2 className="h-5 w-5 text-green-400" />
) : exec.status === "failed" ? (
<XCircle className="h-5 w-5 text-red-400" />
) : (
<Clock className="h-5 w-5 text-muted-foreground" />
)}
</div>
<div class="flex-1 min-w-0">
<div class="font-medium text-foreground">{exec.ruleName}</div>
<div class="text-sm text-muted-foreground">
Triggered by: {triggerLabels[exec.triggerEvent]?.label || exec.triggerEvent}
</div>
</div>
<div class="text-right text-sm">
<div class="text-muted-foreground">{timeAgo(exec.createdAt)}</div>
{exec.durationMs && (
<div class="text-muted-foreground text-xs">{exec.durationMs}ms</div>
)}
</div>
</div>
))}
</div>
)}
</div>
</div>
)}
<!-- Common Automation Patterns -->
{repoId && view === "rules" && (
<div>
<h2 class="text-lg font-semibold text-foreground mb-4">Quick Templates</h2>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<button class="text-left p-4 rounded-lg bg-secondary border border-border hover:bg-secondary/80 transition-colors group" data-template="auto-assign">
<div class="flex items-center gap-2 mb-2">
<Users className="h-5 w-5 text-orange-400" />
<span class="font-medium text-foreground">Auto-assign Reviewer</span>
</div>
<p class="text-sm text-muted-foreground">Automatically assign reviewers when PRs are opened</p>
</button>
<button class="text-left p-4 rounded-lg bg-secondary border border-border hover:bg-secondary/80 transition-colors group" data-template="auto-merge">
<div class="flex items-center gap-2 mb-2">
<GitPullRequest className="h-5 w-5 text-green-400" />
<span class="font-medium text-foreground">Auto-queue on Approve</span>
</div>
<p class="text-sm text-muted-foreground">Add to merge queue when PR is approved</p>
</button>
<button class="text-left p-4 rounded-lg bg-secondary border border-border hover:bg-secondary/80 transition-colors group" data-template="ai-review">
<div class="flex items-center gap-2 mb-2">
<Zap className="h-5 w-5 text-cyan-400" />
<span class="font-medium text-foreground">AI Review on PR</span>
</div>
<p class="text-sm text-muted-foreground">Trigger AI review when PRs are opened</p>
</button>
</div>
</div>
)}
</div>
</div>
</BaseLayout>
<script is:inline define:vars={{ repoId }}>
// Repo selector
const repoSelect = document.getElementById("repo-select");
repoSelect?.addEventListener("change", (e) => {
const repo = e.target.value;
const url = new URL(window.location.href);
if (repo) {
url.searchParams.set("repo", repo);
} else {
url.searchParams.delete("repo");
}
window.location.href = url.toString();
});
async function createRuleFromPrompts() {
if (!repoId) return;
const name = prompt("Automation name", "New Automation Rule");
if (!name) return;
const description = prompt("Description (optional)", "") || "";
const trigger = prompt(
"Trigger event (e.g. pr_opened, pr_approved, ci_failed)",
"pr_opened",
);
if (!trigger) return;
const actionType = prompt(
"Action type (e.g. assign_reviewer, add_to_merge_queue, trigger_ai_review)",
"trigger_ai_review",
);
if (!actionType) return;
const payload = {
repositoryId: repoId,
name,
description,
trigger,
actions: JSON.stringify([{ type: actionType, params: {} }]),
};
const res = await fetch("/api/automation-rules", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!res.ok) {
alert("Failed to create automation");
return;
}
window.location.reload();
}
// Add rule buttons
document.getElementById("add-rule-btn")?.addEventListener("click", async () => {
try {
await createRuleFromPrompts();
} catch (e) {
console.error("Failed to create automation:", e);
alert("Failed to create automation");
}
});
document.getElementById("add-first-rule-btn")?.addEventListener("click", async () => {
try {
await createRuleFromPrompts();
} catch (e) {
console.error("Failed to create automation:", e);
alert("Failed to create automation");
}
});
// Template buttons
document.querySelectorAll("[data-template]").forEach(btn => {
btn.addEventListener("click", async () => {
const template = btn.getAttribute("data-template");
const templates = {
"auto-assign": {
name: "Auto-assign Reviewer",
trigger: "pr_opened",
actions: JSON.stringify([{ type: "assign_reviewer", params: { assignee: "@codeowners" } }]),
},
"auto-merge": {
name: "Auto-queue on Approve",
trigger: "pr_approved",
actions: JSON.stringify([{ type: "add_to_merge_queue", params: { method: "squash" } }]),
},
"ai-review": {
name: "AI Review on PR",
trigger: "pr_opened",
actions: JSON.stringify([{ type: "trigger_ai_review", params: {} }]),
},
};
const data = templates[template];
if (!data) return;
try {
const res = await fetch("/api/automation-rules", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...data, repositoryId: repoId }),
});
if (res.ok) {
window.location.reload();
} else {
alert("Failed to create automation");
}
} catch (e) {
console.error("Failed to create automation:", e);
}
});
});
// Rule row action handlers (toggle/edit/delete)
document.querySelectorAll("[data-rule-id]").forEach((row) => {
const ruleId = row.getAttribute("data-rule-id");
if (!ruleId) return;
row.querySelector('[data-action="toggle"]')?.addEventListener("click", async () => {
const toggleBtn = row.querySelector('[data-action="toggle"]');
const enabled = toggleBtn?.getAttribute("data-enabled") === "true";
try {
const res = await fetch(`/api/automation-rules?id=${encodeURIComponent(ruleId)}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ isEnabled: !enabled }),
});
if (res.ok) {
window.location.reload();
} else {
alert("Failed to update automation");
}
} catch (e) {
console.error("Failed to toggle automation:", e);
}
});
row.querySelector('[data-action="edit"]')?.addEventListener("click", async () => {
const currentName = row.getAttribute("data-rule-name") || "";
const currentDescription = row.getAttribute("data-rule-description") || "";
const currentTrigger = row.getAttribute("data-rule-trigger") || "pr_opened";
const actionsRaw = row.getAttribute("data-rule-actions") || "[]";
let currentActionType = "trigger_ai_review";
try {
const parsed = JSON.parse(actionsRaw);
if (Array.isArray(parsed) && parsed[0]?.type) currentActionType = parsed[0].type;
} catch {}
const name = prompt("Automation name", currentName);
if (!name) return;
const description = prompt("Description (optional)", currentDescription) || "";
const trigger = prompt("Trigger event", currentTrigger);
if (!trigger) return;
const actionType = prompt("Action type", currentActionType);
if (!actionType) return;
try {
const res = await fetch(`/api/automation-rules?id=${encodeURIComponent(ruleId)}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name,
description,
trigger,
actions: JSON.stringify([{ type: actionType, params: {} }]),
}),
});
if (res.ok) {
window.location.reload();
} else {
alert("Failed to update automation");
}
} catch (e) {
console.error("Failed to edit automation:", e);
}
});
row.querySelector('[data-action="delete"]')?.addEventListener("click", async () => {
if (!confirm("Delete this automation rule?")) return;
try {
const res = await fetch(`/api/automation-rules?id=${encodeURIComponent(ruleId)}`, {
method: "DELETE",
});
if (res.ok) {
window.location.reload();
} else {
alert("Failed to delete automation");
}
} catch (e) {
console.error("Failed to delete automation:", e);
}
});
});
</script>