diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c880412..e6ef16a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,6 +34,15 @@ jobs: - name: Install dependencies run: python -m pip install -r requirements-dev.txt + - uses: actions/setup-node@v4 + if: matrix.python-version == '3.13' + with: + node-version: '22' + + - name: Test UI behavior without a browser + if: matrix.python-version == '3.13' + run: node --test tests/frontend/*.test.cjs + - name: Lint (errors only) run: ruff check . diff --git a/README.md b/README.md index bf84b2f..d84e28a 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ A dashboard that analyzes pull request flow in public GitHub repositories and ma ## Try it -Enter a public repository such as `sveltejs/svelte` or `https://github.com/owner/repo`. Analysis runs on Cloudflare Workers; results are cached for six hours. Chat reads that cache on the server and sends Gemini a compact summary of cycle time, complete-week throughput, and aging work. Reanalyze the repository when the cache expires. Private repositories are rejected. Each visitor's IP is limited to six analyses and twelve AI questions per minute. Gemini chat is enabled when `GEMINI_API_KEY` is configured. +Enter a public repository such as `sveltejs/svelte` or `https://github.com/owner/repo`. Analysis runs on Cloudflare Workers; results are kept per repository in Cloudflare KV until explicitly refreshed. Chat reads that cache on the server and sends Gemini a compact summary of cycle time, complete-week throughput, and aging work. Opening a saved repository still checks that it is public, but does not repeat the full analysis scan. Private repositories are rejected. Each visitor's IP is limited to six analyses and twelve AI questions per minute. Gemini chat is enabled when `GEMINI_API_KEY` is configured. ## Local development @@ -17,6 +17,8 @@ uv run uvicorn app:app --reload Open `http://localhost:8000`. The local server uses the GitHub CLI and reads Gemini credentials from the environment or local setup. +The web UI remembers the last repository in the browser and displays when its data was captured. Use **Refresh data** to fetch the latest GitHub data. In local development, raw GitHub data is saved under `.cache/repositories/` and reused across page reloads and server restarts. Keep that directory on persistent storage if the local server is redeployed. The CLI's `raw_data.json` cache is separate. + ## Testing @@ -28,6 +30,7 @@ pip install -r requirements-dev.txt ruff check . pytest --cov # fails below the coverage floor in pyproject.toml pytest -m unit # or -m integration / -m e2e +node --test tests/frontend/*.test.cjs # UI reload and refresh logic, no browser ``` Tests never touch the network, the `gh`/`bws` CLIs, or Gemini; `subprocess.run` is blocked by default and each test runs in a temp directory. diff --git a/analyze.py b/analyze.py index d1734c7..d923bc9 100644 --- a/analyze.py +++ b/analyze.py @@ -12,7 +12,7 @@ RAW_DATA_FILE = "raw_data.json" DASHBOARD_FILE = "dashboard.html" -def run_graphql_query(search_query, count=100): +def run_graphql_query(search_query, count=100, strict=False): import subprocess query = """ query($searchQuery: String!, $first: Int!) { @@ -90,17 +90,23 @@ def run_graphql_query(search_query, count=100): try: res = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", check=True) data = json.loads(res.stdout) + if strict and data.get("errors"): + raise RuntimeError("GraphQL error in pull request search") if "data" in data and "search" in data["data"]: return data["data"]["search"]["nodes"] else: + if strict: + raise RuntimeError("Invalid GraphQL response for pull request search") print("GraphQL Error or empty response:", data) return [] except subprocess.CalledProcessError as e: + if strict: + raise print("Error executing query:", e) print("Stderr:", e.stderr) return [] -def collect_data(repo="sveltejs/svelte"): +def collect_data(repo="sveltejs/svelte", strict=False): import subprocess print(f"Collecting data for {repo}...") @@ -112,7 +118,7 @@ def collect_data(repo="sveltejs/svelte"): # 1. Pre-AI Era (2021) baseline print("Fetching Pre-AI Era (2021) sample...") pre_ai_query = f"repo:{repo} is:pr is:merged merged:2021-06-01..2021-12-31" - pre_ai_nodes = run_graphql_query(pre_ai_query, 30) + pre_ai_nodes = run_graphql_query(pre_ai_query, 30, strict=strict) if strict else run_graphql_query(pre_ai_query, 30) print(f"Retrieved {len(pre_ai_nodes)} Pre-AI PRs.") # 2. Modern Era: Fetch 600 most recent merged PRs in pages of 100 @@ -204,6 +210,8 @@ def collect_data(repo="sveltejs/svelte"): try: res = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", check=True) data = json.loads(res.stdout) + if strict and data.get("errors"): + raise RuntimeError("GraphQL error in merged pull request search") if "data" in data and "search" in data["data"]: page_nodes = data["data"]["search"]["nodes"] recent_nodes.extend(page_nodes) @@ -215,9 +223,13 @@ def collect_data(repo="sveltejs/svelte"): else: break else: + if strict: + raise RuntimeError("Invalid GraphQL response for merged pull requests") print("Error or empty response:", data) break except Exception as e: + if strict: + raise print("Exception during merged PR fetch:", e) break @@ -296,10 +308,16 @@ def collect_data(repo="sveltejs/svelte"): try: res = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", check=True) data = json.loads(res.stdout) + if strict and data.get("errors"): + raise RuntimeError("GraphQL error in open pull request search") if "data" in data and "search" in data["data"]: open_nodes = data["data"]["search"]["nodes"] print(f"Retrieved {len(open_nodes)} active open PRs.") + elif strict: + raise RuntimeError("Invalid GraphQL response for open pull requests") except Exception as e: + if strict: + raise print("Error fetching open PRs:", e) # 4. Issues were fetched in parallel above, independent of PR linkage diff --git a/app.py b/app.py index 2d35151..d37a231 100644 --- a/app.py +++ b/app.py @@ -33,6 +33,7 @@ import sys sys.path.insert(0, str(Path(__file__).parent)) from analyze import collect_data, compute_flow_metrics +from repository_cache import RepositoryCache # --------------------------------------------------------------------------- # App Setup @@ -76,20 +77,36 @@ def _parse_repo_slug(repo_url: str) -> str: url = url[len("https://github.com/"):] if url.startswith("http://github.com/"): url = url[len("http://github.com/"):] + if url.startswith("github.com/"): + url = url[len("github.com/"):] # Remove trailing .git if present if url.endswith(".git"): url = url[:-4] # Remove any /tree/... or /blob/... path segments parts = url.split("/") if len(parts) >= 2: - return f"{parts[0]}/{parts[1]}" + repo = f"{parts[0].lower()}/{parts[1].lower()}" + RepositoryCache().path_for(repo) + return repo raise ValueError(f"Cannot parse repo slug from: {repo_url!r}") def _run_analysis(repo: str, force: bool) -> dict: """Blocking function that collects raw data and computes metrics.""" - raw = collect_data(repo) + cache = RepositoryCache() + raw = None if force else cache.load(repo) + cache_hit = raw is not None + if raw is None: + raw = collect_data(repo, strict=True) + if raw.get("issues") is None: + raise RuntimeError(f"Incomplete GitHub collection for {repo}") metrics = compute_flow_metrics(raw) + if not cache_hit: + try: + cache.save(repo, raw) + except OSError as exc: + print(f"Could not save repository cache for {repo}: {exc}") + metrics["cache_hit"] = cache_hit return metrics diff --git a/cloudflare_app.py b/cloudflare_app.py index 167778d..f0d00b8 100644 --- a/cloudflare_app.py +++ b/cloudflare_app.py @@ -217,7 +217,10 @@ async def analyze_repo(req: AnalyzeRequest, request: Request): if cache and not req.force_refresh: saved = await cache.get(cache_key) if saved: - return json.loads(saved) + metrics = json.loads(saved) + if metrics.get("repo", "").lower() == repo.lower(): + metrics["cache_hit"] = True + return metrics try: raw = await collect_public_data(repo, token) metrics = compute_flow_metrics(raw) @@ -225,8 +228,9 @@ async def analyze_repo(req: AnalyzeRequest, request: Request): raise HTTPException(status_code=502, detail=str(exc)) from exc if not metrics.get("recent_stats", {}).get("total"): raise HTTPException(status_code=422, detail="No merged pull requests were found for this public repository.") + metrics["cache_hit"] = False if cache: - await cache.put(cache_key, json.dumps(metrics, separators=(",", ":")), expiration_ttl=21600) + await cache.put(cache_key, json.dumps(metrics, separators=(",", ":"))) return metrics @@ -283,6 +287,8 @@ async def chat(req: ChatRequest, request: Request): if not key: raise HTTPException(status_code=503, detail="AI chat is not configured yet.") repo = parse_repo(req.repo) + token = getattr(env, "GITHUB_TOKEN", None) if env else None + await public_repo_exists(repo, token) cache = getattr(env, "ANALYTICS_CACHE", None) if env else None if cache is None: raise HTTPException(status_code=503, detail="Analysis cache is not configured yet.") diff --git a/docs/plans/2026-10-15-1026-feat-persist-ui-repository-analysis-plan.md b/docs/plans/2026-10-15-1026-feat-persist-ui-repository-analysis-plan.md new file mode 100644 index 0000000..c82cc9f --- /dev/null +++ b/docs/plans/2026-10-15-1026-feat-persist-ui-repository-analysis-plan.md @@ -0,0 +1,170 @@ +--- +title: "Persist UI Repository Analysis - Plan" +type: feat +date: 2026-10-15 +artifact_contract: ce-unified-plan/v1 +product_contract_source: ce-plan-bootstrap +execution: code +--- + +# Persist UI Repository Analysis - Plan + +## Goal Capsule + +- **Objective:** A returning visitor can reopen a previously analyzed GitHub repository in the UI without waiting for another GitHub scan, including after a page reload or server restart. +- **Leading indicators:** A second API analysis of the same repository makes zero collection calls; a simulated page reload requests the saved repository once; explicit refresh makes exactly one new collection and preserves other repositories' entries. +- **Means:** Store raw analysis data by repository on disk and let the UI reopen its last repository through the existing analysis API (KTD1, KTD3). +- **Authority:** The user's clarification that this concerns the UI. Existing API and metric behavior remain the compatibility baseline. +- **Execution profile:** Add integration coverage for a cache hit before changing the request path; verify the browser reload flow after the server path works. +- **Stop conditions:** Do not use a cache entry for another repository or serve an incomplete entry as a successful analysis. +- **Who finishes:** The implementer verifies and ships the code change; the user decides when to merge it. + +--- + +## Product Contract + +### Summary + +Keep repository analysis available between UI visits. The next visit reuses saved GitHub data, while a deliberate refresh fetches new data. + +### Problem Frame + +The UI always posts `force_refresh: false` to `/api/analyze`, but `app.py` calls `collect_data` for every request and ignores that flag. Its in-memory metrics map supports chat during the current server process but cannot reopen analysis after a restart. The existing CLI cache is one `raw_data.json` file, which is not keyed by repository and is unsuitable for the UI's multi-repository history. + +### Requirements + +**Returning to a repository** + +- R1. Reanalyzing a repository already viewed through the UI reuses its saved GitHub data without calling GitHub again, including after the server restarts. +- R2. Reloading the browser page reopens the last viewed repository and displays its dashboard without a fresh GitHub scan when saved data exists. +- R3. Repository A's saved data is never returned for repository B, regardless of how the repository was entered as a URL or slug. + +**Freshness and recovery** + +- R4. The UI offers a clear action to fetch fresh GitHub data for the displayed repository. A successful refresh replaces that repository's saved data without changing other repositories' entries. +- R5. A missing, unreadable, corrupt, or mismatched saved entry causes a normal collection for the requested repository. A failed collection must not replace a previously valid entry. +- R6. The UI distinguishes data loaded from saved collection from newly collected data and shows when GitHub data was captured. + +### Key Decisions + +- **UI repository revisit is the target** (session-settled: user-directed β€” chosen over a general CLI cache change: the user clarified that repeated scans in the UI are the problem). Governs R1, R2, R4, R6. + +### Scope Boundaries + +- The existing CLI `raw_data.json` workflow is outside this change. The UI's new repository cache must not read that file as a cross-repository cache. +- Saved GitHub data has no automatic expiration in this plan. The user controls freshness through R4; the capture time in R6 makes age visible. +- Previously cached data from the single `raw_data.json` file is not migrated because its repository association cannot be trusted without checking its contents. +- Account-wide history, cloud storage, and cache management screens are outside this change. + +### Acceptance Examples + +- AE1. Given the UI has analyzed `owner/alpha`, when the browser reloads and the last repository reopens, the dashboard appears and no GitHub query runs. Covers R1, R2. +- AE2. Given `owner/alpha` is cached, when the visitor opens `owner/beta`, only beta's matching cache entry may be used; a missing beta entry triggers collection. Covers R3. +- AE3. Given a saved analysis, when the visitor requests fresh data, GitHub is queried and the next ordinary visit uses the new capture. Covers R4, R6. +- AE4. Given an invalid saved entry, when the repository is opened, the API collects it and returns its metrics. Covers R5. + +--- + +## Planning Contract + +### Key Technical Decisions + +- KTD1. **Persist raw data per normalized repository slug.** Put API cache files under an ignored local cache directory and derive their paths only from validated owner/repo components. Raw data preserves `captured_at`; metrics are computed on each request so age-dependent metrics use the current clock. This extends `compute_flow_metrics` without persisting its time-sensitive output. +- KTD2. **Keep the cache boundary in the API path.** `app._run_analysis` checks the repository cache unless `force_refresh` is true, then passes raw data to `compute_flow_metrics`. Leave `analyze.load_or_collect` and the CLI's legacy file behavior alone, per the UI scope decision governing R1 and R2. +- KTD3. **Remember only the last repository in the browser.** Store its normalized slug locally and request it through `/api/analyze` on page load. The server remains the source of analysis data; the browser does not duplicate the metrics payload. +- KTD4. **Use complete, atomic cache replacement.** Validate stored repo identity and raw-data shape before use. Distinguish a successful empty GitHub result from a transport failure before replacing a cache entry: current collection helpers swallow some query failures and return empty lists. A failed cache read is a miss; a failed cache write does not discard a successful response. +- KTD5. **Expose cache provenance in the API response.** Add a small additive field that tells the UI whether the request reused saved data. Keep existing metric fields and chat context intact; display `captured_at` already carried by the metrics payload. + +### High-Level Technical Design + +```mermaid +flowchart TB + UI[UI: last repo or Analyze] --> API[POST /api/analyze] + API --> Gate{Force refresh?} + Gate -->|yes| GH[Collect from GitHub] + Gate -->|no| Cache{Matching valid cache?} + Cache -->|yes| Metrics[Compute current metrics] + Cache -->|no| GH + GH --> Save[Atomically save raw data for this repo] + Save --> Metrics + Metrics --> Render[Render dashboard and prime chat] +``` + +### System-Wide Impact + +- The API retains its in-memory metrics map for `/api/chat`; every cache-backed `/api/analyze` request must repopulate that map so chat works after a server restart. +- The browser's saved last-repository slug is local to that browser. The repository data cache is local to the server filesystem; ephemeral hosting will lose it on deployment restart unless that filesystem is mounted persistently. +- `collect_data` currently also writes `raw_data.json`. The new API cache is independent of that side effect, and the plan does not make `raw_data.json` a source for UI cache hits. + +--- + +## Implementation Units + +### U1. Repository-scoped raw cache + +- **Goal:** Reuse valid saved GitHub data for the requested repository and replace it safely on refresh. +- **Requirements:** R1, R3, R5. +- **Dependencies:** None. +- **Files:** `repository_cache.py` (new), `tests/unit/test_repository_cache.py` (new), `tests/integration/test_collect_data.py` (existing cache contract reference). +- **Approach:** Implement KTD1 and KTD4 as a small file cache around the existing raw bundle shape. Reject slugs that cannot safely form a repository identity or cache path. Keep the API cache separate from `raw_data.json`. +- **Patterns to follow:** `analyze.py` raw bundle keys and `tests/factories.py`'s `small_raw_data`; test isolation in `tests/conftest.py`. +- **Test scenarios:** + - Save data for `owner/alpha`, load it from a new cache instance, and get the same raw bundle with no collection. + - Save alpha and beta; loading either returns only its own bundle, including when input case and URL normalization are considered at the API boundary. + - A cache file with a different `repo`, missing required collection fields, or invalid JSON is treated as a miss. + - A failed replacement leaves the prior complete entry readable; path traversal shaped input cannot address files outside the cache directory. +- **Verification:** Repository identity and `captured_at` survive a process-level cache reopen; bad entries never produce a hit. + +### U2. API cache use and explicit refresh + +- **Goal:** Make repeated `/api/analyze` calls reuse saved data and honor `force_refresh`. +- **Requirements:** R1, R3, R4, R5, R6. +- **Dependencies:** U1. +- **Files:** `app.py`, `analyze.py`, `tests/integration/test_api.py`, `tests/integration/test_collect_data.py`, `tests/e2e/test_pipeline.py`. +- **Approach:** Route `_run_analysis` through U1, preserving current metric computation and `_metrics_cache` population. Expose enough collection failure status from `analyze.py` for KTD4 without changing the CLI's cache behavior. Normalize and validate repository identity before cache lookup. Return the KTD5 provenance field with the existing response shape. +- **Patterns to follow:** `_parse_repo_slug`, `compute_flow_metrics`, `tests/factories.py`'s `FakeGh`, and the existing `TestClient` route tests. +- **Test scenarios:** + - Covers AE1. First request collects alpha; a later request after clearing in-memory metrics returns alpha from disk without invoking `gh`, and chat can use those metrics. + - Covers AE2. A cached alpha never satisfies beta's request; beta collects and gets beta metrics. + - Covers AE3. A request with `force_refresh: true` calls collection even on a cache hit, updates only alpha's cache, and the next ordinary request sees the new capture. + - Covers AE4. A corrupt alpha entry triggers collection; a collection failure returns the current error response and does not publish partial data. + - A GitHub query failure that currently yields an empty list does not overwrite an older valid cache entry; a genuinely empty result may be saved. + - The response reports cache hit versus fresh collection without removing existing metric fields. +- **Verification:** The API makes no GitHub call for a valid cache hit and honors the refresh flag across server restarts. + +### U3. UI reopen and freshness controls + +- **Goal:** Reopen the last repository after page reload and let the visitor request current GitHub data. +- **Requirements:** R2, R4, R6. +- **Dependencies:** U2. +- **Files:** `index.html`, `tests/frontend/repository_restore.test.cjs` (new), `.github/workflows/ci.yml`, `README.md`. +- **Approach:** Remember the normalized slug after successful analysis. On page initialization, put it back in the input and request analysis; use the API's cache provenance and `captured_at` in status text. Add a visible refresh action that sends `force_refresh: true` for the current repository. Reuse the existing loading, error, and render paths so failed restores remain recoverable through the form. +- **Patterns to follow:** `analyzeRepo`, `showLoading`, `showStatus`, `renderDashboard`, and the existing API request shape in `index.html`. Use Node's built-in test and VM APIs to exercise the page script without launching Chromium; API integration tests prove the real cache boundary. +- **Test scenarios:** + - Covers AE1. After a successful analysis, reloading the page restores the same repository and renders the dashboard from a cache-backed API response. + - Covers AE3. The refresh control sends `force_refresh: true`, shows a fresh capture, and an ordinary subsequent load reports a cache hit. + - Missing or unavailable browser storage leaves manual analysis usable; a failed automatic restore shows an error and does not trap the visitor in loading state. +- **Verification:** The page script restores the previous repository and sends a cache-backed request on simulated reload; the UI code makes the data's age and refresh option clear. + +--- + +## Verification Contract + +- Run the relevant unit and integration tests for the cache and API, then the full `pytest --cov` gate and `ruff check .` used by CI. Run the Node test for last-repository restore and refresh controls. +- Verify the combined page-script and server behavior: the Node test simulates reload and refresh; API integration tests reopen persisted data after clearing memory and confirm no new GitHub scan. +- Keep automated tests network-free using the existing `subprocess.run` guard and temporary working directory. The Node test intercepts API responses and does not launch Chromium. + +--- + +## Definition of Done + +- R1–R6 and AE1–AE4 are demonstrated by the unit, API, and Node UI checks above. +- A cache hit leaves GitHub untouched; force refresh collects and replaces one repository's entry; a bad entry cannot leak another repository's data. +- The README explains where the UI cache lives, how long data remains saved, how to refresh it, and the limitation of ephemeral server storage. +- The final diff contains no abandoned cache formats or experimental paths. + +--- + +## Suggested Goal Loop + +`/goal Implement the persisted UI repository analysis in this plan for local and deployed APIs. Verify cache reuse across reloads, explicit refresh, repository isolation, and failure-safe replacement with the repo's Python, Node, lint, and coverage checks. Keep Chromium unused and leave unrelated working-tree changes untouched. Open a focused PR for review; do not merge it.` diff --git a/index.html b/index.html index 7d3474c..caafda5 100644 --- a/index.html +++ b/index.html @@ -119,6 +119,8 @@ color:var(--text-dim); } .btn-ghost:hover{border-color:var(--violet);color:var(--text);} + #refresh-btn:disabled{opacity:.5;cursor:not-allowed;} + #capture-note{color:var(--text-muted);font-size:.82rem;margin:.35rem 0 1rem;} /* Spinner */ .spinner{ @@ -436,7 +438,8 @@ @media(max-width:640px){ #app{padding:1rem;} header{flex-direction:column;align-items:flex-start;} - .repo-bar{max-width:100%;} + .repo-bar{max-width:100%;flex-wrap:wrap;} + .repo-bar input{flex-basis:100%;} .kpi-grid{grid-template-columns:1fr 1fr;} #chat-drawer{width:100vw;} #chat-toggle.open{right:1rem;} @@ -492,6 +495,7 @@

⚑ GitHub Flow Analytics

Analyze +
@@ -511,6 +515,7 @@

No repository loaded yet

πŸ“ β€”
+
@@ -663,12 +668,17 @@

Antigravity AI Coach

let chatOpen = false; let charts = {}; let authConfig = {required:false, client_id:''}; + let latestAnalysisRequest = 0; + let repoInputTouched = false; async function configureAuthentication() { try { const response = await fetch('/api/auth/config'); authConfig = await response.json(); - if (!authConfig.required) return; + if (!authConfig.required) { + restoreLastRepository(); + return; + } document.getElementById('login-gate').classList.add('visible'); if (!authConfig.client_id) { document.getElementById('login-error').textContent = 'Google sign-in is being configured.'; @@ -710,6 +720,7 @@

Antigravity AI Coach

document.getElementById('login-gate').classList.remove('visible'); document.getElementById('account-actions').style.display = 'flex'; document.getElementById('account-email').textContent = email; + restoreLastRepository(); } async function signOut() { @@ -724,33 +735,43 @@

Antigravity AI Coach

} // ── Analyze Repo ─────────────────────────────────────────────────── - async function analyzeRepo() { - const input = document.getElementById('repo-input').value.trim(); + async function analyzeRepo(forceRefresh = false, repoOverride = null) { + if (repoOverride === null) repoInputTouched = true; + const input = repoOverride || document.getElementById('repo-input').value.trim(); if (!input) { showStatus('Please enter a repository URL.', 'error'); return; } + const requestId = ++latestAnalysisRequest; const btn = document.getElementById('analyze-btn'); + const refreshBtn = document.getElementById('refresh-btn'); btn.disabled = true; + refreshBtn.disabled = true; btn.classList.add('loading'); - showLoading('Fetching repository data… this may take 30–60 seconds'); + showLoading(forceRefresh ? 'Fetching fresh repository data…' : 'Loading repository data…'); clearStatus(); try { const res = await fetch('/api/analyze', { method: 'POST', headers: {'Content-Type':'application/json'}, - body: JSON.stringify({ repo_url: input, force_refresh: false }) + body: JSON.stringify({ repo_url: input, force_refresh: forceRefresh }) }); if (!res.ok) { const err = await res.json(); throw new Error(err.detail || `HTTP ${res.status}`); } const data = await res.json(); + if (requestId !== latestAnalysisRequest) return; currentMetrics = data; currentRepo = data.repo; chatHistory = []; + document.getElementById('repo-input').value = data.repo; + try { localStorage.setItem('lastAnalyzedRepo', data.repo); } catch (_) {} renderDashboard(data); - showStatus(`βœ“ Analysis complete for ${data.repo} β€” ${data.recent_stats?.total || 0} PRs analyzed`, 'success'); + const captured = data.captured_at ? new Date(data.captured_at).toLocaleString() : 'unknown time'; + const source = data.cache_hit ? 'Saved GitHub data' : 'Fresh GitHub data'; + document.getElementById('capture-note').textContent = `${source} Β· captured ${captured}`; + showStatus(`βœ“ ${source} loaded for ${data.repo} β€” ${data.recent_stats?.total || 0} PRs analyzed`, 'success'); document.getElementById('chat-repo-label').textContent = data.repo; document.getElementById('chat-toggle').classList.add('has-response'); @@ -758,14 +779,21 @@

Antigravity AI Coach

addChatMessage('assistant', `πŸŽ‰ **Repository loaded: \`${data.repo}\`**\n\nAsk me about cycle time, aging work, or throughput. Review timing and batch size are not yet available from this hosted data source.`); } catch(e) { - showStatus(`Error: ${e.message}`, 'error'); + if (requestId === latestAnalysisRequest) showStatus(`Error: ${e.message}`, 'error'); } finally { - btn.disabled = false; - btn.classList.remove('loading'); - hideLoading(); + if (requestId === latestAnalysisRequest) { + btn.disabled = false; + refreshBtn.disabled = !currentRepo; + btn.classList.remove('loading'); + hideLoading(); + } } } + function refreshRepo() { + if (currentRepo) return analyzeRepo(true, currentRepo); + } + // ── Dashboard Renderer ────────────────────────────────────────────── function renderDashboard(d) { document.getElementById('placeholder').style.display = 'none'; @@ -1405,18 +1433,23 @@

Antigravity AI Coach

} // Allow pressing Enter in the repo input + document.getElementById('repo-input').addEventListener('input', () => { repoInputTouched = true; }); document.getElementById('repo-input').addEventListener('keydown', e => { if (e.key === 'Enter') analyzeRepo(); }); - // Pre-fill from URL param ?repo= - (function() { - const params = new URLSearchParams(window.location.search); - const r = params.get('repo'); - if (r) { - document.getElementById('repo-input').value = r; + function restoreLastRepository() { + if (currentRepo || repoInputTouched || new URLSearchParams(window.location.search).get('repo')) return; + let lastRepo = null; + try { lastRepo = localStorage.getItem('lastAnalyzedRepo'); } catch (_) {} + if (lastRepo) { + document.getElementById('repo-input').value = lastRepo; + analyzeRepo(false, lastRepo); } - })(); + } + + const repoFromUrl = new URLSearchParams(window.location.search).get('repo'); + if (repoFromUrl) document.getElementById('repo-input').value = repoFromUrl; configureAuthentication(); diff --git a/public/index.html b/public/index.html index 7d3474c..caafda5 100644 --- a/public/index.html +++ b/public/index.html @@ -119,6 +119,8 @@ color:var(--text-dim); } .btn-ghost:hover{border-color:var(--violet);color:var(--text);} + #refresh-btn:disabled{opacity:.5;cursor:not-allowed;} + #capture-note{color:var(--text-muted);font-size:.82rem;margin:.35rem 0 1rem;} /* Spinner */ .spinner{ @@ -436,7 +438,8 @@ @media(max-width:640px){ #app{padding:1rem;} header{flex-direction:column;align-items:flex-start;} - .repo-bar{max-width:100%;} + .repo-bar{max-width:100%;flex-wrap:wrap;} + .repo-bar input{flex-basis:100%;} .kpi-grid{grid-template-columns:1fr 1fr;} #chat-drawer{width:100vw;} #chat-toggle.open{right:1rem;} @@ -492,6 +495,7 @@

⚑ GitHub Flow Analytics

Analyze +
@@ -511,6 +515,7 @@

No repository loaded yet

πŸ“ β€”
+
@@ -663,12 +668,17 @@

Antigravity AI Coach

let chatOpen = false; let charts = {}; let authConfig = {required:false, client_id:''}; + let latestAnalysisRequest = 0; + let repoInputTouched = false; async function configureAuthentication() { try { const response = await fetch('/api/auth/config'); authConfig = await response.json(); - if (!authConfig.required) return; + if (!authConfig.required) { + restoreLastRepository(); + return; + } document.getElementById('login-gate').classList.add('visible'); if (!authConfig.client_id) { document.getElementById('login-error').textContent = 'Google sign-in is being configured.'; @@ -710,6 +720,7 @@

Antigravity AI Coach

document.getElementById('login-gate').classList.remove('visible'); document.getElementById('account-actions').style.display = 'flex'; document.getElementById('account-email').textContent = email; + restoreLastRepository(); } async function signOut() { @@ -724,33 +735,43 @@

Antigravity AI Coach

} // ── Analyze Repo ─────────────────────────────────────────────────── - async function analyzeRepo() { - const input = document.getElementById('repo-input').value.trim(); + async function analyzeRepo(forceRefresh = false, repoOverride = null) { + if (repoOverride === null) repoInputTouched = true; + const input = repoOverride || document.getElementById('repo-input').value.trim(); if (!input) { showStatus('Please enter a repository URL.', 'error'); return; } + const requestId = ++latestAnalysisRequest; const btn = document.getElementById('analyze-btn'); + const refreshBtn = document.getElementById('refresh-btn'); btn.disabled = true; + refreshBtn.disabled = true; btn.classList.add('loading'); - showLoading('Fetching repository data… this may take 30–60 seconds'); + showLoading(forceRefresh ? 'Fetching fresh repository data…' : 'Loading repository data…'); clearStatus(); try { const res = await fetch('/api/analyze', { method: 'POST', headers: {'Content-Type':'application/json'}, - body: JSON.stringify({ repo_url: input, force_refresh: false }) + body: JSON.stringify({ repo_url: input, force_refresh: forceRefresh }) }); if (!res.ok) { const err = await res.json(); throw new Error(err.detail || `HTTP ${res.status}`); } const data = await res.json(); + if (requestId !== latestAnalysisRequest) return; currentMetrics = data; currentRepo = data.repo; chatHistory = []; + document.getElementById('repo-input').value = data.repo; + try { localStorage.setItem('lastAnalyzedRepo', data.repo); } catch (_) {} renderDashboard(data); - showStatus(`βœ“ Analysis complete for ${data.repo} β€” ${data.recent_stats?.total || 0} PRs analyzed`, 'success'); + const captured = data.captured_at ? new Date(data.captured_at).toLocaleString() : 'unknown time'; + const source = data.cache_hit ? 'Saved GitHub data' : 'Fresh GitHub data'; + document.getElementById('capture-note').textContent = `${source} Β· captured ${captured}`; + showStatus(`βœ“ ${source} loaded for ${data.repo} β€” ${data.recent_stats?.total || 0} PRs analyzed`, 'success'); document.getElementById('chat-repo-label').textContent = data.repo; document.getElementById('chat-toggle').classList.add('has-response'); @@ -758,14 +779,21 @@

Antigravity AI Coach

addChatMessage('assistant', `πŸŽ‰ **Repository loaded: \`${data.repo}\`**\n\nAsk me about cycle time, aging work, or throughput. Review timing and batch size are not yet available from this hosted data source.`); } catch(e) { - showStatus(`Error: ${e.message}`, 'error'); + if (requestId === latestAnalysisRequest) showStatus(`Error: ${e.message}`, 'error'); } finally { - btn.disabled = false; - btn.classList.remove('loading'); - hideLoading(); + if (requestId === latestAnalysisRequest) { + btn.disabled = false; + refreshBtn.disabled = !currentRepo; + btn.classList.remove('loading'); + hideLoading(); + } } } + function refreshRepo() { + if (currentRepo) return analyzeRepo(true, currentRepo); + } + // ── Dashboard Renderer ────────────────────────────────────────────── function renderDashboard(d) { document.getElementById('placeholder').style.display = 'none'; @@ -1405,18 +1433,23 @@

Antigravity AI Coach

} // Allow pressing Enter in the repo input + document.getElementById('repo-input').addEventListener('input', () => { repoInputTouched = true; }); document.getElementById('repo-input').addEventListener('keydown', e => { if (e.key === 'Enter') analyzeRepo(); }); - // Pre-fill from URL param ?repo= - (function() { - const params = new URLSearchParams(window.location.search); - const r = params.get('repo'); - if (r) { - document.getElementById('repo-input').value = r; + function restoreLastRepository() { + if (currentRepo || repoInputTouched || new URLSearchParams(window.location.search).get('repo')) return; + let lastRepo = null; + try { lastRepo = localStorage.getItem('lastAnalyzedRepo'); } catch (_) {} + if (lastRepo) { + document.getElementById('repo-input').value = lastRepo; + analyzeRepo(false, lastRepo); } - })(); + } + + const repoFromUrl = new URLSearchParams(window.location.search).get('repo'); + if (repoFromUrl) document.getElementById('repo-input').value = repoFromUrl; configureAuthentication(); diff --git a/pyproject.toml b/pyproject.toml index cefb1cd..791c00b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,7 +30,7 @@ markers = [ ] [tool.coverage.run] -source = ["analyze", "app", "issues", "value_classification"] +source = ["analyze", "app", "issues", "repository_cache", "value_classification"] branch = true [tool.coverage.report] diff --git a/repository_cache.py b/repository_cache.py new file mode 100644 index 0000000..e314406 --- /dev/null +++ b/repository_cache.py @@ -0,0 +1,57 @@ +"""Persistent raw GitHub collection cache used by the web API.""" + +import json +import os +import re +import tempfile +from pathlib import Path + + +_OWNER = re.compile(r"[a-z0-9][a-z0-9-]*\Z") +_REPO = re.compile(r"[a-z0-9_.-]+\Z") +_RAW_LISTS = ("pre_ai_prs", "recent_prs", "open_prs") + + +class RepositoryCache: + def __init__(self, root=Path(".cache/repositories")): + self.root = Path(root) + + def path_for(self, repo): + parts = repo.split("/") + if len(parts) != 2 or not _OWNER.fullmatch(parts[0]) or not _REPO.fullmatch(parts[1]) or parts[1] in (".", ".."): + raise ValueError(f"Invalid repository slug: {repo!r}") + return self.root / parts[0] / f"{parts[1]}.json" + + @staticmethod + def _valid(repo, data): + return ( + isinstance(data, dict) + and data.get("repo") == repo + and isinstance(data.get("captured_at"), str) + and bool(data["captured_at"]) + and all(isinstance(data.get(key), list) for key in _RAW_LISTS) + and isinstance(data.get("issues"), dict) + ) + + def load(self, repo): + path = self.path_for(repo) + try: + with path.open(encoding="utf-8") as stream: + data = json.load(stream) + except (OSError, ValueError): + return None + return data if self._valid(repo, data) else None + + def save(self, repo, data): + path = self.path_for(repo) + if not self._valid(repo, data): + raise ValueError(f"Incomplete collection for {repo!r}") + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary = tempfile.mkstemp(dir=path.parent, prefix=f".{path.stem}-", suffix=".tmp") + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + json.dump(data, stream) + os.replace(temporary, path) + finally: + if os.path.exists(temporary): + os.unlink(temporary) diff --git a/tests/e2e/test_pipeline.py b/tests/e2e/test_pipeline.py index 1e9793e..f4a8b58 100644 --- a/tests/e2e/test_pipeline.py +++ b/tests/e2e/test_pipeline.py @@ -36,6 +36,7 @@ def _digest(): @freeze_time("2024-03-01T00:00:00") def test_collect_analyze_chat_and_dashboard(monkeypatch): raw = small_raw_data("acme/widgets") + monkeypatch.setattr(analyze, "collect_issues", lambda repo: {"open": [], "closed": [], "pre_ai": []}) monkeypatch.setattr(subprocess, "run", FakeGh([ graphql_response(raw["pre_ai_prs"]), graphql_response(raw["recent_prs"]), diff --git a/tests/frontend/repository_restore.test.cjs b/tests/frontend/repository_restore.test.cjs new file mode 100644 index 0000000..fdd60a6 --- /dev/null +++ b/tests/frontend/repository_restore.test.cjs @@ -0,0 +1,176 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); + +const html = fs.readFileSync(path.join(__dirname, '..', '..', 'index.html'), 'utf8'); +const script = html.match(/