diff --git a/src/plugins/built-in/globalSearch/src/indexing/passiveObserver.ts b/src/plugins/built-in/globalSearch/src/indexing/passiveObserver.ts index 57f7044f..fe3eef46 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/passiveObserver.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/passiveObserver.ts @@ -297,6 +297,73 @@ function titleFromEndpoint( return (firstLine || fallback).slice(0, 200); } +function shouldSkipPassiveEntity( + ctx: CapturedContext, + entity: unknown, + isPeopleSupport: boolean, +): boolean { + if (!entity || (typeof entity !== "object" && typeof entity !== "string")) { + return true; + } + if (ctx.route.includes("/load/message") && typeof entity === "object") { + const subject = (entity as Record).subject; + if (typeof subject === "string" && subject.startsWith("BQ+TIMETABLE:")) { + return true; + } + } + return isPeopleSupport && !isPeopleEntityWorthIndexing(entity); +} + +function passiveEntityToIndexItem( + ctx: CapturedContext, + entity: unknown, + index: number, + category: ReturnType, + isPeopleSupport: boolean, +): IndexItem | null { + const fallbackId = `${ctx.route}#${index}`; + const entityId = pickId(entity, fallbackId); + const stableId = `passive-${ctx.route.replace(/\//g, "_")}-${entityId}`; + + const content = extractTextFromValue(entity, { + maxChars: MAX_PER_RESPONSE_TEXT_CHARS, + }); + const title = titleFromEndpoint(ctx.route, entity, content, fallbackId); + if (!content && (!title || title === fallbackId)) { + return null; + } + + const deepLinkHints = pickDeepLinkHints(entity); + const sourcePage = sourcePageForRoute(ctx.route); + const coursePm = ctx.route.includes("/load/courses") + ? extractProgrammeMetaclass(ctx.requestBody, entity) + : null; + + return buildIndexItem({ + id: stableId, + text: title, + category, + contentOverride: content, + metadata: { + route: ctx.route, + source: "passive", + observedAt: new Date(ctx.observedAt).toISOString(), + entityType: category, + entityId, + icon: "\ueb71", + sourcePage, + ...(isPeopleSupport ? { supportRecord: true, priority: "low" } : {}), + ...deepLinkHints, + ...(coursePm + ? { programme: coursePm.programme, metaclass: coursePm.metaclass } + : {}), + }, + actionId: "passive", + renderComponentId: "passive", + dateAdded: ctx.observedAt, + }); +} + function synthesizeItems( ctx: CapturedContext, payload: unknown, @@ -307,86 +374,16 @@ function synthesizeItems( if (entities.length === 0) return []; const category = categoryFromRoute(ctx.route); - const now = ctx.observedAt; - const out: IndexItem[] = []; - const isPeopleSupport = ctx.route.includes("/load/message/people"); - + const out: IndexItem[] = []; const limit = Math.min(entities.length, MAX_ITEMS_PER_RESPONSE); + for (let i = 0; i < limit; i++) { const entity = entities[i]; - if (!entity || (typeof entity !== "object" && typeof entity !== "string")) { - continue; - } + if (shouldSkipPassiveEntity(ctx, entity, isPeopleSupport)) continue; - if ( - ctx.route.includes("/load/message") && - entity && - typeof entity === "object" - ) { - const subject = (entity as Record).subject; - if (typeof subject === "string" && subject.startsWith("BQ+TIMETABLE:")) { - continue; - } - } - - // For the messages compose-people endpoint, skip records that don't - // carry a real human name. We never want raw entries like - // `/seqta/student/load/message/people#20` becoming titles, and we - // explicitly route the rest to /messages so they're treated as support - // records, not standalone "people" results. - if (isPeopleSupport && !isPeopleEntityWorthIndexing(entity)) { - continue; - } - - const fallbackId = `${ctx.route}#${i}`; - const entityId = pickId(entity, fallbackId); - const stableId = `passive-${ctx.route.replace(/\//g, "_")}-${entityId}`; - - const content = extractTextFromValue(entity, { - maxChars: MAX_PER_RESPONSE_TEXT_CHARS, - }); - const title = titleFromEndpoint(ctx.route, entity, content, fallbackId); - if (!content && (!title || title === fallbackId)) { - // Skip records that produced neither title nor content; they are - // structurally noise (e.g. tiny acknowledgement payloads). - continue; - } - - const deepLinkHints = pickDeepLinkHints(entity); - const sourcePage = sourcePageForRoute(ctx.route); - const coursePm = ctx.route.includes("/load/courses") - ? extractProgrammeMetaclass(ctx.requestBody, entity) - : null; - - out.push( - buildIndexItem({ - id: stableId, - text: title, - category, - contentOverride: content, - metadata: { - route: ctx.route, - source: "passive", - observedAt: new Date(now).toISOString(), - entityType: category, - entityId, - icon: "\ueb71", - sourcePage, - // Mark message/people as a low-priority support record so the - // search ranker can deprioritize it relative to real messages, - // assessments, courses, etc. - ...(isPeopleSupport ? { supportRecord: true, priority: "low" } : {}), - ...deepLinkHints, - ...(coursePm - ? { programme: coursePm.programme, metaclass: coursePm.metaclass } - : {}), - }, - actionId: "passive", - renderComponentId: "passive", - dateAdded: now, - }), - ); + const item = passiveEntityToIndexItem(ctx, entity, i, category, isPeopleSupport); + if (item) out.push(item); } return out; diff --git a/src/seqta/utils/cloudPfpCache.ts b/src/seqta/utils/cloudPfpCache.ts index b441f8e9..26d8a0fc 100644 --- a/src/seqta/utils/cloudPfpCache.ts +++ b/src/seqta/utils/cloudPfpCache.ts @@ -86,6 +86,56 @@ export type ResolveCloudPfpResult = { fromCache: boolean; }; +function cachedBlobUrl(blob: Blob): ResolveCloudPfpResult { + return { src: URL.createObjectURL(blob), fromCache: true }; +} + +function sessionPfpHash(viewerId: string | null, userId: string): string | null { + if (!viewerId || viewerId !== userId) return null; + return cloudAuth.state.user?.pfpHash ?? null; +} + +function localHashHit( + serverHash: string | null | undefined, + localHash: string | null | undefined, + localBlob: Blob | null | undefined, +): ResolveCloudPfpResult | null { + if (!serverHash || serverHash !== localHash || !(localBlob instanceof Blob)) { + return null; + } + return cachedBlobUrl(localBlob); +} + +async function fetchAndCachePfp( + userId: string, + pfpUrl: string, + serverHash: string, + localHash: string | null | undefined, + localBlob: Blob | null | undefined, +): Promise { + const imageUrl = pfpUrlWithHash(pfpUrl, serverHash); + const headers: HeadersInit = {}; + if (localHash) { + headers["If-None-Match"] = `"${localHash}"`; + } + const token = await cloudAuth.getStoredToken(); + if (token) { + headers.Authorization = `Bearer ${token}`; + } + + const res = await fetch(imageUrl, { headers }); + if (res.status === 304 && localBlob instanceof Blob) { + await store.setItem(hashKey(userId), serverHash); + return cachedBlobUrl(localBlob); + } + if (!res.ok) return null; + + const blob = await res.blob(); + await store.setItem(blobKey(userId), blob); + await store.setItem(hashKey(userId), serverHash); + return { src: URL.createObjectURL(blob), fromCache: false }; +} + /** * Returns an object URL or direct URL for the cloud profile picture. * Order: session hash match → local blob; else meta → download → store blob then hash. @@ -102,20 +152,14 @@ export async function resolveCloudPfp( const localHash = await store.getItem(hashKey(userId)); const localBlob = await store.getItem(blobKey(userId)); - let serverHash: string | null = - viewerId && viewerId === userId ? (cloudAuth.state.user?.pfpHash ?? null) : null; - - if (serverHash && serverHash === localHash && localBlob instanceof Blob) { - return { src: URL.createObjectURL(localBlob), fromCache: true }; - } + let serverHash: string | null = sessionPfpHash(viewerId, userId); + const sessionHit = localHashHit(serverHash, localHash, localBlob); + if (sessionHit) return sessionHit; try { serverHash = await fetchServerHash(userId); } catch { - if (localHash && localBlob instanceof Blob) { - return { src: URL.createObjectURL(localBlob), fromCache: true }; - } - return null; + return localHashHit(localHash, localHash, localBlob); } if (!serverHash) { @@ -124,33 +168,9 @@ export async function resolveCloudPfp( return null; } - if (serverHash === localHash && localBlob instanceof Blob) { - return { src: URL.createObjectURL(localBlob), fromCache: true }; - } + const metaHit = localHashHit(serverHash, localHash, localBlob); + if (metaHit) return metaHit; await clearLocal(userId); - - const imageUrl = pfpUrlWithHash(pfpUrl, serverHash); - const headers: HeadersInit = {}; - if (localHash) { - headers["If-None-Match"] = `"${localHash}"`; - } - const token = await cloudAuth.getStoredToken(); - if (token && isAccountsHostedPfpUrl(pfpUrl)) { - headers.Authorization = `Bearer ${token}`; - } - - const res = await fetch(imageUrl, { headers }); - if (res.status === 304 && localBlob instanceof Blob) { - await store.setItem(hashKey(userId), serverHash); - return { src: URL.createObjectURL(localBlob), fromCache: true }; - } - - if (!res.ok) return null; - - const blob = await res.blob(); - await store.setItem(blobKey(userId), blob); - await store.setItem(hashKey(userId), serverHash); - - return { src: URL.createObjectURL(blob), fromCache: false }; + return fetchAndCachePfp(userId, pfpUrl, serverHash, localHash, localBlob); }