@aglyn/tenant-feature-instance 1.15.2 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firestore-tab-handoff.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n disableNetwork,\n enableNetwork,\n type Firestore,\n} from 'firebase/firestore'\n\n/**\n * A NEWLY OPENED, VISIBLE TAB TAKES THE PRIMARY LEASE FROM A HIDDEN ONE\n * (AGL-3660).\n *\n * ## What the SDK does on its own\n *\n * With `persistentMultipleTabManager`, exactly one tab per origin — the\n * holder of the `owner` row in `firestore/<app>/<project>/main` — runs the\n * network. Every other tab sends its queries to that tab through\n * `localStorage` and reads the answers back out of IndexedDB. Read against\n * `@firebase/firestore` 4.17.2 (`IndexedDbPersistence`):\n *\n * - **A valid lease is never handed over.** `canActAsPrimary` returns `true`\n * for the holder whenever its own lease is under 5 s old\n * (`MAX_PRIMARY_ELIGIBLE_AGE_MS`) and its network is enabled, whatever its\n * visibility. The \"prefer the foreground tab\" rule only applies once the\n * lease has lapsed. A console tab the user left in the background therefore\n * keeps serving the tab they are looking at, for as long as its 4 s renewal\n * timer keeps firing.\n * - **A background holder is a slow server.** Its renewal timer is throttled\n * (production lease rows, 2026-10-08: renewed every ~4.9 s, against a 5 s\n * lapse), and every query the new tab issues waits on that tab's event loop.\n * The workspace read on a fresh `/aglyn-org/media` tab came back only once\n * the new tab had won the lease on a lapse, its own Listen channel opening\n * ~4.7 s in (PR #1313).\n * - **The new tab's first record says it is hidden.** `start()` runs its\n * first election (`updateClientMetadataAndTryBecomePrimary`) before\n * `attachVisibilityHandler()` has read `document.visibilityState`, so the\n * `clientMetadata` row it writes carries `inForeground: false` until the\n * next 4 s tick. When the holder's lease does lapse in that window, the\n * holder finds no better candidate and takes it straight back.\n *\n * ## What this does\n *\n * Once, at boot, in a tab that is visible and online:\n *\n * 1. Snapshot the client ids already registered, synchronously, in the same\n * task as `initializeFirestore` — before anything can start this tab's\n * client. They come from the SDK's `firestore_clients_<prefix>_<id>` keys\n * in `localStorage`, which a tab writes once its persistence has started.\n * 2. Start this tab's Firestore (`enableNetwork` — a no-op on a client whose\n * network is on — resolves once persistence has started and the tab has\n * run its first election). The one id that was not there before is this\n * tab.\n * 3. In ONE IndexedDB transaction over `owner`, `clientMetadata` and\n * `mutations`, decide with {@link decideLeaseClaim}. When the holder is\n * another tab that has recorded itself as hidden, its lease has LAPSED\n * and no write is pending, write this tab's row as foreground and the\n * lease in this tab's name.\n * 4. Cycle this tab's network (`disableNetwork` then `enableNetwork`): each\n * step runs the SDK's own election at once, and the second finds a valid\n * lease that is this tab's and becomes primary.\n *\n * ## Why this is safe\n *\n * - **Never from a live holder (AGL-3788).** A lease renewed under 5 s ago\n * belongs to a tab whose remote store is running: its Watch stream keeps\n * applying events and resuming targets until its next 4 s tick notices the\n * lease is gone. Taking that lease makes two tabs primary over one cache,\n * and their target bookkeeping diverges — a resumed document target that\n * comes back `current` without its key in this cache's mapping is written\n * as a NoDocument, so a live host or org reads as deleted, and the\n * tombstone outlives reloads because a resumed listen only pulls deltas.\n * That is what the Sites page's \"No sites yet\" and an Enterprise org\n * showing Free were, in a browser with several console tabs. The SDK never\n * takes a valid lease (`canActAsPrimary`), and neither does this.\n * - **It is the SDK's own handoff.** A lapsed lease is one the SDK's next\n * election would hand to a foreground tab anyway; this only stops the\n * hidden holder winning it back on a stale `inForeground: false` row. A\n * holder that then finds the lease in another tab's name fails its next\n * `readwrite-primary` transaction (`verifyPrimaryLease`), flips to\n * secondary and throws the `failed-precondition` its sync engine already\n * swallows (`ignoreIfPrimaryLeaseLoss`). IndexedDB serialises our\n * transaction against the SDK's (which span every store), so no election\n * interleaves with it.\n * - **The old holder cannot take it back.** The lease is valid and not its\n * own, so its `canActAsPrimary` is `false`. Should this tab fail to renew,\n * the lease lapses in 5 s and the corrected `inForeground: true` row makes\n * this tab the preferred candidate, not the hidden one.\n * - **Never with a write in flight.** The holder sends pending mutations; a\n * new primary resends every unacknowledged batch. Any row in `mutations`\n * skips the claim, so a write is never sent twice by two tabs.\n * - **Never from a visible holder.** A tab visible in another window serves\n * quickly (measured in production: ~390 ms from a query target written to\n * it being `current`), and taking its lease would only move the work.\n * - **The cycle is invisible in a secondary.** The sync engine ignores its\n * own remote store's online state while secondary\n * (`syncEngineApplyOnlineStateChange`), so no listener sees an offline\n * flicker. If this tab somehow became primary in between, the cycle is the\n * same one `firestore-stall-recovery.ts` runs.\n * - **Every failure is the old behaviour.** Anything unexpected — no\n * database, the store locked (the AGL-3428 wedge), two new tabs at once, a\n * holder that is visible or whose lease is still live — skips the claim,\n * and the SDK's own election runs as it always has.\n *\n * Not chosen: `persistentSingleTabManager` (rejected in AGL-3373/3428, and\n * `forceOwnership` there fails every other tab with\n * `PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG`); `getDocFromServer` (a secondary routes\n * it through the holder like any listen); a per-tab memory cache for the first\n * read (the cache is fixed at `initializeFirestore`); a synthetic\n * `visibilitychange` to rerun the election (also fires the console's own\n * twenty-odd visibility listeners).\n */\n\n/** The SDK's lease lifetime (`MAX_PRIMARY_ELIGIBLE_AGE_MS`). */\nexport const PRIMARY_LEASE_MAX_AGE_MS = 5_000\n\n/**\n * How long the claim transaction may wait to start. The SDK's own take\n * milliseconds; one that cannot start is behind the AGL-3428 wedge, which\n * `firestore-multitab-wedge.ts` handles.\n */\nexport const CLAIM_TIMEOUT_MS = 1_500\n\n/** The SDK's stores and the lease row's key (`indexeddb_sentinels.ts`). */\nconst OWNER_STORE = 'owner'\nconst OWNER_KEY = 'owner'\nconst CLIENT_METADATA_STORE = 'clientMetadata'\nconst MUTATIONS_STORE = 'mutations'\n\n/** `DbPrimaryClient`. */\nexport interface LeaseRow {\n ownerId: string\n allowTabSynchronization: boolean\n leaseTimestampMs: number\n}\n\n/** `DbClientMetadata`. */\nexport interface ClientRow {\n clientId: string\n updateTimeMs: number\n networkEnabled: boolean\n inForeground: boolean\n}\n\n/** Why the claim was not made. */\nexport type LeaseClaimSkip =\n | 'unidentified'\n | 'vacant'\n | 'already-primary'\n | 'exclusive-holder'\n | 'holder-unknown'\n | 'holder-visible'\n | 'holder-live'\n | 'pending-writes'\n\nexport type LeaseClaimDecision =\n { claim: true } | { claim: false; reason: LeaseClaimSkip }\n\n/**\n * Whether this tab (`self`) should take the lease `owner` holds. Pure: the\n * caller reads every input inside the one transaction that writes the result.\n *\n * A vacant or lapsed-and-vacant lease is left to the SDK, whose next election\n * takes it; only a lease another tab holds is ever claimed, only from a\n * holder whose own row says it is in the background, and only once that\n * lease has lapsed — a live one would leave two tabs running as primary.\n */\nexport function decideLeaseClaim(input: {\n owner: LeaseRow | undefined\n holder: ClientRow | undefined\n self: ClientRow | undefined\n pendingWrites: number\n /** The clock the lease is measured against, in ms. */\n now: number\n}): LeaseClaimDecision {\n const { owner, holder, self, pendingWrites, now } = input\n if (!self) return { claim: false, reason: 'unidentified' }\n if (!owner) return { claim: false, reason: 'vacant' }\n if (owner.ownerId === self.clientId)\n return { claim: false, reason: 'already-primary' }\n // A single-tab holder never shares; `persistentMultipleTabManager` never\n // writes `false`, so this is another configuration on the origin.\n if (!owner.allowTabSynchronization)\n return { claim: false, reason: 'exclusive-holder' }\n if (pendingWrites > 0) return { claim: false, reason: 'pending-writes' }\n if (!holder) return { claim: false, reason: 'holder-unknown' }\n if (holder.inForeground) return { claim: false, reason: 'holder-visible' }\n // `MAX_PRIMARY_ELIGIBLE_AGE_MS`: the SDK's lease is valid while younger\n // than this, and a timestamp ahead of our clock is younger still.\n if (now - owner.leaseTimestampMs < PRIMARY_LEASE_MAX_AGE_MS)\n return { claim: false, reason: 'holder-live' }\n return { claim: true }\n}\n\n/** What the boot handoff did. */\nexport type TabHandoffOutcome =\n | { result: 'claimed'; fromOwnerId: string; leaseAgeMs: number }\n | {\n result: 'skipped'\n reason:\n | LeaseClaimSkip\n | 'hidden'\n | 'offline'\n | 'alone'\n | 'no-database'\n | 'locked'\n | 'error'\n }\n\n/** What one claim transaction found and did. */\nexport type ClaimTransactionResult =\n | { state: 'claimed'; fromOwnerId: string; leaseAgeMs: number }\n | { state: 'skipped'; reason: LeaseClaimSkip }\n | { state: 'locked' }\n | { state: 'unavailable' }\n\nexport interface TabHandoffDeps {\n isVisible: () => boolean\n isOnline: () => boolean\n /**\n * Client ids registered on this origin. Must be synchronous: the first call\n * is the snapshot taken before this tab's client can start.\n */\n readClientIds: () => ReadonlySet<string>\n /** Starts this tab's Firestore; resolves once its persistence has started. */\n startClient: () => Promise<void>\n /** Runs the claim for `selfId` in one transaction. */\n claim: (selfId: string | undefined) => Promise<ClaimTransactionResult>\n /** `disableNetwork` then `enableNetwork`: two elections, at once. */\n cycleNetwork: () => Promise<void>\n}\n\n/**\n * The boot handoff, with its browser parts injected. Never rejects.\n */\nexport async function runTabHandoff(\n deps: TabHandoffDeps,\n): Promise<TabHandoffOutcome> {\n try {\n if (!deps.isVisible()) return { result: 'skipped', reason: 'hidden' }\n if (!deps.isOnline()) return { result: 'skipped', reason: 'offline' }\n // Before this tab's Firestore starts, or this tab would be in it.\n const before = deps.readClientIds()\n // No other tab: this one wins the lease at its first election.\n if (before.size === 0) return { result: 'skipped', reason: 'alone' }\n await deps.startClient()\n // The user may have switched away while the client started.\n if (!deps.isVisible()) return { result: 'skipped', reason: 'hidden' }\n const added = [...deps.readClientIds()].filter((id) => !before.has(id))\n // Exactly one new client is this tab. None means this tab's Firestore\n // started before the snapshot; two means another tab started alongside.\n // Either way this tab cannot be told apart, so nothing is claimed.\n if (added.length !== 1) return { result: 'skipped', reason: 'unidentified' }\n const selfId = added[0]\n const outcome = await deps.claim(selfId)\n if (outcome.state === 'locked')\n return { result: 'skipped', reason: 'locked' }\n if (outcome.state === 'unavailable')\n return { result: 'skipped', reason: 'no-database' }\n if (outcome.state === 'skipped')\n return { result: 'skipped', reason: outcome.reason }\n await deps.cycleNetwork()\n return {\n result: 'claimed',\n fromOwnerId: outcome.fromOwnerId,\n leaseAgeMs: outcome.leaseAgeMs,\n }\n } catch {\n return { result: 'skipped', reason: 'error' }\n }\n}\n\n/**\n * Opens `databaseName` only if it already exists, at its current version —\n * never creating it under the SDK (the rule `probePrimaryLease` follows) —\n * and closes on `versionchange` so an SDK upgrade is never held up.\n */\nasync function openExisting(\n factory: IDBFactory,\n databaseName: string,\n): Promise<IDBDatabase | undefined> {\n if (typeof factory.databases !== 'function') return undefined\n const databases = await factory.databases()\n if (!databases.some((database) => database.name === databaseName))\n return undefined\n return new Promise((resolve) => {\n let request: IDBOpenDBRequest\n try {\n request = factory.open(databaseName)\n } catch {\n resolve(undefined)\n return\n }\n request.onupgradeneeded = () => request.transaction?.abort()\n request.onerror = () => resolve(undefined)\n request.onblocked = () => resolve(undefined)\n request.onsuccess = () => {\n const database = request.result\n database.onversionchange = () => database.close()\n resolve(database)\n }\n })\n}\n\nconst hasStores = (database: IDBDatabase, stores: string[]) =>\n stores.every((store) => database.objectStoreNames.contains(store))\n\nconst escapeRegExp = (text: string) =>\n text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\n/**\n * The client ids the SDK has registered under `prefix`\n * (`firestore/<app>/<project>/`), from its `firestore_clients_<prefix>_<id>`\n * keys. Synchronous, so a snapshot can be taken before this tab's client\n * starts. A key whose tab has since closed is harmless here: only ids that\n * APPEAR between two snapshots are read as this tab.\n */\nexport function readSharedClientIds(\n storage: Pick<Storage, 'length' | 'key'> | undefined,\n prefix: string,\n): ReadonlySet<string> {\n const ids = new Set<string>()\n if (!storage) return ids\n // The SDK's own key shape: a client id never contains `_`.\n const clientKey = new RegExp(\n `^firestore_clients_${escapeRegExp(prefix)}_([^_]+)$`,\n )\n try {\n for (let i = 0; i < storage.length; i++) {\n const match = clientKey.exec(storage.key(i) ?? '')\n if (match) ids.add(match[1])\n }\n } catch {\n // Site data blocked: no ids, so the handoff stands down.\n }\n return ids\n}\n\n/**\n * Reads the lease, both client rows and the pending-write count, decides, and\n * writes the claim — all in one `readwrite` transaction, so no election runs\n * between the read and the write. Aborted when it cannot start within\n * `timeoutMs`.\n */\nexport async function claimPrimaryLease(\n factory: IDBFactory | undefined,\n databaseName: string,\n selfId: string | undefined,\n {\n timeoutMs = CLAIM_TIMEOUT_MS,\n now = Date.now,\n }: { timeoutMs?: number; now?: () => number } = {},\n): Promise<ClaimTransactionResult> {\n if (!factory) return { state: 'unavailable' }\n const database = await openExisting(factory, databaseName).catch(\n () => undefined,\n )\n if (!database) return { state: 'unavailable' }\n const stores = [OWNER_STORE, CLIENT_METADATA_STORE, MUTATIONS_STORE]\n if (!hasStores(database, stores)) {\n database.close()\n return { state: 'unavailable' }\n }\n return new Promise<ClaimTransactionResult>((resolve) => {\n let transaction: IDBTransaction\n try {\n transaction = database.transaction(stores, 'readwrite')\n } catch {\n database.close()\n resolve({ state: 'unavailable' })\n return\n }\n let settled = false\n let started = false\n let result: ClaimTransactionResult = { state: 'unavailable' }\n // Only a transaction that cannot START is aborted: once the lease read\n // has landed, the decision and its writes take milliseconds.\n const timer = setTimeout(() => {\n if (started) return\n try {\n transaction.abort()\n } catch {\n // Already finished.\n }\n finish({ state: 'locked' })\n }, timeoutMs)\n const finish = (value: ClaimTransactionResult) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n database.close()\n resolve(value)\n }\n transaction.oncomplete = () => finish(result)\n transaction.onabort = () =>\n finish(started ? { state: 'unavailable' } : { state: 'locked' })\n transaction.onerror = () => finish({ state: 'unavailable' })\n\n const owners = transaction.objectStore(OWNER_STORE)\n const clients = transaction.objectStore(CLIENT_METADATA_STORE)\n const ownerRequest = owners.get(OWNER_KEY)\n ownerRequest.onsuccess = () => {\n started = true\n const owner = ownerRequest.result as LeaseRow | undefined\n const selfRequest = selfId === undefined ? undefined : clients.get(selfId)\n const holderRequest = owner?.ownerId\n ? clients.get(owner.ownerId)\n : undefined\n const countRequest = transaction.objectStore(MUTATIONS_STORE).count()\n countRequest.onsuccess = () => {\n // Requests in one transaction complete in order: both gets landed.\n const self = selfRequest?.result as ClientRow | undefined\n const holder = holderRequest?.result as ClientRow | undefined\n const at = now()\n const decision = decideLeaseClaim({\n owner,\n holder,\n self,\n pendingWrites: countRequest.result,\n now: at,\n })\n if ('reason' in decision) {\n result = { state: 'skipped', reason: decision.reason }\n return\n }\n // The row the SDK's first election should have written, then the\n // lease in this tab's name — `acquireOrExtendPrimaryLease`'s shape.\n clients.put({ ...self, inForeground: true, updateTimeMs: at })\n owners.put(\n {\n ownerId: self!.clientId,\n allowTabSynchronization: true,\n leaseTimestampMs: at,\n } satisfies LeaseRow,\n OWNER_KEY,\n )\n result = {\n state: 'claimed',\n fromOwnerId: owner!.ownerId,\n leaseAgeMs: at - owner!.leaseTimestampMs,\n }\n }\n }\n })\n}\n\nconst browserIndexedDb = (): IDBFactory | undefined => {\n try {\n return typeof window === 'undefined' ? undefined : window.indexedDB\n } catch {\n return undefined\n }\n}\n\nconst browserLocalStorage = (): Storage | undefined => {\n try {\n return typeof window === 'undefined' ? undefined : window.localStorage\n } catch {\n return undefined\n }\n}\n\n/**\n * Runs the handoff for a Firestore that `initializeFirestore` has just\n * configured with the durable multi-tab cache under `prefix`\n * (`firestorePersistencePrefix`). Call it in the same task as\n * `initializeFirestore`, before any read: its first step is the synchronous\n * snapshot of the clients that are not this tab. Fire and forget: it never\n * rejects, and every failure leaves the SDK's own election in charge.\n */\nexport function startFirestoreTabHandoff(\n firestore: Firestore,\n prefix: string,\n): Promise<TabHandoffOutcome> {\n const factory = browserIndexedDb()\n const storage = browserLocalStorage()\n const databaseName = `${prefix}main`\n return runTabHandoff({\n isVisible: () =>\n typeof document !== 'undefined' && document.visibilityState === 'visible',\n isOnline: () =>\n typeof navigator === 'undefined' || navigator.onLine !== false,\n readClientIds: () => readSharedClientIds(storage, prefix),\n startClient: () => enableNetwork(firestore),\n claim: (selfId) => claimPrimaryLease(factory, databaseName, selfId),\n cycleNetwork: async () => {\n await disableNetwork(firestore)\n await enableNetwork(firestore)\n },\n }).then((outcome) => {\n if (outcome.result === 'claimed') {\n console.debug(\n '[firestore] This visible tab took the primary lease from a background tab (AGL-3660).',\n outcome,\n )\n }\n return outcome\n })\n}\n"],"names":["disableNetwork","enableNetwork","PRIMARY_LEASE_MAX_AGE_MS","CLAIM_TIMEOUT_MS","OWNER_STORE","OWNER_KEY","CLIENT_METADATA_STORE","MUTATIONS_STORE","decideLeaseClaim","input","owner","holder","self","pendingWrites","now","claim","reason","ownerId","clientId","allowTabSynchronization","inForeground","leaseTimestampMs","runTabHandoff","deps","isVisible","result","isOnline","before","readClientIds","size","startClient","added","filter","id","has","length","selfId","outcome","state","cycleNetwork","fromOwnerId","leaseAgeMs","openExisting","factory","databaseName","databases","undefined","some","database","name","Promise","resolve","request","open","onupgradeneeded","transaction","abort","onerror","onblocked","onsuccess","onversionchange","close","hasStores","stores","every","store","objectStoreNames","contains","escapeRegExp","text","replace","readSharedClientIds","storage","prefix","ids","Set","clientKey","RegExp","i","match","exec","key","add","claimPrimaryLease","timeoutMs","Date","catch","settled","started","timer","setTimeout","finish","value","clearTimeout","oncomplete","onabort","owners","objectStore","clients","ownerRequest","get","selfRequest","holderRequest","countRequest","count","at","decision","put","updateTimeMs","browserIndexedDb","window","indexedDB","browserLocalStorage","localStorage","startFirestoreTabHandoff","firestore","document","visibilityState","navigator","onLine","then","console","debug"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,cAAc,EACdC,aAAa,QAER,qBAAoB;AAE3B;;;;;;;;;;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AACF;AAEA,MAAMwF,mBAAmB;IACvB,IAAI;QACF,OAAO,OAAOC,WAAW,cAAchE,YAAYgE,OAAOC,SAAS;IACrE,EAAE,eAAM;QACN,OAAOjE;IACT;AACF;AAEA,MAAMkE,sBAAsB;IAC1B,IAAI;QACF,OAAO,OAAOF,WAAW,cAAchE,YAAYgE,OAAOG,YAAY;IACxE,EAAE,eAAM;QACN,OAAOnE;IACT;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,SAASoE,yBACdC,SAAoB,EACpB1C,MAAc;IAEd,MAAM9B,UAAUkE;IAChB,MAAMrC,UAAUwC;IAChB,MAAMpE,eAAe,GAAG6B,OAAO,IAAI,CAAC;IACpC,OAAOnD,cAAc;QACnBE,WAAW,IACT,OAAO4F,aAAa,eAAeA,SAASC,eAAe,KAAK;QAClE3F,UAAU,IACR,OAAO4F,cAAc,eAAeA,UAAUC,MAAM,KAAK;QAC3D3F,eAAe,IAAM2C,oBAAoBC,SAASC;QAClD3C,aAAa,IAAM7B,cAAckH;QACjCpG,OAAO,CAACqB,SAAW+C,kBAAkBxC,SAASC,cAAcR;QAC5DG,cAAc;YACZ,MAAMvC,eAAemH;YACrB,MAAMlH,cAAckH;QACtB;IACF,GAAGK,IAAI,CAAC,CAACnF;QACP,IAAIA,QAAQZ,MAAM,KAAK,WAAW;YAChCgG,QAAQC,KAAK,CACX,yFACArF;QAEJ;QACA,OAAOA;IACT;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firestore-tab-handoff.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n disableNetwork,\n enableNetwork,\n type Firestore,\n} from 'firebase/firestore'\n\n/**\n * A NEWLY OPENED, VISIBLE TAB TAKES THE PRIMARY LEASE FROM A HIDDEN ONE\n * (AGL-3660).\n *\n * ## What the SDK does on its own\n *\n * With `persistentMultipleTabManager`, exactly one tab per origin — the\n * holder of the `owner` row in `firestore/<app>/<project>/main` — runs the\n * network. Every other tab sends its queries to that tab through\n * `localStorage` and reads the answers back out of IndexedDB. Read against\n * `@firebase/firestore` 4.17.2 (`IndexedDbPersistence`):\n *\n * - **A valid lease is never handed over.** `canActAsPrimary` returns `true`\n * for the holder whenever its own lease is under 5 s old\n * (`MAX_PRIMARY_ELIGIBLE_AGE_MS`) and its network is enabled, whatever its\n * visibility. The \"prefer the foreground tab\" rule only applies once the\n * lease has lapsed. A console tab the user left in the background therefore\n * keeps serving the tab they are looking at, for as long as its 4 s renewal\n * timer keeps firing.\n * - **A background holder is a slow server.** Its renewal timer is throttled\n * (production lease rows, 2026-10-08: renewed every ~4.9 s, against a 5 s\n * lapse), and every query the new tab issues waits on that tab's event loop.\n * The workspace read on a fresh `/aglyn-org/media` tab came back only once\n * the new tab had won the lease on a lapse, its own Listen channel opening\n * ~4.7 s in (PR #1313).\n * - **The new tab's first record says it is hidden.** `start()` runs its\n * first election (`updateClientMetadataAndTryBecomePrimary`) before\n * `attachVisibilityHandler()` has read `document.visibilityState`, so the\n * `clientMetadata` row it writes carries `inForeground: false` until the\n * next 4 s tick. When the holder's lease does lapse in that window, the\n * holder finds no better candidate and takes it straight back.\n *\n * ## What this does\n *\n * Once, at boot, in a tab that is visible and online:\n *\n * 1. Snapshot the client ids already registered, synchronously, in the same\n * task as `initializeFirestore` — before anything can start this tab's\n * client. They come from the SDK's `firestore_clients_<prefix>_<id>` keys\n * in `localStorage`, which a tab writes once its persistence has started.\n * 2. Start this tab's Firestore (`enableNetwork` — a no-op on a client whose\n * network is on — resolves once persistence has started and the tab has\n * run its first election). The one id that was not there before is this\n * tab.\n * 3. In ONE IndexedDB transaction over `owner`, `clientMetadata` and\n * `mutations`, decide with {@link decideLeaseClaim}. When the holder is\n * another tab that has recorded itself as hidden, its lease has LAPSED\n * and no write is pending, write this tab's row as foreground and the\n * lease in this tab's name.\n * 4. Cycle this tab's network (`disableNetwork` then `enableNetwork`): each\n * step runs the SDK's own election at once, and the second finds a valid\n * lease that is this tab's and becomes primary.\n *\n * ## Why this is safe\n *\n * - **Never from a live holder (AGL-3788).** A lease renewed under 5 s ago\n * belongs to a tab whose remote store is running: its Watch stream keeps\n * applying events and resuming targets until its next 4 s tick notices the\n * lease is gone. Taking that lease makes two tabs primary over one cache,\n * and their target bookkeeping diverges — a resumed document target that\n * comes back `current` without its key in this cache's mapping is written\n * as a NoDocument, so a live host or org reads as deleted, and the\n * tombstone outlives reloads because a resumed listen only pulls deltas.\n * That is what the Sites page's \"No sites yet\" and an Enterprise org\n * showing Free were, in a browser with several console tabs. The SDK never\n * takes a valid lease (`canActAsPrimary`), and neither does this.\n * - **It is the SDK's own handoff.** A lapsed lease is one the SDK's next\n * election would hand to a foreground tab anyway; this only stops the\n * hidden holder winning it back on a stale `inForeground: false` row. A\n * holder that then finds the lease in another tab's name fails its next\n * `readwrite-primary` transaction (`verifyPrimaryLease`), flips to\n * secondary and throws the `failed-precondition` its sync engine already\n * swallows (`ignoreIfPrimaryLeaseLoss`). IndexedDB serialises our\n * transaction against the SDK's (which span every store), so no election\n * interleaves with it.\n * - **The old holder cannot take it back.** The lease is valid and not its\n * own, so its `canActAsPrimary` is `false`. Should this tab fail to renew,\n * the lease lapses in 5 s and the corrected `inForeground: true` row makes\n * this tab the preferred candidate, not the hidden one.\n * - **Never with a write in flight.** The holder sends pending mutations; a\n * new primary resends every unacknowledged batch. Any row in `mutations`\n * skips the claim, so a write is never sent twice by two tabs.\n * - **Never from a visible holder.** A tab visible in another window serves\n * quickly (measured in production: ~390 ms from a query target written to\n * it being `current`), and taking its lease would only move the work.\n * - **The cycle is invisible in a secondary.** The sync engine ignores its\n * own remote store's online state while secondary\n * (`syncEngineApplyOnlineStateChange`), so no listener sees an offline\n * flicker. If this tab somehow became primary in between, the cycle is the\n * same one `firestore-stall-recovery.ts` runs.\n * - **Every failure is the old behaviour.** Anything unexpected — no\n * database, the store locked (the AGL-3428 wedge), two new tabs at once, a\n * holder that is visible or whose lease is still live — skips the claim,\n * and the SDK's own election runs as it always has.\n *\n * Not chosen: `persistentSingleTabManager` (rejected in AGL-3373/3428, and\n * `forceOwnership` there fails every other tab with\n * `PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG`); `getDocFromServer` (a secondary routes\n * it through the holder like any listen); a per-tab memory cache for the first\n * read (the cache is fixed at `initializeFirestore`); a synthetic\n * `visibilitychange` to rerun the election (also fires the console's own\n * twenty-odd visibility listeners).\n */\n\n/** The SDK's lease lifetime (`MAX_PRIMARY_ELIGIBLE_AGE_MS`). */\nexport const PRIMARY_LEASE_MAX_AGE_MS = 5_000\n\n/**\n * How long the claim transaction may wait to start. The SDK's own take\n * milliseconds; one that cannot start is behind the AGL-3428 wedge, which\n * `firestore-multitab-wedge.ts` handles.\n */\nexport const CLAIM_TIMEOUT_MS = 1_500\n\n/** The SDK's stores and the lease row's key (`indexeddb_sentinels.ts`). */\nconst OWNER_STORE = 'owner'\nconst OWNER_KEY = 'owner'\nconst CLIENT_METADATA_STORE = 'clientMetadata'\nconst MUTATIONS_STORE = 'mutations'\n\n/** `DbPrimaryClient`. */\nexport interface LeaseRow {\n ownerId: string\n allowTabSynchronization: boolean\n leaseTimestampMs: number\n}\n\n/** `DbClientMetadata`. */\nexport interface ClientRow {\n clientId: string\n updateTimeMs: number\n networkEnabled: boolean\n inForeground: boolean\n}\n\n/** Why the claim was not made. */\nexport type LeaseClaimSkip =\n | 'unidentified'\n | 'vacant'\n | 'already-primary'\n | 'exclusive-holder'\n | 'holder-unknown'\n | 'holder-visible'\n | 'holder-live'\n | 'pending-writes'\n\nexport type LeaseClaimDecision =\n { claim: true } | { claim: false; reason: LeaseClaimSkip }\n\n/**\n * Whether this tab (`self`) should take the lease `owner` holds. Pure: the\n * caller reads every input inside the one transaction that writes the result.\n *\n * A vacant or lapsed-and-vacant lease is left to the SDK, whose next election\n * takes it; only a lease another tab holds is ever claimed, only from a\n * holder whose own row says it is in the background, and only once that\n * lease has lapsed — a live one would leave two tabs running as primary.\n */\nexport function decideLeaseClaim(input: {\n owner: LeaseRow | undefined\n holder: ClientRow | undefined\n self: ClientRow | undefined\n pendingWrites: number\n /** The clock the lease is measured against, in ms. */\n now: number\n}): LeaseClaimDecision {\n const { owner, holder, self, pendingWrites, now } = input\n if (!self) return { claim: false, reason: 'unidentified' }\n if (!owner) return { claim: false, reason: 'vacant' }\n if (owner.ownerId === self.clientId)\n return { claim: false, reason: 'already-primary' }\n // A single-tab holder never shares; `persistentMultipleTabManager` never\n // writes `false`, so this is another configuration on the origin.\n if (!owner.allowTabSynchronization)\n return { claim: false, reason: 'exclusive-holder' }\n if (pendingWrites > 0) return { claim: false, reason: 'pending-writes' }\n if (!holder) return { claim: false, reason: 'holder-unknown' }\n if (holder.inForeground) return { claim: false, reason: 'holder-visible' }\n // `MAX_PRIMARY_ELIGIBLE_AGE_MS`: the SDK's lease is valid while younger\n // than this, and a timestamp ahead of our clock is younger still.\n if (now - owner.leaseTimestampMs < PRIMARY_LEASE_MAX_AGE_MS)\n return { claim: false, reason: 'holder-live' }\n return { claim: true }\n}\n\n/** What the boot handoff did. */\nexport type TabHandoffOutcome =\n | { result: 'claimed'; fromOwnerId: string; leaseAgeMs: number }\n | {\n result: 'skipped'\n reason:\n | LeaseClaimSkip\n | 'hidden'\n | 'offline'\n | 'alone'\n | 'no-database'\n | 'locked'\n | 'error'\n }\n\n/** What one claim transaction found and did. */\nexport type ClaimTransactionResult =\n | { state: 'claimed'; fromOwnerId: string; leaseAgeMs: number }\n | { state: 'skipped'; reason: LeaseClaimSkip }\n | { state: 'locked' }\n | { state: 'unavailable' }\n\nexport interface TabHandoffDeps {\n isVisible: () => boolean\n isOnline: () => boolean\n /**\n * Client ids registered on this origin. Must be synchronous: the first call\n * is the snapshot taken before this tab's client can start.\n */\n readClientIds: () => ReadonlySet<string>\n /** Starts this tab's Firestore; resolves once its persistence has started. */\n startClient: () => Promise<void>\n /** Runs the claim for `selfId` in one transaction. */\n claim: (selfId: string | undefined) => Promise<ClaimTransactionResult>\n /** `disableNetwork` then `enableNetwork`: two elections, at once. */\n cycleNetwork: () => Promise<void>\n}\n\n/**\n * The boot handoff, with its browser parts injected. Never rejects.\n */\nexport async function runTabHandoff(\n deps: TabHandoffDeps,\n): Promise<TabHandoffOutcome> {\n try {\n if (!deps.isVisible()) return { result: 'skipped', reason: 'hidden' }\n if (!deps.isOnline()) return { result: 'skipped', reason: 'offline' }\n // Before this tab's Firestore starts, or this tab would be in it.\n const before = deps.readClientIds()\n // No other tab: this one wins the lease at its first election.\n if (before.size === 0) return { result: 'skipped', reason: 'alone' }\n await deps.startClient()\n // The user may have switched away while the client started.\n if (!deps.isVisible()) return { result: 'skipped', reason: 'hidden' }\n const added = [...deps.readClientIds()].filter((id) => !before.has(id))\n // Exactly one new client is this tab. None means this tab's Firestore\n // started before the snapshot; two means another tab started alongside.\n // Either way this tab cannot be told apart, so nothing is claimed.\n if (added.length !== 1) return { result: 'skipped', reason: 'unidentified' }\n const selfId = added[0]\n const outcome = await deps.claim(selfId)\n if (outcome.state === 'locked')\n return { result: 'skipped', reason: 'locked' }\n if (outcome.state === 'unavailable')\n return { result: 'skipped', reason: 'no-database' }\n if (outcome.state === 'skipped')\n return { result: 'skipped', reason: outcome.reason }\n await deps.cycleNetwork()\n return {\n result: 'claimed',\n fromOwnerId: outcome.fromOwnerId,\n leaseAgeMs: outcome.leaseAgeMs,\n }\n } catch {\n return { result: 'skipped', reason: 'error' }\n }\n}\n\n/**\n * Opens `databaseName` only if it already exists, at its current version —\n * never creating it under the SDK (the rule `probePrimaryLease` follows) —\n * and closes on `versionchange` so an SDK upgrade is never held up.\n */\nexport async function openExisting(\n factory: IDBFactory,\n databaseName: string,\n): Promise<IDBDatabase | undefined> {\n if (typeof factory.databases !== 'function') return undefined\n const databases = await factory.databases()\n if (!databases.some((database) => database.name === databaseName))\n return undefined\n return new Promise((resolve) => {\n let request: IDBOpenDBRequest\n try {\n request = factory.open(databaseName)\n } catch {\n resolve(undefined)\n return\n }\n request.onupgradeneeded = () => request.transaction?.abort()\n request.onerror = () => resolve(undefined)\n request.onblocked = () => resolve(undefined)\n request.onsuccess = () => {\n const database = request.result\n database.onversionchange = () => database.close()\n resolve(database)\n }\n })\n}\n\nconst hasStores = (database: IDBDatabase, stores: string[]) =>\n stores.every((store) => database.objectStoreNames.contains(store))\n\nconst escapeRegExp = (text: string) =>\n text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\n/**\n * The client ids the SDK has registered under `prefix`\n * (`firestore/<app>/<project>/`), from its `firestore_clients_<prefix>_<id>`\n * keys. Synchronous, so a snapshot can be taken before this tab's client\n * starts. A key whose tab has since closed is harmless here: only ids that\n * APPEAR between two snapshots are read as this tab.\n */\nexport function readSharedClientIds(\n storage: Pick<Storage, 'length' | 'key'> | undefined,\n prefix: string,\n): ReadonlySet<string> {\n const ids = new Set<string>()\n if (!storage) return ids\n // The SDK's own key shape: a client id never contains `_`.\n const clientKey = new RegExp(\n `^firestore_clients_${escapeRegExp(prefix)}_([^_]+)$`,\n )\n try {\n for (let i = 0; i < storage.length; i++) {\n const match = clientKey.exec(storage.key(i) ?? '')\n if (match) ids.add(match[1])\n }\n } catch {\n // Site data blocked: no ids, so the handoff stands down.\n }\n return ids\n}\n\n/**\n * Reads the lease, both client rows and the pending-write count, decides, and\n * writes the claim — all in one `readwrite` transaction, so no election runs\n * between the read and the write. Aborted when it cannot start within\n * `timeoutMs`.\n */\nexport async function claimPrimaryLease(\n factory: IDBFactory | undefined,\n databaseName: string,\n selfId: string | undefined,\n {\n timeoutMs = CLAIM_TIMEOUT_MS,\n now = Date.now,\n }: { timeoutMs?: number; now?: () => number } = {},\n): Promise<ClaimTransactionResult> {\n if (!factory) return { state: 'unavailable' }\n const database = await openExisting(factory, databaseName).catch(\n () => undefined,\n )\n if (!database) return { state: 'unavailable' }\n const stores = [OWNER_STORE, CLIENT_METADATA_STORE, MUTATIONS_STORE]\n if (!hasStores(database, stores)) {\n database.close()\n return { state: 'unavailable' }\n }\n return new Promise<ClaimTransactionResult>((resolve) => {\n let transaction: IDBTransaction\n try {\n transaction = database.transaction(stores, 'readwrite')\n } catch {\n database.close()\n resolve({ state: 'unavailable' })\n return\n }\n let settled = false\n let started = false\n let result: ClaimTransactionResult = { state: 'unavailable' }\n // Only a transaction that cannot START is aborted: once the lease read\n // has landed, the decision and its writes take milliseconds.\n const timer = setTimeout(() => {\n if (started) return\n try {\n transaction.abort()\n } catch {\n // Already finished.\n }\n finish({ state: 'locked' })\n }, timeoutMs)\n const finish = (value: ClaimTransactionResult) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n database.close()\n resolve(value)\n }\n transaction.oncomplete = () => finish(result)\n transaction.onabort = () =>\n finish(started ? { state: 'unavailable' } : { state: 'locked' })\n transaction.onerror = () => finish({ state: 'unavailable' })\n\n const owners = transaction.objectStore(OWNER_STORE)\n const clients = transaction.objectStore(CLIENT_METADATA_STORE)\n const ownerRequest = owners.get(OWNER_KEY)\n ownerRequest.onsuccess = () => {\n started = true\n const owner = ownerRequest.result as LeaseRow | undefined\n const selfRequest = selfId === undefined ? undefined : clients.get(selfId)\n const holderRequest = owner?.ownerId\n ? clients.get(owner.ownerId)\n : undefined\n const countRequest = transaction.objectStore(MUTATIONS_STORE).count()\n countRequest.onsuccess = () => {\n // Requests in one transaction complete in order: both gets landed.\n const self = selfRequest?.result as ClientRow | undefined\n const holder = holderRequest?.result as ClientRow | undefined\n const at = now()\n const decision = decideLeaseClaim({\n owner,\n holder,\n self,\n pendingWrites: countRequest.result,\n now: at,\n })\n if ('reason' in decision) {\n result = { state: 'skipped', reason: decision.reason }\n return\n }\n // The row the SDK's first election should have written, then the\n // lease in this tab's name — `acquireOrExtendPrimaryLease`'s shape.\n clients.put({ ...self, inForeground: true, updateTimeMs: at })\n owners.put(\n {\n ownerId: self!.clientId,\n allowTabSynchronization: true,\n leaseTimestampMs: at,\n } satisfies LeaseRow,\n OWNER_KEY,\n )\n result = {\n state: 'claimed',\n fromOwnerId: owner!.ownerId,\n leaseAgeMs: at - owner!.leaseTimestampMs,\n }\n }\n }\n })\n}\n\nconst browserIndexedDb = (): IDBFactory | undefined => {\n try {\n return typeof window === 'undefined' ? undefined : window.indexedDB\n } catch {\n return undefined\n }\n}\n\nconst browserLocalStorage = (): Storage | undefined => {\n try {\n return typeof window === 'undefined' ? undefined : window.localStorage\n } catch {\n return undefined\n }\n}\n\n/**\n * Runs the handoff for a Firestore that `initializeFirestore` has just\n * configured with the durable multi-tab cache under `prefix`\n * (`firestorePersistencePrefix`). Call it in the same task as\n * `initializeFirestore`, before any read: its first step is the synchronous\n * snapshot of the clients that are not this tab. Fire and forget: it never\n * rejects, and every failure leaves the SDK's own election in charge.\n */\nexport function startFirestoreTabHandoff(\n firestore: Firestore,\n prefix: string,\n): Promise<TabHandoffOutcome> {\n const factory = browserIndexedDb()\n const storage = browserLocalStorage()\n const databaseName = `${prefix}main`\n return runTabHandoff({\n isVisible: () =>\n typeof document !== 'undefined' && document.visibilityState === 'visible',\n isOnline: () =>\n typeof navigator === 'undefined' || navigator.onLine !== false,\n readClientIds: () => readSharedClientIds(storage, prefix),\n startClient: () => enableNetwork(firestore),\n claim: (selfId) => claimPrimaryLease(factory, databaseName, selfId),\n cycleNetwork: async () => {\n await disableNetwork(firestore)\n await enableNetwork(firestore)\n },\n }).then((outcome) => {\n if (outcome.result === 'claimed') {\n console.debug(\n '[firestore] This visible tab took the primary lease from a background tab (AGL-3660).',\n outcome,\n )\n }\n return outcome\n })\n}\n"],"names":["disableNetwork","enableNetwork","PRIMARY_LEASE_MAX_AGE_MS","CLAIM_TIMEOUT_MS","OWNER_STORE","OWNER_KEY","CLIENT_METADATA_STORE","MUTATIONS_STORE","decideLeaseClaim","input","owner","holder","self","pendingWrites","now","claim","reason","ownerId","clientId","allowTabSynchronization","inForeground","leaseTimestampMs","runTabHandoff","deps","isVisible","result","isOnline","before","readClientIds","size","startClient","added","filter","id","has","length","selfId","outcome","state","cycleNetwork","fromOwnerId","leaseAgeMs","openExisting","factory","databaseName","databases","undefined","some","database","name","Promise","resolve","request","open","onupgradeneeded","transaction","abort","onerror","onblocked","onsuccess","onversionchange","close","hasStores","stores","every","store","objectStoreNames","contains","escapeRegExp","text","replace","readSharedClientIds","storage","prefix","ids","Set","clientKey","RegExp","i","match","exec","key","add","claimPrimaryLease","timeoutMs","Date","catch","settled","started","timer","setTimeout","finish","value","clearTimeout","oncomplete","onabort","owners","objectStore","clients","ownerRequest","get","selfRequest","holderRequest","countRequest","count","at","decision","put","updateTimeMs","browserIndexedDb","window","indexedDB","browserLocalStorage","localStorage","startFirestoreTabHandoff","firestore","document","visibilityState","navigator","onLine","then","console","debug"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,cAAc,EACdC,aAAa,QAER,qBAAoB;AAE3B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsGC,GAED,8DAA8D,GAC9D,OAAO,MAAMC,2BAA2B,KAAK;AAE7C;;;;CAIC,GACD,OAAO,MAAMC,mBAAmB,KAAK;AAErC,yEAAyE,GACzE,MAAMC,cAAc;AACpB,MAAMC,YAAY;AAClB,MAAMC,wBAAwB;AAC9B,MAAMC,kBAAkB;AA+BxB;;;;;;;;CAQC,GACD,OAAO,SAASC,iBAAiBC,KAOhC;IACC,MAAM,EAAEC,KAAK,EAAEC,MAAM,EAAEC,IAAI,EAAEC,aAAa,EAAEC,GAAG,EAAE,GAAGL;IACpD,IAAI,CAACG,MA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a,eAAeA,SAASC,eAAe,KAAK;QAClE3F,UAAU,IACR,OAAO4F,cAAc,eAAeA,UAAUC,MAAM,KAAK;QAC3D3F,eAAe,IAAM2C,oBAAoBC,SAASC;QAClD3C,aAAa,IAAM7B,cAAckH;QACjCpG,OAAO,CAACqB,SAAW+C,kBAAkBxC,SAASC,cAAcR;QAC5DG,cAAc;YACZ,MAAMvC,eAAemH;YACrB,MAAMlH,cAAckH;QACtB;IACF,GAAGK,IAAI,CAAC,CAACnF;QACP,IAAIA,QAAQZ,MAAM,KAAK,WAAW;YAChCgG,QAAQC,KAAK,CACX,yFACArF;QAEJ;QACA,OAAOA;IACT;AACF"}
@@ -18,7 +18,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
18
18
  import { components } from "@aglyn/aglyn";
19
19
  import { pluginInstallToPresets, setKnownPluginInstalls } from "@aglyn/aglyn";
20
20
  import { collection, limit, query } from "firebase/firestore";
21
- import { runInAction } from "mobx";
21
+ import { reaction, runInAction } from "mobx";
22
22
  import { useEffect, useMemo, useRef } from "react";
23
23
  import { useFirestore } from "./firebase/firebase-services.js";
24
24
  import { useHostOrgId } from "./use-host-org-id.js";
@@ -102,27 +102,35 @@ import useFirestoreCollection from "./use-firestore-collection.js";
102
102
  installs
103
103
  ]);
