File size: 30,505 Bytes
cb00361
eb60226
cb00361
 
 
 
 
eb60226
 
 
 
 
 
120b584
cb00361
6ee987f
1046f11
eb60226
 
 
 
6ee987f
 
 
 
 
120b584
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb60226
 
 
cb00361
9ccc0da
 
 
 
 
 
eb60226
cb00361
5e9f468
 
 
 
 
87c0f85
 
 
 
 
 
1046f11
 
 
 
 
 
 
eb60226
 
 
 
 
9ccc0da
eb60226
6ee987f
 
 
5e9f468
 
 
 
 
 
 
 
 
 
6ee987f
 
 
 
 
 
cb00361
6ee987f
cb00361
 
 
eb60226
cb00361
 
 
eb60226
cb00361
 
 
 
 
 
eb60226
 
 
 
 
120b584
cb00361
 
 
 
120b584
eb60226
 
 
cb00361
 
 
 
eb60226
 
 
 
cb00361
 
 
 
 
eb60226
 
 
 
 
 
 
 
cb00361
 
1046f11
cb00361
 
 
 
 
 
 
 
 
 
 
 
1046f11
 
 
eb60226
 
 
cb00361
 
 
 
 
87c0f85
cb00361
 
1046f11
 
cb00361
 
 
 
eb60226
1046f11
cb00361
 
 
 
 
 
 
 
 
87c0f85
 
cb00361
 
 
0e26181
cb00361
0e26181
cb00361
 
 
0e26181
 
cb00361
 
 
 
1046f11
 
 
 
 
 
 
eb60226
 
 
 
 
 
 
 
 
 
 
 
 
 
cb00361
 
 
 
 
 
 
 
 
 
 
 
 
eb60226
 
 
 
cb00361
 
 
 
eb60226
cb00361
eb60226
 
e497738
 
 
eb60226
 
 
 
 
cb00361
 
 
 
eb60226
cb00361
 
eb60226
 
 
 
 
 
 
 
 
 
9ccc0da
 
 
 
 
 
 
 
 
 
5e9f468
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ccc0da
 
 
 
0e26181
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1046f11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ccc0da
eb60226
 
 
 
 
 
1046f11
eb60226
 
 
 
 
0e26181
 
 
 
 
9ccc0da
eb60226
 
 
 
 
 
 
cb00361
eb60226
 
 
cb00361
 
 
 
 
 
 
 
eb60226
 
 
cb00361
eb60226
 
 
 
cb00361
eb60226
cb00361
eb60226
cb00361
0e26181
 
eb60226
 
 
cb00361
 
 
 
 
0e26181
9ccc0da
 
 
 
 
 
 
 
0e26181
 
9ccc0da
0e26181
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb60226
 
9ccc0da
eb60226
 
89076a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb60226
 
 
 
 
 
 
cb00361
 
 
 
 
 
eb60226
 
cb00361
 
9ccc0da
189abed
 
eb60226
89076a2
 
 
 
 
cb00361
 
89076a2
 
 
 
 
87c0f85
89076a2
cb00361
 
 
 
 
 
 
bd6aedd
cb00361
 
 
 
bd6aedd
89076a2
cb00361
 
 
 
 
 
 
 
 
 
 
bd6aedd
 
89076a2
bd6aedd
89076a2
 
 
 
 
eb60226
89076a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1046f11
89076a2
 
1046f11
 
89076a2
 
 
1046f11
89076a2
 
cb00361
 
89076a2
1046f11
 
 
 
 
cb00361
 
5e9f468
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb00361
 
 
89076a2
cb00361
 
 
 
 
 
 
 
 
89076a2
 
cb00361
 
 
 
eb60226
 
89076a2
eb60226
 
cb00361
eb60226
1046f11
 
 
 
 
 
 
 
89076a2
 
1046f11
eb60226
 
 
 
189abed
 
 
 
 
9ccc0da
eb60226
 
 
 
 
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
"""Streamlit front-end for the Autonomous Bug-Fixing Agent.

Supports:
- **Live Agent (Groq LLM + Sandbox):** runs the real LangGraph pipeline against the built-in
  sample buggy repo, any local repository path, or any GitHub repository URL (shallow-cloned
  into an isolated temp workspace).
- **Scripted Demo Mode:** deterministic walkthrough with zero API calls.

Run:  streamlit run src/ui/streamlit_app.py
"""

