From d8749fbca15261aab917d72adfea2c4941674a3b Mon Sep 17 00:00:00 2001 From: Divya Shettar <233538644+divya5623@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:22:06 +0530 Subject: [PATCH 1/4] Support searching organizations by name --- src/context/AppContext.jsx | 4 ++-- src/pages/HomePage.jsx | 2 +- src/services/github.js | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/context/AppContext.jsx b/src/context/AppContext.jsx index 9ee03908..4ab353bd 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' @@ -184,7 +184,7 @@ export function AppProvider({ children }) { 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 rateLimitError = orgRes.find(r => r.status === 'rejected' && r.reason?.message === 'RATE_LIMIT') if (rateLimitError) { diff --git a/src/pages/HomePage.jsx b/src/pages/HomePage.jsx index e21ba5d0..0eb8d671 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/services/github.js b/src/services/github.js index 65964b47..6505d2d7 100644 --- a/src/services/github.js +++ b/src/services/github.js @@ -144,6 +144,43 @@ async function fetchWithCache(url, pat) { export const fetchOrg = (org, pat) => 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') + + // Prefer a login that exactly matches the input after normalization. + const normalize = text => + String(text || '').toLowerCase().replace(/[\s_-]+/g, '') + + const selected = + candidates.find(item => normalize(item.login) === normalize(value)) || + candidates[0] + + // Return the full organization profile, not the search result. + return fetchOrg(selected.login, pat) +} export async function fetchRepos(org, repoCount, pat) { const all = [] const maxPages = pat ? Math.ceil(repoCount / 100) : 5 From 57f11ad2877ad3e848f7b9e5390c4ece94bc940a Mon Sep 17 00:00:00 2001 From: Divya Shettar <233538644+divya5623@users.noreply.github.com> Date: Thu, 5 Nov 2026 00:04:09 +0530 Subject: [PATCH 2/4] Address organization search review feedback --- src/App.test.jsx | 6 ++++++ src/context/AppContext.explore.test.jsx | 26 ++++++++++++++++++------- src/context/AppContext.jsx | 18 +++++++++++++++-- src/pages/HomePage.jsx | 2 +- 4 files changed, 42 insertions(+), 10 deletions(-) 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..11c54607 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(), @@ -33,11 +34,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 +69,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 +87,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 +105,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 +124,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 +143,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')) @@ -151,7 +163,7 @@ describe('AppContext explore rate-limit and error handling', () => { }) 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 4ab353bd..db7b4c6f 100644 --- a/src/context/AppContext.jsx +++ b/src/context/AppContext.jsx @@ -196,8 +196,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...') diff --git a/src/pages/HomePage.jsx b/src/pages/HomePage.jsx index 0eb8d671..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(/[+,]/).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. From bcfd3baa9bccb50ac21759f23bca744c0934548e Mon Sep 17 00:00:00 2001 From: Divya Shettar <233538644+divya5623@users.noreply.github.com> Date: Thu, 5 Nov 2026 00:08:44 +0530 Subject: [PATCH 3/4] Avoid guessing organization search matches --- src/services/github.js | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/src/services/github.js b/src/services/github.js index 6505d2d7..f182f81b 100644 --- a/src/services/github.js +++ b/src/services/github.js @@ -174,12 +174,38 @@ export async function resolveOrg(input, pat) { const normalize = text => String(text || '').toLowerCase().replace(/[\s_-]+/g, '') - const selected = - candidates.find(item => normalize(item.login) === normalize(value)) || - candidates[0] + const exactLoginMatch = candidates.find( + item => normalize(item.login) === normalize(value) + ) + + if (exactLoginMatch) { + return fetchOrg(exactLoginMatch.login, pat) + } + + // Match against full organization profile names when the login differs. + const profileResults = await Promise.allSettled( + candidates.map(item => fetchOrg(item.login, pat)) + ) + + const profileError = profileResults.find( + result => + result.status === 'rejected' && + result.reason?.message !== 'NOT_FOUND' + ) + + if (profileError) throw profileError.reason + + const matchingProfiles = profileResults + .filter(result => result.status === 'fulfilled') + .map(result => result.value) + .filter(org => normalize(org.name) === normalize(value)) + + // Do not guess when no unique organization match exists. + if (matchingProfiles.length !== 1) { + throw new Error('NOT_FOUND') + } - // Return the full organization profile, not the search result. - return fetchOrg(selected.login, pat) + return matchingProfiles[0] } export async function fetchRepos(org, repoCount, pat) { const all = [] From 09698790d21f588ffed106cfb13eab7ccf6a77e5 Mon Sep 17 00:00:00 2001 From: Divya Shettar <233538644+divya5623@users.noreply.github.com> Date: Sat, 7 Nov 2026 10:05:57 +0530 Subject: [PATCH 4/4] Fix organization resolution and partial exploration --- src/context/AppContext.explore.test.jsx | 52 ++++++++++++++++++++-- src/context/AppContext.jsx | 10 +++++ src/pages/OverviewPage.jsx | 10 ++--- src/services/github.js | 59 +++++++++++++++---------- 4 files changed, 98 insertions(+), 33 deletions(-) diff --git a/src/context/AppContext.explore.test.jsx b/src/context/AppContext.explore.test.jsx index 11c54607..f483f47b 100644 --- a/src/context/AppContext.explore.test.jsx +++ b/src/context/AppContext.explore.test.jsx @@ -19,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(',')}
) } @@ -162,6 +164,50 @@ 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.resolveOrg.mockResolvedValue({ login: 'test-org', public_repos: 1 }) github.fetchRepos.mockResolvedValue([{ name: 'test-repo', stargazers_count: 5, forks_count: 2, open_issues_count: 1 }]) diff --git a/src/context/AppContext.jsx b/src/context/AppContext.jsx index db7b4c6f..011e733b 100644 --- a/src/context/AppContext.jsx +++ b/src/context/AppContext.jsx @@ -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,12 +181,20 @@ 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 => 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) { throw new Error('RATE_LIMIT') @@ -466,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/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(', ') + '.'}
)}
- String(text || '').toLowerCase().replace(/[\s_-]+/g, '') - + // Match canonical GitHub logins without removing separators. const exactLoginMatch = candidates.find( - item => normalize(item.login) === normalize(value) - ) + item => String(item.login || '').toLowerCase() === value.toLowerCase() + ); if (exactLoginMatch) { - return fetchOrg(exactLoginMatch.login, pat) + return fetchOrg(exactLoginMatch.login, pat); } - // Match against full organization profile names when the login differs. - const profileResults = await Promise.allSettled( - candidates.map(item => fetchOrg(item.login, pat)) - ) - - const profileError = profileResults.find( - result => - result.status === 'rejected' && - result.reason?.message !== 'NOT_FOUND' - ) - - if (profileError) throw profileError.reason + // 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 => normalize(org.name) === normalize(value)) + .filter(org => + String(org.name || '').trim().toLowerCase() === value.toLowerCase() + ); - // Do not guess when no unique organization match exists. - if (matchingProfiles.length !== 1) { - throw new Error('NOT_FOUND') + // Return only a unique, reliable profile-name match. + if (matchingProfiles.length === 1) { + return matchingProfiles[0]; } - 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 = []