104
104
  useEffect(()=>{
105
- // Single mobx transaction (AGL-371): the drawer re-renders once per
106
- // install sync, not once for the unregister and again per preset.
107
- runInAction(()=>{
105
+ const unregister = ()=>{
108
106
  if (registeredIds.current.length) {
109
107
  components.unregisterPreset(registeredIds.current);
110
108
  registeredIds.current = [];
111
109
  }
112
- // One preset per install PLUS one per element the pinned version
113
- // declares (AGL-1031). Built from the pin, so a declared element appears
114
- // only where the plugin is installed and leaves with a revoked version.
115
- const presets = installs.flatMap((install)=>pluginInstallToPresets(install)).filter((preset)=>Boolean(preset));
116
- if (presets.length) {
117
- components.registerPreset(presets);
118
- registeredIds.current = presets.map((preset)=>preset.$id);
119
- }
110
+ };
111
+ // One preset per install PLUS one per element the pinned version
112
+ // declares (AGL-1031). Built from the pin, so a declared element appears
113
+ // only where the plugin is installed and leaves with a revoked version.
114
+ // A reaction, not a one-off: whether a signed plugin's own elements are
115
+ // registered (which drops its generic entry, AGL-4196) can change after
116
+ // the installs arrive, when its bundle finishes loading.
117
+ const dispose = reaction(()=>installs.flatMap((install)=>pluginInstallToPresets(install)).filter((preset)=>Boolean(preset)), (presets)=>{
118
+ // Single mobx transaction (AGL-371): the drawer re-renders once per
119
+ // install sync, not once for the unregister and again per preset.
120
+ runInAction(()=>{
121
+ unregister();
122
+ if (presets.length) {
123
+ components.registerPreset(presets);
124
+ registeredIds.current = presets.map((preset)=>preset.$id);
125
+ }
126
+ });
127
+ }, {
128
+ fireImmediately: true,
129
+ equals: (a, b)=>a.map((preset)=>preset.$id).join('\n') === b.map((preset)=>preset.$id).join('\n')
120
130
  });
121
131
  return ()=>{
122
- if (registeredIds.current.length) {
123
- components.unregisterPreset(registeredIds.current);
124
- registeredIds.current = [];
125
- }
132
+ dispose();
133
+ unregister();
126
134
  };
127
135
  }, [
128
136
  installs
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-plugin-drawer-registration.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { components } from '@aglyn/aglyn'\nimport { pluginInstallToPresets, setKnownPluginInstalls } from '@aglyn/aglyn'\nimport { collection, limit, query } from 'firebase/firestore'\nimport { runInAction } from 'mobx'\nimport { useEffect, useMemo, useRef } from 'react'\nimport { useFirestore } from './firebase/firebase-services'\nimport { useHostOrgId } from './use-host-org-id'\nimport useFirestoreCollection from './use-firestore-collection'\n\n/**\n * Registers the host's installed plugins as named besigner drawer entries\n * (AGL-190): one preset per install under the Marketplace category, dropping\n * a `marketplacePlugin` node with the listing id pre-pinned. Presets are\n * re-synced whenever installs change and removed on host change/unmount so\n * switching hosts never leaks another host's plugins into the drawer.\n */\nexport function usePluginDrawerRegistration(hostId: string): void {\n const firestore = useFirestore()\n const { data: installDocs } = useFirestoreCollection<any>(\n () => query(collection(firestore, 'hosts', hostId, 'installs'), limit(50)),\n [firestore, hostId],\n { idField: '$id' },\n )\n // Org-wide pins too (AGL-1029). One org pin covers every site, so a plugin\n // installed that way is genuinely available here — but the drawer only ever\n // read the host's own installs, so those plugins had no entry, and the\n // element could not be told they were installed either.\n const orgId = useHostOrgId(hostId)\n // Held at null while `useHostOrgId` is in flight, never `orgs/-pending-`\n // (AGL-1440): installs are member-gated, so the sentinel was a\n // guaranteed-denied listen on every besigner editor session.\n const { data: orgInstallDocs } = useFirestoreCollection<any>(\n () =>\n orgId\n ? query(collection(firestore, 'orgs', orgId, 'installs'), limit(50))\n : null,\n [firestore, orgId],\n { idField: '$id' },\n )\n /**\n * Host pins shadow org pins for the same listing (AGL-656), so the host\n * entry wins — the drawer must not offer the same plugin twice, and the\n * scope reported for it has to be the one actually in force.\n */\n const installs = useMemo(() => {\n const byListing = new Map<string, any>()\n for (const install of (orgInstallDocs as any[]) ?? []) {\n const id = install?.listingId ?? install?.$id\n if (id) byListing.set(id, { ...install, scope: 'org' })\n }\n for (const install of (installDocs as any[]) ?? []) {\n const id = install?.listingId ?? install?.$id\n if (id) byListing.set(id, { ...install, scope: 'host' })\n }\n return [...byListing.values()]\n }, [installDocs, orgInstallDocs])\n // Track the ids we registered so we can unregister exactly those.\n const registeredIds = useRef<string[]>([])\n\n // What the canvas may claim about installation (AGL-1029). Published\n // separately from the presets because the element asks by listing id, and\n // an unknown id is only \"not installed\" if there is a list to be missing\n // from — on the tenant nothing publishes one.\n useEffect(() => {\n setKnownPluginInstalls(\n installs.map((install) => ({\n listingId: install.listingId ?? install.$id,\n displayName: install.displayName ?? install.manifest?.name,\n scope: install.scope,\n // The declared props (and, where a publisher supplied one, how to edit\n // them) so the attributes panel can render real fields — AGL-1049.\n capabilities: install.manifest?.capabilities,\n })),\n )\n return () => setKnownPluginInstalls(undefined)\n }, [installs])\n\n useEffect(() => {\n // Single mobx transaction (AGL-371): the drawer re-renders once per\n // install sync, not once for the unregister and again per preset.\n runInAction(() => {\n if (registeredIds.current.length) {\n components.unregisterPreset(registeredIds.current)\n registeredIds.current = []\n }\n // One preset per install PLUS one per element the pinned version\n // declares (AGL-1031). Built from the pin, so a declared element appears\n // only where the plugin is installed and leaves with a revoked version.\n const presets = installs\n .flatMap((install) => pluginInstallToPresets(install))\n .filter(\n (preset): preset is NonNullable<typeof preset> => Boolean(preset),\n )\n if (presets.length) {\n components.registerPreset(presets)\n registeredIds.current = presets.map((preset) => preset.$id)\n }\n })\n return () => {\n if (registeredIds.current.length) {\n components.unregisterPreset(registeredIds.current)\n registeredIds.current = []\n }\n }\n }, [installs])\n}\n\nexport default usePluginDrawerRegistration\n"],"names":["components","pluginInstallToPresets","setKnownPluginInstalls","collection","limit","query","runInAction","useEffect","useMemo","useRef","useFirestore","useHostOrgId","useFirestoreCollection","usePluginDrawerRegistration","hostId","firestore","data","installDocs","idField","orgId","orgInstallDocs","installs","byListing","Map","install","id","listingId","$id","set","scope","values","registeredIds","map","displayName","manifest","name","capabilities","undefined","current","length","unregisterPreset","presets","flatMap","filter","preset","Boolean","registerPreset"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,UAAU,QAAQ,eAAc;AACzC,SAASC,sBAAsB,EAAEC,sBAAsB,QAAQ,eAAc;AAC7E,SAASC,UAAU,EAAEC,KAAK,EAAEC,KAAK,QAAQ,qBAAoB;AAC7D,SAASC,WAAW,QAAQ,OAAM;AAClC,SAASC,SA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AEA,eAAeR,4BAA2B"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-plugin-drawer-registration.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { components } from '@aglyn/aglyn'\nimport { pluginInstallToPresets, setKnownPluginInstalls } from '@aglyn/aglyn'\nimport { collection, limit, query } from 'firebase/firestore'\nimport { reaction, runInAction } from 'mobx'\nimport { useEffect, useMemo, useRef } from 'react'\nimport { useFirestore } from './firebase/firebase-services'\nimport { useHostOrgId } from './use-host-org-id'\nimport useFirestoreCollection from './use-firestore-collection'\n\n/**\n * Registers the host's installed plugins as named besigner drawer entries\n * (AGL-190): one preset per install under the Marketplace category, dropping\n * a `marketplacePlugin` node with the listing id pre-pinned. Presets are\n * re-synced whenever installs change and removed on host change/unmount so\n * switching hosts never leaks another host's plugins into the drawer.\n */\nexport function usePluginDrawerRegistration(hostId: string): void {\n const firestore = useFirestore()\n const { data: installDocs } = useFirestoreCollection<any>(\n () => query(collection(firestore, 'hosts', hostId, 'installs'), limit(50)),\n [firestore, hostId],\n { idField: '$id' },\n )\n // Org-wide pins too (AGL-1029). One org pin covers every site, so a plugin\n // installed that way is genuinely available here — but the drawer only ever\n // read the host's own installs, so those plugins had no entry, and the\n // element could not be told they were installed either.\n const orgId = useHostOrgId(hostId)\n // Held at null while `useHostOrgId` is in flight, never `orgs/-pending-`\n // (AGL-1440): installs are member-gated, so the sentinel was a\n // guaranteed-denied listen on every besigner editor session.\n const { data: orgInstallDocs } = useFirestoreCollection<any>(\n () =>\n orgId\n ? query(collection(firestore, 'orgs', orgId, 'installs'), limit(50))\n : null,\n [firestore, orgId],\n { idField: '$id' },\n )\n /**\n * Host pins shadow org pins for the same listing (AGL-656), so the host\n * entry wins — the drawer must not offer the same plugin twice, and the\n * scope reported for it has to be the one actually in force.\n */\n const installs = useMemo(() => {\n const byListing = new Map<string, any>()\n for (const install of (orgInstallDocs as any[]) ?? []) {\n const id = install?.listingId ?? install?.$id\n if (id) byListing.set(id, { ...install, scope: 'org' })\n }\n for (const install of (installDocs as any[]) ?? []) {\n const id = install?.listingId ?? install?.$id\n if (id) byListing.set(id, { ...install, scope: 'host' })\n }\n return [...byListing.values()]\n }, [installDocs, orgInstallDocs])\n // Track the ids we registered so we can unregister exactly those.\n const registeredIds = useRef<string[]>([])\n\n // What the canvas may claim about installation (AGL-1029). Published\n // separately from the presets because the element asks by listing id, and\n // an unknown id is only \"not installed\" if there is a list to be missing\n // from — on the tenant nothing publishes one.\n useEffect(() => {\n setKnownPluginInstalls(\n installs.map((install) => ({\n listingId: install.listingId ?? install.$id,\n displayName: install.displayName ?? install.manifest?.name,\n scope: install.scope,\n // The declared props (and, where a publisher supplied one, how to edit\n // them) so the attributes panel can render real fields — AGL-1049.\n capabilities: install.manifest?.capabilities,\n })),\n )\n return () => setKnownPluginInstalls(undefined)\n }, [installs])\n\n useEffect(() => {\n const unregister = () => {\n if (registeredIds.current.length) {\n components.unregisterPreset(registeredIds.current)\n registeredIds.current = []\n }\n }\n // One preset per install PLUS one per element the pinned version\n // declares (AGL-1031). Built from the pin, so a declared element appears\n // only where the plugin is installed and leaves with a revoked version.\n // A reaction, not a one-off: whether a signed plugin's own elements are\n // registered (which drops its generic entry, AGL-4196) can change after\n // the installs arrive, when its bundle finishes loading.\n const dispose = reaction(\n () =>\n installs\n .flatMap((install) => pluginInstallToPresets(install))\n .filter((preset): preset is NonNullable<typeof preset> => Boolean(preset)),\n (presets) => {\n // Single mobx transaction (AGL-371): the drawer re-renders once per\n // install sync, not once for the unregister and again per preset.\n runInAction(() => {\n unregister()\n if (presets.length) {\n components.registerPreset(presets)\n registeredIds.current = presets.map((preset) => preset.$id)\n }\n })\n },\n {\n fireImmediately: true,\n equals: (a, b) => a.map((preset) => preset.$id).join('\\n') === b.map((preset) => preset.$id).join('\\n'),\n },\n )\n return () => {\n dispose()\n unregister()\n }\n }, [installs])\n}\n\nexport default usePluginDrawerRegistration\n"],"names":["components","pluginInstallToPresets","setKnownPluginInstalls","collection","limit","query","reaction","runInAction","useEffect","useMemo","useRef","useFirestore","useHostOrgId","useFirestoreCollection","usePluginDrawerRegistration","hostId","firestore","data","installDocs","idField","orgId","orgInstallDocs","installs","byListing","Map","install","id","listingId","$id","set","scope","values","registeredIds","map","displayName","manifest","name","capabilities","undefined","unregister","current","length","unregisterPreset","dispose","flatMap","filter","preset","Boolean","presets","registerPreset","fireImmediately","equals","a","b","join"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,UAAU,QAAQ,eAAc;AACzC,SAASC,sBAAsB,EAAEC,sBAAsB,QAAQ,eAAc;AAC7E,SAASC,UAAU,EAAEC,KAAK,EAAEC,KAAK,QAAQ,qBAAoB;AAC7D,SAASC,QAAQ,EAAEC,WAAW,QAAQ,OAAM;AAC5C,SAASC,SAAS,EAAEC,OAAO,EAAEC,MAAM,QAAQ,QAAO;AAClD,SAASC,YAAY,QAAQ,kCAA8B;AAC3D,SAASC,YAAY,QAAQ,uBAAmB;AAChD,OAAOC,4BAA4B,gCAA4B;AAE/D;;;;;;CAMC,GACD,OAAO,SAASC,4BAA4BC,MAAc;IACxD,MAAMC,YAAYL;IAClB,MAAM,EAAEM,MAAMC,WAAW,EAAE,GAAGL,uBAC5B,IAAMR,MAAMF,WAAWa,WAAW,SAASD,QAAQ,aAAaX,MAAM,MACtE;QAACY;QAAWD;KAAO,EACnB;QAAEI,SAAS;IAAM;IAEnB,2EAA2E;IAC3E,4EAA4E;IAC5E,uEAAuE;IACvE,wDAAw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