from __future__ import annotations

import importlib
import os
import sys
import time
import uuid
from pathlib import Path
from typing import Any

# Ensure `src/` is on sys.path when launched directly on Streamlit Community Cloud
_SRC_DIR = str(Path(__file__).resolve().parents[1])
if _SRC_DIR not in sys.path:
    sys.path.insert(0, _SRC_DIR)

# Hot-reload guard for Streamlit Community Cloud: if an older commit's modules are cached
# in `sys.modules` across a live GitHub push, reload them in dependency order.
if "agent.state" in sys.modules and not hasattr(sys.modules["agent.state"], "RepoFinding"):
    for _mod in (
        "agent.state",
        "tools.file_tools",
        "tools.git_tools",
        "agent.prompts",
        "agent.llm",
        "agent.nodes",
        "agent.graph",
        "ui.mock_graph",
        "ui.report_pdf",
    ):
        if _mod in sys.modules:
            importlib.reload(sys.modules[_mod])

import streamlit as st
from langgraph.types import Command

from agent.graph import build_graph
from agent.llm import (
    AVAILABLE_GROQ_MODELS,
    default_groq_api_key,
    load_dotenv_into_environ,
    resolve_groq_model,
)
from agent.state import AgentState, FixAttempt, IssueInput, initial_state
from sandbox.docker_runner import DockerSandbox
from tools.aws_tools import (
    archive_run_to_aws,
    is_aws_configured,
    list_runs_from_dynamodb,
)
from tools.file_tools import (
    Workspace,
    WorkspaceError,
    clone_repo_to_temp,
    create_repo_from_uploads,
)
from tools.git_tools import (
    GitError,
    create_github_pull_request,
    fetch_github_issue,
    parse_github_issue_url,
    parse_github_owner_repo,
)
from ui.mock_graph import (
    DEMO_ISSUE_BODY,
    DEMO_ISSUE_TITLE,
    build_mock_graph,
)
from ui.report_pdf import generate_pdf_report

def _load_streamlit_secrets() -> None:
    """Copy `st.secrets` keys (`GROQ_API_KEY`, `SANDBOX_BACKEND`, etc.) into `os.environ`."""
    try:
        for k in (
            "GROQ_API_KEY",
            "GROQ_MODEL",
            "SANDBOX_BACKEND",
            "CHECKPOINTER",
            "DATABASE_URL",
            "AWS_S3_BUCKET",
            "AWS_DYNAMODB_TABLE",
            "AWS_REGION",
        ):
            if k in st.secrets and not os.environ.get(k):
                os.environ[k] = str(st.secrets[k])
    except Exception:  # noqa: BLE001
        pass


load_dotenv_into_environ()
_load_streamlit_secrets()

FIXTURE_REPO = Path(__file__).resolve().parents[2] / "tests" / "fixtures" / "buggy_repo"

STEP_LABELS = {
    "ingest_issue": "Ingest issue & prepare workspace",
    "inspect_repo": "Inspect repository & rank relevant files",
    "write_repro_test": "Write reproduction test (Groq LLM)",
    "run_repro_test": "Run reproduction test (expect failure)",
    "propose_fix": "Propose code fix (Groq LLM)",
    "apply_fix": "Apply search/replace edits & compute diff",
    "run_tests": "Run test suite in sandbox",
    "analyze_failure": "Analyze failure / reviewer feedback",
    "human_approval": "Human-in-the-loop approval",
    "commit_and_pr": "Commit approved patch",
    "escalate": "Escalate",
}


@st.cache_resource
def get_live_graph(_version: str = "v3"):
    return build_graph()


@st.cache_resource
def get_demo_graph(_version: str = "v3"):
    return build_mock_graph()


def _active_graph():
    return get_demo_graph() if st.session_state.get("run_mode") == "demo" else get_live_graph()


