Spaces:
Sleeping
feat: Next.js frontend with live IDE, URL routing, retry logic, and step tracker
Browse files- Add Next.js frontend with 3-pane IDE layout (explorer, editor, discovery)
- Implement URL-based routing: /owner/repo auto-loads repository
- Add live file highlighting as agent analyzes codebase
- Add VS Code-style bottom terminal drawer with step progress tracker
- Stream fix code directly into editor during step 4 (fix generation)
- Show fixedFileView in editor after analysis completes
- Add Result Actions panel with PR button and refinement chat
- Add retry with exponential backoff for GLM 429 rate limit errors
- Add inter-step delays to prevent burst rate limiting
- Fix hydration mismatch from browser extensions (suppressHydrationWarning)
- Add /api/file_content endpoint for browsing repo source files
- Make layout fit 100vh with compact top bar
Files changed (24)
- backend/agent.py+78-5
- backend/api.pyAdded+275
- backend/github_client.py+35
- backend/llm_client.py+71-24
- frontend/.gitignoreAdded+41
- frontend/AGENTS.mdAdded+5
- frontend/CLAUDE.mdAdded+1
- frontend/README.mdAdded+36
- frontend/eslint.config.mjsAdded+18
- frontend/next.config.tsAdded+7
- frontend/package-lock.jsonAdded
- frontend/package.jsonAdded+24
- frontend/public/file.svgAdded
- frontend/public/globe.svgAdded
- frontend/public/next.svgAdded
- frontend/public/vercel.svgAdded
- frontend/public/window.svgAdded
- frontend/src/app/[owner]/[repo]/page.tsxAdded+421
- frontend/src/app/favicon.icoAdded
- frontend/src/app/globals.cssAdded+219
- frontend/src/app/layout.tsxAdded+30
- frontend/src/app/page.tsxAdded+576
- frontend/tsconfig.jsonAdded+34
- requirements.txt+3
137 unmodified lines1381391401411421431441451461471481493 unmodified lines1531541551561571581591 unmodified line1611621631641651665 unmodified lines17217317417517617717817918018118218312 unmodified lines19619719819920020123 unmodified lines2252262272282292302317 unmodified lines239240241242243244136 unmodified lines381382383384385386387137 unmodified linest1 = time.time()result.bug_summary = self._step1_issue_understanding(result.issue_data, stream_callback)result.step_timings["1_issue"] = time.time() - t1self._emit("1_issue", "complete",f"Bug analysis complete in {result.step_timings['1_issue']:.1f}s")# ── Step 2: Codebase Mapping ──────────────────────────────────self._emit("2_mapping", "running", "Scanning codebase to identify suspect files...")t2 = time.time()3 unmodified linesresult.bug_summary,result.file_tree,result.issue_data,stream_callback,repo_url=repo_url,)result.step_timings["2_mapping"] = time.time() - t21 unmodified linef"Identified {len(result.suspect_file_paths)} suspect files in "f"{result.step_timings['2_mapping']:.1f}s")# ── Step 3: Deep Code Analysis ────────────────────────────────self._emit("3_analysis", "running",f"Reading {len(result.suspect_file_paths)} files + performing root cause analysis...")5 unmodified linesresult.root_cause_analysis = self._step3_deep_analysis(result.bug_summary,result.original_file_contents,stream_callback,)result.step_timings["3_analysis"] = time.time() - t3self._emit("3_analysis", "complete",f"Root cause identified in {result.step_timings['3_analysis']:.1f}s")# ── Step 4: Fix Generation ────────────────────────────────────self._emit("4_fix", "running", "Generating corrected file contents...")t4 = time.time()12 unmodified linesf"Generated fixes for {len(result.fixed_files)} file(s) in "f"{result.step_timings['4_fix']:.1f}s")# ── Step 5: Diff & Explanation ────────────────────────────────self._emit("5_diff", "running", "Generating diff and PR explanation...")t5 = time.time()23 unmodified linesf"# Root Cause\n{result.root_cause_analysis}\n\n"f"# Fix Explanation\n{result.fix_explanation}")result.confidence_eval = self._run_confidence_eval(combined)result.step_timings["6_confidence"] = time.time() - t6self._emit("6_confidence", "complete",f"Confidence eval done in {result.step_timings['6_confidence']:.1f}s")7 unmodified linesreturn result# ── Pipeline Steps ────────────────────────────────────────────────────────def _step1_issue_understanding(136 unmodified lines]return self._llm_call(messages, stream_cb, temperature=0.3)def _run_confidence_eval(self, analysis: str) -> str:self._current_step = "6_confidence"prompt = CONFIDENCE_EVAL_PROMPT.format(analysis=analysis[:4000])messages = [137 unmodified lines1381391401411421431441451461471481491503 unmodified lines1541551561571581591601 unmodified line1621631641651661671685 unmodified lines17417517617717817918018118218318418518612 unmodified lines19920020120220320420523 unmodified lines2292302312322332342357 unmodified lines243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317136 unmodified lines454455456457458459460137 unmodified linest1 = time.time()result.bug_summary = self._step1_issue_understanding(result.issue_data, None # reasoning step — don't stream to UI)result.step_timings["1_issue"] = time.time() - t1self._emit("1_issue", "complete",f"Bug analysis complete in {result.step_timings['1_issue']:.1f}s")time.sleep(2) # avoid burst rate-limiting# ── Step 2: Codebase Mapping ──────────────────────────────────self._emit("2_mapping", "running", "Scanning codebase to identify suspect files...")t2 = time.time()3 unmodified linesresult.bug_summary,result.file_tree,result.issue_data,None, # reasoning step — don't stream to UIrepo_url=repo_url,)result.step_timings["2_mapping"] = time.time() - t21 unmodified linef"Identified {len(result.suspect_file_paths)} suspect files in "f"{result.step_timings['2_mapping']:.1f}s")time.sleep(2) # avoid burst rate-limiting# ── Step 3: Deep Code Analysis ────────────────────────────────self._emit("3_analysis", "running",f"Reading {len(result.suspect_file_paths)} files + performing root cause analysis...")5 unmodified linesresult.root_cause_analysis = self._step3_deep_analysis(result.bug_summary,result.original_file_contents,None, # reasoning step — don't stream to UI)result.step_timings["3_analysis"] = time.time() - t3self._emit("3_analysis", "complete",f"Root cause identified in {result.step_timings['3_analysis']:.1f}s")time.sleep(2) # avoid burst rate-limiting# ── Step 4: Fix Generation ────────────────────────────────────self._emit("4_fix", "running", "Generating corrected file contents...")t4 = time.time()12 unmodified linesf"Generated fixes for {len(result.fixed_files)} file(s) in "f"{result.step_timings['4_fix']:.1f}s")time.sleep(2) # avoid burst rate-limiting# ── Step 5: Diff & Explanation ────────────────────────────────self._emit("5_diff", "running", "Generating diff and PR explanation...")t5 = time.time()23 unmodified linesf"# Root Cause\n{result.root_cause_analysis}\n\n"f"# Fix Explanation\n{result.fix_explanation}")result.confidence_eval = self._run_confidence_eval(combined) # don't streamresult.step_timings["6_confidence"] = time.time() - t6self._emit("6_confidence", "complete",f"Confidence eval done in {result.step_timings['6_confidence']:.1f}s")7 unmodified linesreturn resultdef refine_fix(self,feedback: str,result: AgentResult,on_status: StatusCallback = None,stream_callback: Optional[Callable[[str], None]] = None,) -> AgentResult:"""Re-runs Step 4 and Step 5 by appending user feedback to the existing context.Modifies and returns the same AgentResult object."""self._status = on_status or (lambda *a: None)try:# ── Refine Fix Generation ─────────────────────────────────────self._emit("4_refine", "running", "Refining the code based on your feedback...")t4 = time.time()# We append the feedback to the root cause to guide the fix generationrefined_root_cause = (result.root_cause_analysis +f"\n\n[USER FEEDBACK ON PREVIOUS FIX]:\n"f"The user reviewed the proposed fix and said:\n'{feedback}'\n\n"f"Please update and refine the code correction to satisfy this feedback.")result.fix_generation_raw = self._step4_fix_generation(refined_root_cause,result.original_file_contents,stream_callback,)result.fixed_files = parse_fixed_files_from_llm_response(result.fix_generation_raw,result.suspect_file_paths,)result.step_timings["4_refine"] = time.time() - t4self._emit("4_refine", "complete",f"Generated refined fixes for {len(result.fixed_files)} file(s) in "f"{result.step_timings['4_refine']:.1f}s")# ── Regenerate Diff & Explanation ─────────────────────────────self._emit("5_diff", "running", "Generating updated diff and PR explanation...")t5 = time.time()result.diffs = generate_all_diffs(result.original_file_contents, result.fixed_files)result.diff_formatted = format_diff_for_display(result.diffs)result.diff_stats = get_diff_stats(result.diffs)result.fix_explanation = self._step5_explanation(result.bug_summary,refined_root_cause,result.diff_formatted,stream_callback,)result.step_timings["5_diff_refined"] = time.time() - t5self._emit("5_diff", "complete",f"Updated PR explanation ready in {result.step_timings['5_diff_refined']:.1f}s")except Exception as e:logger.exception("FixFlow refinement failed")step = self._current_step or "unknown"result.step_errors[step] = str(e)self._emit(step, "error", f"❌ Refinement failed: {e}")raisereturn result# ── Pipeline Steps ────────────────────────────────────────────────────────def _step1_issue_understanding(136 unmodified lines]return self._llm_call(messages, stream_cb, temperature=0.3)def _run_confidence_eval(self, analysis: str, stream_cb: Optional[Callable] = None) -> str:self._current_step = "6_confidence"prompt = CONFIDENCE_EVAL_PROMPT.format(analysis=analysis[:4000])messages = [
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275import asyncioimport jsonimport loggingimport timeimport uuidfrom threading import Threadfrom typing import Dict, Any
from fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom sse_starlette.sse import EventSourceResponse
from backend.agent import FixFlowAgentfrom backend.config import GLM_MODEL, GLM_BASE_URL, GLM_API_KEY, GITHUB_TOKENfrom backend.github_client import GitHubClientfrom backend.llm_client import GLMClient
logger = logging.getLogger(__name__)
app = FastAPI(title="FixFlow API")
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
SESSION_CACHE: Dict[str, Any] = {}
class AnalyzeRequest(BaseModel): issue_url: str repo_url: str run_confidence: bool = True
@app.get("/api/analyze")async def analyze_endpoint(issue_url: str, repo_url: str, run_confidence: bool = True): if not GLM_API_KEY: raise HTTPException(status_code=400, detail="Missing GLM API key in backend config")
session_id = str(uuid.uuid4()) queue = asyncio.Queue()
def sync_runner(): llm = GLMClient( api_key=GLM_API_KEY, base_url=GLM_BASE_URL, model=GLM_MODEL, ) gh = GitHubClient(token=GITHUB_TOKEN) agent = FixFlowAgent(llm_client=llm, github_client=gh)
def on_status(step: str, status: str, message: str): asyncio.run_coroutine_threadsafe( queue.put({"type": "status", "data": {"step": step, "status": status, "message": message}}), loop )
def on_stream(chunk: str): asyncio.run_coroutine_threadsafe( queue.put({"type": "stream", "data": {"chunk": chunk}}), loop )
try: result = agent.run( issue_url=issue_url, repo_url=repo_url, on_status=on_status, stream_callback=on_stream, run_confidence_eval=run_confidence, ) payload = { "bug_summary": result.bug_summary, "relevant_files_analysis": result.relevant_files_analysis, "suspect_file_paths": result.suspect_file_paths, "root_cause_analysis": result.root_cause_analysis, "diff_formatted": result.diff_formatted, "fix_explanation": result.fix_explanation, "diff_stats": result.diff_stats, "step_timings": result.step_timings, "fixed_files": result.fixed_files, "issue_title": result.issue_data.get("title", "Bug fix") } SESSION_CACHE[session_id] = result asyncio.run_coroutine_threadsafe( queue.put({"type": "done", "data": {"result": payload, "session_id": session_id}}), loop ) except Exception as e: logger.exception("Agent run failed") asyncio.run_coroutine_threadsafe( queue.put({"type": "error", "data": {"error": str(e)}}), loop ) finally: asyncio.run_coroutine_threadsafe( queue.put({"type": "eof"}), loop )
loop = asyncio.get_running_loop() thread = Thread(target=sync_runner) thread.start()
async def event_generator(): while True: try: # Wait up to 15s before sending a heartbeat ping to keep connection alive msg = await asyncio.wait_for(queue.get(), timeout=15.0) if msg["type"] == "eof": break yield { "event": msg["type"], "data": json.dumps(msg["data"]) } except asyncio.TimeoutError: # Send a heartbeat comment to prevent browser SSE timeout yield {"event": "heartbeat", "data": json.dumps({"alive": True})}
return EventSourceResponse(event_generator())
class PRRequest(BaseModel): repo_url: str title: str body: str fixed_files: Dict[str, str]
@app.post("/api/pr")def create_pr(req: PRRequest): if not GITHUB_TOKEN: raise HTTPException(status_code=400, detail="Missing GITHUB_TOKEN in backend config for PR creation") gh = GitHubClient(token=GITHUB_TOKEN) branch_name = f"fixflow-patch-{int(time.time())}" try: url = gh.create_pull_request( repo_url=req.repo_url, branch_name=branch_name, files_content=req.fixed_files, title=req.title, body=req.body ) return {"url": url} except Exception as e: logger.exception("PR creation failed") raise HTTPException(status_code=400, detail=str(e))
@app.get("/api/repo_info")def get_repo_info(repo_url: str): """ Fetch repository file tree and list open issues. """ try: gh = GitHubClient(token=GITHUB_TOKEN) # Fetch repo tree (flat list) tree = gh.fetch_repo_tree(repo_url) # Fetch top 10 open issues issues = gh.list_open_issues(repo_url, limit=10) return { "tree": tree, "issues": issues, "repo_url": repo_url } except Exception as e: logger.exception("Repo info fetch failed") raise HTTPException(status_code=400, detail=str(e))
raise HTTPException(status_code=400, detail=str(e))
@app.get("/api/file_content")def get_file_content(repo_url: str, file_path: str): """ Fetch the raw content of a specific file in the repository. """ try: gh = GitHubClient(token=GITHUB_TOKEN) content = gh.fetch_file_content(repo_url, file_path) return {"content": content, "path": file_path} except Exception as e: logger.exception("File content fetch failed") raise HTTPException(status_code=400, detail=str(e))
@app.get("/api/refine")async def refine_endpoint(session_id: str, feedback: str): if not GLM_API_KEY: raise HTTPException(status_code=400, detail="Missing GLM API key in backend config") if session_id not in SESSION_CACHE: raise HTTPException(status_code=404, detail="Session not found or expired")
queue = asyncio.Queue()
def sync_runner(): llm = GLMClient( api_key=GLM_API_KEY, base_url=GLM_BASE_URL, model=GLM_MODEL, ) gh = GitHubClient(token=GITHUB_TOKEN) agent = FixFlowAgent(llm_client=llm, github_client=gh) previous_result = SESSION_CACHE[session_id]
def on_status(step: str, status: str, message: str): asyncio.run_coroutine_threadsafe( queue.put({"type": "status", "data": {"step": step, "status": status, "message": message}}), loop )
def on_stream(chunk: str): asyncio.run_coroutine_threadsafe( queue.put({"type": "stream", "data": {"chunk": chunk}}), loop )
try: result = agent.refine_fix( feedback=feedback, result=previous_result, on_status=on_status, stream_callback=on_stream, ) payload = { "bug_summary": result.bug_summary, "relevant_files_analysis": result.relevant_files_analysis, "suspect_file_paths": result.suspect_file_paths, "root_cause_analysis": result.root_cause_analysis, "diff_formatted": result.diff_formatted, "fix_explanation": result.fix_explanation, "diff_stats": result.diff_stats, "step_timings": result.step_timings, "fixed_files": result.fixed_files, "issue_title": result.issue_data.get("title", "Bug fix") } SESSION_CACHE[session_id] = result asyncio.run_coroutine_threadsafe( queue.put({"type": "done", "data": {"result": payload, "session_id": session_id}}), loop ) except Exception as e: logger.exception("Agent run failed") asyncio.run_coroutine_threadsafe( queue.put({"type": "error", "data": {"error": str(e)}}), loop ) finally: asyncio.run_coroutine_threadsafe( queue.put({"type": "eof"}), loop )
loop = asyncio.get_running_loop() thread = Thread(target=sync_runner) thread.start()
async def event_generator(): while True: try: msg = await asyncio.wait_for(queue.get(), timeout=15.0) if msg["type"] == "eof": break yield { "event": msg["type"], "data": json.dumps(msg["data"]) } except asyncio.TimeoutError: yield {"event": "heartbeat", "data": json.dumps({"alive": True})}
return EventSourceResponse(event_generator())119 unmodified lines120121122123124125119 unmodified lines"repo_name": repo_name,}# ── Repo Tree ─────────────────────────────────────────────────────────────def fetch_repo_tree(119 unmodified lines120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160119 unmodified lines"repo_name": repo_name,}def list_open_issues(self, repo_url: str, limit: int = 20) -> List[Dict]:"""List open issues for a repository.Returns a list of structured dicts: {title, number, url, author, created_at, body_snippet}"""owner, repo_name = parse_repo_url(repo_url)logger.info("Listing open issues for %s/%s", owner, repo_name)try:repo = self._gh.get_repo(f"{owner}/{repo_name}")# state='open' by defaultissues = repo.get_issues(state='open', sort='updated', direction='desc')result = []for issue in issues:# Skip Pull Requests (PyGithub get_issues() returns both)if issue.pull_request:continueresult.append({"title": issue.title,"number": issue.number,"url": issue.html_url,"author": issue.user.login if issue.user else "unknown","created_at": str(issue.created_at),"body_snippet": (issue.body[:200] + "...") if issue.body else "",})if len(result) >= limit:breakreturn resultexcept GithubException as e:raise RuntimeError(f"Failed to list issues: {e.data.get('message', str(e))}") from e# ── Repo Tree ─────────────────────────────────────────────────────────────def fetch_repo_tree(
123456789101112131421 unmodified lines363738394041424344454647483 unmodified lines525354555657585960616263646566676869701 unmodified line727374757677782 unmodified lines81828384858687888990919293949596979899"""LLM Client for GLM 5.1 via Z.ai API (OpenAI-compatible endpoint)."""import timeimport loggingfrom typing import Iterator, List, Dict, Any, Optionalimport openaifrom backend.config import GLM_API_KEY, GLM_BASE_URL, GLM_MODEL, LOG_LLM_CALLSlogger = logging.getLogger(__name__)class GLMClient:"""OpenAI-compatible wrapper for Z.ai's GLM models."""21 unmodified lines)return self._clientdef chat(self,messages: List[Dict[str, str]],temperature: float = 0.3,max_tokens: int = 4096,) -> str:"""Synchronous chat completion. Returns the full response string."""client = self._get_client()start = time.time()3 unmodified linesself.model, len(messages), temperature,)response = client.chat.completions.create(model=self.model,messages=messages,temperature=temperature,max_tokens=max_tokens,)content = response.choices[0].message.content or ""elapsed = time.time() - startif LOG_LLM_CALLS:logger.info("[GLM] completed in %.2fs | output_chars=%d", elapsed, len(content))return contentdef chat_stream(self,1 unmodified linetemperature: float = 0.3,max_tokens: int = 4096,) -> Iterator[str]:"""Streaming chat completion. Yields text chunks as they arrive."""client = self._get_client()if LOG_LLM_CALLS:2 unmodified linesself.model, len(messages),)response = client.chat.completions.create(model=self.model,messages=messages,temperature=temperature,max_tokens=max_tokens,stream=True,)for chunk in response:delta = chunk.choices[0].deltaif delta and delta.content:yield delta.contentdef update_api_key(self, api_key: str) -> None:"""Allow hot-swapping the API key (e.g. from Streamlit sidebar)."""self.api_key = api_keyself._client = None # Force re-initialization1234567891011121314151617181921 unmodified lines414243444546474849505152535455565758593 unmodified lines6364656667686970717273747576777879808182838485868788899091929394959697981 unmodified line1001011021031041051062 unmodified lines109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146"""LLM Client for GLM 5.1 via Z.ai API (OpenAI-compatible endpoint).Includes automatic retry with exponential backoff for rate-limit (429) errors."""import timeimport loggingimport randomfrom typing import Iterator, List, Dict, Any, Optionalimport openaifrom backend.config import GLM_API_KEY, GLM_BASE_URL, GLM_MODEL, LOG_LLM_CALLSlogger = logging.getLogger(__name__)MAX_RETRIES = 5INITIAL_BACKOFF = 5 # secondsclass GLMClient:"""OpenAI-compatible wrapper for Z.ai's GLM models."""21 unmodified lines)return self._clientdef _backoff_wait(self, attempt: int) -> None:"""Exponential backoff with jitter. Waits and logs the wait time."""wait = INITIAL_BACKOFF * (2 ** attempt) + random.uniform(0, 2)logger.warning("[GLM] Rate limited (429). Retrying in %.1fs (attempt %d/%d)...", wait, attempt + 1, MAX_RETRIES)time.sleep(wait)def chat(self,messages: List[Dict[str, str]],temperature: float = 0.3,max_tokens: int = 4096,) -> str:"""Synchronous chat completion with automatic retry on 429."""client = self._get_client()start = time.time()3 unmodified linesself.model, len(messages), temperature,)last_error = Nonefor attempt in range(MAX_RETRIES):try:response = client.chat.completions.create(model=self.model,messages=messages,temperature=temperature,max_tokens=max_tokens,)content = response.choices[0].message.content or ""elapsed = time.time() - startif LOG_LLM_CALLS:logger.info("[GLM] completed in %.2fs | output_chars=%d", elapsed, len(content))return contentexcept openai.RateLimitError as e:last_error = eif attempt < MAX_RETRIES - 1:self._backoff_wait(attempt)else:raise RuntimeError(f"GLM API rate limit exceeded after {MAX_RETRIES} retries. "f"Please wait a moment and try again. Detail: {e}") from eexcept openai.APIError as e:raise RuntimeError(f"GLM API error: {e}") from eraise RuntimeError(f"GLM request failed after {MAX_RETRIES} attempts: {last_error}")def chat_stream(self,1 unmodified linetemperature: float = 0.3,max_tokens: int = 4096,) -> Iterator[str]:"""Streaming chat completion with automatic retry on 429."""client = self._get_client()if LOG_LLM_CALLS:2 unmodified linesself.model, len(messages),)last_error = Nonefor attempt in range(MAX_RETRIES):try:response = client.chat.completions.create(model=self.model,messages=messages,temperature=temperature,max_tokens=max_tokens,stream=True,)for chunk in response:delta = chunk.choices[0].deltaif delta and delta.content:yield delta.contentreturn # Completed successfullyexcept openai.RateLimitError as e:last_error = eif attempt < MAX_RETRIES - 1:self._backoff_wait(attempt)else:raise RuntimeError(f"GLM API rate limit exceeded after {MAX_RETRIES} retries. "f"Please wait a moment and try again. Detail: {e}") from eexcept openai.APIError as e:raise RuntimeError(f"GLM API error: {e}") from eraise RuntimeError(f"GLM stream failed after {MAX_RETRIES} attempts: {last_error}")def update_api_key(self, api_key: str) -> None:"""Allow hot-swapping the API key (e.g. from Streamlit sidebar)."""self.api_key = api_keyself._client = None # Force re-initialization
1234567891011121314151617181920212223242526272829303132333435363738394041# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies/node_modules/.pnp.pnp.*.yarn/*!.yarn/patches!.yarn/plugins!.yarn/releases!.yarn/versions
# testing/coverage
# next.js/.next//out/
# production/build
# misc.DS_Store*.pem
# debugnpm-debug.log*yarn-debug.log*yarn-error.log*.pnpm-debug.log*
# env files (can opt-in for committing if needed).env*
# vercel.vercel
# typescript*.tsbuildinfonext-env.d.ts12345<!-- BEGIN:nextjs-agent-rules --># This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.<!-- END:nextjs-agent-rules -->1@AGENTS.md123456789101112131415161718192021222324252627282930313233343536This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bashnpm run dev# oryarn dev# orpnpm dev# orbun dev```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.123456789101112131415161718import { defineConfig, globalIgnores } from "eslint/config";import nextVitals from "eslint-config-next/core-web-vitals";import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([ ...nextVitals, ...nextTs, // Override default ignores of eslint-config-next. globalIgnores([ // Default ignores of eslint-config-next: ".next/**", "out/**", "build/**", "next-env.d.ts", ]),]);
export default eslintConfig;1234567import type { NextConfig } from "next";
const nextConfig: NextConfig = { /* config options here */};
export default nextConfig;123456789101112131415161718192021222324{ "name": "frontend", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "eslint" }, "dependencies": { "next": "16.2.2", "react": "19.2.4", "react-dom": "19.2.4" }, "devDependencies": { "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", "eslint": "^9", "eslint-config-next": "16.2.2", "typescript": "^5" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421"use client";
import React, { useState, useRef, useEffect } from 'react';import { useParams, useRouter } from 'next/navigation';
type UI_STATE = 'LOADING_REPO' | 'REPO_DASHBOARD';
interface GitHubIssue { title: string; number: number; url: string; author: string; created_at: string; body_snippet: string;}
interface RepoFile { path: string; size: number; type: string;}
export default function RepoDashboard() { const params = useParams(); const router = useRouter(); const owner = params.owner as string; const repo = params.repo as string; const repoUrl = `https://github.com/${owner}/${repo}`;
const [uiState, setUiState] = useState<UI_STATE>('LOADING_REPO'); const [repoInfo, setRepoInfo] = useState<{ tree: RepoFile[], issues: GitHubIssue[] } | null>(null); const [selectedFilePath, setSelectedFilePath] = useState<string | null>(null); const [selectedFileContent, setSelectedFileContent] = useState<string>(""); const [isLoadingFile, setIsLoadingFile] = useState(false); const [error, setError] = useState("");
const [issueUrl, setIssueUrl] = useState(""); const [runConfidence] = useState(true); const [running, setRunning] = useState(false); const [statusName, setStatusName] = useState(""); const [statusMessage, setStatusMessage] = useState(""); const [streamChunks, setStreamChunks] = useState<string[]>([]); const [result, setResult] = useState<any>(null); const [analyzingFiles, setAnalyzingFiles] = useState<string[]>([]); const [terminalExpanded, setTerminalExpanded] = useState(true); const [completedSteps, setCompletedSteps] = useState<{step: string, message: string, status: string}[]>([]); const [fixedFileView, setFixedFileView] = useState<{path: string, content: string} | null>(null); const [sessionId, setSessionId] = useState(""); const [feedback, setFeedback] = useState("");
const logsEndRef = useRef<HTMLDivElement>(null);
// Auto-load repo on mount useEffect(() => { const loadRepo = async () => { try { const res = await fetch(`http://127.0.0.1:8000/api/repo_info?repo_url=${encodeURIComponent(repoUrl)}`); if (!res.ok) { const data = await res.json(); throw new Error(data.detail || "Failed to fetch repository info"); } const data = await res.json(); setRepoInfo(data); setUiState('REPO_DASHBOARD'); if (data.tree && data.tree.length > 0) { handleFileClick(data.tree[0].path, repoUrl); } } catch (err: any) { setError(err.message); } }; loadRepo(); }, [owner, repo]);
useEffect(() => { if (logsEndRef.current) { logsEndRef.current.scrollIntoView({ behavior: "smooth" }); } }, [streamChunks, statusMessage, running]);
useEffect(() => { if (statusMessage) { const pathRegex = /([a-zA-Z0-9._\-/]+\.(py|js|tsx|ts|html|css|json|md))/g; const matches = statusMessage.match(pathRegex); if (matches) { setAnalyzingFiles(prev => [...new Set([...prev, ...matches])]); const validPath = matches.find(p => repoInfo?.tree.some(f => f.path === p)); if (validPath && validPath !== selectedFilePath) { handleFileClick(validPath, repoUrl); } } } }, [statusMessage]);
const handleFileClick = async (path: string, url?: string) => { const repoUrlToUse = url || repoUrl; setSelectedFilePath(path); setIsLoadingFile(true); try { const res = await fetch(`http://127.0.0.1:8000/api/file_content?repo_url=${encodeURIComponent(repoUrlToUse)}&file_path=${encodeURIComponent(path)}`); if (!res.ok) throw new Error("Failed to fetch file content"); const data = await res.json(); setSelectedFileContent(data.content); } catch { setSelectedFileContent("// Error loading file content..."); } finally { setIsLoadingFile(false); } };
const handleAnalyze = (selectedIssueUrl?: string) => { const finalIssueUrl = selectedIssueUrl || issueUrl; if (!finalIssueUrl) { setError("Please provide an Issue URL"); return; }
setRunning(true); setError(""); setResult(null); setStreamChunks([]); setAnalyzingFiles([]); setCompletedSteps([]); setFixedFileView(null); setTerminalExpanded(true); setStatusName("Starting"); setStatusMessage("Connecting to FixFlow API...");
const params = new URLSearchParams({ issue_url: finalIssueUrl, repo_url: repoUrl, run_confidence: runConfidence.toString() }); const eventSource = new EventSource(`http://127.0.0.1:8000/api/analyze?${params.toString()}`); setupEventSource(eventSource); };
const handleRefine = () => { if (!feedback || !sessionId) return; setRunning(true); setError(""); setStreamChunks([]); setAnalyzingFiles([]); setCompletedSteps([]); setFixedFileView(null); setTerminalExpanded(true); setStatusName("Refining"); setStatusMessage("Sending feedback to FixFlow..."); const params = new URLSearchParams({ session_id: sessionId, feedback }); setFeedback(""); const eventSource = new EventSource(`http://127.0.0.1:8000/api/refine?${params.toString()}`); setupEventSource(eventSource); };
const setupEventSource = (eventSource: EventSource) => { eventSource.addEventListener("status", (e: Event) => { const data = JSON.parse((e as MessageEvent).data); const { step, status, message } = data; setStatusName(step); setStatusMessage(message); if (status === "complete" || status === "error") { setCompletedSteps(prev => [...prev, { step, status, message }]); } }); eventSource.addEventListener("stream", (e: Event) => { const data = JSON.parse((e as MessageEvent).data); setStreamChunks(prev => [...prev, data.chunk]); }); eventSource.addEventListener("done", (e: Event) => { const data = JSON.parse((e as MessageEvent).data); const r = data.result; setResult(r); if (data.session_id) setSessionId(data.session_id); if (r?.fixed_files) { const paths = Object.keys(r.fixed_files); if (paths.length > 0) { setFixedFileView({ path: paths[0], content: r.fixed_files[paths[0]] }); setSelectedFilePath(paths[0]); } } }); eventSource.addEventListener("error", (e: Event) => { const data = JSON.parse((e as MessageEvent).data); setError(data.error || "Unknown stream error"); setRunning(false); eventSource.close(); }); eventSource.addEventListener("eof", () => { setRunning(false); setStatusName("Done"); setStatusMessage("Fix generated — review the highlighted file in the editor."); setCompletedSteps(prev => [...prev, { step: "done", status: "complete", message: "Fix generated — review highlighted file!" }]); eventSource.close(); }); eventSource.addEventListener("heartbeat", () => {}); eventSource.onerror = (e) => console.error("SSE Error:", e); };
const handleOpenPR = async () => { if (!result) return; try { const res = await fetch("http://127.0.0.1:8000/api/pr", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ repo_url: repoUrl, title: result.issue_title, body: result.fix_explanation + "\n\n---\n*Generated autonomously by FixFlow*", fixed_files: result.fixed_files }) }); const data = await res.json(); if (!res.ok) throw new Error(data.detail || "Failed to create PR"); window.open(data.url, "_blank"); } catch (err: any) { alert("Error: " + err.message); } };
// ── Loading Screen ──────────────────────────────────────────────────────── if (uiState === 'LOADING_REPO') { return ( <div style={{ height: '100vh', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}> <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 24px', borderBottom: '1px solid var(--border-color)', flexShrink: 0 }}> <span style={{ fontSize: '1.4rem', cursor: 'pointer' }} onClick={() => router.push('/')}>🔧</span> <span style={{ fontWeight: 800, fontSize: '1.2rem', background: 'linear-gradient(135deg, var(--primary), var(--secondary))', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>FixFlow</span> <span style={{ color: 'var(--text-muted)', fontSize: '0.8rem', fontFamily: 'monospace' }}>/ {owner} / {repo}</span> </div> <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 16 }}> <div className="loading-spinner" style={{ width: 36, height: 36 }} /> <p style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>Cloning <strong style={{ color: 'var(--text-main)' }}>{owner}/{repo}</strong>...</p> {error && <div style={{ color: 'var(--error)', fontSize: '0.85rem' }}>❌ {error}</div>} </div> </div> ); }
// ── IDE Dashboard ───────────────────────────────────────────────────────── if (!repoInfo) return null;
return ( <div style={{ height: '100vh', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}> {/* Top Bar */} <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 24px', borderBottom: '1px solid var(--border-color)', flexShrink: 0 }}> <span style={{ fontSize: '1.4rem', cursor: 'pointer' }} onClick={() => router.push('/')}>🔧</span> <span style={{ fontWeight: 800, fontSize: '1.2rem', background: 'linear-gradient(135deg, var(--primary), var(--secondary))', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>FixFlow</span> <span style={{ color: 'var(--border-color)' }}>/</span> <a href={repoUrl} target="_blank" rel="noreferrer" style={{ color: 'var(--text-muted)', fontSize: '0.85rem', fontFamily: 'monospace', textDecoration: 'none' }}> {owner}/<strong style={{ color: 'var(--text-main)' }}>{repo}</strong> </a> <span style={{ marginLeft: 'auto', fontSize: '0.75rem', color: 'var(--text-muted)' }}>{repoInfo.tree.length} files</span> </div>
{/* Main IDE */} <div style={{ flex: 1, padding: '16px', display: 'flex', overflow: 'hidden' }}> <div style={{ display: 'grid', gridTemplateColumns: '240px 1fr 300px', gap: 16, flex: 1, minHeight: 0 }}>
{/* Left: Explorer */} <div className="glass-panel" style={{ padding: 16, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}> <h3 style={{ marginBottom: 12, fontSize: '0.8rem', color: 'var(--text-main)', opacity: 0.6, letterSpacing: '0.1em' }}>📁 EXPLORER</h3> <div style={{ flex: 1, overflowY: 'auto', fontSize: '0.78rem', color: 'var(--text-muted)', fontFamily: 'monospace' }}> {repoInfo.tree.map((file, i) => { const isAnalyzing = analyzingFiles.includes(file.path); return ( <div key={i} onClick={() => handleFileClick(file.path)} className={isAnalyzing ? 'analyzing-glow' : ''} style={{ padding: '5px 8px', cursor: 'pointer', borderRadius: '4px', marginBottom: '1px', backgroundColor: selectedFilePath === file.path ? 'rgba(139, 92, 246, 0.15)' : 'transparent', color: selectedFilePath === file.path ? 'var(--primary)' : 'inherit', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', transition: 'all 0.2s ease' }} > <span style={{ marginRight: 6 }}>{isAnalyzing ? '🧠' : '📄'}</span> {file.path} </div> ); })} </div> </div>
{/* Center: Editor + Terminal Drawer */} <div style={{ display: 'flex', flexDirection: 'column', minHeight: 0 }}> <div className="terminal-window" style={{ flex: 1, display: 'flex', flexDirection: 'column', borderBottomLeftRadius: 0, borderBottomRightRadius: 0, minHeight: 0 }}> <div className="terminal-header"> <div className="terminal-dot dot-red"></div> <div className="terminal-dot dot-yellow"></div> <div className="terminal-dot dot-green"></div> <div style={{ marginLeft: '12px', fontSize: '0.75rem', color: 'var(--text-muted)', fontFamily: 'monospace' }}> {running && (statusName === '4_fix' || statusName === '4_refine') ? '🔧 Generating Fix...' : selectedFilePath || 'Editor'} </div> </div> <div style={{ flex: 1, overflow: 'auto', backgroundColor: '#0d0d12' }}> {fixedFileView && !running ? ( <pre style={{ margin: 0, padding: '20px', fontSize: '0.83rem', fontFamily: 'monospace', color: '#a3be8c', lineHeight: '1.6' }}> {fixedFileView.content} </pre> ) : running && (statusName === '4_fix' || statusName === '4_refine') && streamChunks.length > 0 ? ( <pre style={{ margin: 0, padding: '20px', fontSize: '0.83rem', fontFamily: 'monospace', color: '#a3be8c', lineHeight: '1.6' }}> {streamChunks.join('')} <span style={{ borderRight: '2px solid var(--primary)' }}> </span> <div ref={logsEndRef} /> </pre> ) : ( <pre style={{ margin: 0, padding: '20px', fontSize: '0.83rem', fontFamily: 'monospace', color: '#d1d5db', lineHeight: '1.6' }}> {selectedFileContent || '// Select a file to browse source code'} </pre> )} </div> </div>
{/* Terminal Drawer */} <div className="terminal-drawer" style={{ height: terminalExpanded ? '200px' : '40px', borderRadius: '0 0 12px 12px' }}> <div className="terminal-drawer-header" onClick={() => setTerminalExpanded(!terminalExpanded)}> <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}> {running && <span className="loading-spinner" style={{ width: 12, height: 12 }} />} <span style={{ color: running ? 'var(--primary)' : 'var(--text-muted)' }}> {statusName ? `AGENT — [${statusName.toUpperCase()}]` : 'FIXFLOW AGENT CONSOLE'} </span> </div> <span>{terminalExpanded ? '▼' : '▲ Show Progress'}</span> </div> <div className="terminal-drawer-body" style={{ padding: '10px 16px' }}> {completedSteps.map((s, i) => ( <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6, fontSize: '0.78rem' }}> <span style={{ color: s.status === 'error' ? 'var(--error)' : 'var(--success)', flexShrink: 0 }}> {s.status === 'error' ? '✗' : '✓'} </span> <span style={{ color: 'var(--text-muted)' }}>{s.message}</span> </div> ))} {running && statusMessage && ( <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: '0.78rem' }}> <span className="loading-spinner" style={{ width: 10, height: 10, flexShrink: 0 }} /> <span style={{ color: 'var(--primary)' }}>{statusMessage}</span> </div> )} <div ref={logsEndRef} /> </div> </div> </div>
{/* Right: Discovery or Result */} <div className="glass-panel" style={{ padding: 16, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}> {result && !running ? ( <> <h3 style={{ marginBottom: 6, fontSize: '0.85rem', color: 'var(--success)' }}>✅ FIX READY</h3> <p style={{ fontSize: '0.72rem', color: 'var(--text-muted)', marginBottom: 12, lineHeight: 1.5 }}> {result.bug_summary?.slice(0, 150)}... </p> <div style={{ marginBottom: 12 }}> <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)', marginBottom: 6, letterSpacing: '0.1em' }}>CHANGED FILES:</div> {Object.keys(result.fixed_files || {}).map((path) => ( <div key={path} onClick={() => setFixedFileView({ path, content: result.fixed_files[path] })} style={{ padding: '6px 10px', borderRadius: 6, marginBottom: 4, cursor: 'pointer', fontSize: '0.72rem', fontFamily: 'monospace', backgroundColor: fixedFileView?.path === path ? 'rgba(163, 190, 140, 0.15)' : 'rgba(255,255,255,0.04)', color: fixedFileView?.path === path ? '#a3be8c' : 'var(--text-muted)', border: fixedFileView?.path === path ? '1px solid rgba(163,190,140,0.3)' : '1px solid transparent', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} > 📝 {path} </div> ))} </div> <div style={{ flex: 1 }} /> <button type="button" className="glow-btn" style={{ width: '100%', marginBottom: 8, padding: '10px', fontSize: '0.82rem' }} onClick={handleOpenPR}> 🚀 Open Pull Request </button> <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}> <input className="input-field" style={{ flex: 1, padding: '7px 10px', fontSize: '0.75rem' }} placeholder="Refine the fix..." value={feedback} onChange={(e) => setFeedback(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && handleRefine()} /> <button type="button" className="glow-btn" style={{ padding: '8px 12px', fontSize: '0.8rem' }} onClick={handleRefine} disabled={!feedback}>↩</button> </div> <button type="button" style={{ background: 'none', border: 'none', color: 'var(--text-muted)', cursor: 'pointer', fontSize: '0.72rem' }} onClick={() => { setResult(null); setFixedFileView(null); setCompletedSteps([]); }}> ← Pick another issue </button> </> ) : ( <> <h3 style={{ marginBottom: 12, fontSize: '0.8rem', color: 'var(--text-main)', opacity: 0.6, letterSpacing: '0.1em' }}>🐛 ISSUES</h3> <div style={{ flex: 1, overflowY: 'auto' }}> {repoInfo.issues.length === 0 ? ( <p style={{ fontSize: '0.8rem', color: 'var(--text-muted)', textAlign: 'center', paddingTop: 20 }}>No open issues found.</p> ) : repoInfo.issues.map((issue) => ( <div key={issue.number} className="step-card" style={{ cursor: running ? 'default' : 'pointer', padding: '10px', marginBottom: 8, opacity: running ? 0.5 : 1 }} onClick={() => !running && handleAnalyze(issue.url)} > <div style={{ fontWeight: 600, fontSize: '0.78rem', marginBottom: 2 }}>#{issue.number} {issue.title}</div> <div style={{ fontSize: '0.68rem', color: 'var(--text-muted)' }}>@{issue.author}</div> </div> ))} </div> {!running && ( <div style={{ borderTop: '1px solid var(--border-color)', paddingTop: 12, marginTop: 8 }}> <input className="input-field" style={{ padding: '8px 10px', fontSize: '0.78rem', marginBottom: 8 }} placeholder="Paste issue URL..." value={issueUrl} onChange={(e) => setIssueUrl(e.target.value)} /> <button type="button" className="glow-btn" style={{ width: '100%', padding: '9px', fontSize: '0.78rem' }} onClick={() => handleAnalyze()} disabled={!issueUrl}> Analyze </button> </div> )} </> )} {error && <div style={{ marginTop: 8, fontSize: '0.75rem', color: 'var(--error)' }}>❌ {error}</div>} </div> </div> </div> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219:root { --bg-dark: #0a0a0f; --bg-card: rgba(20, 20, 25, 0.7); --bg-input: rgba(30, 30, 40, 0.6); --border-color: rgba(255, 255, 255, 0.08); --accent-glow: rgba(108, 99, 255, 0.3); --primary: #8b5cf6; --secondary: #6c63ff; --text-main: #f0f0ff; --text-muted: #9ca3af; --success: #10b981; --error: #ef4444;}
* { box-sizing: border-box; margin: 0; padding: 0;}
html, body { height: 100%; overflow: hidden;}
body { background-color: var(--bg-dark); color: var(--text-main); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; line-height: 1.5; background-image: radial-gradient(circle at 15% 50%, rgba(108, 99, 255, 0.05), transparent 25%), radial-gradient(circle at 85% 30%, rgba(139, 92, 246, 0.05), transparent 25%);}
.glass-panel { background: var(--bg-card); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); border: 1px solid var(--border-color); border-radius: 16px; box-shadow: 0 4px 30px rgba(0, 0, 0, 0.2);}
.glow-btn { background: linear-gradient(135deg, var(--secondary), var(--primary)); color: white; border: none; padding: 12px 24px; border-radius: 8px; font-weight: 600; cursor: pointer; transition: all 0.3s ease; box-shadow: 0 4px 15px var(--accent-glow);}
.glow-btn:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(108, 99, 255, 0.5);}
.glow-btn:disabled { opacity: 0.6; cursor: not-allowed; transform: none; box-shadow: none;}
.input-field { width: 100%; background: var(--bg-input); border: 1px solid var(--border-color); color: var(--text-main); padding: 14px 16px; border-radius: 8px; font-size: 1rem; transition: border-color 0.2s, box-shadow 0.2s; outline: none;}
.input-field:focus { border-color: var(--primary); box-shadow: 0 0 0 2px var(--accent-glow);}
.terminal-window { background: #111115; border-radius: 12px; overflow: hidden; border: 1px solid var(--border-color);}
.terminal-header { background: rgba(255, 255, 255, 0.03); padding: 10px 16px; display: flex; align-items: center; border-bottom: 1px solid var(--border-color); gap: 8px;}
.terminal-dot { width: 12px; height: 12px; border-radius: 50%;}
.dot-red { background: #ff5f56; }.dot-yellow { background: #ffbd2e; }.dot-green { background: #27c93f; }
.terminal-body { padding: 16px; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 0.9rem; color: #a0a0cc; max-height: 400px; overflow-y: auto;}
.log-entry { margin-bottom: 8px; animation: fadeIn 0.3s ease;}
.log-prefix { color: var(--primary); margin-right: 8px;}
.step-card { padding: 16px; border-radius: 8px; background: rgba(255,255,255,0.02); border: 1px solid transparent; transition: all 0.3s ease;}
.step-card.active { border-color: var(--primary); background: rgba(139, 92, 246, 0.05); box-shadow: inset 0 0 20px rgba(139, 92, 246, 0.05);}
.analyzing-glow { color: var(--primary) !important; background-color: rgba(139, 92, 246, 0.1) !important; box-shadow: 0 0 10px rgba(139, 92, 246, 0.2); animation: pulseGlow 2s infinite ease-in-out;}
.terminal-drawer { background: #0a0a0f; border-top: 1px solid var(--border-color); overflow: hidden; transition: height 0.3s ease; position: relative;}
.terminal-drawer-header { padding: 8px 16px; background: rgba(255, 255, 255, 0.02); border-bottom: 1px solid var(--border-color); font-size: 0.75rem; color: var(--text-muted); display: flex; justify-content: space-between; align-items: center; cursor: pointer;}
.terminal-drawer-body { padding: 12px 20px; max-height: 250px; overflow-y: auto; font-family: monospace; font-size: 0.8rem; color: #a0a0cc; white-space: pre-wrap;}
.diff-view { background: #1a1a24; border-radius: 8px; padding: 16px; overflow-x: auto; font-family: monospace; white-space: pre; color: #d1d5db;}
.diff-add { color: #a3be8c; }.diff-remove { color: #bf616a; }.diff-header { color: #81a1c1; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); }}
@keyframes pulseGlow { 0% { box-shadow: 0 0 0 0 rgba(139, 92, 246, 0.4); } 70% { box-shadow: 0 0 0 10px rgba(139, 92, 246, 0); } 100% { box-shadow: 0 0 0 0 rgba(139, 92, 246, 0); }}
.loading-spinner { display: inline-block; width: 20px; height: 20px; border: 2px solid rgba(255,255,255,0.2); border-radius: 50%; border-top-color: white; animation: spin 1s ease-in-out infinite;}
@keyframes spin { to { transform: rotate(360deg); }}123456789101112131415161718192021222324252627282930import type { Metadata } from "next";import { Geist, Geist_Mono } from "next/font/google";import "./globals.css";
const geistSans = Geist({ variable: "--font-geist-sans", subsets: ["latin"],});
const geistMono = Geist_Mono({ variable: "--font-geist-mono", subsets: ["latin"],});
export const metadata: Metadata = { title: "FixFlow", description: "Autonomous Bug Resolution Agent by Z.ai",};
export default function RootLayout({ children,}: Readonly<{ children: React.ReactNode;}>) { return ( <html lang="en" className={`${geistSans.variable} ${geistMono.variable}`} suppressHydrationWarning> <body suppressHydrationWarning>{children}</body> </html> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576"use client";
import React, { useState, useRef, useEffect } from 'react';import { useRouter } from 'next/navigation';
type UI_STATE = 'INPUT_REPO' | 'LOADING_REPO' | 'REPO_DASHBOARD' | 'DONE';
interface GitHubIssue { title: string; number: number; url: string; author: string; created_at: string; body_snippet: string;}
interface RepoFile { path: string; size: number; type: string;}
export default function Home() { const router = useRouter(); const [uiState, setUiState] = useState<UI_STATE>('INPUT_REPO'); const [repoUrl, setRepoUrl] = useState(""); const [issueUrl, setIssueUrl] = useState(""); const [runConfidence, setRunConfidence] = useState(true); const [repoInfo, setRepoInfo] = useState<{ tree: RepoFile[], issues: GitHubIssue[] } | null>(null); const [selectedFilePath, setSelectedFilePath] = useState<string | null>(null); const [selectedFileContent, setSelectedFileContent] = useState<string>(""); const [isLoadingFile, setIsLoadingFile] = useState(false); const [statusName, setStatusName] = useState(""); const [statusMessage, setStatusMessage] = useState(""); const [running, setRunning] = useState(false); const [error, setError] = useState(""); const [streamChunks, setStreamChunks] = useState<string[]>([]); const [result, setResult] = useState<any>(null); const [analyzingFiles, setAnalyzingFiles] = useState<string[]>([]); const [terminalExpanded, setTerminalExpanded] = useState(true); const [completedSteps, setCompletedSteps] = useState<{step: string, message: string, status: string}[]>([]); // When results arrive, show fixed files inline const [fixedFileView, setFixedFileView] = useState<{path: string, content: string} | null>(null); const [sessionId, setSessionId] = useState(""); const [feedback, setFeedback] = useState("");
const logsEndRef = useRef<HTMLDivElement>(null);
useEffect(() => { if (logsEndRef.current) { logsEndRef.current.scrollIntoView({ behavior: "smooth" }); } }, [streamChunks, statusMessage, running]);
// Handle path detection in status messages to show "live context" useEffect(() => { if (statusMessage) { // Simple path detection (looks for strings with / or .py, .js, etc.) const pathRegex = /([a-zA-Z0-9._\-/]+\.(py|js|tsx|ts|html|css|json|md))/g; const matches = statusMessage.match(pathRegex); if (matches) { setAnalyzingFiles(prev => [...new Set([...prev, ...matches])]); // Auto-focus the first detected path if it exists in our tree const validPath = matches.find(p => repoInfo?.tree.some(f => f.path === p)); if (validPath && validPath !== selectedFilePath) { handleFileClick(validPath); } } } }, [statusMessage]);
const handleFetchRepo = () => { if (!repoUrl) return; setError(""); try { // Handle full GitHub URL: https://github.com/owner/repo const url = new URL(repoUrl.trim().replace(/\/+$/, '')); const parts = url.pathname.replace(/^\//, '').split('/'); if (parts.length >= 2 && parts[0] && parts[1]) { router.push(`/${parts[0]}/${parts[1]}`); return; } } catch { // Not a full URL — try treating as "owner/repo" const parts = repoUrl.trim().replace(/^github\.com\//, '').split('/'); if (parts.length >= 2 && parts[0] && parts[1]) { router.push(`/${parts[0]}/${parts[1]}`); return; } } setError("Please enter a valid GitHub URL (e.g. https://github.com/owner/repo)"); };
const handleFileClick = async (path: string) => { setSelectedFilePath(path); setIsLoadingFile(true); try { const res = await fetch(`http://127.0.0.1:8000/api/file_content?repo_url=${encodeURIComponent(repoUrl)}&file_path=${encodeURIComponent(path)}`); if (!res.ok) throw new Error("Failed to fetch file content"); const data = await res.json(); setSelectedFileContent(data.content); } catch (err) { setSelectedFileContent("// Error loading file content..."); } finally { setIsLoadingFile(false); } };
const handleAnalyze = (selectedIssueUrl?: string) => { const finalIssueUrl = selectedIssueUrl || issueUrl; if (!finalIssueUrl || !repoUrl) { setError("Please provide an Issue URL"); return; } setRunning(true); setError(""); setResult(null); setStreamChunks([]); setAnalyzingFiles([]); setCompletedSteps([]); setFixedFileView(null); setTerminalExpanded(true); setStatusName("Starting"); setStatusMessage("Connecting to FixFlow API...");
const params = new URLSearchParams({ issue_url: finalIssueUrl, repo_url: repoUrl, run_confidence: runConfidence.toString(), });
const eventSource = new EventSource(`http://127.0.0.1:8000/api/analyze?${params.toString()}`); setupEventSource(eventSource); };
const handleRefine = () => { if (!feedback || !sessionId) return; setRunning(true); setError(""); setStreamChunks([]); setAnalyzingFiles([]); setCompletedSteps([]); setFixedFileView(null); setTerminalExpanded(true); setStatusName("Refining"); setStatusMessage("Sending feedback to FixFlow..."); const params = new URLSearchParams({ session_id: sessionId, feedback: feedback, }); setFeedback(""); const eventSource = new EventSource(`http://127.0.0.1:8000/api/refine?${params.toString()}`); setupEventSource(eventSource); };
const setupEventSource = (eventSource: EventSource) => { eventSource.addEventListener("status", (e: Event) => { const data = JSON.parse((e as MessageEvent).data); const { step, status, message } = data; setStatusName(step); setStatusMessage(message); if (status === "complete" || status === "error") { setCompletedSteps(prev => [...prev, { step, status, message }]); } });
eventSource.addEventListener("stream", (e: Event) => { const data = JSON.parse((e as MessageEvent).data); setStreamChunks((prev) => [...prev, data.chunk]); });
eventSource.addEventListener("done", (e: Event) => { const data = JSON.parse((e as MessageEvent).data); const r = data.result; setResult(r); if (data.session_id) setSessionId(data.session_id); // Auto-load the first fixed file into the editor so the user sees the change if (r?.fixed_files) { const paths = Object.keys(r.fixed_files); if (paths.length > 0) { const firstPath = paths[0]; setFixedFileView({ path: firstPath, content: r.fixed_files[firstPath] }); setSelectedFilePath(firstPath); } } });
eventSource.addEventListener("error", (e: Event) => { const data = JSON.parse((e as MessageEvent).data); setError(data.error || "Unknown stream error"); setRunning(false); eventSource.close(); });
eventSource.addEventListener("eof", () => { setRunning(false); setStatusName("Done"); setStatusMessage("Fix generated — Review the highlighted file in the editor."); setCompletedSteps(prev => [...prev, { step: "done", status: "complete", message: "Fix generated — review the highlighted file in the editor!" }]); eventSource.close(); // Stay on REPO_DASHBOARD — the fix is shown in the editor }); eventSource.addEventListener("heartbeat", () => {});
eventSource.onerror = (e) => { console.error("SSE Error:", e); }; };
const handleOpenPR = async () => { if (!result) return; try { const res = await fetch("http://127.0.0.1:8000/api/pr", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ repo_url: repoUrl, title: result.issue_title, body: result.fix_explanation + "\n\n---\n*Generated autonomously by FixFlow*", fixed_files: result.fixed_files }) }); const data = await res.json(); if (!res.ok) throw new Error(data.detail || "Failed to create PR"); window.open(data.url, "_blank"); } catch (err: any) { alert("Error: " + err.message); } };
// ── Render Helpers ────────────────────────────────────────────────────────
const renderInputRepo = () => ( <div className="glass-panel" style={{ padding: 40, marginBottom: 40, animation: 'fadeIn 0.5s ease' }}> <h2 style={{ marginBottom: 24, fontSize: '1.5rem', fontWeight: 600 }}>🚀 Connect a Repository</h2> <p style={{ color: 'var(--text-muted)', marginBottom: 24 }}>Enter a GitHub URL to start the autonomous bug resolution process.</p> <div style={{ marginBottom: 32 }}> <label style={{ display: 'block', marginBottom: 8, fontSize: '0.9rem', color: 'var(--text-muted)' }}>Repository URL</label> <input className="input-field" placeholder="https://github.com/owner/repo" value={repoUrl} onChange={(e) => setRepoUrl(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && handleFetchRepo()} /> </div>
<button type="button" className="glow-btn" style={{ width: '100%', fontSize: '1.1rem', padding: '16px' }} onClick={handleFetchRepo} disabled={!repoUrl || running} > {running ? "Fetching..." : "Clone & Explore Repo"} </button> {error && <div style={{ marginTop: 20, color: 'var(--error)', backgroundColor: 'rgba(239, 68, 68, 0.1)', padding: 12, borderRadius: 8 }}>❌ {error}</div>} </div> );
const renderLoadingRepo = () => ( <div className="glass-panel" style={{ padding: 60, textAlign: 'center', marginBottom: 40 }}> <div className="loading-spinner" style={{ width: 40, height: 40, marginBottom: 24 }} /> <h2 style={{ fontSize: '1.5rem', fontWeight: 600, marginBottom: 8 }}>Indexing Repository...</h2> <p style={{ color: 'var(--text-muted)' }}>We're fetching the file tree and discovering open issues from GitHub.</p> </div> );
const renderRepoDashboard = () => { if (!repoInfo) return null; return ( <div style={{ animation: 'fadeIn 0.5s ease', height: '100%', display: 'flex', flexDirection: 'column' }}> <div style={{ display: 'grid', gridTemplateColumns: '240px 1fr 300px', gap: 16, flex: 1, minHeight: 0 }}> {/* Left Pane: Explorer with analyzing-glow */} <div className="glass-panel" style={{ padding: 16, display: 'flex', flexDirection: 'column' }}> <h3 style={{ marginBottom: 16, fontSize: '0.9rem', color: 'var(--text-main)', opacity: 0.8 }}>📁 EXPLORER</h3> <div style={{ flex: 1, overflowY: 'auto', fontSize: '0.8rem', color: 'var(--text-muted)', fontFamily: 'monospace' }}> {repoInfo.tree.map((file, i) => { const isAnalyzing = analyzingFiles.includes(file.path); return ( <div key={i} onClick={() => handleFileClick(file.path)} className={isAnalyzing ? 'analyzing-glow' : ''} style={{ padding: '6px 8px', cursor: 'pointer', borderRadius: '4px', marginBottom: '2px', backgroundColor: selectedFilePath === file.path ? 'rgba(139, 92, 246, 0.15)' : 'transparent', color: selectedFilePath === file.path ? 'var(--primary)' : 'inherit', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', transition: 'all 0.3s ease' }} > <span style={{ marginRight: 6 }}>{isAnalyzing ? '🧠' : '📄'}</span> {file.path} </div> ); })} </div> </div>
{/* Center Pane: Editor + Integrated Step Tracker */} <div style={{ display: 'flex', flexDirection: 'column', height: '100%', gap: 0 }}> {/* Editor */} <div className="terminal-window" style={{ flex: 1, display: 'flex', flexDirection: 'column', position: 'relative', borderBottomLeftRadius: 0, borderBottomRightRadius: 0 }}> <div className="terminal-header"> <div className="terminal-dot dot-red"></div> <div className="terminal-dot dot-yellow"></div> <div className="terminal-dot dot-green"></div> <div style={{ marginLeft: '12px', fontSize: '0.75rem', color: 'var(--text-muted)', fontFamily: 'monospace' }}> {/* Show streaming code in editor during step 4 */} {running && (statusName === '4_fix' || statusName === '4_refine') ? '🔧 Generating Fix...' : selectedFilePath || 'Editor'} </div> </div> <div style={{ flex: 1, overflow: 'auto', backgroundColor: '#0d0d12' }}> {/* Priority 1: Fix just generated — show it in the editor with green */} {fixedFileView && !running ? ( <pre style={{ margin: 0, padding: '24px', fontSize: '0.85rem', fontFamily: 'monospace', color: '#a3be8c', lineHeight: '1.6' }}> {fixedFileView.content} </pre> ) : running && (statusName === '4_fix' || statusName === '4_refine') && streamChunks.length > 0 ? ( /* Priority 2: Stream the fix being generated live */ <pre style={{ margin: 0, padding: '24px', fontSize: '0.85rem', fontFamily: 'monospace', color: '#a3be8c', lineHeight: '1.6' }}> {streamChunks.join('')} <span style={{ borderRight: '2px solid var(--primary)' }}> </span> <div ref={logsEndRef} /> </pre> ) : ( /* Default: show selected file */ <pre style={{ margin: 0, padding: '24px', fontSize: '0.85rem', fontFamily: 'monospace', color: '#d1d5db', lineHeight: '1.6' }}> {selectedFileContent || '// Select a file to browse source code'} </pre> )} </div> </div>
{/* Bottom Step Progress Tracker */} <div className="terminal-drawer" style={{ height: terminalExpanded ? '220px' : '40px', borderRadius: '0 0 12px 12px' }}> <div className="terminal-drawer-header" onClick={() => setTerminalExpanded(!terminalExpanded)}> <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}> {running && <span className="loading-spinner" style={{ width: 12, height: 12 }} />} <span style={{ color: running ? 'var(--primary)' : 'var(--text-muted)' }}> {statusName ? `AGENT — [${statusName.toUpperCase()}]` : 'FIXFLOW AGENT CONSOLE'} </span> </div> <span>{terminalExpanded ? '▼' : '▲ Show Progress'}</span> </div> <div className="terminal-drawer-body" style={{ padding: '12px 16px' }}> {/* Completed steps */} {completedSteps.map((s, i) => ( <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8, fontSize: '0.8rem' }}> <span style={{ color: s.status === 'error' ? 'var(--error)' : 'var(--success)', flexShrink: 0 }}> {s.status === 'error' ? '✗' : '✓'} </span> <span style={{ color: 'var(--text-muted)' }}>{s.message}</span> </div> ))} {/* Current running step */} {running && statusMessage && ( <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: '0.8rem' }}> <span className="loading-spinner" style={{ width: 10, height: 10, flexShrink: 0 }} /> <span style={{ color: 'var(--primary)' }}>{statusMessage}</span> </div> )} <div ref={logsEndRef} /> </div> </div> </div>
{/* Right Pane: Discovery OR Result Actions */} <div className="glass-panel" style={{ padding: 16, display: 'flex', flexDirection: 'column' }}> {result && !running ? ( /* ── Result Actions Panel ── */ <> <h3 style={{ marginBottom: 4, fontSize: '0.9rem', color: 'var(--success)', display: 'flex', alignItems: 'center', gap: 8 }}> <span style={{ fontSize: '1.1rem' }}>✅</span> FIX READY </h3> <p style={{ fontSize: '0.75rem', color: 'var(--text-muted)', marginBottom: 16 }}> {result.bug_summary?.slice(0, 120)}... </p>
{/* Fixed files list — click to view each */} <div style={{ marginBottom: 16 }}> <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)', marginBottom: 8 }}>CHANGED FILES:</div> {Object.keys(result.fixed_files || {}).map((path) => ( <div key={path} onClick={() => setFixedFileView({ path, content: result.fixed_files[path] })} style={{ padding: '6px 10px', borderRadius: 6, marginBottom: 6, cursor: 'pointer', fontSize: '0.75rem', fontFamily: 'monospace', backgroundColor: fixedFileView?.path === path ? 'rgba(163, 190, 140, 0.15)' : 'rgba(255,255,255,0.04)', color: fixedFileView?.path === path ? '#a3be8c' : 'var(--text-muted)', border: fixedFileView?.path === path ? '1px solid rgba(163,190,140,0.3)' : '1px solid transparent', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} > 📝 {path} </div> ))} </div>
<div style={{ flex: 1 }} />
{/* Action Buttons */} <button type="button" className="glow-btn" style={{ width: '100%', marginBottom: 10, padding: '10px', fontSize: '0.85rem' }} onClick={handleOpenPR}> 🚀 Open Pull Request </button>
<div style={{ borderTop: '1px solid var(--border-color)', paddingTop: 12, marginTop: 4, display: 'flex', gap: 8 }}> <input className="input-field" style={{ flex: 1, padding: '8px 10px', fontSize: '0.75rem' }} placeholder="Refine the fix..." value={feedback} onChange={(e) => setFeedback(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && handleRefine()} /> <button type="button" className="glow-btn" style={{ padding: '8px 12px', fontSize: '0.75rem' }} onClick={handleRefine} disabled={!feedback}> ↩ </button> </div>
<button type="button" style={{ marginTop: 10, background: 'none', border: 'none', color: 'var(--text-muted)', cursor: 'pointer', fontSize: '0.75rem', width: '100%' }} onClick={() => { setResult(null); setFixedFileView(null); setCompletedSteps([]); }} > ← Start a new issue </button> </> ) : ( /* ── Discovery Panel ── */ <> <h3 style={{ marginBottom: 16, fontSize: '0.9rem', color: 'var(--text-main)', opacity: 0.8, display: 'flex', justifyContent: 'space-between' }}> <span>🐛 DISCOVERY</span> {!running && ( <button onClick={() => setUiState('INPUT_REPO')} style={{ background: 'none', border: 'none', color: 'var(--primary)', cursor: 'pointer', fontSize: '0.7rem' }}>Change Repo</button> )} </h3> <div style={{ flex: 1, overflowY: 'auto' }}> {repoInfo.issues.map((issue) => ( <div key={issue.number} className="step-card" style={{ cursor: running ? 'default' : 'pointer', border: '1px solid rgba(255,255,255,0.05)', padding: '12px', marginBottom: 10, opacity: running ? 0.5 : 1 }} onClick={() => !running && handleAnalyze(issue.url)} > <div style={{ fontWeight: 600, color: 'var(--text-main)', marginBottom: 4, fontSize: '0.8rem' }}>#{issue.number} {issue.title}</div> <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)' }}>@{issue.author}</div> </div> ))} </div> {!running && ( <div style={{ borderTop: '1px solid var(--border-color)', paddingTop: 16, marginTop: 16 }}> <input className="input-field" style={{ padding: '8px 12px', fontSize: '0.8rem', marginBottom: 8 }} placeholder="Paste direct Issue URL..." value={issueUrl} onChange={(e) => setIssueUrl(e.target.value)} /> <button type="button" className="glow-btn" style={{ width: '100%', padding: '10px', fontSize: '0.8rem' }} onClick={() => handleAnalyze()} disabled={!issueUrl}>Analyze Manually</button> </div> )} </> )} </div> </div> </div> ); };
const renderResult = () => ( <div style={{ animation: 'fadeIn 0.5s ease', maxWidth: '1000px', margin: '0 auto' }}> <div className="glass-panel" style={{ padding: 32, marginBottom: 24 }}> <h2 style={{ marginBottom: 16, color: 'var(--success)' }}>✅ Fix Successfully Generated</h2> <p style={{ marginBottom: 24, padding: 16, background: 'rgba(0,0,0,0.2)', borderRadius: 8, fontSize: '0.95rem' }}> {result.bug_summary} </p> <h3 style={{ marginBottom: 16, borderBottom: '1px solid var(--border-color)', paddingBottom: 8 }}>Analysis & Methodology</h3> <p style={{ marginBottom: 24, whiteSpace: 'pre-wrap', fontSize: '0.95rem', color: '#d1d5db' }}> {result.root_cause_analysis} </p>
<h3 style={{ marginBottom: 16, borderBottom: '1px solid var(--border-color)', paddingBottom: 8 }}>Unified Diff</h3> <div className="diff-view" style={{ marginBottom: 24 }}> {result.diff_formatted.split('\n').map((line: string, i: number) => { let className = ""; if (line.startsWith('+') && !line.startsWith('+++')) className = "diff-add"; else if (line.startsWith('-') && !line.startsWith('---')) className = "diff-remove"; else if (line.startsWith('@@') || line.startsWith('---') || line.startsWith('+++')) className = "diff-header"; return <div key={i} className={className}>{line}</div> })} </div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}> <button type="button" className="glow-btn" style={{ background: 'rgba(255,255,255,0.05)', boxShadow: 'none', border: '1px solid var(--border-color)' }} onClick={() => { setResult(null); setSessionId(""); setStreamChunks([]); setUiState('INPUT_REPO'); }} > Start New Task </button> <button type="button" className="glow-btn" onClick={handleOpenPR} disabled={running}> 🚀 Open GitHub Pull Request </button> </div> </div> <div className="glass-panel" style={{ padding: 24, marginTop: 24, display: 'flex', gap: 12 }}> <input className="input-field" placeholder="Refine the fix? Tell the agent what to change..." value={feedback} onChange={(e) => setFeedback(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && handleRefine()} style={{ flex: 1 }} /> <button type="button" className="glow-btn" onClick={handleRefine} disabled={!feedback || running} > {running ? 'Refining...' : 'Refine'} </button> </div> </div> );
return ( <div style={{ height: '100vh', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}> {/* Compact top bar */} <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 24px', borderBottom: '1px solid var(--border-color)', flexShrink: 0 }}> <span style={{ fontSize: '1.4rem' }}>🔧</span> <span style={{ fontWeight: 800, fontSize: '1.2rem', background: 'linear-gradient(135deg, var(--primary), var(--secondary))', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>FixFlow</span> <span style={{ color: 'var(--text-muted)', fontSize: '0.7rem', letterSpacing: '0.12em', marginLeft: 4 }}>AUTONOMOUS REPOSITORY AGENT</span> </div>
{/* Main content area */} <div style={{ flex: 1, overflow: 'auto', padding: uiState === 'REPO_DASHBOARD' ? '16px' : '40px 20px', display: 'flex', flexDirection: 'column' }}> {uiState === 'INPUT_REPO' && renderInputRepo()} {uiState === 'LOADING_REPO' && renderLoadingRepo()} {uiState === 'REPO_DASHBOARD' && renderRepoDashboard()} {uiState === 'DONE' && renderResult()} </div> </div> );}12345678910111213141516171819202122232425262728293031323334{ "compilerOptions": { "target": "ES2017", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react-jsx", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./src/*"] } }, "include": [ "next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts", "**/*.mts" ], "exclude": ["node_modules"]}2 unmodified lines3452 unmodified linesPyGithub>=2.1.0requests>=2.31.0python-dotenv>=1.0.02 unmodified lines3456782 unmodified linesPyGithub>=2.1.0requests>=2.31.0python-dotenv>=1.0.0fastapiuvicornsse-starlette