gpt-engineer-app[bot] commited on
Commit
d5d7aef
Β·
2 Parent(s): 9c0c90be3ca9bc

Added auto-detect branch mode

Browse files

X-Lovable-Edit-ID: edt-29d303ae-e795-41a3-baef-75884fa632d8

src/routes/dashboard.branch-debug.tsx CHANGED
@@ -2,7 +2,7 @@ import { createFileRoute } from "@tanstack/react-router";
2
  import { useState, useEffect, useRef } from "react";
3
  import { GitBranch, Play, RotateCcw, Shield, ChevronLeft, ChevronRight, Check, Loader2, Sparkles, FileCode, ExternalLink, Copy, Eye, ArrowRight } from "lucide-react";
4
  import { useServerFn } from "@tanstack/react-start";
5
- import { debugBranch, type DebugResult, type Suspect } from "@/server/branch-debug.functions";
6
  import { Button } from "@/components/ui/button";
7
  import { Textarea } from "@/components/ui/textarea";
8
  import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogDescription } from "@/components/ui/dialog";
@@ -16,6 +16,25 @@ export const Route = createFileRoute("/dashboard/branch-debug")({
16
 
17
  type Zone = "user" | "server" | "ai";
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  const STEPS: {
20
  id: number; label: string; sublabel: string; color: string; icon: string;
21
  zone: Zone; code: string; detail: string; codeLabel: string;
@@ -113,16 +132,21 @@ function BranchDebugPage() {
113
  const [analyzing, setAnalyzing] = useState(false);
114
  const [editorBase, setEditorBase] = useState(() => localStorage.getItem("branchdebug.editorBase") ?? "vscode://file/");
115
  const debugFn = useServerFn(debugBranch);
 
 
 
116
 
117
  const runAnalysis = async () => {
118
  if (!diff.trim() || !failure.trim()) {
119
- toast.error("Provide both a diff and a failure description.");
120
  return;
121
  }
122
  setAnalyzing(true);
123
  setResult(null);
124
  try {
125
- const res = await debugFn({ data: { diff, failureDescription: failure } });
 
 
126
  setResult(res);
127
  toast.success(`Found ${res.suspects.length} suspect${res.suspects.length === 1 ? "" : "s"}`);
128
  } catch (e: any) {
@@ -197,6 +221,7 @@ index aaa..bbb 100644
197
  result={result} analyzing={analyzing}
198
  onRun={runAnalysis} onSample={loadSample}
199
  editorBase={editorBase} setEditorBase={(v) => { setEditorBase(v); localStorage.setItem("branchdebug.editorBase", v); }}
 
200
  />
201
  )}
202
 
@@ -507,28 +532,60 @@ const CONFIDENCE_STYLES = {
507
 
508
  function AnalyzerView({
509
  diff, setDiff, failure, setFailure, result, analyzing, onRun, onSample, editorBase, setEditorBase,
 
510
  }: {
511
  diff: string; setDiff: (v: string) => void;
512
  failure: string; setFailure: (v: string) => void;
513
  result: DebugResult | null; analyzing: boolean;
514
  onRun: () => void; onSample: () => void;
515
  editorBase: string; setEditorBase: (v: string) => void;
 
 
516
  }) {
517
  return (
518
  <div className="flex-1 grid grid-cols-1 lg:grid-cols-[480px_1fr] min-h-0 overflow-hidden">
519
  {/* Input panel */}
520
  <div className="border-r border-border overflow-y-auto p-6 space-y-4 bg-surface/20">
521
  <div>
522
- <div className="flex items-center justify-between mb-2">
523
- <label className="text-[10px] font-mono uppercase tracking-widest text-muted-foreground">Unified git diff</label>
524
- <button onClick={onSample} className="text-[10px] font-mono uppercase tracking-widest text-primary hover:underline">Load sample</button>
 
 
 
 
 
 
 
 
 
 
525
  </div>
526
  <Textarea
527
  value={diff}
528
  onChange={(e) => setDiff(e.target.value)}
529
- placeholder="Paste output of `git diff main..feature/...`"
530
  className="font-mono text-xs h-64 resize-none bg-background"
531
  />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532
  </div>
533
  <div>
534
  <label className="text-[10px] font-mono uppercase tracking-widest text-muted-foreground mb-2 block">Failure description</label>
@@ -550,7 +607,7 @@ function AnalyzerView({
550
  <p className="text-[10px] text-muted-foreground mt-1">Used to jump directly to suspect lines in your editor.</p>
551
  </div>
552
  <Button onClick={onRun} disabled={analyzing} className="w-full gap-2">
553
- {analyzing ? <><Loader2 className="h-4 w-4 animate-spin" /> Analyzing…</> : <><Sparkles className="h-4 w-4" /> Analyze branch</>}
554
  </Button>
555
  <div className="rounded-lg border border-yellow-500/30 bg-yellow-500/5 p-3 flex gap-2 text-[11px] text-muted-foreground">
556
  <Shield className="h-3.5 w-3.5 text-yellow-500 shrink-0 mt-0.5" />
 
2
  import { useState, useEffect, useRef } from "react";
3
  import { GitBranch, Play, RotateCcw, Shield, ChevronLeft, ChevronRight, Check, Loader2, Sparkles, FileCode, ExternalLink, Copy, Eye, ArrowRight } from "lucide-react";
4
  import { useServerFn } from "@tanstack/react-start";
5
+ import { debugBranch, debugSnippet, type DebugResult, type Suspect } from "@/server/branch-debug.functions";
6
  import { Button } from "@/components/ui/button";
7
  import { Textarea } from "@/components/ui/textarea";
8
  import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogDescription } from "@/components/ui/dialog";
 
16
 
17
  type Zone = "user" | "server" | "ai";
18
 
19
+ const LANGUAGES = [
20
+ { id: "auto", label: "Auto-detect language" },
21
+ { id: "python", label: "Python" },
22
+ { id: "cpp", label: "C / C++" },
23
+ { id: "typescript", label: "TypeScript / JS" },
24
+ { id: "rust", label: "Rust" },
25
+ { id: "go", label: "Go" },
26
+ { id: "java", label: "Java" },
27
+ ];
28
+
29
+ function detectInputType(text: string): "diff" | "snippet" | "unknown" {
30
+ if (!text || text.trim().length < 10) return "unknown";
31
+ const lines = text.trim().split("\n");
32
+ const diffHeaders = lines.filter((l) => /^(diff --git|---\s|\+\+\+\s|@@\s|index [a-f0-9])/.test(l)).length;
33
+ const diffLines = lines.filter((l) => /^[+\-](?![+\-])/.test(l)).length;
34
+ if (diffHeaders >= 1 || (diffLines / lines.length > 0.3 && diffLines >= 3)) return "diff";
35
+ return "snippet";
36
+ }
37
+
38
  const STEPS: {
39
  id: number; label: string; sublabel: string; color: string; icon: string;
40
  zone: Zone; code: string; detail: string; codeLabel: string;
 
132
  const [analyzing, setAnalyzing] = useState(false);
133
  const [editorBase, setEditorBase] = useState(() => localStorage.getItem("branchdebug.editorBase") ?? "vscode://file/");
134
  const debugFn = useServerFn(debugBranch);
135
+ const snippetFn = useServerFn(debugSnippet);
136
+ const [language, setLanguage] = useState("auto");
137
+ const detected = detectInputType(diff);
138
 
139
  const runAnalysis = async () => {
140
  if (!diff.trim() || !failure.trim()) {
141
+ toast.error("Provide both code and a failure description.");
142
  return;
143
  }
144
  setAnalyzing(true);
145
  setResult(null);
146
  try {
147
+ const res = detected === "snippet"
148
+ ? await snippetFn({ data: { snippet: diff, failureDescription: failure, language: language === "auto" ? undefined : language } })
149
+ : await debugFn({ data: { diff, failureDescription: failure } });
150
  setResult(res);
151
  toast.success(`Found ${res.suspects.length} suspect${res.suspects.length === 1 ? "" : "s"}`);
152
  } catch (e: any) {
 
221
  result={result} analyzing={analyzing}
222
  onRun={runAnalysis} onSample={loadSample}
223
  editorBase={editorBase} setEditorBase={(v) => { setEditorBase(v); localStorage.setItem("branchdebug.editorBase", v); }}
224
+ detected={detected} language={language} setLanguage={setLanguage}
225
  />
226
  )}
227
 
 
532
 
533
  function AnalyzerView({
534
  diff, setDiff, failure, setFailure, result, analyzing, onRun, onSample, editorBase, setEditorBase,
535
+ detected, language, setLanguage,
536
  }: {
537
  diff: string; setDiff: (v: string) => void;
538
  failure: string; setFailure: (v: string) => void;
539
  result: DebugResult | null; analyzing: boolean;
540
  onRun: () => void; onSample: () => void;
541
  editorBase: string; setEditorBase: (v: string) => void;
542
+ detected: "diff" | "snippet" | "unknown";
543
+ language: string; setLanguage: (v: string) => void;
544
  }) {
545
  return (
546
  <div className="flex-1 grid grid-cols-1 lg:grid-cols-[480px_1fr] min-h-0 overflow-hidden">
547
  {/* Input panel */}
548
  <div className="border-r border-border overflow-y-auto p-6 space-y-4 bg-surface/20">
549
  <div>
550
+ <div className="flex items-center justify-between mb-2 gap-2 flex-wrap">
551
+ <label className="text-[10px] font-mono uppercase tracking-widest text-muted-foreground">Git diff or code snippet</label>
552
+ <div className="flex items-center gap-2">
553
+ {detected !== "unknown" && (
554
+ <span className={cn(
555
+ "text-[9px] font-mono uppercase tracking-widest px-2 py-0.5 rounded border",
556
+ detected === "diff" ? "border-purple-400/40 bg-purple-400/10 text-purple-300" : "border-primary/40 bg-primary/10 text-primary"
557
+ )}>
558
+ {detected === "diff" ? "βŽ‡ git diff" : "{} snippet"}
559
+ </span>
560
+ )}
561
+ <button onClick={onSample} className="text-[10px] font-mono uppercase tracking-widest text-primary hover:underline">Load sample</button>
562
+ </div>
563
  </div>
564
  <Textarea
565
  value={diff}
566
  onChange={(e) => setDiff(e.target.value)}
567
+ placeholder={"Paste a git diff (git diff main..feature/...) β€” OR β€” paste a raw code snippet and we'll analyze it directly."}
568
  className="font-mono text-xs h-64 resize-none bg-background"
569
  />
570
+ {detected === "snippet" && (
571
+ <div className="mt-2 flex items-center gap-2">
572
+ <label className="text-[10px] font-mono uppercase tracking-widest text-muted-foreground">Language</label>
573
+ <select
574
+ value={language}
575
+ onChange={(e) => setLanguage(e.target.value)}
576
+ className="text-[11px] font-mono px-2 py-1 rounded-md bg-background border border-border focus:border-primary outline-none"
577
+ >
578
+ {LANGUAGES.map((l) => <option key={l.id} value={l.id}>{l.label}</option>)}
579
+ </select>
580
+ </div>
581
+ )}
582
+ {detected !== "unknown" && (
583
+ <p className="text-[10px] text-muted-foreground mt-2 leading-relaxed">
584
+ {detected === "diff"
585
+ ? "βŽ‡ Diff mode β€” AI maps changed lines β†’ failure β†’ ranked suspects."
586
+ : "{} Snippet mode β€” AI analyzes this code directly for bugs matching your failure. No diff needed."}
587
+ </p>
588
+ )}
589
  </div>
590
  <div>
591
  <label className="text-[10px] font-mono uppercase tracking-widest text-muted-foreground mb-2 block">Failure description</label>
 
607
  <p className="text-[10px] text-muted-foreground mt-1">Used to jump directly to suspect lines in your editor.</p>
608
  </div>
609
  <Button onClick={onRun} disabled={analyzing} className="w-full gap-2">
610
+ {analyzing ? <><Loader2 className="h-4 w-4 animate-spin" /> Analyzing…</> : <><Sparkles className="h-4 w-4" /> Analyze {detected === "snippet" ? "snippet" : detected === "diff" ? "diff" : "code"}</>}
611
  </Button>
612
  <div className="rounded-lg border border-yellow-500/30 bg-yellow-500/5 p-3 flex gap-2 text-[11px] text-muted-foreground">
613
  <Shield className="h-3.5 w-3.5 text-yellow-500 shrink-0 mt-0.5" />
src/server/branch-debug.functions.ts CHANGED
@@ -327,3 +327,123 @@ export const debugBranch = createServerFn({ method: "POST" })
327
  return analyzeDiff(data.diff, data.failureDescription);
328
  });
329
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
327
  return analyzeDiff(data.diff, data.failureDescription);
328
  });
329
 
330
+ // ───────────────────────── Snippet mode (no diff) ─────────────────────────
331
+ // For users pasting a raw code snippet instead of a unified diff.
332
+ // We still run the IP Shield sanitizer, then ask the AI to locate bugs by line.
333
+
334
+ const SnippetInputSchema = z.object({
335
+ snippet: z.string().min(1).max(200_000),
336
+ failureDescription: z.string().min(1).max(5_000),
337
+ language: z.string().max(40).optional(),
338
+ });
339
+
340
+ const snippetTool = {
341
+ type: "function" as const,
342
+ function: {
343
+ name: "submit_snippet_analysis",
344
+ description: "Submit ranked bug suspects for a raw code snippet (no diff).",
345
+ parameters: {
346
+ type: "object",
347
+ properties: {
348
+ summary: { type: "string" },
349
+ suspects: {
350
+ type: "array",
351
+ minItems: 1,
352
+ items: {
353
+ type: "object",
354
+ properties: {
355
+ line: { type: "number", description: "1-based line number in the snippet." },
356
+ functionToken: { type: "string", description: "Anonymized function/block token, or empty string." },
357
+ confidence: { type: "string", enum: ["high", "medium", "low"] },
358
+ mechanism: { type: "string" },
359
+ changeSummary: { type: "string", description: "Short label of the suspicious pattern." },
360
+ codeFragment: { type: "string", description: "The exact suspect line(s), anonymized." },
361
+ },
362
+ required: ["line", "functionToken", "confidence", "mechanism", "changeSummary", "codeFragment"],
363
+ additionalProperties: false,
364
+ },
365
+ },
366
+ },
367
+ required: ["summary", "suspects"],
368
+ additionalProperties: false,
369
+ },
370
+ },
371
+ };
372
+
373
+ const SNIPPET_SYSTEM = `You are BranchDebug in SNIPPET mode. The user pasted a raw code snippet (not a diff) where identifiers are tokenized as fn_NNNN.
374
+ Find bugs that match the failure description: off-by-one errors, bad thresholds, null/undefined dereferences, race conditions, wrong operators, leaked resources, etc.
375
+ Return 1-N ranked suspects with the 1-based line number from the snippet. Be conservative β€” only mark "high" if the mechanism directly explains the failure. Always call submit_snippet_analysis.`;
376
+
377
+ export async function analyzeSnippet(
378
+ snippet: string,
379
+ failureDescription: string,
380
+ language?: string,
381
+ ): Promise<DebugResult> {
382
+ const apiKey = process.env.LOVABLE_API_KEY;
383
+ if (!apiKey) throw new Error("LOVABLE_API_KEY not configured");
384
+
385
+ const { sanitized, reverseMap, stats, audit } = sanitize(snippet);
386
+ const numbered = sanitized.split("\n").map((l, i) => `${String(i + 1).padStart(4, " ")} | ${l}`).join("\n");
387
+
388
+ const userContent = `LANGUAGE: ${language || "auto-detect"}\n\nFAILURE DESCRIPTION (sanitized):\n${sanitize(failureDescription).sanitized}\n\nCODE SNIPPET (line-numbered, sanitized):\n${numbered.slice(0, 40_000)}`;
389
+
390
+ const resp = await fetch("https://ai.gateway.lovable.dev/v1/chat/completions", {
391
+ method: "POST",
392
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
393
+ body: JSON.stringify({
394
+ model: "google/gemini-2.5-flash",
395
+ messages: [
396
+ { role: "system", content: SNIPPET_SYSTEM },
397
+ { role: "user", content: userContent },
398
+ ],
399
+ tools: [snippetTool],
400
+ tool_choice: { type: "function", function: { name: "submit_snippet_analysis" } },
401
+ }),
402
+ });
403
+
404
+ if (!resp.ok) {
405
+ const text = await resp.text();
406
+ if (resp.status === 429) throw new Error("Rate limit reached. Try again shortly.");
407
+ if (resp.status === 402) throw new Error("AI credits exhausted. Add credits in Workspace > Usage.");
408
+ throw new Error(`AI gateway error ${resp.status}: ${text.slice(0, 300)}`);
409
+ }
410
+
411
+ const json = await resp.json();
412
+ const toolCall = json.choices?.[0]?.message?.tool_calls?.[0];
413
+ if (!toolCall?.function?.arguments) throw new Error("AI did not return structured analysis.");
414
+
415
+ const parsed = JSON.parse(toolCall.function.arguments) as {
416
+ summary: string;
417
+ suspects: { line: number; functionToken: string; confidence: "high" | "medium" | "low"; mechanism: string; changeSummary: string; codeFragment: string }[];
418
+ };
419
+
420
+ const snippetLines = snippet.split("\n");
421
+ const suspects: Suspect[] = parsed.suspects.map((s) => ({
422
+ filePath: language ? `snippet.${language}` : "snippet",
423
+ functionName: s.functionToken ? restore(s.functionToken, reverseMap) : null,
424
+ lineStart: s.line,
425
+ lineEnd: s.line,
426
+ confidence: s.confidence,
427
+ mechanism: restore(s.mechanism, reverseMap),
428
+ changeSummary: restore(s.changeSummary, reverseMap),
429
+ beforeSnippet: null,
430
+ afterSnippet: snippetLines[s.line - 1] ?? restore(s.codeFragment, reverseMap),
431
+ })).sort((a, b) => {
432
+ const order = { high: 0, medium: 1, low: 2 } as const;
433
+ return order[a.confidence] - order[b.confidence];
434
+ });
435
+
436
+ return {
437
+ summary: restore(parsed.summary, reverseMap),
438
+ suspects,
439
+ sanitizationStats: stats,
440
+ audit,
441
+ };
442
+ }
443
+
444
+ export const debugSnippet = createServerFn({ method: "POST" })
445
+ .inputValidator((d: unknown) => SnippetInputSchema.parse(d))
446
+ .handler(async ({ data }): Promise<DebugResult> => {
447
+ return analyzeSnippet(data.snippet, data.failureDescription, data.language);
448
+ });
449
+