def _config() -> dict[str, Any]:
    return {
        "configurable": {
            "thread_id": st.session_state.thread_id,
            "delay": st.session_state.get("delay", 0.3),
            "groq_model": st.session_state.get("groq_model"),
            "groq_api_key": st.session_state.get("groq_api_key") or None,
            "sandbox_backend": st.session_state.get("sandbox_backend", "auto"),
            "commit_in_git": False,
        }
    }


# ------------------------------------------------------------------------ running


def advance(payload: AgentState | Command) -> None:
    """Stream the active graph until it pauses at `interrupt()` or finishes, then rerun."""
    graph = _active_graph()
    t0 = time.perf_counter()
    try:
        with st.status("Agent running...", expanded=True) as status:
            for chunk in graph.stream(payload, _config(), stream_mode="updates"):
                for node, update in chunk.items():
                    if node.startswith("__"):
                        continue
                    st.session_state.log.append((node, update or {}))
                    status.update(label=f"Ran: {STEP_LABELS.get(node, node)}")
                    st.write(f"βœ… {STEP_LABELS.get(node, node)}")
            status.update(label="Agent paused or finished", state="complete", expanded=False)
    except Exception as exc:
        st.session_state.last_error = str(exc)
    st.session_state.elapsed_s = round(
        st.session_state.get("elapsed_s", 0.0) + (time.perf_counter() - t0), 2
    )
    st.rerun()


def start_run(
    *,
    mode: str,
    repo_source: str,
    repo_input: str,
    uploaded_files: list[tuple[str, bytes]] | None = None,
    issue_title: str,
    issue_body: str,
    issue_url: str | None = None,
    issue_number: int | None = None,
) -> None:
    st.session_state.last_error = None
    st.session_state.run_mode = mode
    st.session_state.thread_id = f"{mode}-{uuid.uuid4().hex[:8]}"
    st.session_state.log = []
    st.session_state.elapsed_s = 0.0

    if mode == "demo":
        issue = IssueInput(title=issue_title, body=issue_body, repo_path=Path("demo-repo"))
        advance(initial_state(issue))
        return

    try:
        if repo_source == "Built-in sample buggy repo":
            target_path = FIXTURE_REPO
        elif repo_source == "Upload .zip or .py files":
            target_path = create_repo_from_uploads(uploaded_files or [])
        elif repo_source == "GitHub URL (shallow clone)":
            with st.spinner(f"Cloning {repo_input.strip()}..."):
                target_path = clone_repo_to_temp(repo_input)
            st.session_state.repo_github_url = repo_input.strip()
        else:
            st.session_state.repo_github_url = ""
            target_path = Path(repo_input.strip()).expanduser().resolve()
            if not target_path.is_dir():
                raise WorkspaceError(f"Local folder does not exist: {target_path}")
        if repo_source != "GitHub URL (shallow clone)":
            st.session_state.repo_github_url = ""
    except Exception as exc:
        st.session_state.last_error = str(exc)
        return

    issue = IssueInput(
        title=issue_title.strip(),
        body=issue_body.strip(),
        url=issue_url,
        number=issue_number,
        repo_path=target_path,
    )
    advance(initial_state(issue))


# ---------------------------------------------------------------------- rendering


