Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions src/components/PeopleSearchTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
}

/** Human summary of an email lookup batch, e.g. "Found 3 new emails · 1 already had one · 2 not found". */
export function summarizeEmailResults(results: { status: string; email?: string | null }[], checked: number) {

Check warning on line 60 in src/components/PeopleSearchTab.tsx

View workflow job for this annotation

GitHub Actions / web

Fast refresh only works when a file only exports components. Use a new file to share constants or functions between components
const already = results.filter((r) => r.status === 'already_has_email').length
const found = results.filter((r) => r.status !== 'already_has_email' && !!r.email).length
const failed = results.filter((r) => r.status === 'error').length
Expand Down Expand Up @@ -89,11 +89,19 @@
if (!alive) return
setEnabledSources(e)
if (e.parallel) setSources((cur) => new Set([...cur, 'parallel']))
if (e.firecrawl) setSources((cur) => new Set([...cur, 'firecrawl']))
// Firecrawl is opt-in (slowest source); it is only enabled for selection, not auto-checked.
}).catch(() => { /* keep Parallel disabled if the probe fails */ })
return () => { alive = false }
}, [])
const [loading, setLoading] = useState(false)
const [elapsed, setElapsed] = useState(0)
useEffect(() => {
if (!loading) return
setElapsed(0)
const t0 = Date.now()
const id = setInterval(() => setElapsed(Math.round((Date.now() - t0) / 1000)), 1000)
return () => clearInterval(id)
}, [loading])
const [results, setResults] = useState<SourcedCandidate[]>([])
const [sourceStats, setSourceStats] = useState<Record<string, { count: number; error?: string }>>({})
const [selected, setSelected] = useState<Set<string>>(new Set())
Expand Down Expand Up @@ -130,8 +138,9 @@
setResults(res.candidates)
setSourceStats(res.sources)
void recordHistory(query.trim() || [titles, companies].filter(Boolean).join(' · '), res.candidates.length, { source: 'people_search', titles, locations, skills, companies, status: res.candidates.length ? 'success' : 'no_results' })
const failed = Object.entries(res.sources).filter(([, s]) => s.error).map(([k]) => k)
if (failed.length) toast({ title: 'Some sources failed', description: failed.join(', ') })
const failed = Object.entries(res.sources).filter(([, s]) => s.error)
if (failed.length) toast({ title: 'Some sources failed', description: failed.map(([k, s]) => `${k}: ${s.error}`).join(' · '), variant: res.candidates.length ? undefined : 'destructive' })
else if (!res.candidates.length) toast({ title: 'No results', description: 'Try a broader query or more sources.' })
} catch (e) {
toast({ title: 'Search failed', description: e instanceof Error ? e.message : String(e), variant: 'destructive' })
} finally {
Expand Down Expand Up @@ -208,7 +217,7 @@
<div className="flex gap-2">
<input aria-label="people query" className={inputCls} placeholder="e.g. senior ML infrastructure engineers with CUDA experience" value={query} onChange={(e) => setQuery(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && runSearch()} />
<button onClick={runSearch} disabled={loading} className="inline-flex items-center gap-1.5 rounded-md bg-primary px-4 py-2 text-sm text-primary-foreground disabled:opacity-50">
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Search className="w-4 h-4" />}Search
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Search className="w-4 h-4" />}{loading ? `Searching… ${elapsed}s` : 'Search'}
</button>
</div>
<div className="grid grid-cols-1 md:grid-cols-4 gap-2">
Expand Down
22 changes: 18 additions & 4 deletions src/services/candidateSources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export interface CandidateFiltersInput {

export interface SourceCandidatesResponse {
candidates: SourcedCandidate[]
sources: Record<string, { count: number; est_cost_usd: number; error?: string }>
sources: Record<string, { count: number; est_cost_usd: number; ms?: number; error?: string }>
enabled: Record<SourceKey, boolean>
raw_count: number
est_cost_usd: number
Expand Down Expand Up @@ -92,10 +92,18 @@ export function splitList(v: string): string[] {
return v.split(/[,\n]/).map((s) => s.trim()).filter(Boolean)
}

async function invoke<T>(name: string, body: Record<string, unknown>): Promise<T> {
/** Client-side cap for a People Search request (server caps each source at 30s). */
export const PEOPLE_SEARCH_TIMEOUT_MS = 100_000

async function invoke<T>(name: string, body: Record<string, unknown>, opts: { timeoutMs?: number } = {}): Promise<T> {
const { data: { session } } = await supabase.auth.getSession()
if (!session?.access_token) throw new Error('Authentication required – please sign in.')
const res = await fetch(`${SUPABASE_URL}/functions/v1/${name}`, {
const ctrl = opts.timeoutMs ? new AbortController() : null
const timer = ctrl ? setTimeout(() => ctrl.abort(), opts.timeoutMs) : undefined
let res: Response
try {
res = await fetch(`${SUPABASE_URL}/functions/v1/${name}`, {
signal: ctrl?.signal,
method: 'POST',
headers: {
apikey: SUPABASE_KEY,
Expand All @@ -104,6 +112,12 @@ async function invoke<T>(name: string, body: Record<string, unknown>): Promise<T
},
body: JSON.stringify(body),
})
} catch (e) {
if (ctrl?.signal.aborted) throw new Error(`Search timed out after ${Math.round((opts.timeoutMs || 0) / 1000)}s. Try fewer sources or a narrower query.`)
throw new Error(`Network error: ${e instanceof Error ? e.message : String(e)}`)
} finally {
clearTimeout(timer)
}
const data = await res.json().catch(() => ({ error: `HTTP ${res.status}` }))
if (!res.ok || data?.error) {
throw new Error(data?.message || data?.error || `HTTP ${res.status}`)
Expand All @@ -119,7 +133,7 @@ export function sourceCandidates(input: {
person_name?: string
harmonic_enrich?: boolean
}): Promise<SourceCandidatesResponse> {
return invoke('source-candidates', input)
return invoke('source-candidates', input, { timeoutMs: PEOPLE_SEARCH_TIMEOUT_MS })
}

export function startDeepSearch(input: {
Expand Down
35 changes: 28 additions & 7 deletions supabase/functions/source-candidates/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,19 @@ async function addTalentFlags(rows: any[]): Promise<any[]> {
}).filter((c) => !c.is_bot && c.gh_type !== "Organization"); // orgs (e.g. README owners) are not people
}

/** Per-source wall-clock budget: a slow provider becomes a per-source error instead of hanging the search. */
const SOURCE_TIMEOUT_MS = 30_000;
/** Budget for each optional post-processing call (enrich, GitHub handle lookup, site scrape). */
const POST_STEP_TIMEOUT_MS = 8_000;

function withTimeout<T>(p: Promise<T>, ms: number, message: string): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined;
return Promise.race([
p,
new Promise<T>((_, reject) => { timer = setTimeout(() => reject(new Error(message)), ms); }),
]).finally(() => clearTimeout(timer));
}

serve(async (req) => {
if (req.method === "OPTIONS") return new Response(null, { headers: getCorsHeaders(req) });
const headers = { ...getCorsHeaders(req), "Content-Type": "application/json" };
Expand Down Expand Up @@ -143,35 +156,43 @@ serve(async (req) => {
return new Response(JSON.stringify({ error: "No enabled people sources for this request", enabled }), { status: 422, headers });
}

const settled = await Promise.allSettled(tasks.map((t) => t.run()));
const sources: Record<string, { count: number; est_cost_usd: number; total?: number | null; error?: string; detail?: Record<string, unknown> }> = {};
const timings: Record<string, number> = {};
const settled = await Promise.allSettled(tasks.map(async (t) => {
const t0 = Date.now();
try {
return await withTimeout(t.run(), SOURCE_TIMEOUT_MS, `${t.source} timed out after ${SOURCE_TIMEOUT_MS / 1000}s`);
} finally {
timings[t.source] = Date.now() - t0;
}
}));
const sources: Record<string, { count: number; est_cost_usd: number; total?: number | null; ms?: number; error?: string; detail?: Record<string, unknown> }> = {};
// Order = merge priority for field conflicts: structured sources first.
const priority: SourceName[] = ["harmonic", "github", "exa", "parallel", "firecrawl"];
const bySource = new Map<SourceName, UnifiedCandidate[]>();
settled.forEach((r, i) => {
const s = tasks[i].source;
if (r.status === "fulfilled") {
sources[s] = { count: r.value.candidates.length, est_cost_usd: Number(r.value.cost.toFixed(4)), total: r.value.total, ...(r.value.detail ? { detail: r.value.detail } : {}) };
sources[s] = { count: r.value.candidates.length, est_cost_usd: Number(r.value.cost.toFixed(4)), total: r.value.total, ms: timings[s], ...(r.value.detail ? { detail: r.value.detail } : {}) };
bySource.set(s, r.value.candidates);
} else {
const msg = r.reason instanceof Error ? r.reason.message : String(r.reason);
console.error(`source ${s} failed:`, msg);
sources[s] = { count: 0, est_cost_usd: 0, error: msg.slice(0, 200) };
sources[s] = { count: 0, est_cost_usd: 0, ms: timings[s], error: msg.slice(0, 200) };
}
});
const all = priority.flatMap((s) => bySource.get(s) || []);

// Optional: resolve top LinkedIn candidates to Harmonic people so they dedup by Harmonic URN.
if (harmonicCfg && body.harmonic_enrich === true) {
const targets = all.filter((c) => c.linkedinUrl && !c.harmonicUrn).slice(0, HARMONIC_ENRICH_TOP);
const enriched = await Promise.allSettled(targets.map((c) => harmonicPersonByLinkedin(harmonicCfg, c.linkedinUrl!)));
const enriched = await Promise.allSettled(targets.map((c) => withTimeout(harmonicPersonByLinkedin(harmonicCfg, c.linkedinUrl!), POST_STEP_TIMEOUT_MS, "harmonic enrich timed out")));
for (const r of enriched) if (r.status === "fulfilled" && r.value) all.push(r.value);
}

// Free GitHub handle lookup (name + company) for top web-profile results without one.
const nameTargets = all.filter((c) => !c.githubLogin && c.currentCompany && c.sources.some((h) => h.provider === "exa"))
.sort((a, b) => (a.sources[0]?.rank ?? 99) - (b.sources[0]?.rank ?? 99)).slice(0, GITHUB_NAME_LOOKUPS);
const handles = await Promise.allSettled(nameTargets.map((c) => githubHandleByNameCompany(getEnv("GITHUB_TOKEN"), c.fullName, c.currentCompany!, fetch, c.location)));
const handles = await Promise.allSettled(nameTargets.map((c) => withTimeout(githubHandleByNameCompany(getEnv("GITHUB_TOKEN"), c.fullName, c.currentCompany!, fetch, c.location), POST_STEP_TIMEOUT_MS, "github lookup timed out")));
handles.forEach((r, i) => {
if (r.status === "fulfilled" && r.value) {
nameTargets[i].githubLogin = r.value.login.toLowerCase();
Expand All @@ -197,7 +218,7 @@ serve(async (req) => {
if (enabled.firecrawl && requested.has("firecrawl")) {
const kw = extractSearchTerms(query, filters).keywords;
const targets = (candidates as any[]).filter((c) => isPersonalSiteUrl(c.blog_url)).slice(0, FIRECRAWL_LIMITS.scrapes);
const ev = await Promise.allSettled(targets.map((c) => firecrawlScrapeEvidence(getEnv("FIRECRAWL_API_KEY")!, String(c.blog_url).startsWith("http") ? c.blog_url : `https://${c.blog_url}`)));
const ev = await Promise.allSettled(targets.map((c) => withTimeout(firecrawlScrapeEvidence(getEnv("FIRECRAWL_API_KEY")!, String(c.blog_url).startsWith("http") ? c.blog_url : `https://${c.blog_url}`), POST_STEP_TIMEOUT_MS, "firecrawl scrape timed out")));
let scraped = 0;
ev.forEach((r, i) => {
const text = r.status === "fulfilled" ? r.value : null;
Expand Down
Loading