From b8a9721f1f45903af8287ca296530b40a7a978e2 Mon Sep 17 00:00:00 2001 From: StroepWafel Date: Wed, 2 Sep 2026 14:41:35 +0930 Subject: [PATCH] UI watcher --- .../built-in/globalSearch/src/indexing/db.ts | 182 +++++++++++++++--- .../globalSearch/src/indexing/indexer.ts | 16 +- .../src/indexing/indexingState.test.ts | 18 ++ .../src/indexing/indexingState.ts | 10 + .../globalSearch/src/indexing/jobs/courses.ts | 22 ++- .../src/indexing/passiveObserver.ts | 9 +- .../globalSearch/src/indexing/types.ts | 6 + 7 files changed, 224 insertions(+), 39 deletions(-) create mode 100644 src/plugins/built-in/globalSearch/src/indexing/indexingState.test.ts create mode 100644 src/plugins/built-in/globalSearch/src/indexing/indexingState.ts diff --git a/src/plugins/built-in/globalSearch/src/indexing/db.ts b/src/plugins/built-in/globalSearch/src/indexing/db.ts index 5fc4d133..a8042176 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/db.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/db.ts @@ -4,6 +4,7 @@ const VERSION_KEY = "betterseqta-index-version"; let dbPromise: Promise | null = null; let cachedDb: IDBDatabase | null = null; +let upgradeChain: Promise = Promise.resolve(); function getCurrentVersion(): number { const storedVersion = localStorage.getItem(VERSION_KEY); @@ -180,48 +181,161 @@ function idbRequest(request: IDBRequest): Promise { }); } -async function objectStore( +function runStoreTransaction( + db: IDBDatabase, store: string, - mode: IDBTransactionMode = "readonly", -): Promise { - const db = await openDB(); + mode: IDBTransactionMode, + run: (objectStore: IDBObjectStore) => void | Promise, +): Promise { + return new Promise((resolve, reject) => { + const tx = db.transaction(store, mode); + const objectStoreRef = tx.objectStore(store); - if (!db.objectStoreNames.contains(store)) { - await upgradeDB(store); - const upgradedDb = await openDB(); - return upgradedDb.transaction(store, mode).objectStore(store); + Promise.resolve(run(objectStoreRef)).catch(reject); + + tx.oncomplete = () => resolve(); + tx.onerror = () => reject(tx.error ?? new Error(`IndexedDB transaction failed for ${store}`)); + tx.onabort = () => reject(tx.error ?? new Error(`IndexedDB transaction aborted for ${store}`)); + }); +} + +async function withUpgradeLock(fn: () => Promise): Promise { + const previous = upgradeChain; + let release!: () => void; + upgradeChain = new Promise((resolve) => { + release = resolve; + }); + await previous; + try { + return await fn(); + } finally { + release(); } +} - return db.transaction(store, mode).objectStore(store); +async function openDatabaseWithStores( + version: number, + storesToCreate: string[], +): Promise { + return new Promise((resolve, reject) => { + let request: IDBOpenDBRequest; + try { + request = indexedDB.open(DB_NAME, version); + } catch (error) { + reject(error); + return; + } + + request.onupgradeneeded = () => { + const db = request.result; + if (!db.objectStoreNames.contains(META_STORE)) { + db.createObjectStore(META_STORE); + } + for (const store of storesToCreate) { + if (!db.objectStoreNames.contains(store)) { + db.createObjectStore(store); + } + } + }; + + request.onsuccess = () => { + attachConnection(request.result); + resolve(request.result); + }; + request.onerror = () => reject(request.error); + }); } async function upgradeDB(newStore: string): Promise { - invalidateConnection(); + await withUpgradeLock(async () => { + invalidateConnection(); - let baseVersion = 0; + let baseVersion = 0; - try { - const db = await openDatabase(); - baseVersion = db.version; + try { + const db = await openDatabase(); + if (db.objectStoreNames.contains(newStore)) { + attachConnection(db); + return; + } + baseVersion = db.version; + db.close(); + cachedDb = null; + dbPromise = null; + } catch (error) { + console.warn("[DB] Could not probe database version before upgrade:", error); + } + + try { + await openDatabaseWithStores(baseVersion + 1, [newStore]); + } catch (error) { + console.error("Error upgrading database:", error); + throw error; + } + }); +} + +/** + * Creates any missing object stores in a single version bump so later job + * writes do not race passive observer traffic on a mid-run upgrade. + */ +export async function ensureStoresExist(stores: string[]): Promise { + const uniqueStores = [...new Set(stores.filter(Boolean))]; + if (uniqueStores.length === 0) return; + + await withUpgradeLock(async () => { + let db: IDBDatabase; + try { + db = await openDB(); + } catch (error) { + console.warn("[DB] ensureStoresExist: could not open database:", error); + return; + } + + const missing = uniqueStores.filter( + (store) => !db.objectStoreNames.contains(store), + ); + if (missing.length === 0) return; + + invalidateConnection(); + const baseVersion = db.version; db.close(); cachedDb = null; dbPromise = null; - } catch (error) { - console.warn("[DB] Could not probe database version before upgrade:", error); + + try { + await openDatabaseWithStores(baseVersion + 1, missing); + } catch (error) { + console.error("[DB] ensureStoresExist failed:", error); + throw error; + } + }); +} + +async function withObjectStore( + store: string, + mode: IDBTransactionMode, + run: (objectStore: IDBObjectStore) => Promise, +): Promise { + let db = await openDB(); + + if (!db.objectStoreNames.contains(store)) { + await upgradeDB(store); + db = await openDB(); } - try { - await openDatabase(baseVersion + 1, newStore); - } catch (error) { - console.error("Error upgrading database:", error); - throw error; - } + let result!: T; + await runStoreTransaction(db, store, mode, async (objectStoreRef) => { + result = await run(objectStoreRef); + }); + return result; } export async function getAll(store: string): Promise { try { - const s = await objectStore(store); - return await idbRequest(s.getAll()); + return await withObjectStore(store, "readonly", async (s) => + idbRequest(s.getAll()), + ); } catch (error) { console.error(`Error in getAll for store ${store}:`, error); return []; @@ -230,8 +344,9 @@ export async function getAll(store: string): Promise { export async function get(store: string, key: string): Promise { try { - const s = await objectStore(store); - return await idbRequest(s.get(key)); + return await withObjectStore(store, "readonly", async (s) => + idbRequest(s.get(key)), + ); } catch (error) { console.error(`Error in get for store ${store}, key ${key}:`, error); return null; @@ -244,8 +359,9 @@ export async function put( key?: string, ): Promise { try { - const s = await objectStore(store, "readwrite"); - await idbRequest(key ? s.put(value, key) : s.put(value)); + await withObjectStore(store, "readwrite", async (s) => { + await idbRequest(key ? s.put(value, key) : s.put(value)); + }); } catch (error) { console.error(`Error in put for store ${store}:`, error); throw error; @@ -297,8 +413,9 @@ function runStoreDiffTransaction( export async function remove(store: string, key: string): Promise { try { - const s = await objectStore(store, "readwrite"); - await idbRequest(s.delete(key)); + await withObjectStore(store, "readwrite", async (s) => { + await idbRequest(s.delete(key)); + }); } catch (error) { console.error(`Error in remove for store ${store}, key ${key}:`, error); throw error; @@ -307,8 +424,9 @@ export async function remove(store: string, key: string): Promise { export async function clear(store: string): Promise { try { - const s = await objectStore(store, "readwrite"); - await idbRequest(s.clear()); + await withObjectStore(store, "readwrite", async (s) => { + await idbRequest(s.clear()); + }); } catch (error) { console.error(`Error in clear for store ${store}:`, error); throw error; diff --git a/src/plugins/built-in/globalSearch/src/indexing/indexer.ts b/src/plugins/built-in/globalSearch/src/indexing/indexer.ts index 88e4ca2f..287e8783 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/indexer.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/indexer.ts @@ -1,4 +1,4 @@ -import { applyStoreDiff, get, getAll, put, remove } from "./db"; +import { applyStoreDiff, ensureStoresExist, get, getAll, put, remove } from "./db"; import { jobs } from "./jobs"; import { decorateIndexItems } from "./renderComponents"; import type { IndexItem, Job, JobContext } from "./types"; @@ -8,6 +8,7 @@ import { getVectorizedItemIds, pruneOrphanVectorEmbeddings } from "./utils"; import { INDEX_SCHEMA_VERSION, SCHEMA_VERSION_KEY } from "./schemaVersion"; import { resetSearchIndexes } from "./resetIndexes"; import { isIndexingPaused } from "./indexingPause"; +import { setIndexingActive } from "./indexingState"; import { verboseDebug } from '@/utils/verboseLog'; const META_STORE = "meta"; @@ -304,10 +305,13 @@ export async function runIndexing(): Promise { } startHeartbeat(); + setIndexingActive(true); verboseDebug("%c[Indexer] Starting indexing...", "color: green"); try { const jobIds = Object.keys(jobs); + await ensureStoresExist([META_STORE, ...jobIds]); + let completedJobs = 0; const totalSteps = jobIds.length + 1; dispatchProgress(completedJobs, totalSteps, true, "Starting jobs"); @@ -379,6 +383,15 @@ export async function runIndexing(): Promise { removeItem, getProgress: () => loadProgress(jobId), setProgress: (p) => saveProgress(jobId, p), + reportJobProgress: ({ processed, total, status }) => { + const stepProgress = total > 0 ? processed / total : 0; + dispatchProgress( + completedJobs + stepProgress, + totalSteps, + true, + status ?? `Running job: ${job.label}`, + ); + }, }; verboseDebug(`%c[Indexer] Running job "${jobId}"...`, "color: #4ea1ff"); @@ -500,6 +513,7 @@ export async function runIndexing(): Promise { }), ); } finally { + setIndexingActive(false); stopHeartbeat(); } } diff --git a/src/plugins/built-in/globalSearch/src/indexing/indexingState.test.ts b/src/plugins/built-in/globalSearch/src/indexing/indexingState.test.ts new file mode 100644 index 00000000..3ce9395f --- /dev/null +++ b/src/plugins/built-in/globalSearch/src/indexing/indexingState.test.ts @@ -0,0 +1,18 @@ +import { + isIndexingActive, + setIndexingActive, +} from "./indexingState"; + +describe("indexingState", () => { + afterEach(() => { + setIndexingActive(false); + }); + + it("tracks whether structured indexing is running", () => { + expect(isIndexingActive()).toBe(false); + setIndexingActive(true); + expect(isIndexingActive()).toBe(true); + setIndexingActive(false); + expect(isIndexingActive()).toBe(false); + }); +}); diff --git a/src/plugins/built-in/globalSearch/src/indexing/indexingState.ts b/src/plugins/built-in/globalSearch/src/indexing/indexingState.ts new file mode 100644 index 00000000..c06f18b3 --- /dev/null +++ b/src/plugins/built-in/globalSearch/src/indexing/indexingState.ts @@ -0,0 +1,10 @@ +/** True while `runIndexing()` holds the indexer lock in this tab. */ +let indexingActive = false; + +export function setIndexingActive(active: boolean): void { + indexingActive = active; +} + +export function isIndexingActive(): boolean { + return indexingActive; +} diff --git a/src/plugins/built-in/globalSearch/src/indexing/jobs/courses.ts b/src/plugins/built-in/globalSearch/src/indexing/jobs/courses.ts index 2e1122b8..3e2e3e39 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/jobs/courses.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/jobs/courses.ts @@ -104,7 +104,7 @@ export const coursesJob: Job = { return score; }, - run: async (_ctx) => { + run: async (ctx) => { const subjects = await fetchActiveSubjects(); if (subjects.length === 0) { verboseDebug("[Courses job] No active subjects discovered."); @@ -113,6 +113,8 @@ export const coursesJob: Job = { const items: IndexItem[] = []; const seenIds = new Set(); + const totalSubjects = subjects.length; + let processedSubjects = 0; // Sequential per-subject fetch keeps load on SEQTA bounded; the shared // API layer also limits concurrency per route as a defense in depth. @@ -121,6 +123,12 @@ export const coursesJob: Job = { if (seenIds.has(id)) continue; seenIds.add(id); + ctx.reportJobProgress?.({ + processed: processedSubjects, + total: totalSubjects, + status: `Running job: Courses (${processedSubjects + 1}/${totalSubjects})`, + }); + const payload = await seqtaFetchPayload( "/seqta/student/load/courses", { @@ -129,7 +137,10 @@ export const coursesJob: Job = { }, ); - if (!payload) continue; + if (!payload) { + processedSubjects++; + continue; + } const title = (typeof payload.t === "string" && payload.t.trim()) || @@ -168,8 +179,15 @@ export const coursesJob: Job = { renderComponentId: "course", }), ); + processedSubjects++; } + ctx.reportJobProgress?.({ + processed: totalSubjects, + total: totalSubjects, + status: "Running job: Courses (saving)", + }); + verboseDebug( `[Courses job] Indexed ${items.length} courses across ${subjects.length} subjects.`, ); diff --git a/src/plugins/built-in/globalSearch/src/indexing/passiveObserver.ts b/src/plugins/built-in/globalSearch/src/indexing/passiveObserver.ts index fbce588b..31b12fd9 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/passiveObserver.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/passiveObserver.ts @@ -11,6 +11,7 @@ import { isSensitiveSeqtaPath, normalizeSeqtaPath } from "./api"; import { mergeDynamicItems } from "../utils/dynamicItems"; import { decorateIndexItems } from "./renderComponents"; import { isIndexingPaused } from "./indexingPause"; +import { isIndexingActive } from "./indexingState"; import { isAssessmentListRoute } from "./routeFilters"; /** @@ -384,7 +385,7 @@ function synthesizeItems( /* ------------------------------------------------------------------ */ async function persistItems(items: IndexItem[]): Promise { - if (items.length === 0 || isIndexingPaused()) return; + if (items.length === 0 || isIndexingPaused() || isIndexingActive()) return; // Dedupe against existing entries. We replace on collision so the latest // observation wins (e.g. if a message changes title). @@ -405,10 +406,10 @@ async function persistItems(items: IndexItem[]): Promise { } function scheduleFlush() { - if (pendingFlush || isIndexingPaused()) return; + if (pendingFlush || isIndexingPaused() || isIndexingActive()) return; pendingFlush = setTimeout(() => { pendingFlush = null; - if (!pendingDirty || isIndexingPaused()) return; + if (!pendingDirty || isIndexingPaused() || isIndexingActive()) return; pendingDirty = false; void flushDynamicItems(); }, FLUSH_DEBOUNCE_MS); @@ -425,7 +426,7 @@ export function pausePassiveObserver(): void { } async function flushDynamicItems(): Promise { - if (isIndexingPaused()) return; + if (isIndexingPaused() || isIndexingActive()) return; if (pendingChangedItems.size === 0) return; const rawChanged = Array.from(pendingChangedItems.values()); diff --git a/src/plugins/built-in/globalSearch/src/indexing/types.ts b/src/plugins/built-in/globalSearch/src/indexing/types.ts index e642bb08..9cec8258 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/types.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/types.ts @@ -24,6 +24,12 @@ export interface JobContext { removeItem: (id: string, storeId?: string) => Promise; getProgress: () => Promise; setProgress: (progress: T) => Promise; + /** Optional live status/progress while a long-running job is in flight. */ + reportJobProgress?: (detail: { + processed: number; + total: number; + status?: string; + }) => void; } export interface Job {