def render_event(node: str, update: dict[str, Any]) -> None:
    label = STEP_LABELS.get(node, node)
    attempts: list[FixAttempt] = update.get("attempts", [])

    if node == "propose_fix" and attempts:
        a = attempts[-1]
        with st.expander(f"πŸ› οΈ {label} (attempt {a.iteration})", expanded=False):
            st.write(a.rationale)
            if a.patches:
                st.code("\n".join(p.unified_diff for p in a.patches), language="diff")
            elif a.edits:
                for edit in a.edits:
                    st.caption(f"Edit `{edit.path}`")
                    st.code(f"- {edit.search}\n+ {edit.replace}", language="diff")
    elif node == "apply_fix" and attempts:
        a = attempts[-1]
        if a.patch_error:
            st.write(f"⚠️ {label}: {a.patch_error}")
        elif a.patches:
            with st.expander(f"🩹 {label} (attempt {a.iteration})", expanded=False):
                st.code("\n".join(p.unified_diff for p in a.patches), language="diff")
    elif node == "run_tests" and attempts:
        a = attempts[-1]
        icon = "🟒" if a.result and a.result.passed else "πŸ”΄"
        with st.expander(f"{icon} {label} (attempt {a.iteration})", expanded=False):
            out = ""
            if a.result:
                out = (a.result.stdout + "\n" + a.result.stderr).strip()
            st.code(out, language="text")
    elif node == "write_repro_test" and "repro_test" in update:
        with st.expander(f"πŸ§ͺ {label} (`{update['repro_test'].path}`)", expanded=False):
            st.code(update["repro_test"].content, language="python")
    elif node == "inspect_repo" and "repo" in update:
        if "issue" in update:
            det = update["issue"]
            st.info(f"πŸ” **Auto-detected bug in repository:** {det.title}\n\n{det.body}")
        with st.expander(f"πŸ”Ž {label}", expanded=False):
            for path, src in update["repo"].relevant_files.items():
                st.caption(path)
                st.code(src, language="python")
    elif node == "run_repro_test":
        repro = update.get("repro_test")
        ok = repro.confirmed_failing if repro else True
        verdict = "bug reproduced (failed as expected)" if ok else "did not fail as expected"
        st.write(f"βœ… {label}: {verdict}")
    elif node == "analyze_failure":
        diag = update.get("diagnosis") or "feeding the failure back into the next attempt"
        st.write(f"πŸ” {label}: {diag}")
    elif node == "human_approval":
        approval = update.get("approval")
        verdict = "approved" if approval and approval.approved else "changes requested / rejected"
        st.write(f"πŸ§‘ {label}: {verdict}")
        if approval and approval.feedback:
            st.caption(f"Feedback: {approval.feedback}")
    else:
        st.write(f"βœ… {label}")


def _render_report_download(values: dict[str, Any], key_suffix: str) -> None:
    try:
        pdf_bytes = generate_pdf_report(values)
        st.download_button(
            "πŸ“„ Download PDF Bug & Fix Report",
            data=pdf_bytes,
            file_name="bugfix-report.pdf",
            mime="application/pdf",
            key=f"pdf-{key_suffix}",
        )
        if is_aws_configured() and st.session_state.get("thread_id"):
            archive_key = f"aws_archive_{st.session_state.thread_id}_{values.get('status')}"
            if archive_key not in st.session_state:
                zip_bytes = None
                ws_root = values.get("workspace_root")
                if ws_root:
                    try:
                        zip_bytes = Workspace.open(ws_root).export_zip_bytes()
                    except Exception:  # noqa: BLE001
                        zip_bytes = None
                st.session_state[archive_key] = archive_run_to_aws(
                    st.session_state.thread_id,
                    values,
                    pdf_bytes=pdf_bytes,
                    zip_bytes=zip_bytes,
                )
            arc = st.session_state[archive_key]
            if arc.s3_pdf_url:
                st.caption(
                    f"☁️ Archived to Amazon S3 (`s3://{arc.s3_bucket}/{arc.s3_pdf_key}`) · "
                    f"[Open S3 Pre-Signed PDF Report]({arc.s3_pdf_url})"
                )
            if arc.dynamodb_saved:
                st.caption("βœ… Run metadata persisted to Amazon DynamoDB (`BugFixAgentRuns`)")
    except Exception as exc:  # noqa: BLE001
        st.caption(f"Could not generate PDF report: {exc}")


def _render_zip_download(values: dict[str, Any], key_suffix: str) -> None:
    ws_root = values.get("workspace_root")
    if not ws_root:
        return
    try:
        zip_bytes = Workspace.open(ws_root).export_zip_bytes()
        st.download_button(
            "πŸ“¦ Download Fixed Repo (.zip)",
            data=zip_bytes,
            file_name="fixed-repository.zip",
            mime="application/zip",
            key=f"zip-{key_suffix}",
            use_container_width=True,
        )
    except Exception as exc:  # noqa: BLE001
        st.caption(f"Could not export repository zip: {exc}")


