app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

inbox-view.ts (40607B)


      1 import {
      2   projectConversationThread,
      3   unavailableThread,
      4   type ThreadSnapshot,
      5   type ThreadMessage
      6 } from './conversation-thread.ts';
      7 import type { PrivateRecordHandle } from '../persistence/private-records.ts';
      8 import {
      9   privateBlocksForIdentity,
     10   mountLocalPrivateBlocks,
     11   localPrivateBlocksSnapshot,
     12   localPrivatePeerAllowed,
     13   subscribeLocalPrivateBlocks,
     14   blockLocalPrivatePeer,
     15   type PrivateBlockResult
     16 } from '../persistence/local-private-blocks.ts';
     17 import { canonicalPublicKey } from '../contracts/public-key.ts';
     18 import {
     19   groupInboxMessages,
     20   type InboxListSnapshot,
     21   type InboxListRow
     22 } from './inbox-list.ts';
     23 import {
     24   captureMessageMetadata,
     25   messageMetadataSnapshot,
     26   markDisplayedMessage,
     27   type MessageMetadata
     28 } from '../persistence/message-metadata.ts';
     29 import {
     30   captureConversationDirectory,
     31   rememberAdmittedConversation,
     32   closeConversationDirectory,
     33   resolveLocalConversation,
     34   type ConversationDirectory
     35 } from './conversation-directory.ts';
     36 import {
     37   conversationSnapshot,
     38   type AdmittedConversation
     39 } from './admit-conversation.ts';
     40 import { decryptionQueueConversations } from './decryption-queue.ts';
     41 import {
     42   captureOlderInbox,
     43   loadOlderInbox,
     44   stopOlderInbox,
     45   olderInboxSnapshot,
     46   type OlderInbox
     47 } from './history-pagination.ts';
     48 import {
     49   identityMessagingOwnership,
     50   identitySessionSnapshot,
     51   subscribeIdentityInvalidation,
     52   type IdentitySession,
     53   type IdentitySnapshot
     54 } from '../runtime/identity-session.ts';
     55 import {
     56   privateSessionOwnership,
     57   subscribePrivateSessionClose,
     58   closePrivateSession,
     59   type PrivateSession
     60 } from '../runtime/private-session.ts';
     61 import {
     62   inboxSetupViewOwnership,
     63   inboxSetupViewSnapshot,
     64   subscribeInboxSetupView,
     65   closeInboxSetupView,
     66   unlockInboxSetupView,
     67   observeInboxSetupView,
     68   type InboxSetupView
     69 } from './inbox-setup-view.ts';
     70 import {
     71   openBrowserDatabase,
     72   closeBrowserDatabase,
     73   type BrowserDatabase
     74 } from '../persistence/database.ts';
     75 import {
     76   createPrivateStorageRepository,
     77   listPrivateSendRecords,
     78   type PrivateStorageRepository
     79 } from '../persistence/private-storage.ts';
     80 import {
     81   captureUnlockedSession,
     82   closeUnlockedSession,
     83   readUnlockedMessages,
     84   unlockedConversationCurrent,
     85   type UnlockedSession
     86 } from './unlocked-session.ts';
     87 import {
     88   captureDecryptionQueue,
     89   refreshDecryptionQueue,
     90   runDecryptionBatch,
     91   decryptionQueueSnapshot,
     92   stopDecryptionQueue,
     93   type DecryptionQueue
     94 } from './decryption-queue.ts';
     95 import {
     96   captureInboxSync,
     97   startInboxSync,
     98   refreshInboxSync,
     99   inboxSyncSnapshot,
    100   inboxSyncHistoryOwnership,
    101   stopInboxSync,
    102   type InboxSync
    103 } from './inbox-sync.ts';
    104 import { messagingReadinessSnapshot } from './readiness.ts';
    105 import {
    106   selfRecoveryAcknowledgementSnapshot,
    107   verifySelfRecoveryAcknowledgement,
    108   type SelfRecoveryAcknowledgement
    109 } from '../persistence/private-sends.ts';
    110 declare const inboxViewBrand: unique symbol;
    111 export type InboxView = Readonly<{ [inboxViewBrand]: true }>;
    112 export type InboxViewSnapshot = Readonly<{
    113   state: string;
    114   reason: string | null;
    115   busy: boolean;
    116   owner?: string;
    117   identity: IdentitySnapshot;
    118   queued: number;
    119   count: number;
    120   lastCheckedAt: number | null;
    121   historyComplete: false;
    122   cleanupRequired: boolean;
    123 }>;
    124 type Inputs = Readonly<{
    125   identity: IdentitySession;
    126   setup: InboxSetupView;
    127   conversationId?: string;
    128 }>;
    129 export type InboxReplyOwnership = Readonly<{
    130   owner: string;
    131   identity: IdentitySession;
    132   session: PrivateSession;
    133   database: BrowserDatabase;
    134   repository: PrivateStorageRepository;
    135   unlocked: UnlockedSession;
    136   room: AdmittedConversation;
    137   setup: InboxSetupView;
    138   peer: string;
    139   parent: string;
    140   current(): boolean;
    141   acceptLocalReply(
    142     receipt: SelfRecoveryAcknowledgement,
    143     review: unknown
    144   ): Promise<boolean>;
    145 }>;
    146 type Controller = {
    147   block(id: unknown, review: unknown): Promise<PrivateBlockResult>;
    148   blocked(id: unknown): boolean;
    149   reply(id: unknown, rumor: unknown): InboxReplyOwnership | undefined;
    150   snapshot(): InboxViewSnapshot;
    151   thread(id: unknown): ThreadSnapshot;
    152   threadRevision(): number;
    153   message(id: unknown, rumor: unknown): ThreadMessage | undefined;
    154   resolve(id: unknown, review: unknown): Promise<boolean>;
    155   displayed(
    156     id: unknown,
    157     rumors: readonly string[],
    158     review: unknown
    159   ): Promise<boolean>;
    160   setup(): InboxSetupView | undefined;
    161   list(): InboxListSnapshot;
    162   row(peer: unknown): InboxListRow | undefined;
    163   revision(): number;
    164   open(peer: unknown, review: unknown): Promise<string | undefined>;
    165   older(review: unknown): Promise<boolean>;
    166   olderAvailable(): boolean;
    167   subscribe(listener: (view: InboxViewSnapshot) => void): () => void;
    168   unlock(review: unknown): Promise<boolean>;
    169   check(review: unknown): Promise<boolean>;
    170   read(review: unknown): Promise<boolean>;
    171   stop(): void;
    172   close(): boolean;
    173 };
    174 const views = new WeakMap<InboxView, Controller>();
    175 const unavailable = (): InboxViewSnapshot => ({
    176   state: 'unavailable',
    177   reason: null,
    178   busy: false,
    179   identity: { state: 'guest', reason: 'unavailable' },
    180   queued: 0,
    181   count: 0,
    182   lastCheckedAt: null,
    183   historyComplete: false,
    184   cleanupRequired: false
    185 });
    186 // The original setup/identity objects, not their copied readiness projections,
    187 // own this per-page orchestration. Mounting/subscribing never prompts or sends.
    188 export function createInboxView(input: Inputs): InboxView | undefined {
    189   if (typeof window === 'undefined') return;
    190   const original = identityMessagingOwnership(input.identity),
    191     setup = inboxSetupViewOwnership(input.setup);
    192   if (
    193     !original?.current() ||
    194     !setup?.current() ||
    195     setup.identity !== input.identity
    196   )
    197     return;
    198   const capture = original,
    199     token = Object.freeze({}) as InboxView;
    200   const capturedPreferences = privateBlocksForIdentity(input.identity);
    201   if (!capturedPreferences) return;
    202   const preferences = capturedPreferences;
    203   let closed = false,
    204     busy = false,
    205     epoch = 0,
    206     reason: string | null = null,
    207     lastCheckedAt: number | null = null,
    208     checkPending = false,
    209     sampling = false,
    210     refreshedRetained = -1;
    211   let session: PrivateSession | undefined,
    212     database: BrowserDatabase | undefined,
    213     repository: PrivateStorageRepository | undefined,
    214     unlocked: UnlockedSession | undefined,
    215     queue: DecryptionQueue | undefined,
    216     sync: InboxSync | undefined;
    217   let metadata: MessageMetadata | undefined,
    218     directory: ConversationDirectory | undefined,
    219     older: OlderInbox | undefined;
    220   let list: InboxListSnapshot = groupInboxMessages('', [], []);
    221   let threadId: string | undefined,
    222     threadPeer: string | undefined,
    223     threadEpoch = 0;
    224   let threadModel: ThreadSnapshot = unavailableThread();
    225   const threadProofs = new Map<
    226     string,
    227     Readonly<{ room: AdmittedConversation; message: ThreadMessage }>
    228   >();
    229   let sendRecords: readonly PrivateRecordHandle[] =
    230     Array.from<PrivateRecordHandle>([]);
    231   let listReason: string | null = null;
    232   let repliedPeers = Array.from<string>([]);
    233   let listRevision = 0;
    234   const rowProofs = new Map<
    235     string,
    236     Readonly<{ data: InboxListRow; room: AdmittedConversation }>
    237   >();
    238   let off = () => {},
    239     privateOff = () => {},
    240     setupOff = () => {},
    241     preferencesOff = () => {},
    242     pendingCleanup = Array.from<() => void>([]);
    243   const listeners = new Map<symbol, (view: InboxViewSnapshot) => void>();
    244   function current(generation = epoch) {
    245     const owner = inboxSetupViewOwnership(input.setup);
    246     return (
    247       !closed &&
    248       generation === epoch &&
    249       capture.current() &&
    250       owner?.identity === input.identity &&
    251       owner.current()
    252     );
    253   }
    254   function privateCurrent() {
    255     const owner = session && privateSessionOwnership(session);
    256     return (
    257       !!owner?.current() &&
    258       owner.owner === capture.owner &&
    259       owner.session === capture.session &&
    260       current()
    261     );
    262   }
    263   function threadRooms(id: unknown) {
    264     if (
    265       id !== threadId ||
    266       !threadPeer ||
    267       !localPrivatePeerAllowed(preferences, threadPeer) ||
    268       !privateCurrent() ||
    269       !unlocked ||
    270       !queue
    271     )
    272       return;
    273     const rooms = decryptionQueueConversations(queue).filter((room) => {
    274       const data = conversationSnapshot(room);
    275       return (
    276         data?.owner === capture.owner &&
    277         data.peer === threadPeer &&
    278         unlockedConversationCurrent(unlocked!, room)
    279       );
    280     });
    281     return rooms;
    282   }
    283   function refreshThread() {
    284     threadProofs.clear();
    285     threadModel = unavailableThread();
    286     const rooms = threadRooms(threadId);
    287     if (!rooms || !threadPeer) return;
    288     const data = rooms.map(conversationSnapshot);
    289     if (data.some((row) => !row)) return;
    290     threadModel = projectConversationThread(
    291       capture.owner,
    292       threadPeer,
    293       data.filter((row) => row !== undefined),
    294       sendRecords
    295     );
    296     if (threadModel.status !== 'ready') return;
    297     const byRumor = new Map<string, AdmittedConversation>();
    298     for (const room of rooms) {
    299       const row = conversationSnapshot(room);
    300       if (row) byRumor.set(row.rumorId, room);
    301     }
    302     for (const message of threadModel.messages) {
    303       const room = byRumor.get(message.data.rumorId);
    304       if (room) threadProofs.set(message.data.rumorId, { room, message });
    305     }
    306   }
    307   function messageSnapshot(
    308     id: unknown,
    309     rumor: unknown
    310   ): ThreadMessage | undefined {
    311     if (
    312       id !== threadId ||
    313       typeof rumor !== 'string' ||
    314       !privateCurrent() ||
    315       !unlocked ||
    316       threadModel.status !== 'ready'
    317     )
    318       return;
    319     const proof = threadProofs.get(rumor);
    320     if (!proof || !unlockedConversationCurrent(unlocked, proof.room)) return;
    321     const actual = conversationSnapshot(proof.room);
    322     if (
    323       !actual ||
    324       actual.owner !== capture.owner ||
    325       actual.peer !== threadPeer ||
    326       !localPrivatePeerAllowed(preferences, actual.peer) ||
    327       actual.rumorId !== rumor
    328     )
    329       return;
    330     return {
    331       data: { ...actual },
    332       citations: proof.message.citations.map((row) => ({ ...row })),
    333       parent: proof.message.parent,
    334       delivery: proof.message.delivery?.slice() ?? null
    335     };
    336   }
    337   function threadSnapshot(id: unknown): ThreadSnapshot {
    338     if (id !== threadId || !privateCurrent() || threadModel.status !== 'ready')
    339       return unavailableThread();
    340     const messages = threadModel.messages.map((row) =>
    341       messageSnapshot(id, row.data.rumorId)
    342     );
    343     return messages.some((row) => !row)
    344       ? unavailableThread()
    345       : {
    346           status: 'ready',
    347           messages: messages.filter((row) => row !== undefined)
    348         };
    349   }
    350   async function block(
    351     id: unknown,
    352     review: unknown
    353   ): Promise<PrivateBlockResult> {
    354     const room = threadRooms(id)?.[0];
    355     if (!room || !unlocked || review !== 'reviewed_local_private_block')
    356       return { status: 'invalid' };
    357     return blockLocalPrivatePeer(preferences, room, unlocked, review);
    358   }
    359   function blocked(id: unknown): boolean {
    360     const actual = localPrivateBlocksSnapshot(preferences);
    361     return (
    362       current() &&
    363       id === threadId &&
    364       !!threadPeer &&
    365       actual.state === 'ready' &&
    366       actual.peers.includes(threadPeer)
    367     );
    368   }
    369   function replyOwnership(
    370     id: unknown,
    371     rumor: unknown
    372   ): InboxReplyOwnership | undefined {
    373     if (
    374       typeof rumor !== 'string' ||
    375       !messageSnapshot(id, rumor) ||
    376       !session ||
    377       !database ||
    378       !repository ||
    379       !unlocked
    380     )
    381       return;
    382     const proof = threadProofs.get(rumor);
    383     if (!proof) return;
    384     const data = conversationSnapshot(proof.room);
    385     if (!data) return;
    386     const generation = epoch,
    387       selection = threadEpoch,
    388       originalSession = session,
    389       originalRepository = repository,
    390       originalCache = unlocked,
    391       originalDatabase = database;
    392     const admitted = () =>
    393       current(generation) &&
    394       privateCurrent() &&
    395       selection === threadEpoch &&
    396       id === threadId &&
    397       threadPeer === data.peer &&
    398       session === originalSession &&
    399       repository === originalRepository &&
    400       unlocked === originalCache &&
    401       !!messageSnapshot(id, rumor) &&
    402       unlockedConversationCurrent(originalCache, proof.room);
    403     if (!admitted()) return;
    404     return {
    405       owner: capture.owner,
    406       identity: input.identity,
    407       session: originalSession,
    408       database: originalDatabase,
    409       repository: originalRepository,
    410       unlocked: originalCache,
    411       room: proof.room,
    412       setup: input.setup,
    413       peer: data.peer,
    414       parent: data.rumorId,
    415       current: admitted,
    416       async acceptLocalReply(receipt, review) {
    417         const saved = selfRecoveryAcknowledgementSnapshot(receipt);
    418         if (
    419           review !== 'reviewed_local_reply' ||
    420           !admitted() ||
    421           saved?.owner !== capture.owner ||
    422           saved.peer !== data.peer ||
    423           !(await verifySelfRecoveryAcknowledgement(
    424             originalRepository,
    425             receipt
    426           )) ||
    427           !admitted()
    428         )
    429           return false;
    430         // Presentation in this unlocked view only, backed by the actual native
    431         // self receipt. No order/notification or persistent acceptance field.
    432         if (!repliedPeers.includes(data.peer))
    433           repliedPeers = repliedPeers.concat(data.peer);
    434         listRevision++;
    435         await refreshList(generation);
    436         if (!admitted()) return false;
    437         notify();
    438         return true;
    439       }
    440     };
    441   }
    442   async function resolve(id: unknown, review: unknown) {
    443     if (review !== 'reviewed_conversation_navigation') return false;
    444     const selection = ++threadEpoch,
    445       generation = epoch;
    446     threadId = undefined;
    447     threadPeer = undefined;
    448     threadProofs.clear();
    449     threadModel = unavailableThread();
    450     notify();
    451     if (!directory || !privateCurrent()) return false;
    452     const result = await resolveLocalConversation(directory, id);
    453     if (
    454       selection !== threadEpoch ||
    455       !current(generation) ||
    456       !privateCurrent() ||
    457       result.status !== 'resolved' ||
    458       result.owner !== capture.owner
    459     )
    460       return false;
    461     threadId = result.conversationId;
    462     threadPeer = result.peer;
    463     refreshThread();
    464     notify();
    465     return true;
    466   }
    467   async function displayed(
    468     id: unknown,
    469     rumors: readonly string[],
    470     review: unknown
    471   ) {
    472     if (
    473       review !== 'reviewed_displayed_conversation' ||
    474       !Array.isArray(rumors) ||
    475       !metadata
    476     )
    477       return false;
    478     const rooms = threadRooms(id),
    479       selection = threadEpoch,
    480       generation = epoch,
    481       originalMetadata = metadata;
    482     if (!rooms || rumors.length > 2000) return false;
    483     for (const rumor of rumors) {
    484       const room = rooms.find(
    485         (value) => conversationSnapshot(value)?.rumorId === rumor
    486       );
    487       if (
    488         !room ||
    489         selection !== threadEpoch ||
    490         !current(generation) ||
    491         !privateCurrent() ||
    492         id !== threadId
    493       )
    494         return false;
    495       const result = await markDisplayedMessage(
    496         originalMetadata,
    497         room,
    498         'displayed_message'
    499       );
    500       if (result.status !== 'saved' && result.status !== 'existing')
    501         return false;
    502     }
    503     if (selection !== threadEpoch || !current(generation) || !privateCurrent())
    504       return false;
    505     await refreshList(generation);
    506     return selection === threadEpoch && current(generation) && privateCurrent();
    507   }
    508   function rowSnapshot(peer: unknown): InboxListRow | undefined {
    509     if (
    510       typeof peer !== 'string' ||
    511       !privateCurrent() ||
    512       !unlocked ||
    513       !queue ||
    514       list.status !== 'ready'
    515     )
    516       return;
    517     const proof = rowProofs.get(peer);
    518     if (!proof || !unlockedConversationCurrent(unlocked, proof.room)) return;
    519     const actual = conversationSnapshot(proof.room);
    520     if (
    521       !actual ||
    522       actual.owner !== capture.owner ||
    523       actual.peer !== peer ||
    524       !localPrivatePeerAllowed(preferences, actual.peer) ||
    525       actual.rumorId !== proof.data.latest.rumorId
    526     )
    527       return;
    528     return { ...proof.data, latest: { ...actual } };
    529   }
    530   function listSnapshot(): InboxListSnapshot {
    531     if (!privateCurrent() || !unlocked || !queue)
    532       return { status: 'locked', requests: [], conversations: [] };
    533     if (list.status !== 'ready')
    534       return { status: list.status, requests: [], conversations: [] };
    535     if (localPrivateBlocksSnapshot(preferences).state !== 'ready')
    536       return { status: 'unavailable', requests: [], conversations: [] };
    537     const requests = list.requests
    538         .filter((row) => localPrivatePeerAllowed(preferences, row.peer))
    539         .map((row) => rowSnapshot(row.peer)),
    540       conversations = list.conversations
    541         .filter((row) => localPrivatePeerAllowed(preferences, row.peer))
    542         .map((row) => rowSnapshot(row.peer));
    543     if (requests.some((row) => !row) || conversations.some((row) => !row))
    544       return { status: 'unavailable', requests: [], conversations: [] };
    545     return {
    546       status: 'ready',
    547       requests: requests
    548         .filter((row) => row !== undefined)
    549         .filter((row) => !repliedPeers.includes(row.peer)),
    550       conversations: conversations
    551         .filter((row) => row !== undefined)
    552         .concat(
    553           requests
    554             .filter((row) => row !== undefined)
    555             .filter((row) => repliedPeers.includes(row.peer))
    556         )
    557         .sort(
    558           (a, b) =>
    559             b.latest.createdAt - a.latest.createdAt ||
    560             b.latest.rumorId.localeCompare(a.latest.rumorId) ||
    561             a.peer.localeCompare(b.peer)
    562         )
    563     };
    564   }
    565   async function refreshList(generation = epoch) {
    566     if (!privateCurrent() || !unlocked || !metadata) return false;
    567     try {
    568       const local = await messageMetadataSnapshot(metadata);
    569       const sends = repository && (await listPrivateSendRecords(repository));
    570       if (!current(generation) || !privateCurrent() || !unlocked) return false;
    571       sendRecords = sends?.ok ? sends.value : [];
    572       const cached = readUnlockedMessages(unlocked);
    573       if (
    574         local.status !== 'ready' ||
    575         local.owner !== capture.owner ||
    576         cached.status !== 'ready'
    577       ) {
    578         list = { status: 'unavailable', requests: [], conversations: [] };
    579         rowProofs.clear();
    580         listRevision++;
    581         listReason = 'storage_unavailable';
    582         return false;
    583       }
    584       list = groupInboxMessages(
    585         capture.owner,
    586         cached.messages.filter((message) =>
    587           localPrivatePeerAllowed(preferences, message.peer)
    588         ),
    589         local.readRumors
    590       );
    591       rowProofs.clear();
    592       const rooms = queue && decryptionQueueConversations(queue),
    593         byRumor = new Map<string, AdmittedConversation>();
    594       for (const room of rooms ?? []) {
    595         const observed = conversationSnapshot(room);
    596         if (observed) byRumor.set(observed.rumorId, room);
    597       }
    598       for (const row of list.requests.concat(list.conversations)) {
    599         const room = byRumor.get(row.latest.rumorId);
    600         if (room) rowProofs.set(row.peer, { data: row, room });
    601       }
    602       refreshThread();
    603       listRevision++;
    604       listReason = list.status === 'ready' ? null : 'unavailable';
    605       return list.status === 'ready';
    606     } catch {
    607       if (current(generation) && privateCurrent()) {
    608         list = { status: 'unavailable', requests: [], conversations: [] };
    609         rowProofs.clear();
    610         listRevision++;
    611         listReason = 'storage_unavailable';
    612       }
    613       return false;
    614     }
    615   }
    616   function olderAvailable() {
    617     if (busy || !privateCurrent() || !unlocked || !repository || !sync)
    618       return false;
    619     const transport = inboxSyncSnapshot(sync),
    620       ownership = inboxSyncHistoryOwnership(sync),
    621       own = inboxSetupViewOwnership(input.setup),
    622       original = session && privateSessionOwnership(session);
    623     if (
    624       !own?.current() ||
    625       !own.resolver ||
    626       !original?.current() ||
    627       !ownership?.current() ||
    628       transport?.backfill !== 'complete' ||
    629       transport.pending !== 0
    630     )
    631       return false;
    632     return (
    633       messagingReadinessSnapshot(
    634         input.identity,
    635         session,
    636         own.policy,
    637         own.resolver,
    638         undefined,
    639         own.observeAccess
    640       ).ownAccess === 'qualified_exercised'
    641     );
    642   }
    643   async function open(peer: unknown, review: unknown) {
    644     if (
    645       review !== 'reviewed_admitted_conversation_navigation' ||
    646       busy ||
    647       !privateCurrent() ||
    648       !queue ||
    649       !directory ||
    650       !canonicalPublicKey(peer)
    651     )
    652       return;
    653     if (!localPrivatePeerAllowed(preferences, peer as string)) return;
    654     const room = decryptionQueueConversations(queue).find(
    655       (value) => conversationSnapshot(value)?.peer === peer
    656     );
    657     if (!room) return;
    658     const generation = epoch;
    659     busy = true;
    660     notify();
    661     try {
    662       const result = await rememberAdmittedConversation(
    663         directory,
    664         room,
    665         review
    666       );
    667       if (!current(generation) || !privateCurrent()) return;
    668       if (result.status !== 'saved' && result.status !== 'existing') {
    669         reason = 'unavailable';
    670         return;
    671       }
    672       await refreshList(generation);
    673       if (!current(generation) || !privateCurrent()) return;
    674       return '/messages/' + result.conversationId;
    675     } catch {
    676       if (current(generation)) reason = 'unavailable';
    677       return;
    678     } finally {
    679       if (current(generation)) {
    680         busy = false;
    681         notify();
    682       }
    683     }
    684   }
    685   async function loadOlder(review: unknown) {
    686     if (
    687       review !== 'reviewed_load_older' ||
    688       !olderAvailable() ||
    689       !sync ||
    690       !queue
    691     )
    692       return false;
    693     older ??= captureOlderInbox(sync, review);
    694     if (!older) return false;
    695     const generation = epoch;
    696     busy = true;
    697     notify();
    698     try {
    699       const result = await loadOlderInbox(older, review);
    700       if (!current(generation) || !privateCurrent() || !queue) return false;
    701       await refreshDecryptionQueue(queue);
    702       if (!current(generation) || !privateCurrent()) return false;
    703       await refreshList(generation);
    704       return current(generation) && privateCurrent() && result;
    705     } catch {
    706       if (current(generation)) reason = 'unavailable';
    707       return false;
    708     } finally {
    709       if (current(generation)) {
    710         busy = false;
    711         notify();
    712       }
    713     }
    714   }
    715   function snapshot(): InboxViewSnapshot {
    716     if (!current())
    717       return { ...unavailable(), cleanupRequired: pendingCleanup.length > 0 };
    718     const identity = identitySessionSnapshot(input.identity),
    719       setupState = inboxSetupViewSnapshot(input.setup);
    720     if (!privateCurrent() || !unlocked || !queue)
    721       return {
    722         ...unavailable(),
    723         owner: capture.owner,
    724         identity,
    725         state: busy
    726           ? 'unlocking'
    727           : [
    728                 'compatible',
    729                 'compatible_existing',
    730                 'access_unavailable',
    731                 'verified'
    732               ].includes(setupState.status)
    733             ? 'locked'
    734             : 'setup',
    735         reason,
    736         busy: busy || setupState.busy
    737       };
    738     const cached = readUnlockedMessages(unlocked),
    739       decrypt = decryptionQueueSnapshot(queue),
    740       paging = older && olderInboxSnapshot(older),
    741       transport = sync && inboxSyncSnapshot(sync);
    742     const scope = inboxSetupViewOwnership(input.setup);
    743     const exercised =
    744       !!scope?.resolver &&
    745       messagingReadinessSnapshot(
    746         input.identity,
    747         session,
    748         scope.policy,
    749         scope.resolver,
    750         undefined,
    751         scope.observeAccess
    752       ).ownAccess === 'qualified_exercised';
    753     if (!privateCurrent()) return unavailable();
    754     const partial =
    755       localPrivateBlocksSnapshot(preferences).state !== 'ready' ||
    756       reason !== null ||
    757       !exercised ||
    758       cached.status !== 'ready' ||
    759       list.status === 'unavailable' ||
    760       !!paging?.reason ||
    761       decrypt.state === 'paused' ||
    762       transport?.state === 'needs_action' ||
    763       transport?.state === 'stopped';
    764     const checked =
    765       lastCheckedAt !== null && !!sync && !!inboxSyncHistoryOwnership(sync);
    766     return {
    767       state:
    768         busy || decrypt.busy
    769           ? 'unlocking'
    770           : partial
    771             ? 'partial'
    772             : checked && decrypt.queued === 0 && cached.messages.length === 0
    773               ? 'empty'
    774               : 'ready',
    775       reason:
    776         (localPrivateBlocksSnapshot(preferences).state !== 'ready'
    777           ? 'local_preferences_unavailable'
    778           : null) ??
    779         reason ??
    780         listReason ??
    781         paging?.reason ??
    782         decrypt.reason ??
    783         transport?.reason ??
    784         (!exercised ? 'access_unavailable' : null),
    785       busy: busy || decrypt.busy || setupState.busy,
    786       owner: capture.owner,
    787       identity,
    788       queued: decrypt.queued,
    789       count: cached.messages.filter((message) =>
    790         localPrivatePeerAllowed(preferences, message.peer)
    791       ).length,
    792       lastCheckedAt,
    793       historyComplete: false,
    794       cleanupRequired: pendingCleanup.length > 0
    795     };
    796   }
    797   function notify() {
    798     for (const listener of listeners.values())
    799       try {
    800         listener(snapshot());
    801       } catch {
    802         /* Isolate presentation. */
    803       }
    804   }
    805   function releasePrivate() {
    806     privateOff();
    807     privateOff = () => {};
    808     const originalQueue = queue,
    809       originalSync = sync,
    810       originalUnlocked = unlocked,
    811       originalSession = session,
    812       originalDatabase = database,
    813       originalDirectory = directory,
    814       originalOlder = older;
    815     const tasks = pendingCleanup.concat([
    816       () => {
    817         if (originalOlder) stopOlderInbox(originalOlder);
    818       },
    819       () => {
    820         if (originalDirectory) closeConversationDirectory(originalDirectory);
    821       },
    822       () => {
    823         if (originalQueue) stopDecryptionQueue(originalQueue);
    824       },
    825       () => {
    826         if (originalSync) stopInboxSync(originalSync);
    827       },
    828       () => {
    829         if (originalUnlocked) closeUnlockedSession(originalUnlocked);
    830       },
    831       () => {
    832         if (originalSession && !closePrivateSession(originalSession))
    833           throw Error('private_cleanup_required');
    834       },
    835       () => {
    836         if (originalDatabase) closeBrowserDatabase(originalDatabase);
    837       }
    838     ]);
    839     pendingCleanup = [];
    840     for (const cleanup of tasks)
    841       try {
    842         cleanup();
    843       } catch {
    844         pendingCleanup = pendingCleanup.concat(cleanup);
    845       }
    846     if (pendingCleanup.length > 0) reason = 'cleanup_required';
    847     threadEpoch++;
    848     threadProofs.clear();
    849     threadModel = unavailableThread();
    850     threadId = undefined;
    851     threadPeer = undefined;
    852     sendRecords = [];
    853     repliedPeers = [];
    854     metadata = undefined;
    855     directory = undefined;
    856     older = undefined;
    857     list = { status: 'locked', requests: [], conversations: [] };
    858     listReason = null;
    859     rowProofs.clear();
    860     listRevision++;
    861     queue = undefined;
    862     sync = undefined;
    863     unlocked = undefined;
    864     session = undefined;
    865     repository = undefined;
    866     database = undefined;
    867     lastCheckedAt = null;
    868     checkPending = false;
    869   }
    870   function stop() {
    871     epoch++;
    872     reason = 'stopped';
    873     releasePrivate();
    874     busy = false;
    875     notify();
    876   }
    877   async function sample() {
    878     if (sampling || closed) return;
    879     if (!current()) {
    880       notify();
    881       return;
    882     }
    883     observeInboxSetupView(input.setup);
    884     if (!queue || !privateCurrent()) {
    885       notify();
    886       return;
    887     }
    888     sampling = true;
    889     const generation = epoch;
    890     try {
    891       const transport = sync && inboxSyncSnapshot(sync);
    892       // Read native ciphertext only after actual ingress changes, never on
    893       // every idle presentation tick and never as automatic SDK decryption.
    894       if (
    895         transport &&
    896         transport.pending === 0 &&
    897         transport.retained !== refreshedRetained &&
    898         !decryptionQueueSnapshot(queue).busy
    899       ) {
    900         const retained = transport.retained;
    901         const refreshed = await refreshDecryptionQueue(queue);
    902         if (!current(generation) || !privateCurrent()) return;
    903         refreshedRetained = retained;
    904         if (!refreshed) {
    905           notify();
    906           return;
    907         }
    908       }
    909       if (!current(generation) || !privateCurrent()) return;
    910       if (
    911         checkPending &&
    912         sync &&
    913         transport?.backfill === 'complete' &&
    914         transport.pending === 0 &&
    915         inboxSyncHistoryOwnership(sync)?.current()
    916       ) {
    917         const checked = Date.now();
    918         if (
    919           current(generation) &&
    920           privateCurrent() &&
    921           inboxSyncHistoryOwnership(sync)?.current()
    922         ) {
    923           lastCheckedAt = checked;
    924           checkPending = false;
    925         }
    926       }
    927       notify();
    928     } catch {
    929       if (current(generation)) {
    930         reason = 'unavailable';
    931         notify();
    932       }
    933     } finally {
    934       sampling = false;
    935     }
    936   }
    937   async function read(reviewed: unknown) {
    938     if (
    939       reviewed !== 'reviewed_decrypt_batch' ||
    940       (input.conversationId !== undefined &&
    941         (threadId !== input.conversationId || !threadPeer)) ||
    942       busy ||
    943       !queue ||
    944       !privateCurrent()
    945     )
    946       return false;
    947     busy = true;
    948     reason = null;
    949     const generation = epoch;
    950     notify();
    951     try {
    952       const result = await runDecryptionBatch(queue, reviewed);
    953       if (!current(generation) || !privateCurrent()) return false;
    954       await refreshList(generation);
    955       return current(generation) && privateCurrent() && result;
    956     } finally {
    957       if (current(generation)) {
    958         busy = false;
    959         notify();
    960       }
    961     }
    962   }
    963   async function unlock(reviewed: unknown) {
    964     if (reviewed !== 'reviewed_messages_unlock' || busy || !current())
    965       return false;
    966     if (queue && privateCurrent()) return await read('reviewed_decrypt_batch');
    967     const setupState = inboxSetupViewSnapshot(input.setup);
    968     if (
    969       ![
    970         'compatible',
    971         'compatible_existing',
    972         'access_unavailable',
    973         'verified'
    974       ].includes(setupState.status)
    975     )
    976       return false;
    977     busy = true;
    978     reason = null;
    979     const generation = epoch;
    980     notify();
    981     try {
    982       await mountLocalPrivateBlocks(preferences);
    983       if (
    984         !current(generation) ||
    985         localPrivateBlocksSnapshot(preferences).state !== 'ready'
    986       ) {
    987         reason = 'local_preferences_unavailable';
    988         return false;
    989       }
    990       await unlockInboxSetupView(input.setup);
    991       if (!current(generation)) return false;
    992       const original = inboxSetupViewOwnership(input.setup),
    993         acquired = original?.session,
    994         owner = acquired && privateSessionOwnership(acquired);
    995       if (
    996         !original?.resolver ||
    997         !acquired ||
    998         !owner?.current() ||
    999         owner.owner !== capture.owner ||
   1000         owner.session !== capture.session ||
   1001         !original.current()
   1002       )
   1003         return false;
   1004       session = acquired;
   1005       const opened = await openBrowserDatabase();
   1006       if (!current(generation) || !privateCurrent()) {
   1007         if (opened.state === 'ready') closeBrowserDatabase(opened.owner);
   1008         return false;
   1009       }
   1010       if (opened.state !== 'ready') {
   1011         reason = 'storage_unavailable';
   1012         return false;
   1013       }
   1014       database = opened.owner;
   1015       repository = createPrivateStorageRepository(database, capture.owner);
   1016       unlocked = captureUnlockedSession(session, reviewed);
   1017       queue =
   1018         repository &&
   1019         unlocked &&
   1020         captureDecryptionQueue(
   1021           repository,
   1022           session,
   1023           input.identity,
   1024           unlocked,
   1025           'reviewed_inbox_unlock'
   1026         );
   1027       if (!queue || !unlocked) {
   1028         reason = 'unavailable';
   1029         return false;
   1030       }
   1031       metadata = captureMessageMetadata(
   1032         database,
   1033         session,
   1034         unlocked,
   1035         'reviewed_local_message_metadata'
   1036       );
   1037       directory =
   1038         metadata &&
   1039         captureConversationDirectory(
   1040           session,
   1041           metadata,
   1042           'reviewed_conversation_directory'
   1043         );
   1044       if (!metadata || !directory) {
   1045         reason = 'storage_unavailable';
   1046         return false;
   1047       }
   1048       privateOff = subscribePrivateSessionClose(session, () => {
   1049         epoch++;
   1050         releasePrivate();
   1051         busy = false;
   1052         notify();
   1053         if (pendingCleanup.length > 0)
   1054           queueMicrotask(() => {
   1055             releasePrivate();
   1056             notify();
   1057           });
   1058       });
   1059       if (!privateCurrent()) return false;
   1060       if (
   1061         input.conversationId !== undefined &&
   1062         !(await resolve(
   1063           input.conversationId,
   1064           'reviewed_conversation_navigation'
   1065         ))
   1066       ) {
   1067         reason = 'unavailable';
   1068         return false;
   1069       }
   1070       const result = await runDecryptionBatch(queue, 'reviewed_decrypt_batch');
   1071       if (!current(generation) || !privateCurrent()) return false;
   1072       await refreshList(generation);
   1073       return current(generation) && privateCurrent() && result;
   1074     } catch {
   1075       if (current(generation)) reason = 'unavailable';
   1076       return false;
   1077     } finally {
   1078       if (current(generation)) {
   1079         busy = false;
   1080         notify();
   1081       }
   1082     }
   1083   }
   1084   async function check(reviewed: unknown) {
   1085     if (
   1086       reviewed !== 'reviewed_foreground_inbox' ||
   1087       busy ||
   1088       !privateCurrent() ||
   1089       !session ||
   1090       !repository ||
   1091       !unlocked
   1092     )
   1093       return false;
   1094     const scope = inboxSetupViewOwnership(input.setup);
   1095     if (!scope?.resolver || !scope.current() || !scope.observeAccess) {
   1096       reason = 'access_unavailable';
   1097       notify();
   1098       return false;
   1099     }
   1100     const generation = epoch;
   1101     reason = null;
   1102     if (sync) {
   1103       if (
   1104         !refreshInboxSync(
   1105           sync,
   1106           reviewed,
   1107           lastCheckedAt === null ? undefined : Math.floor(lastCheckedAt / 1000)
   1108         )
   1109       ) {
   1110         reason = inboxSyncSnapshot(sync)?.reason ?? 'check_incomplete';
   1111         notify();
   1112         return false;
   1113       }
   1114     } else {
   1115       sync = captureInboxSync(
   1116         repository,
   1117         session,
   1118         scope.policy,
   1119         scope.resolver,
   1120         unlocked,
   1121         scope.observeAccess,
   1122         reviewed
   1123       );
   1124       if (!sync || !startInboxSync(sync, reviewed)) {
   1125         reason = 'access_unavailable';
   1126         notify();
   1127         return false;
   1128       }
   1129     }
   1130     checkPending = true;
   1131     notify();
   1132     await sample();
   1133     if (current(generation) && privateCurrent()) await refreshList(generation);
   1134     return current(generation) && privateCurrent();
   1135   }
   1136   views.set(token, {
   1137     block,
   1138     blocked,
   1139     reply: replyOwnership,
   1140     snapshot,
   1141     thread: threadSnapshot,
   1142     threadRevision: () => (privateCurrent() ? listRevision + threadEpoch : -1),
   1143     message: messageSnapshot,
   1144     resolve,
   1145     displayed,
   1146     list: listSnapshot,
   1147     row: rowSnapshot,
   1148     revision: () => (privateCurrent() ? listRevision : -1),
   1149     open,
   1150     older: loadOlder,
   1151     olderAvailable,
   1152     setup: () => (current() ? input.setup : undefined),
   1153     subscribe(listener) {
   1154       const key = Symbol();
   1155       listeners.set(key, listener);
   1156       listener(snapshot());
   1157       return () => {
   1158         listeners.delete(key);
   1159       };
   1160     },
   1161     unlock,
   1162     check,
   1163     read,
   1164     stop,
   1165     close() {
   1166       // Retain this first terminal fanout before cleanup can reenter Close or
   1167       // unsubscribe another observer. Authority is revoked before callbacks.
   1168       const terminalListeners = closed ? [] : Array.from(listeners.values());
   1169       if (!closed) {
   1170         closed = true;
   1171         epoch++;
   1172         clearInterval(timer);
   1173         off();
   1174         setupOff();
   1175         preferencesOff();
   1176       }
   1177       releasePrivate();
   1178       // Cleanup retains the original genuine setup independently of current
   1179       // admission. Logout hides effect access, while disposal still closes
   1180       // its identity observer, database and runtime public-view owner.
   1181       try {
   1182         closeInboxSetupView(input.setup);
   1183       } catch {
   1184         pendingCleanup = pendingCleanup.concat(() =>
   1185           closeInboxSetupView(input.setup)
   1186         );
   1187       }
   1188       listeners.clear();
   1189       for (const listener of terminalListeners)
   1190         try {
   1191           listener(snapshot());
   1192         } catch {
   1193           /* Isolate terminal presentation without stranding other observers. */
   1194         }
   1195       return pendingCleanup.length === 0;
   1196     }
   1197   });
   1198   off = subscribeIdentityInvalidation(input.identity, () => {
   1199     if (!capture.current()) {
   1200       epoch++;
   1201       releasePrivate();
   1202       busy = false;
   1203       notify();
   1204     }
   1205   });
   1206   setupOff = subscribeInboxSetupView(input.setup, notify);
   1207   preferencesOff = subscribeLocalPrivateBlocks(preferences, () => {
   1208     refreshThread();
   1209     listRevision++;
   1210     notify();
   1211   });
   1212   const timer = setInterval(() => {
   1213     void sample();
   1214   }, 200);
   1215   if (!current()) {
   1216     views.get(token)?.close();
   1217     return;
   1218   }
   1219   return token;
   1220 }
   1221 export function inboxViewSnapshot(
   1222   token: InboxView | undefined
   1223 ): InboxViewSnapshot {
   1224   return (token && views.get(token)?.snapshot()) || unavailable();
   1225 }
   1226 export function inboxViewSetup(
   1227   token: InboxView | undefined
   1228 ): InboxSetupView | undefined {
   1229   return token && views.get(token)?.setup();
   1230 }
   1231 export function subscribeInboxView(
   1232   token: InboxView | undefined,
   1233   listener: (view: InboxViewSnapshot) => void
   1234 ): () => void {
   1235   return (token && views.get(token)?.subscribe(listener)) || (() => {});
   1236 }
   1237 export function unlockInboxView(
   1238   token: InboxView,
   1239   review: unknown
   1240 ): Promise<boolean> {
   1241   return views.get(token)?.unlock(review) ?? Promise.resolve(false);
   1242 }
   1243 export function checkInboxView(
   1244   token: InboxView,
   1245   review: unknown
   1246 ): Promise<boolean> {
   1247   return views.get(token)?.check(review) ?? Promise.resolve(false);
   1248 }
   1249 export function readNewInboxView(
   1250   token: InboxView,
   1251   review: unknown
   1252 ): Promise<boolean> {
   1253   return views.get(token)?.read(review) ?? Promise.resolve(false);
   1254 }
   1255 export function stopInboxView(token: InboxView): void {
   1256   views.get(token)?.stop();
   1257 }
   1258 export function closeInboxView(token: InboxView): boolean {
   1259   return views.get(token)?.close() ?? true;
   1260 }
   1261 
   1262 // Fresh genuine original cache observation. Returned rows are detached and
   1263 // never replace the original room/native authority used by explicit Open.
   1264 export function inboxListSnapshot(
   1265   token: InboxView | undefined
   1266 ): InboxListSnapshot {
   1267   return (
   1268     (token && views.get(token)?.list()) || {
   1269       status: 'unavailable',
   1270       requests: [],
   1271       conversations: []
   1272     }
   1273   );
   1274 }
   1275 export function openInboxConversation(
   1276   token: InboxView,
   1277   peer: unknown,
   1278   review: unknown
   1279 ): Promise<string | undefined> {
   1280   return views.get(token)?.open(peer, review) ?? Promise.resolve(undefined);
   1281 }
   1282 export function loadOlderInboxView(
   1283   token: InboxView,
   1284   review: unknown
   1285 ): Promise<boolean> {
   1286   return views.get(token)?.older(review) ?? Promise.resolve(false);
   1287 }
   1288 export function inboxViewOlderAvailable(token: InboxView | undefined): boolean {
   1289   return !!token && !!views.get(token)?.olderAvailable();
   1290 }
   1291 
   1292 export function inboxConversationRow(
   1293   token: InboxView | undefined,
   1294   peer: unknown
   1295 ): InboxListRow | undefined {
   1296   return token ? views.get(token)?.row(peer) : undefined;
   1297 }
   1298 export function inboxListRevision(token: InboxView | undefined): number {
   1299   return token ? (views.get(token)?.revision() ?? -1) : -1;
   1300 }
   1301 
   1302 export function inboxThreadSnapshot(
   1303   token: InboxView | undefined,
   1304   id: unknown
   1305 ): ThreadSnapshot {
   1306   return (token && views.get(token)?.thread(id)) || unavailableThread();
   1307 }
   1308 export function inboxMessageSnapshot(
   1309   token: InboxView,
   1310   id: unknown,
   1311   rumor: unknown
   1312 ): ThreadMessage | undefined {
   1313   return views.get(token)?.message(id, rumor);
   1314 }
   1315 export function resolveInboxConversation(
   1316   token: InboxView,
   1317   id: unknown,
   1318   review: unknown
   1319 ): Promise<boolean> {
   1320   return views.get(token)?.resolve(id, review) ?? Promise.resolve(false);
   1321 }
   1322 export function markInboxConversationDisplayed(
   1323   token: InboxView,
   1324   id: unknown,
   1325   rumors: readonly string[],
   1326   review: unknown
   1327 ): Promise<boolean> {
   1328   return (
   1329     views.get(token)?.displayed(id, rumors, review) ?? Promise.resolve(false)
   1330   );
   1331 }
   1332 
   1333 export function inboxThreadRevision(token: InboxView | undefined): number {
   1334   return token ? (views.get(token)?.threadRevision() ?? -1) : -1;
   1335 }
   1336 
   1337 export function inboxReplyOwnership(
   1338   token: InboxView,
   1339   id: unknown,
   1340   rumor: unknown
   1341 ): InboxReplyOwnership | undefined {
   1342   return views.get(token)?.reply(id, rumor);
   1343 }
   1344 export function blockInboxConversation(
   1345   view: InboxView,
   1346   id: unknown,
   1347   review: unknown
   1348 ): Promise<PrivateBlockResult> {
   1349   return (
   1350     views.get(view)?.block(id, review) ?? Promise.resolve({ status: 'invalid' })
   1351   );
   1352 }
   1353 export function inboxConversationBlocked(
   1354   view: InboxView | undefined,
   1355   id: unknown
   1356 ): boolean {
   1357   return !!view && !!views.get(view)?.blocked(id);
   1358 }