diff --git a/src/App.test.jsx b/src/App.test.jsx index 1039be40..89a9cd25 100644 --- a/src/App.test.jsx +++ b/src/App.test.jsx @@ -1,3 +1,9 @@ +// Mock the browser ResizeObserver API for the test environment. +globalThis.ResizeObserver ??= class { + observe() {} + unobserve() {} + disconnect() {} +} import { describe, it, expect, vi } from 'vitest' import { render, screen } from '@testing-library/react' import { MemoryRouter } from 'react-router-dom' diff --git a/src/context/AppContext.explore.test.jsx b/src/context/AppContext.explore.test.jsx index dd23cdf9..f483f47b 100644 --- a/src/context/AppContext.explore.test.jsx +++ b/src/context/AppContext.explore.test.jsx @@ -11,6 +11,7 @@ vi.mock('../services/cache', () => ({ vi.mock('../services/github', () => ({ fetchOrg: vi.fn(), + resolveOrg: vi.fn(), fetchRepos: vi.fn(), fetchContributors: vi.fn(), fetchIssues: vi.fn(), @@ -18,14 +19,16 @@ vi.mock('../services/github', () => ({ fetchPulls: vi.fn(), })) -function TestExplorer() { - const { explore, error, loading, model } = useApp() +function TestExplorer({ names = ['test-org'] } = {}) { + const { explore, error, loading, model, orgs, failedOrgNames } = useApp() return (
- + {loading && Loading...} {error && {error}} {model && Model Loaded} + {orgs.map(org => org.login).join(',')} + {(failedOrgNames || []).join(',')}
) } @@ -33,11 +36,22 @@ function TestExplorer() { describe('AppContext explore rate-limit and error handling', () => { beforeEach(() => { vi.clearAllMocks() + if (typeof globalThis.localStorage === 'undefined') { + const store = new Map() + globalThis.localStorage = { + getItem: key => store.has(String(key)) ? store.get(String(key)) : null, + setItem: (key, value) => store.set(String(key), String(value)), + removeItem: key => store.delete(String(key)), + clear: () => store.clear(), + key: index => Array.from(store.keys())[index] ?? null, + get length() { return store.size } + } + } localStorage.clear() }) it('correctly reports rate limit error instead of "No valid organizations found" when fetchOrg hits rate limit', async () => { - github.fetchOrg.mockRejectedValue(new Error('RATE_LIMIT')) + github.resolveOrg.mockRejectedValue(new Error('RATE_LIMIT')) render( @@ -57,7 +71,7 @@ describe('AppContext explore rate-limit and error handling', () => { it('shows actionable refresh rate limit message when PAT is configured', async () => { localStorage.setItem('oe_pat', 'test-pat-token') - github.fetchOrg.mockRejectedValue(new Error('RATE_LIMIT')) + github.resolveOrg.mockRejectedValue(new Error('RATE_LIMIT')) render( @@ -75,7 +89,7 @@ describe('AppContext explore rate-limit and error handling', () => { }) it('reports "No valid organizations found" when organization truly does not exist (NOT_FOUND)', async () => { - github.fetchOrg.mockRejectedValue(new Error('NOT_FOUND')) + github.resolveOrg.mockRejectedValue(new Error('NOT_FOUND')) render( @@ -93,7 +107,7 @@ describe('AppContext explore rate-limit and error handling', () => { }) it('propagates unexpected API failures instead of masking as "No valid organizations found"', async () => { - github.fetchOrg.mockRejectedValue(new Error('Network error: connection reset')) + github.resolveOrg.mockRejectedValue(new Error('Network error: connection reset')) render( @@ -112,7 +126,7 @@ describe('AppContext explore rate-limit and error handling', () => { }) it('reports rate limit error when fetchRepos hits rate limit', async () => { - github.fetchOrg.mockResolvedValue({ login: 'test-org', public_repos: 1 }) + github.resolveOrg.mockResolvedValue({ login: 'test-org', public_repos: 1 }) github.fetchRepos.mockRejectedValue(new Error('RATE_LIMIT')) render( @@ -131,7 +145,7 @@ describe('AppContext explore rate-limit and error handling', () => { }) it('reports rate limit error and does not load a model when fetchContributors hits rate limit', async () => { - github.fetchOrg.mockResolvedValue({ login: 'test-org', public_repos: 1 }) + github.resolveOrg.mockResolvedValue({ login: 'test-org', public_repos: 1 }) github.fetchRepos.mockResolvedValue([{ name: 'test-repo' }]) github.fetchContributors.mockRejectedValue(new Error('RATE_LIMIT')) @@ -150,8 +164,52 @@ describe('AppContext explore rate-limit and error handling', () => { expect(screen.queryByTestId('model-loaded')).not.toBeInTheDocument() }) + it('retains successful organizations and records NOT_FOUND input names', async () => { + github.resolveOrg.mockImplementation(async name => { + if (name === 'missing-org') throw new Error('NOT_FOUND') + return { login: 'test-org', public_repos: 1 } + }) + github.fetchRepos.mockResolvedValue([{ name: 'test-repo', stargazers_count: 5, forks_count: 2, open_issues_count: 1 }]) + github.fetchContributors.mockResolvedValue([{ login: 'dev1', contributions: 10 }]) + + render( + + + + ) + + await act(async () => { + screen.getByText('Explore').click() + }) + + expect(await screen.findByTestId('model-loaded')).toBeInTheDocument() + expect(screen.getByTestId('resolved-org-logins').textContent).toBe('test-org') + expect(screen.getByTestId('failed-org-names').textContent).toBe('missing-org') + expect(github.fetchRepos).toHaveBeenCalledTimes(1) + }) + + it('fetches repositories only once when different inputs resolve to the same login', async () => { + github.resolveOrg.mockResolvedValue({ login: 'same-org', public_repos: 1 }) + github.fetchRepos.mockResolvedValue([{ name: 'test-repo', stargazers_count: 5, forks_count: 2, open_issues_count: 1 }]) + github.fetchContributors.mockResolvedValue([{ login: 'dev1', contributions: 10 }]) + + render( + + + + ) + + await act(async () => { + screen.getByText('Explore').click() + }) + + expect(await screen.findByTestId('model-loaded')).toBeInTheDocument() + expect(screen.getByTestId('resolved-org-logins').textContent).toBe('same-org') + expect(github.fetchRepos).toHaveBeenCalledTimes(1) + }) + it('successfully loads analytical model for a valid organization search', async () => { - github.fetchOrg.mockResolvedValue({ login: 'test-org', public_repos: 1 }) + github.resolveOrg.mockResolvedValue({ login: 'test-org', public_repos: 1 }) github.fetchRepos.mockResolvedValue([{ name: 'test-repo', stargazers_count: 5, forks_count: 2, open_issues_count: 1 }]) github.fetchContributors.mockResolvedValue([{ login: 'dev1', contributions: 10 }]) diff --git a/src/context/AppContext.jsx b/src/context/AppContext.jsx index 9ee03908..011e733b 100644 --- a/src/context/AppContext.jsx +++ b/src/context/AppContext.jsx @@ -1,5 +1,5 @@ import { createContext, useContext, useState, useCallback, useEffect, useMemo, useRef } from 'react' -import { fetchOrg, fetchRepos, fetchContributors, fetchIssues, fetchRateLimit, fetchPulls } from '../services/github' +import { resolveOrg, fetchRepos, fetchContributors, fetchIssues, fetchRateLimit, fetchPulls } from '../services/github' import { buildAnalyticalModel, getTopRepositories } from '../services/analytics' import { saveAnalysis, loadAnalysis } from '../services/cache' @@ -42,6 +42,7 @@ export function AppProvider({ children }) { const [isComplete, setIsComplete] = useState(false) const [auditComplete, setAuditComplete] = useState(false) const [lastOrgNames, setLastOrgNames] = useState([]) + const [failedOrgNames, setFailedOrgNames] = useState([]) // True until the cached analysis has been read, so routes that need a model // wait for the restore instead of bouncing to the picker on first paint. const [hydrating, setHydrating] = useState(true) @@ -180,11 +181,19 @@ export function AppProvider({ children }) { setOrgs([]); setIssuesData({}); setLastOrgNames(names); + setFailedOrgNames([]); setAuditComplete(false); setAdvanceAnalyticsComplete(false); try { setLoadMsg('Fetching organization metadata...') - const orgRes = await Promise.allSettled(names.map(n => fetchOrg(n, pat))) + const orgRes = await Promise.allSettled(names.map(n => resolveOrg(n, pat))) + + const failedNames = orgRes.flatMap((result, index) => + result.status === 'rejected' && result.reason?.message === 'NOT_FOUND' + ? [names[index]] + : [] + ); + setFailedOrgNames(failedNames); const rateLimitError = orgRes.find(r => r.status === 'rejected' && r.reason?.message === 'RATE_LIMIT') if (rateLimitError) { @@ -196,8 +205,22 @@ export function AppProvider({ children }) { throw (unexpectedError.reason || new Error('Failed to fetch organization data.')) } - const validOrgs = orgRes.filter(r => r.status === 'fulfilled').map(r => r.value) - if (!validOrgs.length) throw new Error('No valid organizations found. Check the names and try again.') + const resolvedOrgs = orgRes + .filter(r => r.status === 'fulfilled') + .map(r => r.value) + + const seenLogins = new Set() + const validOrgs = resolvedOrgs.filter(org => { + const login = String(org.login || '').toLowerCase() + if (!login || seenLogins.has(login)) return false + + seenLogins.add(login) + return true + }) + + if (!validOrgs.length) { + throw new Error('No valid organizations found. Check the names and try again.') + } setOrgs(validOrgs) setLoadMsg('Fetching repositories...') @@ -452,6 +475,7 @@ export function AppProvider({ children }) { runAdvanceAnalytics, refreshRateLimit, advanceAnalyticsLoading, advanceAnalyticsComplete, runFullAnalytics, isComplete, auditComplete, lastOrgNames, hydrating, + failedOrgNames, explore, runFullExplore, runAudit, runGovernanceAnalysis, setError, staleRepoStats }}> {children} diff --git a/src/pages/HomePage.jsx b/src/pages/HomePage.jsx index e21ba5d0..1e5e8a48 100644 --- a/src/pages/HomePage.jsx +++ b/src/pages/HomePage.jsx @@ -15,7 +15,7 @@ export default function HomePage() { const recent = JSON.parse(localStorage.getItem('oe_recent') || '[]') const addChip = raw => { - const parts = raw.split(/[,+\s]+/).map(s => s.trim()).filter(Boolean) + const parts = raw.split(',').map(s => s.trim()).filter(Boolean) setChips(prev => { // Deduplicate case-insensitively: `AOSSIE-Org` and `aossie-org` are // the same org, so keep only the first-seen casing. diff --git a/src/pages/OverviewPage.jsx b/src/pages/OverviewPage.jsx index fecdaaac..515b1b7d 100644 --- a/src/pages/OverviewPage.jsx +++ b/src/pages/OverviewPage.jsx @@ -15,7 +15,7 @@ const LANG_COLORS = ['#22c55e', '#f5c518', '#3b82f6', '#ef4444', '#a855f7', '#f9 const fmt = n => n > 999 ? (n / 1000).toFixed(1) + 'k' : String(n) export default function OverviewPage() { - const { orgs, model, totalRepo, isComplete, loading, runFullExplore } = useApp() + const { orgs, model, totalRepo, isComplete, loading, runFullExplore, failedOrgNames = [], lastOrgNames = [] } = useApp() const { theme } = useTheme() const navigate = useNavigate() const [open, setOpen] = useState(false) @@ -23,9 +23,7 @@ export default function OverviewPage() { const [showAllOrgs, setShowAllOrgs] = useState(false) const infoRef = useRef(null) const location = useLocation(); - const chips = location.state?.chips || []; - const verifiedOrgs = orgs.map(o => o.login); - const notVerifiedOrgs = chips.filter(c => !verifiedOrgs.some(org => c.trim() === org)); + useEffect(() => { function handleClickOutside(event) { @@ -110,9 +108,9 @@ export default function OverviewPage() { onRun={runFullExplore} /> {/* Org identity bar */} - {chips.length > orgs.length && ( + {failedOrgNames.length > 0 && (
- {`Analysis completed with warnings: ${chips.length - orgs.length} of ${chips.length} organizations could not be loaded: ${notVerifiedOrgs.join(', ')}.`} + {'Analysis completed with warnings: ' + failedOrgNames.length + ' of ' + lastOrgNames.length + ' organizations could not be loaded: ' + failedOrgNames.join(', ') + '.'}
)}
fetchWithCache(`https://api.github.com/orgs/${org}`, pat) +export async function resolveOrg(input, pat) { + const value = String(input ?? '').trim() + if (!value) throw new Error('NOT_FOUND') + + // Prefer direct lookup for a GitHub organization login. + if (!/\s/.test(value)) { + try { + return await fetchOrg(value, pat) + } catch (error) { + if (error?.message !== 'NOT_FOUND') throw error + } + } + + // Search GitHub for organizations matching the supplied name. + const query = encodeURIComponent(`${value} in:name type:org`) + const results = await fetchWithCache( + `https://api.github.com/search/users?q=${query}&per_page=10`, + pat + ) + + const candidates = (results.items || []).filter( + item => item.type === 'Organization' + ) + + if (!candidates.length) throw new Error('NOT_FOUND') + + // Match canonical GitHub logins without removing separators. + const exactLoginMatch = candidates.find( + item => String(item.login || '').toLowerCase() === value.toLowerCase() + ); + + if (exactLoginMatch) { + return fetchOrg(exactLoginMatch.login, pat); + } + + // Fetch candidate profiles in small batches to limit concurrent requests. + const profileResults = []; + for (let i = 0; i < candidates.length; i += 2) { + const batch = await Promise.allSettled( + candidates.slice(i, i + 2).map(item => fetchOrg(item.login, pat)) + ); + profileResults.push(...batch); + + // Stop immediately when GitHub reports a rate limit. + const rateLimit = batch.find( + result => result.status === 'rejected' && result.reason?.message === 'RATE_LIMIT' + ); + if (rateLimit) throw rateLimit.reason; + } + + // Match the full profile name, ignoring only letter casing and outer spaces. + const matchingProfiles = profileResults + .filter(result => result.status === 'fulfilled') + .map(result => result.value) + .filter(org => + String(org.name || '').trim().toLowerCase() === value.toLowerCase() + ); + + // Return only a unique, reliable profile-name match. + if (matchingProfiles.length === 1) { + return matchingProfiles[0]; + } + + const profileError = profileResults.find( + result => + result.status === 'rejected' && + result.reason?.message !== 'NOT_FOUND' + ); + + if (profileError) throw profileError.reason; + + // Never guess when no unique organization match exists. + throw new Error('NOT_FOUND'); +} export async function fetchRepos(org, repoCount, pat) { const all = [] const maxPages = pat ? Math.ceil(repoCount / 100) : 5