def _split_diff_before_after(diff_text: str) -> tuple[str, str]:
    """Extract readable Before vs. After code blocks from a unified diff."""
    before_lines: list[str] = []
    after_lines: list[str] = []
    for line in diff_text.splitlines():
        if line.startswith(("---", "+++", "@@")):
            continue
        if line.startswith("-"):
            before_lines.append(line[1:])
        elif line.startswith("+"):
            after_lines.append(line[1:])
        elif line.startswith(" "):
            before_lines.append(line[1:])
            after_lines.append(line[1:])
        else:
            before_lines.append(line)
            after_lines.append(line)
    return "\n".join(before_lines), "\n".join(after_lines)


def _render_code_comparison(diff_text: str, values: dict[str, Any]) -> None:
    """Render tabbed Unified Diff + Side-by-Side Before/After view."""
    tab_diff, tab_split = st.tabs(["πŸ”€ Unified Diff", "πŸ“Š Side-by-Side (Before vs. After)"])
    with tab_diff:
        st.code(diff_text, language="diff")
    with tab_split:
        ws_root = values.get("workspace_root")
        rendered_files = False
        if ws_root:
            try:
                ws = Workspace.open(ws_root)
                for rel in ws.changed_files():
                    base_src = ws.read_baseline(rel)
                    if base_src is None:
                        continue  # skip newly added test files; show modified source files
                    new_src = ws.read(rel)
                    st.caption(f"File: `{rel}`")
                    col_b, col_a = st.columns(2)
                    with col_b:
                        st.markdown("**Before (Baseline)**")
                        st.code(base_src, language="python")
                    with col_a:
                        st.markdown("**After (Fixed)**")
                        st.code(new_src, language="python")
                    rendered_files = True
            except Exception:  # noqa: BLE001
                rendered_files = False
        if not rendered_files:
            before_txt, after_txt = _split_diff_before_after(diff_text)
            col_b, col_a = st.columns(2)
            with col_b:
                st.markdown("**Before (Baseline)**")
                st.code(before_txt, language="python")
            with col_a:
                st.markdown("**After (Fixed)**")
                st.code(after_txt, language="python")


def _compute_telemetry(
    values: dict[str, Any], log: list[tuple[str, dict[str, Any]]]
) -> dict[str, str]:
    """Compute live run telemetry (LLM calls, sandbox test runs, est. tokens, elapsed time)."""
    llm_nodes = {"write_repro_test", "propose_fix", "analyze_failure"}
    llm_calls = sum(1 for n, u in log if n in llm_nodes or (n == "inspect_repo" and "issue" in u))
    sandbox_runs = sum(1 for n, _ in log if n in {"run_repro_test", "run_tests"})

    total_chars = 0
    if values.get("issue"):
        total_chars += len(values["issue"].title) + len(values["issue"].body)
    if values.get("repo"):
        total_chars += sum(len(v) for v in values["repo"].relevant_files.values())
    if values.get("repro_test"):
        total_chars += len(values["repro_test"].content)
    for att in values.get("attempts") or []:
        total_chars += len(att.rationale) + sum(len(p.unified_diff) for p in att.patches)
    est_tokens = max(120, (total_chars // 4) * max(1, llm_calls))
    elapsed = st.session_state.get("elapsed_s", 0.0)
    return {
        "iterations": f"{values.get('iteration', 0)} / 8",
        "llm_calls": str(llm_calls),
        "sandbox_runs": str(sandbox_runs),
        "est_tokens": f"~{est_tokens:,}",
        "elapsed": f"{elapsed:.1f}s",
    }


def render_approval(payload: dict[str, Any], values: dict[str, Any]) -> None:
    st.subheader("⏸️ Waiting for your approval")
    st.caption(
        "The agent is paused by a LangGraph `interrupt()`. "
        "Nothing is committed until you approve."
    )
    st.markdown(f"**Fix proposed (iteration {payload['iteration']}):** {payload['rationale']}")
    _render_code_comparison(payload["diff"], values)
    st.markdown("**Test results**")
    st.code(payload["test_output"], language="text")
    with st.expander("Reproduction test"):
        st.code(payload["repro_test"], language="python")

    dl1, dl2 = st.columns(2)
    with dl1:
        _render_report_download(values, key_suffix=f"approval-{payload['iteration']}")
    with dl2:
        _render_zip_download(values, key_suffix=f"approval-{payload['iteration']}")

    feedback = st.text_area(
        "Feedback for the agent (required to request changes)",
        key=f"fb-{payload['iteration']}",
        placeholder="e.g. handle the empty-list case",
    )
    approve, changes, reject = st.columns(3)
    if approve.button("βœ… Approve", type="primary", use_container_width=True):
        advance(Command(resume={"approved": True, "reviewer": "user"}))
    if changes.button("✏️ Request changes", use_container_width=True):
        if feedback.strip():
            advance(
                Command(
                    resume={
                        "approved": False,
                        "feedback": feedback.strip(),
                        "reviewer": "user",
                    }
                )
            )
        else:
            st.warning("Add feedback so the agent knows what to change.")
    if reject.button("β›” Reject", use_container_width=True):
        advance(Command(resume={"approved": False, "reviewer": "user"}))


def render_outcome(values: dict[str, Any]) -> None:
    status = str(values.get("status"))
    is_demo = st.session_state.get("run_mode") == "demo"
    if status == "committed":
        note = "Demo commit" if is_demo else "Approved commit"
        st.success(
            f"{note} `{values['commit_sha']}` on `{values['branch']}` "
            "(download the fixed repository `.zip`, unified `.patch`, or PDF report below, "
            "or push a Pull Request directly to GitHub)."
        )
        attempts: list[FixAttempt] = values["attempts"]
        patch = "\n".join(p.unified_diff for p in attempts[-1].patches)
        if values.get("workspace_root"):
            try:
                patch = Workspace.open(values["workspace_root"]).full_diff() or patch
            except Exception:  # noqa: BLE001
                pass
        col1, col2, col3 = st.columns(3)
        with col1:
            st.download_button(
                "⬇️ Download patch (.patch)",
                patch,
                file_name="fix.patch",
                use_container_width=True,
            )
        with col2:
            _render_zip_download(values, key_suffix="committed")
        with col3:
            _render_report_download(values, key_suffix="committed")

        # One-click GitHub Pull Request creation (for live runs)
        if not is_demo and values.get("workspace_root"):
            with st.expander("πŸš€ Push Branch & Open GitHub Pull Request", expanded=bool(st.session_state.get("repo_github_url"))):
                default_gh_url = st.session_state.get("repo_github_url") or (values.get("issue").url if values.get("issue") else "") or ""
                gh_url = st.text_input(
                    "Target GitHub Repository URL",
                    value=default_gh_url,
                    placeholder="https://github.com/owner/repo",
                    key="pr-repo-url",
                )
                gh_token = st.text_input(
                    "GitHub Personal Access Token (`repo` scope β€” session-only, never stored)",
                    value=os.environ.get("GITHUB_TOKEN", ""),
                    type="password",
                    placeholder="ghp_... or github_pat_...",
                    key="pr-gh-token",
                )
                if st.button("πŸš€ Create Branch & Open Pull Request on GitHub", type="primary"):
                    if not parse_github_owner_repo(gh_url):
                        st.error("Please enter a valid GitHub repository URL (`https://github.com/owner/repo`).")
                    elif not gh_token.strip():
                        st.error("Please enter a GitHub Personal Access Token with write access to the repository.")
                    else:
                        try:
                            with st.spinner("Creating branch, committing files, and opening Pull Request..."):
                                ws = Workspace.open(values["workspace_root"])
                                issue_obj = values["issue"]
                                pr_res = create_github_pull_request(
                                    ws,
                                    repo_url=gh_url,
                                    github_token=gh_token,
                                    issue_title=issue_obj.title,
                                    issue_body=issue_obj.body,
                                    rationale=attempts[-1].rationale,
                                )
                            st.success(f"πŸŽ‰ Pull Request opened on `{pr_res.branch}`: {pr_res.pr_url}")
                            if pr_res.pr_url:
                                st.link_button("πŸ”— View Pull Request on GitHub", pr_res.pr_url)
                        except GitError as exc:
                            st.error(f"GitHub PR error: {exc}")
    elif status == "escalated":
        st.error(f"Escalated: {values.get('error')}")
        _render_report_download(values, key_suffix="escalated")


def _render_findings_report(values: dict[str, Any]) -> None:
    """Render the complete multi-issue repository audit report covering all detected issues."""
    repo_ctx = values.get("repo")
    findings = list(repo_ctx.findings) if repo_ctx and getattr(repo_ctx, "findings", None) else []
    if not findings:
        return

    badge_map = {
        "Critical": "πŸ”΄ **CRITICAL**",
        "High": "🟠 **HIGH**",
        "Medium": "🟑 **MEDIUM**",
        "Low": "πŸ”΅ **LOW**",
    }
    st.subheader(f"πŸ“‹ Repository Issues Report ({len(findings)} Issue(s) Found)")
    for idx, f in enumerate(findings, start=1):
        badge = badge_map.get(f.severity, f"🟠 **{f.severity.upper()}**")
        with st.expander(f"Issue #{idx}: {badge} β€” `{f.file_path}` Β· {f.title}", expanded=True):
            st.markdown(f"**Root Cause / Details:** {f.description}")
            if f.suggested_fix:
                st.markdown(f"**Recommended Fix:** {f.suggested_fix}")
    _render_report_download(values, key_suffix="audit-top")
    st.divider()


# --------------------------------------------------------------------------- page


def main() -> None:
    st.set_page_config(page_title="Autonomous Bug-Fixing Agent", page_icon="🐞", layout="wide")
    st.session_state.setdefault("thread_id", None)
    st.session_state.setdefault("log", [])
    st.session_state.setdefault("delay", 0.3)
    st.session_state.setdefault("run_mode", "demo")
    st.session_state.setdefault("last_error", None)
    st.session_state.setdefault("groq_model", resolve_groq_model())
    st.session_state.setdefault("groq_api_key", "")
    st.session_state.setdefault("sandbox_backend", "auto")

    st.title("🐞 Autonomous Bug-Fixing Agent")

    docker_up = DockerSandbox.is_available()
    has_env_key = bool(default_groq_api_key())
    has_any_key = has_env_key or bool(st.session_state.get("groq_api_key", "").strip())

    with st.sidebar:
        st.header("Scan GitHub Repository")
        repo_input = st.text_input(
            "GitHub Repository URL",
            placeholder="https://github.com/owner/repo",
            help="Paste any public GitHub repository URL. Leave blank to scan the built-in sample buggy repository.",
        )

        with st.expander("βš™οΈ Advanced Settings", expanded=False):
            mode_choice = st.radio(
                "Agent backend",
                options=["Live Groq Agent", "Scripted Demo (no API calls)"],
                index=0 if has_any_key else 1,
            )
            is_demo_choice = mode_choice.startswith("Scripted")
            model_options = list(AVAILABLE_GROQ_MODELS)
            default_idx = (
                model_options.index(st.session_state.groq_model)
                if st.session_state.groq_model in model_options
                else 0
            )
            st.session_state.groq_model = st.selectbox(
                "LLM Model (Groq or AWS Bedrock)",
                options=model_options,
                index=default_idx,
            )
            st.session_state.groq_api_key = st.text_input(
                "Groq API Key override (optional if set in .env or using Bedrock)",
                value=st.session_state.groq_api_key,
                type="password",
                placeholder="Using GROQ_API_KEY from .env" if has_env_key else "gsk_...",
            )
            st.session_state.sandbox_backend = st.selectbox(
                "Sandbox backend",
                options=["auto", "local", "docker"],
                index=0,
                help=f"Docker daemon reachable: {docker_up}",
            )
            st.slider("Demo step delay (s)", 0.0, 1.5, key="delay", step=0.1)

        is_bedrock_model = str(st.session_state.get("groq_model", "")).startswith("bedrock/")
        if not is_demo_choice and not has_any_key and not is_bedrock_model:
            st.session_state.groq_api_key = st.text_input(
                "πŸ”‘ Groq API Key (required for Live Groq mode)",
                value=st.session_state.groq_api_key,
                type="password",
                placeholder="gsk_...",
            )

        if st.button("▢️ Start run", type="primary", use_container_width=True):
            clean_url = repo_input.strip()
            effective_source = (
                "GitHub URL (shallow clone)" if clean_url else "Built-in sample buggy repo"
            )
            effective_repo_input = clean_url
            effective_title = (
                "Auto-detect all issues in repository" if clean_url else DEMO_ISSUE_TITLE
            )
            effective_body = (
                "Scan repository files, report all bugs and defects found across the repository, "
                "write a failing pytest reproduction test for the primary bug, and fix it."
                if clean_url
                else DEMO_ISSUE_BODY
            )
            effective_url: str | None = None
            effective_num: int | None = None

            if clean_url and not is_demo_choice:
                try:
                    fetched = fetch_github_issue(clean_url)
                    effective_repo_input = fetched.repo_clone_url
                    effective_url = fetched.html_url
                    effective_num = fetched.number
                    if not fetched.auto_detect and fetched.title:
                        effective_title = fetched.title
                        effective_body = fetched.body or fetched.title
                except Exception:  # noqa: BLE001
                    pass

            start_run(
                mode="demo" if is_demo_choice else "live",
                repo_source=effective_source,
                repo_input=effective_repo_input,
                issue_title=effective_title,
                issue_body=effective_body,
                issue_url=effective_url,
                issue_number=effective_num,
            )

        if is_aws_configured():
            with st.expander("☁️ AWS Cloud History (DynamoDB & S3)", expanded=False):
                runs = list_runs_from_dynamodb(limit=8)
                if not runs:
                    st.caption("No past runs logged in DynamoDB yet.")
                for r in runs:
                    st.markdown(
                        f"**`{r['run_id']}`** Β· `{r['status']}` ({r['findings_count']} issues)\n\n"
                        f"<small>{r['issue_title'][:60]}</small>",
                        unsafe_allow_html=True,
                    )
                    if r.get("s3_pdf_url"):
                        st.markdown(f"[πŸ“„ S3 PDF Report]({r['s3_pdf_url']})")
                    st.divider()

    if is_demo_choice:
        st.warning(
            "**Demo mode selected.** Runs the deterministic scripted agent (no LLM calls, no "
            "commits). Open **βš™οΈ Advanced Settings** and switch to **Live Groq Agent** to scan any GitHub URL."
        )
    else:
        sandbox_note = (
            "Docker container sandbox"
            if docker_up and st.session_state.sandbox_backend != "local"
            else "Local subprocess sandbox (secrets scrubbed, not container-isolated)"
        )
        st.info(
            f"**Live Groq mode (`{st.session_state.groq_model}`).** "
            f"Paste a GitHub repository URL in the sidebar and click **Start run** to scan all issues and generate a full report. "
            f"Tests execute in: **{sandbox_note}**."
        )

    if st.session_state.last_error:
        st.error(f"Run error: {st.session_state.last_error}")

    if st.session_state.thread_id is None:
        st.info("Paste a GitHub repository URL in the sidebar and press **Start run**.")
        return

    snap = _active_graph().get_state(_config())
    values = snap.values
    telemetry = _compute_telemetry(values, st.session_state.log)
    m1, m2, m3, m4, m5 = st.columns(5)
    m1.metric("Fix iterations", telemetry["iterations"])
    m2.metric("LLM calls", telemetry["llm_calls"])
    m3.metric("Sandbox runs", telemetry["sandbox_runs"])
    m4.metric("Est. tokens", telemetry["est_tokens"])
    m5.metric("Elapsed time", telemetry["elapsed"])

    _render_findings_report(values)

    st.subheader("Timeline")

    for node, update in st.session_state.log:
        render_event(node, update)

    interrupt_payload = None
    if snap.tasks and snap.tasks[0].interrupts:
        interrupt_payload = snap.tasks[0].interrupts[0].value

    if interrupt_payload is not None:  # paused at human_approval
        render_approval(interrupt_payload, values)
    else:
        render_outcome(values)


main()